yfqiu-nlp commited on
Commit
8163775
·
verified ·
1 Parent(s): 817d608

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +162 -0
  2. LICENSE +21 -0
  3. README.md +139 -0
  4. app.py +90 -0
  5. data-formatter.py +69 -0
  6. datasheet.md +311 -0
  7. disc_edit.py +251 -0
  8. edit_cli.py +124 -0
  9. edit_dataset.py +603 -0
  10. eq-kubric/3d_data/GSO.json +0 -0
  11. eq-kubric/3d_data/GSO_dict_all.json +1035 -0
  12. eq-kubric/3d_data/GSO_dict_filtered.json +583 -0
  13. eq-kubric/create_scene.py +49 -0
  14. eq-kubric/main.py +16 -0
  15. eq-kubric/my_kubric_twoframe_attribute.py +587 -0
  16. eq-kubric/my_kubric_twoframe_closer.py +479 -0
  17. eq-kubric/my_kubric_twoframe_rotate.py +590 -0
  18. eq-kubric/utils/__init__.py +49 -0
  19. eval_disc_edit.py +33 -0
  20. hf_push.py +15 -0
  21. main.py +800 -0
  22. requirements.txt +229 -0
  23. stable_diffusion/LICENSE +82 -0
  24. stable_diffusion/README.md +215 -0
  25. stable_diffusion/Stable_Diffusion_v1_Model_Card.md +144 -0
  26. stable_diffusion/assets/stable-samples/txt2img/merged-0006.png.REMOVED.git-id +1 -0
  27. stable_diffusion/assets/stable-samples/txt2img/merged-0007.png.REMOVED.git-id +1 -0
  28. stable_diffusion/assets/txt2img-preview.png.REMOVED.git-id +1 -0
  29. stable_diffusion/configs/autoencoder/autoencoder_kl_16x16x16.yaml +54 -0
  30. stable_diffusion/configs/autoencoder/autoencoder_kl_32x32x4.yaml +53 -0
  31. stable_diffusion/data/example_conditioning/text_conditional/sample_0.txt +1 -0
  32. stable_diffusion/ldm/data/__init__.py +0 -0
  33. stable_diffusion/ldm/data/base.py +23 -0
  34. stable_diffusion/ldm/data/imagenet.py +394 -0
  35. stable_diffusion/ldm/data/lsun.py +92 -0
  36. stable_diffusion/ldm/lr_scheduler.py +98 -0
  37. stable_diffusion/ldm/models/diffusion/__init__.py +0 -0
  38. stable_diffusion/ldm/models/diffusion/ddim.py +241 -0
  39. stable_diffusion/ldm/models/diffusion/ddpm.py +1445 -0
  40. stable_diffusion/ldm/models/diffusion/ddpm_edit.py +1459 -0
  41. stable_diffusion/ldm/models/diffusion/ddpm_edit_disc.py +1669 -0
  42. stable_diffusion/ldm/models/diffusion/dpm_solver/__init__.py +1 -0
  43. stable_diffusion/ldm/models/diffusion/dpm_solver/dpm_solver.py +1184 -0
  44. stable_diffusion/ldm/models/diffusion/dpm_solver/sampler.py +82 -0
  45. stable_diffusion/ldm/models/diffusion/plms.py +236 -0
  46. stable_diffusion/ldm/modules/attention.py +275 -0
  47. stable_diffusion/ldm/modules/diffusionmodules/__init__.py +0 -0
  48. stable_diffusion/ldm/modules/diffusionmodules/model.py +835 -0
  49. stable_diffusion/ldm/modules/diffusionmodules/openaimodel.py +961 -0
  50. stable_diffusion/ldm/modules/distributions/__init__.py +0 -0
.gitignore ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 McGill NLP
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # *AURORA: Learning Action and Reasoning-Centric Image Editing from Videos and Simulation*
2
+
3
+ [![Website](https://img.shields.io/badge/Website-AURORA.svg)](https://aurora-editing.github.io/)
4
+ [![arxiv](https://img.shields.io/badge/arXiv-2407.03471-b31b1b.svg)](https://arxiv.org/abs/2407.03471)
5
+ [![HF Datasets: AURORA](https://img.shields.io/badge/HF%20Datasets-AURORA-FFD21E.svg)](https://huggingface.co/datasets/McGill-NLP/AURORA)
6
+ [![HF Datasets: AURORA-Bench](https://img.shields.io/badge/HF%20Datasets-AURORABench-FFD21E.svg)](https://huggingface.co/datasets/McGill-NLP/aurora-bench)
7
+ [![HF Demo](https://img.shields.io/badge/HF%20DEMO-FFD21E.svg)](https://huggingface.co/spaces/McGill-NLP/AURORA)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/McGill-NLP/AURORA/blob/main/LICENSE)
9
+
10
+ AURORA (Action Reasoning Object Attribute) enables training an instruction-guided image editing model that can perform action and reasoning-centric edits, in addition to "simpler" established object, attribute or global edits. Here we release 1) training data, 2) trained model, 3) benchmark, 4) reproducible training and evaluation.
11
+
12
+ <p align="center">
13
+ <img src="aurora.png" width="75%" alt="Overview"/>
14
+ </p>
15
+
16
+ Please reach out to [[email protected]](mailto:[email protected]) or raise an issue if anything does not work!
17
+
18
+
19
+
20
+ ## Updates
21
+ **5th December 2024**: uploaded cleaner (actually usable) human ratings on AURORA-Bench. This can be useful for evaluating metrics via human correlation across a wide range of tasks. It includes 2K human ratings on outputs from 5 models.
22
+
23
+ ## Data
24
+
25
+ On the data side, we release three artifacts and a [Datasheet documentation](https://github.com/McGill-NLP/AURORA/blob/main/datasheet.md):
26
+ 1. The training dataset (AURORA)
27
+ 2. A benchmark for testing diverse editing skills (AURORA-Bench): object-centric, action-centric, reasoning-centric, and global edits
28
+ 3. Human ratings on AURORA-Bench, i.e. for other researchers working image editing metrics
29
+
30
+ You can also check out our [Huggingface dataset](https://huggingface.co/datasets/McGill-NLP/AURORA).
31
+
32
+ ### Training Data (AURORA)
33
+
34
+ The edit instructions are stored as `data/TASK/train.json` for each of the four tasks.
35
+
36
+ For the image pairs, you can download them easily via zenodo:
37
+ ```
38
+ wget https://zenodo.org/record/11552426/files/ag_images.zip
39
+ wget https://zenodo.org/record/11552426/files/kubric_images.zip
40
+ wget https://zenodo.org/record/11552426/files/magicbrush_images.zip
41
+ ```
42
+
43
+ Now put them into their respective directory `data/NAME` and rename them images.zip.
44
+ So in the end you should have `data/kubric/images` as a directory etc.
45
+
46
+ For Something-Something-Edit, you need to go to the [original source](https://developer.qualcomm.com/software/ai-datasets/something-something) and download all the zip files and put *all* the videos in a folder named `data/something/videos/`.
47
+
48
+ Then run
49
+ ```
50
+ cd data/something
51
+ python extract_frames.py
52
+ python filter_keywords.py
53
+ ```
54
+
55
+ For each sub-dataset of AURORA, an entry would look like this:
56
+
57
+
58
+ ```json
59
+ [
60
+ {
61
+ "instruction": "Leave the door while standing closer",
62
+ "input": "data/ag/images/1K0SU.mp4_4_left.png",
63
+ "output": "data/ag/images/1K0SU.mp4_4_right.png"
64
+ },
65
+ {"..."}
66
+ ]
67
+ ```
68
+
69
+ If you are interested in developing your own similar Kubric data, it takes some effort (i.e. Docker+Blender setup), but we provide some starting code under `eq-kubric`.
70
+
71
+ ### Benchmark: AURORA-Bench
72
+
73
+ For measuring how well models do on various editing skills (action, reasoning, object/attribute, global), we introduce AURORA-Bench hosted here on this repository under `test.json` with the respective images under `data/TASK/images/`.
74
+
75
+ ### Human Ratings
76
+
77
+ We also release human ratings of image editing outputs on AURORA-Bench examples, which forms the basis of our main evaluation in the paper.
78
+ The output images and assocaciated human ratings can be downloaded from Google Drive and is straightforward to use e.g. for computing correlations with a new metric: [json](https://drive.google.com/file/d/1uWpVOit_eUvI6GnY_Bvaj_vPd3H8cTbT/view?usp=sharing), [images files](https://drive.google.com/file/d/1wUwlxN1ArqTlCQQgnsj7DoXNoPRX71Ao/view?usp=sharing)
79
+
80
+ ## Running stuff
81
+
82
+ Similar to [MagicBrush](https://github.com/OSU-NLP-Group/MagicBrush) we adopt the [pix2pix codebase](https://github.com/timothybrooks/instruct-pix2pix) for running and training models.
83
+
84
+ ### Inference
85
+
86
+ Please create a python environment and install the requirements.txt file (it is unfortunately important to use 3.9 due to taming-transformers):
87
+ ```
88
+ python3.9 -m venv env
89
+ pip3 install -r requirements.txt
90
+ ```
91
+
92
+ You can download our trained checkpoint from Google Drive: [Link](https://drive.google.com/file/d/1omV0xGyX6rVx1gp2EFgdcK8qSw1gUcnx/view?usp=sharing), place it in the main directory and run our AURORA-trained model on an example image:
93
+ ```
94
+ python3 edit_cli.py
95
+ ```
96
+
97
+ ### Training
98
+ To reproduce our training, first download an initial checkpoint that is the reproduced MagicBrush model: [Google Drive Link](https://drive.google.com/file/d/1qwkRwsa9jJu1uyYkaWOGL1CpXWlBI1jN/view?usp=sharing)
99
+
100
+ Due to weird versioning of libraries/python, you have to go to `env/src/taming-transformers/taming/data/utils.py` and comment out line 11: `from torch._six import string_classes`.
101
+
102
+ Now you can run the the train script (hyperparameters can be changed under `configs/finetune_magicbrush_ag_something_kubric_15-15-1-1_init-magic.yaml`):
103
+
104
+ ```
105
+ python3 main.py --gpus 0,
106
+ ```
107
+
108
+ Specify more gpus with i.e. `--gpus 0,1,2,3`.
109
+
110
+
111
+ ## Reproduce Evaluation
112
+
113
+ We primarily rely on human evaluation of model outputs on AURORA-Bench.
114
+ However our second proposed evaluation metric is automatic and here is how you reproduce it.
115
+
116
+ First, run `python3 disc_edit.py --task TASK` (i.e. `--task whatsup`). This will generate outputs in a folder called itm_evaluation, that will then be evaluated via `python3 eval_disc_edit.py`
117
+
118
+ ## Citation
119
+
120
+ ```bibtex
121
+ @inproceedings{krojer2024aurora,
122
+ author={Benno Krojer and Dheeraj Vattikonda and Luis Lara and Varun Jampani and Eva Portelance and Christopher Pal and Siva Reddy},
123
+ title={{Learning Action and Reasoning-Centric Image Editing from Videos and Simulations}},
124
+ booktitle={NeurIPS},
125
+ year={2024},
126
+ note={Spotlight Paper},
127
+ url={https://arxiv.org/abs/2407.03471}
128
+ }
129
+ ```
130
+
131
+ ## Acknowledgements & License
132
+
133
+ We use the [MIT License](https://github.com/McGill-NLP/AURORA/blob/main/LICENSE).
134
+
135
+ We want to thank several repositories that made our life much easier on this project:
136
+
137
+ 1. The [MagicBrush](https://github.com/OSU-NLP-Group/MagicBrush) and [InstructPix2Pix](https://github.com/timothybrooks/instruct-pix2pix) code base and datasets, especially the correspondance with MagicBrush authors helped us a lot.
138
+ 2. The dataset/engines we use to build AURORA: [Something Something v2](https://developer.qualcomm.com/software/ai-datasets/something-something), [Action-Genome](https://github.com/JingweiJ/ActionGenome) and [Kubric](https://github.com/google-research/kubric)
139
+ 3. Source code from [EQBEN](https://github.com/Wangt-CN/EqBen) for generating images with the Kubric engine
app.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import math
3
+ import gradio as gr
4
+ import torch
5
+ from PIL import Image, ImageOps
6
+ from diffusers import StableDiffusionInstructPix2PixPipeline
7
+
8
+ def main():
9
+ pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained("McGill-NLP/AURORA", safety_checker=None).to("cuda")
10
+ example_image = Image.open("example.jpg").convert("RGB")
11
+
12
+ def generate(
13
+ input_image: Image.Image,
14
+ instruction: str,
15
+ steps: int,
16
+ seed: int,
17
+ text_cfg_scale: float,
18
+ image_cfg_scale: float,
19
+ ):
20
+ width, height = input_image.size
21
+ factor = 512 / max(width, height)
22
+ factor = math.ceil(min(width, height) * factor / 64) * 64 / min(width, height)
23
+ width = int((width * factor) // 64) * 64
24
+ height = int((height * factor) // 64) * 64
25
+ input_image = ImageOps.fit(input_image, (width, height), method=Image.Resampling.LANCZOS)
26
+
27
+ if instruction == "":
28
+ return [input_image, seed]
29
+
30
+ generator = torch.manual_seed(seed)
31
+ edited_image = pipe(
32
+ instruction, image=input_image,
33
+ guidance_scale=text_cfg_scale, image_guidance_scale=image_cfg_scale,
34
+ num_inference_steps=steps, generator=generator,
35
+ ).images[0]
36
+ return [seed, text_cfg_scale, image_cfg_scale, edited_image]
37
+
38
+ def reset():
39
+ return ["", 50, 42, 7.5, 1.5, None, None]
40
+
41
+ with gr.Blocks() as demo:
42
+ gr.HTML("""<h1 style="font-weight: 900; margin-bottom: 10px;">
43
+ AURORA: Learning Action and Reasoning-Centric Image Editing from Videos and Simulations
44
+ </h1>
45
+ <p>
46
+ AURORA (Action Reasoning Object Attribute) enables training an instruction-guided image editing model that can perform action and reasoning-centric edits, in addition to "simpler" established object, attribute or global edits.
47
+ </p>""")
48
+
49
+ with gr.Row():
50
+ with gr.Column(scale=3):
51
+ instruction = gr.Textbox(value="move the lemon to the right of the table", lines=1, label="Edit instruction", interactive=True)
52
+ with gr.Column(scale=1, min_width=100):
53
+ generate_button = gr.Button("Generate", variant="primary")
54
+ with gr.Column(scale=1, min_width=100):
55
+ reset_button = gr.Button("Reset", variant="stop")
56
+
57
+ with gr.Row():
58
+ input_image = gr.Image(value=example_image, label="Input image", type="pil", interactive=True)
59
+ edited_image = gr.Image(label=f"Edited image", type="pil", interactive=False)
60
+
61
+ with gr.Row():
62
+ steps = gr.Number(value=50, precision=0, label="Steps", interactive=True)
63
+ seed = gr.Number(value=42, precision=0, label="Seed", interactive=True)
64
+ text_cfg_scale = gr.Number(value=7.5, label=f"Text CFG", interactive=True)
65
+ image_cfg_scale = gr.Number(value=1.5, label=f"Image CFG", interactive=True)
66
+
67
+ generate_button.click(
68
+ fn=generate,
69
+ inputs=[
70
+ input_image,
71
+ instruction,
72
+ steps,
73
+ seed,
74
+ text_cfg_scale,
75
+ image_cfg_scale,
76
+ ],
77
+ outputs=[seed, text_cfg_scale, image_cfg_scale, edited_image],
78
+ )
79
+ reset_button.click(
80
+ fn=reset,
81
+ inputs=[],
82
+ outputs=[instruction, steps, seed, text_cfg_scale, image_cfg_scale, edited_image, input_image],
83
+ )
84
+
85
+ demo.queue()
86
+ demo.launch()
87
+ # demo.launch(share=True)
88
+
89
+ if __name__ == "__main__":
90
+ main()
data-formatter.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import argparse
3
+ import os
4
+
5
+ if __name__ == "__main__":
6
+ parser = argparse.ArgumentParser()
7
+ parser.add_argument("--dataset", type=str, required=True)
8
+ parser.add_argument("--training-format", type=str, required=True)
9
+ args = parser.parse_args()
10
+
11
+ # Load the input JSON file
12
+ with open("data/{s}/train.json".format(s=args.dataset), "r") as f:
13
+ data = json.load(f)
14
+
15
+ jsonl_data = []
16
+
17
+ # Convert the input JSON to JSONL format
18
+ for key, value in enumerate(data):
19
+
20
+ if args.dataset == "something":
21
+ input_path = value["input"]
22
+ output_path = value["output"]
23
+ file_check = os.path.exists(input_path) and os.path.exists(output_path)
24
+ else:
25
+ file_check = True
26
+
27
+ if file_check:
28
+
29
+ if args.training_format == "sft-editing":
30
+ entry = {
31
+ "id": f"{int(key):012d}",
32
+ "images": ["AURORA/"+value["input"], "AURORA/"+value["output"]],
33
+ "conversations": [
34
+ {
35
+ "from": "human",
36
+ "value": f"<image>\nEditing the given image according to the following prompt: {value['instruction']}"
37
+ },
38
+ {
39
+ "from": "gpt",
40
+ "value": "<image>"
41
+ }
42
+ ]
43
+ }
44
+ elif args.training_format == "sft-action-verbolise":
45
+ entry = {
46
+ "id": f"{int(key):012d}",
47
+ "images": ["AURORA/"+value["input"], "AURORA/"+value["output"]],
48
+ "conversations": [
49
+ {
50
+ "from": "human",
51
+ "value": f"You are given two sequential observations in the form of images.\n\nPast observations:\n<image>\nNext observation after taking the action:\n<image>\n\nYour task is to infer and describe the most likely action that occurred between the past and next observations. The action should be described concisely in natural language, capturing key changes that explain the state transition."
52
+ },
53
+ {
54
+ "from": "gpt",
55
+ "value": "The most likely action that occurred between the observations is: "+value['instruction']
56
+ }
57
+ ]
58
+ }
59
+ else:
60
+ raise NotImplementedError
61
+ jsonl_data.append(entry)
62
+
63
+ else:
64
+ continue
65
+
66
+ # Save to a JSONL file
67
+ with open("data/{s}/{f}-train.jsonl".format(s=args.dataset, f=args.training_format), "w") as f:
68
+ for line in jsonl_data:
69
+ f.write(json.dumps(line) + "\n")
datasheet.md ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Datasheet for dataset "AURORA"
2
+
3
+ Questions from the [Datasheets for Datasets](https://arxiv.org/abs/1803.09010) paper, v7.
4
+
5
+ Jump to section:
6
+
7
+ - [Motivation](#motivation)
8
+ - [Composition](#composition)
9
+ - [Collection process](#collection-process)
10
+ - [Preprocessing/cleaning/labeling](#preprocessingcleaninglabeling)
11
+ - [Uses](#uses)
12
+ - [Distribution](#distribution)
13
+ - [Maintenance](#maintenance)
14
+
15
+ ## Motivation
16
+
17
+ _The questions in this section are primarily intended to encourage dataset creators
18
+ to clearly articulate their reasons for creating the dataset and to promote transparency
19
+ about funding interests._
20
+
21
+ ### For what purpose was the dataset created?
22
+
23
+ We collected AURORA since there is no current high-quality dataset for instruction-guided image editing where the instruction is an action such as "move carrots into the sink". As a result, the current image editing are quite limited and not as "general" as one would hope. This is an important subtask of image editing and can enable many downstream applications. There have been few training datasets for these sort of edit instructions and the ones that exist have very noisy data, i.e. where the target image shows far more changes than described in the text, or the change described is not even properly shown.
24
+
25
+ ### Who created the dataset (e.g., which team, research group) and on behalf of which entity (e.g., company, institution, organization)?
26
+ It was developed primarily at "Mila - Quebec Artificial Intelligence Institute", specifically in Siva Reddy's lab by his PhD student Benno Krojer. Other collaborators on the paper were involved in the ideation, many of them also at Mila and one of them at Stability AI.
27
+
28
+ ### Who funded the creation of the dataset?
29
+ The dataset was funded by the PI, Siva Reddy.
30
+
31
+ ### Any other comments?
32
+ None.
33
+
34
+ ## Composition
35
+
36
+ _Most of these questions are intended to provide dataset consumers with the
37
+ information they need to make informed decisions about using the dataset for
38
+ specific tasks. The answers to some of these questions reveal information
39
+ about compliance with the EU’s General Data Protection Regulation (GDPR) or
40
+ comparable regulations in other jurisdictions._
41
+
42
+ ### What do the instances that comprise the dataset represent (e.g., documents, photos, people, countries)?
43
+
44
+ Each datapoint is a triplet of (source image, prompt, target image), i.e. (an image of a dog, "make the dog smile", an image of a dog smiling).
45
+ Our data consists of four sub-datasets:
46
+ 1. MagicBrush: **Source images** are diverse web-scrapped images ([MS-COCO](https://cocodataset.org/#home) which comes from websites like Flickr). **Prompt** and **target images** were previously crowd-sourced with humans using the DALL-E 2 editing interface.
47
+ 2. Action-Genome-Edit and Something-Something-Edit:** source** and **target images** are video frames depicting activities mostly at home; the **prompt** is human written (crowd-sourced by us or in the case of Something Something at the time of video recording in the original dataset).
48
+ 3. Kubric-Edit: **Source** and **target images** were generated in a simulation engine (Kubric), and depict non-human objects. The **prompt** is templated.
49
+
50
+ ### How many instances are there in total (of each type, if appropriate)?
51
+ 9K (MagicBrush) + 11K (Action-Genome-Edit) + 119K (Something-Something-Edit) + 150K (Kubric-Edit) = 149K + 150K = 399K
52
+
53
+ ### Does the dataset contain all possible instances or is it a sample (not necessarily random) of instances from a larger set?
54
+
55
+ It is not really a sample, but we did have to filter out video frames that were too noisy or showed too much change such as camera movement.
56
+
57
+ ### What data does each instance consist of?
58
+
59
+ Two raw images (source & target), and a string (the prompt).
60
+
61
+ ### Is there a label or target associated with each instance?
62
+
63
+ The **target image** is the structure that the model has to predict during training and test time.
64
+
65
+ ### Is any information missing from individual instances?
66
+
67
+ No.
68
+
69
+ ### Are relationships between individual instances made explicit (e.g., users’ movie ratings, social network links)?
70
+
71
+ In MagicBrush there are sequential edits, that are indicated by the json key "img_id".
72
+ In Action-Genome edit, some datapoints can come from the same video clip, which can be checked in the filename.
73
+
74
+ ### Are there recommended data splits (e.g., training, development/validation, testing)?
75
+
76
+ We release training data separately from the AURORA-Bench data. The test data is much smaller and the test split of each of our training sub-datasets contributes to it.
77
+
78
+ ### Are there any errors, sources of noise, or redundancies in the dataset?
79
+
80
+ The main source of noise comes with the video-frame-based data where sometimes there can be more changes than described in language. Or the change described in the prompt is not shown clearly.
81
+
82
+ ### Is the dataset self-contained, or does it link to or otherwise rely on external resources (e.g., websites, tweets, other datasets)?
83
+
84
+ Self-contained, except that we ask people to download the videos from the original Something Something website, instead of providing the actual image files.
85
+
86
+ ### Does the dataset contain data that might be considered confidential (e.g., data that is protected by legal privilege or by doctor-patient confidentiality, data that includes the content of individuals’ non-public communications)?
87
+
88
+ No, it was crowd-souced with paid workers who agreed to work on this task.
89
+
90
+ ### Does the dataset contain data that, if viewed directly, might be offensive, insulting, threatening, or might otherwise cause anxiety?
91
+
92
+ No.
93
+
94
+ ### Does the dataset relate to people?
95
+
96
+ Especially the Action-Genome-Edit data depicts people in their homes.
97
+
98
+ ### Does the dataset identify any subpopulations (e.g., by age, gender)?
99
+
100
+ We do not know the exact recruitment for Action-Genome and Something Something videos (we build on top of these), but there are usually requirements such as speaking English.
101
+ In our case, we only worked with 7 workers that had shown to produce high-quality data. We do not know their age or other personal details as this information is not direclty shown in Amazon Mechanical Turk.
102
+
103
+ ### Is it possible to identify individuals (i.e., one or more natural persons), either directly or indirectly (i.e., in combination with other data) from the dataset?
104
+
105
+ If someone really tried, they might be able to identify some of the people in Action-Genome-Edit since they are shown fully and in their home. This would have to rely on advanced facial recognition and matching with other databases.
106
+
107
+ ### Does the dataset contain data that might be considered sensitive in any way (e.g., data that reveals racial or ethnic origins, sexual orientations, religious beliefs, political opinions or union memberships, or locations; financial or health data; biometric or genetic data; forms of government identification, such as social security numbers; criminal history)?
108
+
109
+ No.
110
+
111
+ ### Any other comments?
112
+ None.
113
+
114
+ ## Collection process
115
+
116
+ _\[T\]he answers to questions here may provide information that allow others to
117
+ reconstruct the dataset without access to it._
118
+
119
+ ### How was the data associated with each instance acquired?
120
+
121
+ _Was the data directly observable (e.g., raw text, movie ratings), reported by subjects (e.g.,
122
+ survey responses), or indirectly inferred/derived from other data (e.g., part-of-speech tags,
123
+ model-based guesses for age or language)? If data was reported by subjects or indirectly
124
+ inferred/derived from other data, was the data validated/verified? If so, please describe how._
125
+
126
+ For the sub-datasets MagicBrush, Action-Genome-Edit and Something-Something-Edit the prompts were written by humans and in the case of MagicBrush, the edited images were also produced in collaboration with an AI editing tool (DALL-E 2).
127
+ Only Kubric-Edit is fully synthetic.
128
+
129
+ The data was verified for "truly minimal" image pairs (as described in the paper), i.e. that all the changes from source to target are also described in the prompt. Only for Something-Something-Edit, this was not done on an instance-level but based on categories/labels and thus there will be some non-minimal pairs.
130
+
131
+ ### What mechanisms or procedures were used to collect the data (e.g., hardware apparatus or sensor, manual human curation, software program, software API)?
132
+
133
+ _How were these mechanisms or procedures validated?_
134
+
135
+ For the data we collected ourselves with humans (Action-Genome-Edit), we used Amazon Mechanical Turk (see Appendix of the paper for screenshots of our interface).
136
+ We recruited the best workers from previous test runs and had lengthy e-mail exchanges to verify everything makes sense for them and we get good quality.
137
+ For Kubric-Edit we used a simulation engine called Kubric.
138
+
139
+ ### If the dataset is a sample from a larger set, what was the sampling strategy (e.g., deterministic, probabilistic with specific sampling probabilities)?
140
+
141
+ ### Who was involved in the data collection process (e.g., students, crowdworkers, contractors) and how were they compensated (e.g., how much were crowdworkers paid)?
142
+
143
+ We worked with 7 workers from Amazon Mechanical Turk and paid them 0.22$ USD per example, resulting in an estimated 10-20$ per hour.
144
+
145
+ ### Over what timeframe was the data collected?
146
+
147
+ _Does this timeframe match the creation timeframe of the data associated with the instances (e.g.
148
+ recent crawl of old news articles)? If not, please describe the timeframe in which the data
149
+ associated with the instances was created._
150
+
151
+ Around a week at the end of April 2024 for the main collection of Action-Genome. For the others, we constructed it from March to May with refinements.
152
+
153
+ ### Were any ethical review processes conducted (e.g., by an institutional review board)?
154
+
155
+ No.
156
+
157
+ ### Does the dataset relate to people?
158
+
159
+ Only in the sense that the prompts were written by people and that 1-2 dataset we build on top of depicts people.
160
+
161
+ ### Did you collect the data from the individuals in question directly, or obtain it via third parties or other sources (e.g., websites)?
162
+
163
+ We collected it directly from AMT.
164
+
165
+ ### Were the individuals in question notified about the data collection?
166
+
167
+ _If so, please describe (or show with screenshots or other information) how notice was provided,
168
+ and provide a link or other access point to, or otherwise reproduce, the exact language of the
169
+ notification itself._
170
+
171
+ Workers on AMT see the posting with details like price and task description. In our case, we simply emailed workers from previous collections, and also told them it is for a research publication (i.e. linking to similar papers to give them an idea of what they are working on).
172
+
173
+ ### Did the individuals in question consent to the collection and use of their data?
174
+
175
+ They implicitly agreed to various uses through the terms of service by MTurk: https://www.mturk.com/participation-agreement
176
+
177
+ ### If consent was obtained, were the consenting individuals provided with a mechanism to revoke their consent in the future or for certain uses?
178
+
179
+ I am not sure about that part of MTurk's legal agreement but would guess no. I could not find an exact passage describing this, perhaps the the section "Use of Information; Publicity and Confidentiality"
180
+
181
+ ### Has an analysis of the potential impact of the dataset and its use on data subjects (e.g., a data protection impact analysis) been conducted?
182
+
183
+ No.
184
+
185
+ ### Any other comments?
186
+
187
+ None.
188
+
189
+ ## Preprocessing/cleaning/labeling
190
+
191
+ _The questions in this section are intended to provide dataset consumers with the information
192
+ they need to determine whether the “raw” data has been processed in ways that are compatible
193
+ with their chosen tasks. For example, text that has been converted into a “bag-of-words” is
194
+ not suitable for tasks involving word order._
195
+
196
+ ### Was any preprocessing/cleaning/labeling of the data done (e.g., discretization or bucketing, tokenization, part-of-speech tagging, SIFT feature extraction, removal of instances, processing of missing values)?
197
+
198
+ We mainly filtered out image pairs with too many changes: We told workers to discard images with too many (or in rare cases too few changes). We automatically pre-filtered by "CLIP-score" (the cosine similarity between the visual embeddings of source and target image) for Action-Genome-Edit and Something-Something-Edit.
199
+
200
+ ### Was the “raw” data saved in addition to the preprocessed/cleaned/labeled data (e.g., to support unanticipated future uses)?
201
+
202
+ It was not directly saved but can be accessed again by downloading the original sources we build upon such as Action-Genome videos (or frames from [EQBEN](https://github.com/Wangt-CN/EqBen), or the Something Something dataset.
203
+
204
+ ### Is the software used to preprocess/clean/label the instances available?
205
+
206
+ We provide scripts on how to go from raw videos/frames to the cleaner ones on our repository.
207
+
208
+ ### Any other comments?
209
+
210
+ None.
211
+
212
+ ## Uses
213
+
214
+ _These questions are intended to encourage dataset creators to reflect on the tasks
215
+ for which the dataset should and should not be used. By explicitly highlighting these tasks,
216
+ dataset creators can help dataset consumers to make informed decisions, thereby avoiding
217
+ potential risks or harms._
218
+
219
+ ### Has the dataset been used for any tasks already?
220
+
221
+ We used it to train an image editing model. We expect similar applications, also to video generation models.
222
+ MagicBrush has been used by several people.
223
+
224
+ ### Is there a repository that links to any or all papers or systems that use the dataset?
225
+
226
+ Our code repository, or [MagicBrush](https://github.com/OSU-NLP-Group/MagicBrush).
227
+
228
+ ### What (other) tasks could the dataset be used for?
229
+
230
+ Training models for video generation, change descriptions (i.e. Vision-and-Language LLMs) or discrimination of two similar images.
231
+ A possible negative application further down the road is surveillance systems that need to detect minor changes.
232
+
233
+ ### Is there anything about the composition of the dataset or the way it was collected and preprocessed/cleaned/labeled that might impact future uses?
234
+
235
+ Not that I can think of.
236
+
237
+ ### Are there tasks for which the dataset should not be used?
238
+
239
+ Unsure.
240
+
241
+ ### Any other comments?
242
+
243
+ None.
244
+
245
+ ## Distribution
246
+
247
+ ### Will the dataset be distributed to third parties outside of the entity (e.g., company, institution, organization) on behalf of which the dataset was created?
248
+
249
+ We will fully open-source it and provide access via Zenodo/json files as well as Huggingface Datasets.
250
+
251
+ ### How will the dataset will be distributed (e.g., tarball on website, API, GitHub)?
252
+
253
+ Both Zenodo and Huggingface datasets.
254
+
255
+ ### When will the dataset be distributed?
256
+
257
+ The weeks after submission to NeurIPS Dataset & Benchmark track, so in June 2024.
258
+
259
+ ### Will the dataset be distributed under a copyright or other intellectual property (IP) license, and/or under applicable terms of use (ToU)?
260
+
261
+ We stick with the standard open-source license: MIT License
262
+
263
+ ### Have any third parties imposed IP-based or other restrictions on the data associated with the instances?
264
+
265
+ Something Something is the only dataset with a restricted license (it seems, I don't speak legalese: [License Terms](https://developer.qualcomm.com/software/ai-datasets/something-something)).
266
+ So we are planning to link to their website and provide scripts to get to our final data.
267
+
268
+ ### Do any export controls or other regulatory restrictions apply to the dataset or to individual instances?
269
+
270
+ [Official access and licensing](https://developer.qualcomm.com/software/ai-datasets/something-something) of Something Something dataset.
271
+
272
+ ### Any other comments?
273
+
274
+ None.
275
+
276
+ ## Maintenance
277
+
278
+ _These questions are intended to encourage dataset creators to plan for dataset maintenance
279
+ and communicate this plan with dataset consumers._
280
+
281
+ ### Who is supporting/hosting/maintaining the dataset?
282
+
283
+ The main author is responsible for ensuring long-term accessibility, which relies on Zenodo and Huggingface.
284
+
285
+ ### How can the owner/curator/manager of the dataset be contacted (e.g., email address)?
286
+
287
+ [email protected] (or after I finish my PhD [email protected])
288
+
289
+ ### Is there an erratum?
290
+
291
+ Not yet!
292
+
293
+ ### Will the dataset be updated (e.g., to correct labeling errors, add new instances, delete instances)?
294
+
295
+ Not sure yet. If we find that people are interested in the data or trained model, we will continue our efforts.
296
+
297
+ ### If the dataset relates to people, are there applicable limits on the retention of the data associated with the instances (e.g., were individuals in question told that their data would be retained for a fixed period of time and then deleted)?
298
+
299
+ No.
300
+
301
+ ### Will older versions of the dataset continue to be supported/hosted/maintained?
302
+
303
+ If there ever was an update, yes.
304
+
305
+ ### If others want to extend/augment/build on/contribute to the dataset, is there a mechanism for them to do so?
306
+
307
+ Since we use a non-restricting license (MIT license), anyone can build on top or include in their training data mixture.
308
+
309
+ ### Any other comments?
310
+
311
+ No. We hope the data is useful to people!
disc_edit.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import random
5
+ import sys
6
+ from argparse import ArgumentParser
7
+
8
+ import einops
9
+ import k_diffusion as K
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn as nn
13
+ from einops import rearrange
14
+ from omegaconf import OmegaConf
15
+ from PIL import Image, ImageOps
16
+ from torch import autocast
17
+ from PIL import Image, ImageDraw, ImageFont
18
+ import textwrap
19
+ import json
20
+ import os
21
+ from dataset_loading import get_dataset
22
+ from edit_dataset import EditITMDataset
23
+ from torch.utils.data import DataLoader
24
+ from tqdm import tqdm
25
+ import clip
26
+ from collections import defaultdict
27
+
28
+ sys.path.append("./stable_diffusion")
29
+ from stable_diffusion.ldm.util import instantiate_from_config
30
+
31
+ # Assuming CFGDenoiser and other dependencies are correctly set up,
32
+ # no changes needed there for image aspect ratio handling.
33
+
34
+
35
+ def calculate_clip_similarity(generated_images, original_image, clip_model, preprocess, device):
36
+ original_image_processed = preprocess(original_image).unsqueeze(0).to(device)
37
+
38
+ with torch.no_grad():
39
+ original_features = clip_model.encode_image(original_image_processed)
40
+
41
+ similarities = []
42
+ for img in generated_images:
43
+ img_processed = preprocess(img).unsqueeze(0).to(device)
44
+ with torch.no_grad():
45
+ generated_features = clip_model.encode_image(img_processed)
46
+ similarity = torch.nn.functional.cosine_similarity(generated_features, original_features, dim=-1)
47
+ similarities.append(similarity.item())
48
+
49
+ #concat both img and original_image for visualization
50
+ # original_image_np = np.array(original_image)
51
+ # img_np = np.array(img)
52
+ # both = np.concatenate((original_image_np, img_np), axis=1)
53
+ # both = Image.fromarray(both)
54
+ # if not os.path.exists('eval_output/edit_itm/flickr_edit_clip_sim/'):
55
+ # os.makedirs('eval_output/edit_itm/flickr_edit_clip_sim/')
56
+ # random_id = random.randint(0, 100000)
57
+ # both.save(f'eval_output/edit_itm/flickr_edit_clip_sim/{similarity.item()}_{random_id}.png')
58
+
59
+ # average_similarity = sum(similarities) / len(similarities)
60
+ # dist = 1 - average_similarity
61
+ dists = [1 - sim for sim in similarities]
62
+ return dists
63
+
64
+
65
+ class CFGDenoiser(nn.Module):
66
+ def __init__(self, model):
67
+ super().__init__()
68
+ self.inner_model = model
69
+
70
+ def forward(self, z, sigma, cond, uncond, text_cfg_scale, image_cfg_scale, conditional_only=False):
71
+ # cfg_z = einops.repeat(z, "1 ... -> n ...", n=3)
72
+ cfg_z = z.repeat(3, 1, 1, 1)
73
+ # cfg_sigma = einops.repeat(sigma, "1 ... -> n ...", n=3)
74
+ cfg_sigma = sigma.repeat(3)
75
+ cfg_cond = {
76
+ "c_crossattn": [torch.cat([cond["c_crossattn"][0], uncond["c_crossattn"][0], uncond["c_crossattn"][0]])],
77
+ "c_concat": [torch.cat([cond["c_concat"][0], cond["c_concat"][0], uncond["c_concat"][0]])],
78
+ }
79
+ out_cond, out_img_cond, out_uncond = self.inner_model(cfg_z, cfg_sigma, cond=cfg_cond).chunk(3)
80
+ if conditional_only:
81
+ return out_cond
82
+ else:
83
+ return out_uncond + text_cfg_scale * (out_cond - out_img_cond) + image_cfg_scale * (out_img_cond - out_uncond)
84
+
85
+ def load_model_from_config(config, ckpt, vae_ckpt=None, verbose=False):
86
+ print(f"Loading model from {ckpt}")
87
+ pl_sd = torch.load(ckpt, map_location="cpu")
88
+ if "global_step" in pl_sd:
89
+ print(f"Global Step: {pl_sd['global_step']}")
90
+ sd = pl_sd["state_dict"]
91
+ if vae_ckpt is not None:
92
+ print(f"Loading VAE from {vae_ckpt}")
93
+ vae_sd = torch.load(vae_ckpt, map_location="cpu")["state_dict"]
94
+ sd = {
95
+ k: vae_sd[k[len("first_stage_model.") :]] if k.startswith("first_stage_model.") else v
96
+ for k, v in sd.items()
97
+ }
98
+ model = instantiate_from_config(config.model)
99
+ m, u = model.load_state_dict(sd, strict=False)
100
+ if len(m) > 0 and verbose:
101
+ print("missing keys:")
102
+ print(m)
103
+ if len(u) > 0 and verbose:
104
+ print("unexpected keys:")
105
+ print(u)
106
+ return model
107
+
108
+ def calculate_accuracy(losses):
109
+ correct_count = 0
110
+ for loss in losses:
111
+ if loss[0] < min(loss[1:]):
112
+ correct_count += 1
113
+ return correct_count, len(losses) # Return counts for aggregation
114
+
115
+
116
+ def main():
117
+ parser = ArgumentParser()
118
+ parser.add_argument("--config", default="configs/generate.yaml", type=str)
119
+ parser.add_argument("--ckpt", default="aurora-mixratio-15-15-1-1-42k-steps.ckpt", type=str)
120
+ parser.add_argument("--vae-ckpt", default=None, type=str)
121
+ parser.add_argument("--task", default='flickr_edit', type=str)
122
+ parser.add_argument("--batchsize", default=1, type=int)
123
+ parser.add_argument("--samples", default=4, type=int)
124
+ parser.add_argument("--size", default=512, type=int)
125
+ parser.add_argument("--steps", default=20, type=int)
126
+ parser.add_argument("--cfg-text", default=7.5, type=float)
127
+ parser.add_argument("--cfg-image", default=1.5, type=float)
128
+ parser.add_argument('--targets', type=str, nargs='*', help="which target groups for mmbias",default='')
129
+ parser.add_argument("--device", default=0, type=int, help="GPU device index")
130
+ parser.add_argument("--log_imgs", action="store_true")
131
+ parser.add_argument("--conditional_only", action="store_true")
132
+ parser.add_argument("--metric", default="latent", type=str)
133
+ parser.add_argument("--split", default='test', type=str)
134
+ parser.add_argument("--skip", default=1, type=int)
135
+ args = parser.parse_args()
136
+ device = torch.device(f"cuda:{args.device}" if torch.cuda.is_available() else "cpu")
137
+
138
+ config = OmegaConf.load(args.config)
139
+ model = load_model_from_config(config, args.ckpt, args.vae_ckpt)
140
+ model.eval()
141
+ model.to(dtype=torch.float)
142
+ model = model.to(device)
143
+ model_wrap = K.external.CompVisDenoiser(model)
144
+ model_wrap_cfg = CFGDenoiser(model_wrap)
145
+ null_token = model.get_learned_conditioning([""])
146
+
147
+ clip_model, preprocess = clip.load("ViT-B/32", device=device)
148
+
149
+ dataset = EditITMDataset(split=args.split, task=args.task, min_resize_res=args.size, max_resize_res=args.size, crop_res=args.size)
150
+ dataloader= DataLoader(dataset,batch_size=args.batchsize,num_workers=1,worker_init_fn=None,shuffle=False, persistent_workers=True)
151
+
152
+ if os.path.exists(f'itm_evaluation/{args.split}/{args.task}/{args.ckpt.replace("/", "_")}_results.json'):
153
+ with open(f'itm_evaluation/{args.split}/{args.task}/{args.ckpt.replace("/", "_")}_results.json', 'r') as f:
154
+ results = json.load(f)
155
+ results = defaultdict(dict, results)
156
+ else:
157
+ results = defaultdict(dict)
158
+
159
+ for i, batch in tqdm(enumerate(dataloader), total=len(dataloader)):
160
+ if len(batch['input'][0].shape) < 3:
161
+ continue
162
+ for j, prompt in enumerate(batch['texts']):
163
+ # check if we already have results for this image
164
+ img_id = batch['path'][0] + f'_{i}'
165
+ # if img_id in results and ('pos' in results[img_id] and 'neg' in results[img_id]):
166
+ # continue
167
+
168
+ with torch.no_grad(), autocast("cuda"), model.ema_scope():
169
+ prompt = prompt[0]
170
+ cond = {}
171
+ cond["c_crossattn"] = [model.get_learned_conditioning([prompt])]
172
+ input_image = batch['input'][0].to(device)
173
+ cond["c_concat"] = [model.encode_first_stage(input_image.unsqueeze(0)).mode()]
174
+ scaled_input = model.scale_factor * input_image
175
+
176
+ uncond = {}
177
+ uncond["c_crossattn"] = [null_token]
178
+ uncond["c_concat"] = [torch.zeros_like(cond["c_concat"][0])]
179
+
180
+ sigmas = model_wrap.get_sigmas(args.steps)
181
+ # move everything to the device
182
+ cond = {k: [v.to(device) for v in vs] for k, vs in cond.items()}
183
+ uncond = {k: [v.to(device) for v in vs] for k, vs in uncond.items()}
184
+
185
+ cond["c_concat"][0] = cond["c_concat"][0].repeat(args.samples, 1, 1, 1)
186
+ cond["c_crossattn"][0] = cond["c_crossattn"][0].repeat(args.samples, 1, 1)
187
+ uncond["c_concat"][0] = uncond["c_concat"][0].repeat(args.samples, 1, 1, 1)
188
+ uncond["c_crossattn"][0] = uncond["c_crossattn"][0].repeat(args.samples, 1, 1)
189
+
190
+ extra_args = {
191
+ "cond": cond,
192
+ "uncond": uncond,
193
+ "text_cfg_scale": args.cfg_text,
194
+ "image_cfg_scale": args.cfg_image,
195
+ "conditional_only": args.conditional_only,
196
+ }
197
+ # torch.manual_seed(i)
198
+ torch.manual_seed(42)
199
+ z = torch.randn_like(cond["c_concat"][0]) * sigmas[0]
200
+ z = K.sampling.sample_euler_ancestral(model_wrap_cfg, z, sigmas, extra_args=extra_args, disable=True)
201
+ x = model.decode_first_stage(z)
202
+ x = torch.clamp((x + 1.0) / 2.0, min=0.0, max=1.0)
203
+
204
+ ######## LOG IMAGES ########
205
+ input_image_pil = ((input_image + 1) * 0.5).clamp(0, 1)
206
+ input_image_pil = input_image_pil.permute(1, 2, 0) # Change from CxHxW to HxWxC for PIL
207
+ input_image_pil = (input_image_pil * 255).type(torch.uint8).cpu().numpy()
208
+
209
+ for k in range(2):
210
+ x_ = 255.0 * rearrange(x[k], "c h w -> h w c")
211
+ edited_image = x_.type(torch.uint8).cpu().numpy()
212
+ both = np.concatenate((input_image_pil, edited_image), axis=1)
213
+ both = Image.fromarray(both)
214
+ out_base = f'itm_evaluation/{args.split}/{args.task}/{args.ckpt.replace("/", "_")}'
215
+ if not os.path.exists(out_base):
216
+ os.makedirs(out_base)
217
+ prompt_str = prompt.replace(' ', '_')[0:100]
218
+ both.save(f'{out_base}/{i}_{"correct" if j == 0 else "incorrect"}_sample{k}_{prompt}.png')
219
+
220
+ ######## CLIP ########
221
+
222
+ edited_images = []
223
+ for k in range(args.samples):
224
+ x_ = 255.0 * rearrange(x[k], "c h w -> h w c")
225
+ edited_image = Image.fromarray(x_.type(torch.uint8).cpu().numpy())
226
+ edited_images.append(edited_image)
227
+ input_image_pil = ((input_image + 1) * 0.5).clamp(0, 1)
228
+ input_image_pil = input_image_pil.permute(1, 2, 0) # Change from CxHxW to HxWxC for PIL
229
+ input_image_pil = (input_image_pil * 255).type(torch.uint8).cpu().numpy()
230
+ input_image_pil = Image.fromarray(input_image_pil)
231
+ dists_clip = calculate_clip_similarity(edited_images, input_image_pil, clip_model, preprocess, device)
232
+
233
+ ######## LATENT ########
234
+ z = z.flatten(1)
235
+ original_latent = cond["c_concat"][0].flatten(1)
236
+ dists_latent = torch.norm(z - original_latent, dim=1, p=2).cpu().numpy().tolist()
237
+ cos_sim = torch.nn.functional.cosine_similarity(z, original_latent, dim=1).cpu().numpy().tolist()
238
+ cos_dists_latent = [1 - sim for sim in cos_sim]
239
+ ######## SAVE RESULTS ########
240
+ img_id = batch['path'][0] + f'_{i}'
241
+ results[img_id]['pos' if j == 0 else 'neg'] = {
242
+ "prompt" : prompt,
243
+ "clip": dists_clip,
244
+ "latent_l2": dists_latent,
245
+ "latent_cosine": cos_dists_latent
246
+ }
247
+ with open(f'itm_evaluation/{args.split}/{args.task}/{args.ckpt.replace("/", "_")}_results.json', 'w') as f:
248
+ json.dump(results, f, indent=2)
249
+
250
+ if __name__ == "__main__":
251
+ main()
edit_cli.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import random
5
+ import sys
6
+ from argparse import ArgumentParser
7
+
8
+ import einops
9
+ import k_diffusion as K
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn as nn
13
+ from einops import rearrange
14
+ from omegaconf import OmegaConf
15
+ from PIL import Image, ImageOps
16
+ from torch import autocast
17
+
18
+ sys.path.append("./stable_diffusion")
19
+
20
+ from stable_diffusion.ldm.util import instantiate_from_config
21
+
22
+
23
+ class CFGDenoiser(nn.Module):
24
+ def __init__(self, model):
25
+ super().__init__()
26
+ self.inner_model = model
27
+
28
+ def forward(self, z, sigma, cond, uncond, text_cfg_scale, image_cfg_scale):
29
+ cfg_z = einops.repeat(z, "1 ... -> n ...", n=3)
30
+ cfg_sigma = einops.repeat(sigma, "1 ... -> n ...", n=3)
31
+ cfg_cond = {
32
+ "c_crossattn": [torch.cat([cond["c_crossattn"][0], uncond["c_crossattn"][0], uncond["c_crossattn"][0]])],
33
+ "c_concat": [torch.cat([cond["c_concat"][0], cond["c_concat"][0], uncond["c_concat"][0]])],
34
+ }
35
+ out_cond, out_img_cond, out_uncond = self.inner_model(cfg_z, cfg_sigma, cond=cfg_cond).chunk(3)
36
+ return out_uncond + text_cfg_scale * (out_cond - out_img_cond) + image_cfg_scale * (out_img_cond - out_uncond)
37
+
38
+
39
+ def load_model_from_config(config, ckpt, vae_ckpt=None, verbose=False):
40
+ print(f"Loading model from {ckpt}")
41
+ pl_sd = torch.load(ckpt, map_location="cpu")
42
+ if "global_step" in pl_sd:
43
+ print(f"Global Step: {pl_sd['global_step']}")
44
+ sd = pl_sd["state_dict"]
45
+ if vae_ckpt is not None:
46
+ print(f"Loading VAE from {vae_ckpt}")
47
+ vae_sd = torch.load(vae_ckpt, map_location="cpu")["state_dict"]
48
+ sd = {
49
+ k: vae_sd[k[len("first_stage_model.") :]] if k.startswith("first_stage_model.") else v
50
+ for k, v in sd.items()
51
+ }
52
+ model = instantiate_from_config(config.model)
53
+ m, u = model.load_state_dict(sd, strict=False)
54
+ if len(m) > 0 and verbose:
55
+ print("missing keys:")
56
+ print(m)
57
+ if len(u) > 0 and verbose:
58
+ print("unexpected keys:")
59
+ print(u)
60
+ return model
61
+
62
+
63
+ def main():
64
+ parser = ArgumentParser()
65
+ parser.add_argument("--resolution", default=512, type=int)
66
+ parser.add_argument("--steps", default=50, type=int)
67
+ parser.add_argument("--config", default="configs/generate.yaml", type=str)
68
+ parser.add_argument("--ckpt", default="aurora-mixratio-15-15-1-1-42k-steps.ckpt", type=str)
69
+ parser.add_argument("--vae-ckpt", default=None, type=str)
70
+ parser.add_argument("--input", default='example.jpg', type=str)
71
+ parser.add_argument("--output", default='example_output.jpg', type=str)
72
+ parser.add_argument("--edit", default='move the lemon to the right of the table', type=str)
73
+ parser.add_argument("--cfg-text", default=7.5, type=float)
74
+ parser.add_argument("--cfg-image", default=1.5, type=float)
75
+ parser.add_argument("--seed", default=42, type=int)
76
+ args = parser.parse_args()
77
+
78
+ config = OmegaConf.load(args.config)
79
+ model = load_model_from_config(config, args.ckpt, args.vae_ckpt)
80
+ model.eval().to('cuda:7')
81
+ model_wrap = K.external.CompVisDenoiser(model)
82
+ model_wrap_cfg = CFGDenoiser(model_wrap)
83
+ null_token = model.get_learned_conditioning([""])
84
+
85
+ seed = random.randint(0, 100000) if args.seed is None else args.seed
86
+ input_image = Image.open(args.input).convert("RGB")
87
+ width, height = input_image.size
88
+ factor = args.resolution / max(width, height)
89
+ factor = math.ceil(min(width, height) * factor / 64) * 64 / min(width, height)
90
+ width = int((width * factor) // 64) * 64
91
+ height = int((height * factor) // 64) * 64
92
+ input_image = ImageOps.fit(input_image, (width, height), method=Image.Resampling.LANCZOS)
93
+
94
+ with torch.no_grad(), autocast("cuda"), model.ema_scope():
95
+ cond = {}
96
+ cond["c_crossattn"] = [model.get_learned_conditioning([args.edit])]
97
+ input_image = 2 * torch.tensor(np.array(input_image)).float() / 255 - 1
98
+ input_image = rearrange(input_image, "h w c -> 1 c h w").to(model.device)
99
+ cond["c_concat"] = [model.encode_first_stage(input_image).mode()]
100
+
101
+ uncond = {}
102
+ uncond["c_crossattn"] = [null_token]
103
+ uncond["c_concat"] = [torch.zeros_like(cond["c_concat"][0])]
104
+
105
+ sigmas = model_wrap.get_sigmas(args.steps)
106
+
107
+ extra_args = {
108
+ "cond": cond,
109
+ "uncond": uncond,
110
+ "text_cfg_scale": args.cfg_text,
111
+ "image_cfg_scale": args.cfg_image,
112
+ }
113
+ torch.manual_seed(seed)
114
+ z = torch.randn_like(cond["c_concat"][0]) * sigmas[0]
115
+ z = K.sampling.sample_euler_ancestral(model_wrap_cfg, z, sigmas, extra_args=extra_args)
116
+ x = model.decode_first_stage(z)
117
+ x = torch.clamp((x + 1.0) / 2.0, min=0.0, max=1.0)
118
+ x = 255.0 * rearrange(x, "1 c h w -> h w c")
119
+ edited_image = Image.fromarray(x.type(torch.uint8).cpu().numpy())
120
+ edited_image.save(args.output)
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
edit_dataset.py ADDED
@@ -0,0 +1,603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import math
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+ import torch
10
+ import torchvision
11
+ from einops import rearrange
12
+ from PIL import Image
13
+ from torch.utils.data import Dataset
14
+ import os
15
+ from datasets import load_dataset, DownloadConfig
16
+ from tqdm import tqdm
17
+
18
+ from PIL import ImageFile
19
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
20
+
21
+ class FinetuneDataset(Dataset):
22
+ def __init__(
23
+ self,
24
+ path: str = '',
25
+ split: str = "train",
26
+ splits: tuple[float, float, float] = (0.9, 0.05, 0.05),
27
+ min_resize_res: int = 256,
28
+ max_resize_res: int = 256,
29
+ crop_res: int = 256,
30
+ flip_prob: float = 0.5,
31
+ msr_vtt_cc_full: bool = False,
32
+ mix: list[str] = ['magicbrush', 'something', 'hq'],
33
+ mix_factors: list[float] = [40, 1, 1],
34
+ copy_prob: float = 0.0,
35
+ kubric_100k: bool = False,
36
+ ):
37
+ self.split = split
38
+ assert split in ("train", "val", "test")
39
+ assert sum(splits) == 1
40
+ self.path = path
41
+ self.min_resize_res = min_resize_res
42
+ self.max_resize_res = max_resize_res
43
+ self.crop_res = crop_res
44
+ self.flip_prob = flip_prob
45
+ self.mix_factors = mix_factors
46
+ self.msr_vtt_cc_full = msr_vtt_cc_full
47
+ self.copy_prob = copy_prob
48
+
49
+ self.data = []
50
+ for dataset in mix:
51
+ if dataset != 'hq':
52
+ for _ in range(mix_factors[mix.index(dataset)]):
53
+ if kubric_100k and dataset == 'kubric':
54
+ self.data.extend(json.load(open(f'data/{dataset}/train_100k.json', 'r')))
55
+ print("LODADED KUBRIC 100K")
56
+ else:
57
+ self.data.extend(json.load(open(f'data/{dataset}/train.json', 'r')))
58
+ # if dataset == 'msr-vtt-cc':
59
+ # self.data.extend(json.load(open(f'data/{dataset}/train_gpt.json', 'r')))
60
+
61
+ if split == 'val':
62
+ self.data = self.data[:2]
63
+
64
+ def __len__(self) -> int:
65
+ return len(self.data)
66
+
67
+ def __getitem__(self, i: int) -> dict[str, Any]:
68
+ # if i < len(self.data):
69
+ ex = self.data[i]
70
+ img_path0 = ex['input']
71
+ img_path1 = ex['output']
72
+ prompt = ex['instruction']
73
+ dataset = img_path0.split('/')[1]
74
+ if dataset == 'kubric':
75
+ subtask = img_path0.split('/')[2]
76
+ else:
77
+ subtask = '___'
78
+
79
+ if type(prompt) == list:
80
+ prompt = prompt[0]
81
+ spatial = 'left' in prompt.lower() or 'right' in prompt.lower()
82
+ image_1 = Image.open(img_path1).convert('RGB') if i < len(self.data) else img_path1
83
+
84
+ if subtask not in ['closer', 'counting', 'further_location', 'rotate']:
85
+ if self.copy_prob > 0 and torch.rand(1) < self.copy_prob:
86
+ image_0 = Image.open(img_path1).convert('RGB') if i < len(self.data) else img_path1
87
+ else:
88
+ image_0 = Image.open(img_path0).convert('RGB') if i < len(self.data) else img_path0
89
+ else:
90
+ image_0 = Image.open(img_path0).convert('RGB') if i < len(self.data) else img_path0
91
+
92
+ reize_res = torch.randint(self.min_resize_res, self.max_resize_res + 1, ()).item()
93
+ image_0 = image_0.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
94
+ image_1 = image_1.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
95
+
96
+ image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
97
+ image_1 = rearrange(2 * torch.tensor(np.array(image_1)).float() / 255 - 1, "h w c -> c h w")
98
+
99
+ crop = torchvision.transforms.RandomCrop(self.crop_res)
100
+ flip_prob = 0.0 if spatial else self.flip_prob
101
+ flip = torchvision.transforms.RandomHorizontalFlip(float(flip_prob))
102
+ image_0, image_1 = flip(crop(torch.cat((image_0, image_1)))).chunk(2)
103
+
104
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
105
+
106
+
107
+ class MagicEditDataset(Dataset):
108
+ def __init__(
109
+ self,
110
+ path: str = '../../change_descriptions/something-something',
111
+ split: str = "train",
112
+ splits: tuple[float, float, float] = (0.9, 0.05, 0.05),
113
+ min_resize_res: int = 256,
114
+ max_resize_res: int = 256,
115
+ crop_res: int = 256,
116
+ flip_prob: float = 0.0,
117
+ debug: bool = False,
118
+ ):
119
+ self.min_resize_res = min_resize_res
120
+ self.max_resize_res = max_resize_res
121
+ self.crop_res = crop_res
122
+ self.flip_prob = flip_prob
123
+
124
+ print("Dataset params")
125
+ print(self.min_resize_res, self.max_resize_res, self.crop_res, self.flip_prob)
126
+
127
+ #clean json (if first and last are not both present, remove)
128
+ split = "train" if split == "train" else "dev"
129
+ self.dataset = load_dataset("osunlp/MagicBrush")[split]
130
+
131
+ # if split == 'dev':
132
+ # eval_data = json.load(open('eval_data/video_edit.json', 'r'))
133
+ # dummy_image = Image.new('RGB', (1, 1), (0, 0, 0))
134
+ # eval_data = {
135
+ # 'source_img': [Image.open(x['img0']) for x in eval_data],
136
+ # 'target_img': [Image.open(x['img1']) for x in eval_data],
137
+ # 'instruction': [x['edit'] if type(x['edit']) == str else x['edit'][0] for x in eval_data],
138
+ # 'img_id': ['' for _ in eval_data],
139
+ # 'turn_index': np.array([1 for _ in eval_data], dtype=np.int32),
140
+ # 'mask_img': [dummy_image for _ in eval_data] # Replace each entry with the dummy image
141
+ # }
142
+ # eval_dataset = HuggingFaceDataset.from_dict(eval_data)
143
+ # self.dataset = concatenate_datasets([self.dataset, eval_dataset])
144
+
145
+ if debug:
146
+ self.dataset = self.dataset.shuffle(seed=42).select(range(50))
147
+
148
+ def __len__(self) -> int:
149
+ return len(self.dataset)
150
+
151
+ def __getitem__(self, i: int) -> dict[str, Any]:
152
+
153
+ prompt = self.dataset[i]['instruction']
154
+ if type(prompt) == list:
155
+ prompt = prompt[0]
156
+ image_0 = self.dataset[i]['source_img']
157
+ image_1 = self.dataset[i]['target_img']
158
+ if image_0.mode == 'RGBA':
159
+ image_0 = image_0.convert('RGB')
160
+ if image_1.mode == 'RGBA':
161
+ image_1 = image_1.convert('RGB')
162
+ reize_res = torch.randint(self.min_resize_res, self.max_resize_res + 1, ()).item()
163
+ image_0 = image_0.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
164
+ image_1 = image_1.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
165
+
166
+ image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
167
+ image_1 = rearrange(2 * torch.tensor(np.array(image_1)).float() / 255 - 1, "h w c -> c h w")
168
+
169
+ crop = torchvision.transforms.RandomCrop(self.crop_res)
170
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
171
+ image_0, image_1 = flip(crop(torch.cat((image_0, image_1)))).chunk(2)
172
+
173
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
174
+
175
+
176
+ class FrameEditDataset(Dataset):
177
+ def __init__(
178
+ self,
179
+ path: str = '../../change_descriptions/something-something',
180
+ split: str = "train",
181
+ splits: tuple[float, float, float] = (0.9, 0.05, 0.05),
182
+ task: str = 'flickr30k_text',
183
+ min_resize_res: int = 256,
184
+ max_resize_res: int = 256,
185
+ crop_res: int = 256,
186
+ flip_prob: float = 0.0,
187
+ debug: bool = False,
188
+ ):
189
+ self.split = split
190
+ self.task = task
191
+ if split == "train":
192
+ path = os.path.join(path, 'train.json')
193
+ self.json = json.load(open(path, 'r'))
194
+ np.random.shuffle(self.json)
195
+ self.min_resize_res = min_resize_res
196
+ self.max_resize_res = max_resize_res
197
+ self.crop_res = crop_res
198
+ self.flip_prob = flip_prob
199
+
200
+ #clean json (if first and last are not both present, remove)
201
+ if split == 'train':
202
+ new_json = []
203
+ for i in range(len(self.json)):
204
+ video_id = self.json[i]['id']
205
+ img_path0 = f'../../change_descriptions/something-something/frames/{video_id}/first.jpg'
206
+ img_path1 = f'../../change_descriptions/something-something/frames/{video_id}/last.jpg'
207
+ if os.path.exists(img_path0) and os.path.exists(img_path1):
208
+ new_json.append(self.json[i])
209
+ self.json = new_json
210
+ if debug:
211
+ self.json = self.json[:50]
212
+
213
+ def __len__(self) -> int:
214
+ return len(self.json)
215
+
216
+ def __getitem__(self, i: int) -> dict[str, Any]:
217
+ if self.split == 'train':
218
+ video_id = self.json[i]['id']
219
+ img_path0 = f'../../change_descriptions/something-something/frames/{video_id}/first.jpg'
220
+ img_path1 = f'../../change_descriptions/something-something/frames/{video_id}/last.jpg'
221
+ prompt = self.json[i]['label']
222
+
223
+ image_0 = Image.open(img_path0).convert('RGB')
224
+ image_1 = Image.open(img_path1).convert('RGB')
225
+
226
+ reize_res = torch.randint(self.min_resize_res, self.max_resize_res + 1, ()).item()
227
+ # image_0 = image_0.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
228
+ # image_1 = image_1.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
229
+ image_0 = image_0.resize((self.crop_res, self.crop_res))
230
+ image_1 = image_1.resize((self.crop_res, self.crop_res))
231
+
232
+ image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
233
+ image_1 = rearrange(2 * torch.tensor(np.array(image_1)).float() / 255 - 1, "h w c -> c h w")
234
+
235
+ crop = torchvision.transforms.RandomCrop(self.crop_res)
236
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
237
+ image_0, image_1 = flip(crop(torch.cat((image_0, image_1)))).chunk(2)
238
+
239
+ # if i ever wanna reverse time
240
+ # if torch.rand(1) > 0.5:
241
+ # image_0, image_1 = image_1, image_0
242
+ # prompt = caption0
243
+ if self.split == 'train':
244
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
245
+ else:
246
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=texts))
247
+
248
+ class EditITMDataset(Dataset):
249
+ def __init__(
250
+ self,
251
+ path: str = '../../change_descriptions/something-something',
252
+ split: str = "test",
253
+ splits: tuple[float, float, float] = (0.9, 0.05, 0.05),
254
+ task: str = 'flickr30k_text',
255
+ min_resize_res: int = 256,
256
+ max_resize_res: int = 256,
257
+ crop_res: int = 256,
258
+ flip_prob: float = 0.0,
259
+ debug: bool = False,
260
+ ):
261
+ self.split = split
262
+ self.task = task
263
+ # if task == 'flickr_edit':
264
+ # path = 'data/flickr_edit/valid.json' if split == 'val' else 'data/flickr_edit/test.json'
265
+ # self.json = json.load(open(path, 'r'))
266
+ # #clean json, if "pos" key is empty string, remove
267
+ # self.json = [x for x in self.json if x['pos'] != '']
268
+ if task == 'whatsup':
269
+ path = 'data/whatsup/itm_test.json' if split == 'test' else 'data/whatsup/itm_valid.json'
270
+ self.json = json.load(open(path, 'r'))
271
+ elif task == 'svo':
272
+ path = 'data/svo/itm_test.json' if split == 'test' else 'data/svo/itm_valid.json'
273
+ self.json = json.load(open(path, 'r'))
274
+ else:
275
+ path = f'data/{task}/valid.json'
276
+ self.json = json.load(open(path, 'r'))
277
+ self.json = [x for x in self.json if x.get('pos', '') != '']
278
+ self.min_resize_res = min_resize_res
279
+ self.max_resize_res = max_resize_res
280
+ self.crop_res = crop_res
281
+ self.flip_prob = flip_prob
282
+
283
+ if debug:
284
+ self.json = self.json[:50]
285
+
286
+ def __len__(self) -> int:
287
+ return len(self.json)
288
+
289
+ def __getitem__(self, i: int) -> dict[str, Any]:
290
+ ex = self.json[i]
291
+ pos = ex.get('pos', '')
292
+ if pos == '':
293
+ pos = ex['prompt']
294
+ neg = ex.get('neg', '')
295
+ if neg == '':
296
+ neg = ex['prompt']
297
+ img_path0 = ex['input']
298
+ texts = [pos, neg]
299
+ # if self.task == 'whatsup' or self.task == 'svo':
300
+ # img_path0 = f"data/{self.task}/images/{ex['image']}" if self.task == 'flickr_edit' else ex['image']
301
+ # texts = [ex['pos'], ex['neg']]
302
+ # else:
303
+ # img_path0 = ex['input']
304
+ # texts = ex['pos'], ex['prompt']
305
+ # subtasks = ex['type'] if self.task == 'flickr_edit' else ''
306
+ try:
307
+ image_0 = Image.open(img_path0).convert('RGB')
308
+ reize_res = torch.randint(self.min_resize_res, self.max_resize_res + 1, ()).item()
309
+ image_0 = image_0.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
310
+ image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
311
+ except:
312
+ image_0 = 0
313
+
314
+ return dict(input=image_0, texts=texts, path=img_path0)
315
+
316
+ class OldFrameEditDataset(Dataset):
317
+ def __init__(
318
+ self,
319
+ path: str = '../../change_descriptions/something-something',
320
+ split: str = "train",
321
+ splits: tuple[float, float, float] = (0.9, 0.05, 0.05),
322
+ task: str = 'flickr30k_text',
323
+ min_resize_res: int = 256,
324
+ max_resize_res: int = 256,
325
+ crop_res: int = 256,
326
+ flip_prob: float = 0.0,
327
+ debug: bool = False,
328
+ ):
329
+ if split == "train":
330
+ path = os.path.join(path, 'train.json')
331
+ elif split == "val":
332
+ path = os.path.join(path, 'validation.json')
333
+ self.json = json.load(open(path, 'r'))
334
+ np.random.shuffle(self.json)
335
+ self.min_resize_res = min_resize_res
336
+ self.max_resize_res = max_resize_res
337
+ self.crop_res = crop_res
338
+ self.flip_prob = flip_prob
339
+
340
+ #clean json (if first and last are not both present, remove)
341
+ new_json = []
342
+ for i in range(len(self.json)):
343
+ video_id = self.json[i]['id']
344
+ img_path0 = f'../../change_descriptions/something-something/frames/{video_id}/first.jpg'
345
+ img_path1 = f'../../change_descriptions/something-something/frames/{video_id}/last.jpg'
346
+ if os.path.exists(img_path0) and os.path.exists(img_path1):
347
+ new_json.append(self.json[i])
348
+ self.json = new_json
349
+ if debug:
350
+ self.json = self.json[:50]
351
+
352
+ def __len__(self) -> int:
353
+ return len(self.json)
354
+
355
+ def __getitem__(self, i: int) -> dict[str, Any]:
356
+ video_id = self.json[i]['id']
357
+ img_path0 = f'../../change_descriptions/something-something/frames/{video_id}/first.jpg'
358
+ img_path1 = f'../../change_descriptions/something-something/frames/{video_id}/last.jpg'
359
+ prompt = self.json[i]['label']
360
+ image_0 = Image.open(img_path0)
361
+ image_1 = Image.open(img_path1)
362
+
363
+ reize_res = torch.randint(self.min_resize_res, self.max_resize_res + 1, ()).item()
364
+ image_0 = image_0.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
365
+ image_1 = image_1.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
366
+
367
+ image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
368
+ image_1 = rearrange(2 * torch.tensor(np.array(image_1)).float() / 255 - 1, "h w c -> c h w")
369
+
370
+ crop = torchvision.transforms.RandomCrop(self.crop_res)
371
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
372
+ image_0, image_1 = flip(crop(torch.cat((image_0, image_1)))).chunk(2)
373
+
374
+ # if i ever wanna reverse time
375
+ # if torch.rand(1) > 0.5:
376
+ # image_0, image_1 = image_1, image_0
377
+ # prompt = caption0
378
+
379
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
380
+
381
+
382
+ class EditDataset(Dataset):
383
+ def __init__(
384
+ self,
385
+ path: str = 'data/clip-filtered-dataset',
386
+ split: str = "train",
387
+ splits: tuple[float, float, float] = (0.9, 0.05, 0.05),
388
+ min_resize_res: int = 256,
389
+ max_resize_res: int = 256,
390
+ crop_res: int = 256,
391
+ flip_prob: float = 0.0,
392
+ ):
393
+ self.split = split
394
+ assert split in ("train", "val", "test")
395
+ assert sum(splits) == 1
396
+ self.path = path
397
+ self.min_resize_res = min_resize_res
398
+ self.max_resize_res = max_resize_res
399
+ self.crop_res = crop_res
400
+ self.flip_prob = flip_prob
401
+
402
+ self.genhowto = open('data/genhowto/genhowto_train_clip0.7_filtered.txt', 'r').readlines()
403
+ # self.genhowto = open('data/genhowto/genhowto_train.txt', 'r').readlines()
404
+ self.genhowto = [x.strip() for x in self.genhowto]
405
+
406
+ new_genhowto = []
407
+ for i in range(len(self.genhowto)):
408
+ img_path, prompt, prompt2 = self.genhowto[i].split(':')
409
+ new_genhowto.append((img_path, prompt, 'action'))
410
+ new_genhowto.append((img_path, prompt2, 'state'))
411
+ self.genhowto = new_genhowto
412
+
413
+ with open(Path(self.path, "seeds.json")) as f:
414
+ self.seeds = json.load(f)
415
+
416
+ split_0, split_1 = {
417
+ "train": (0.0, splits[0]),
418
+ "val": (splits[0], splits[0] + splits[1]),
419
+ "test": (splits[0] + splits[1], 1.0),
420
+ }[split]
421
+
422
+ idx_0 = math.floor(split_0 * len(self.seeds))
423
+ idx_1 = math.floor(split_1 * len(self.seeds))
424
+ self.seeds = self.seeds[idx_0:idx_1]
425
+ # shuffle seeds and genhowto
426
+ # np.random.seed(42)
427
+ # np.random.shuffle(self.seeds)
428
+ # np.random.shuffle(self.genhowto)
429
+
430
+ def __len__(self) -> int:
431
+ return len(self.seeds) + len(self.genhowto)
432
+
433
+ def __getitem__(self, i: int) -> dict[str, Any]:
434
+ if i < len(self.seeds):
435
+ name, seeds = self.seeds[i]
436
+ propt_dir = Path(self.path, name)
437
+ seed = seeds[torch.randint(0, len(seeds), ()).item()]
438
+ with open(propt_dir.joinpath("prompt.json")) as fp:
439
+ prompt = json.load(fp)["edit"]
440
+ image_0 = Image.open(propt_dir.joinpath(f"{seed}_0.jpg"))
441
+ image_1 = Image.open(propt_dir.joinpath(f"{seed}_1.jpg"))
442
+ else:
443
+ ex = self.genhowto[i - len(self.seeds)]
444
+ # img_path, prompt, prompt2 = ex.split(':')
445
+ # img_path = img_path.replace('changeit_detected_without_test', 'changeit_detected')
446
+ # img_path = 'data/genhowto/' + img_path
447
+ # full_img = Image.open(img_path).convert('RGB')
448
+ # image_0 = full_img.crop((0, 0, full_img.width // 3, full_img.height))
449
+ # image_1 = full_img.crop((full_img.width * 2 // 3, 0, full_img.width, full_img.height))
450
+ # image_2 = full_img.crop((full_img.width // 3, 0, full_img.width * 2 // 3, full_img.height))
451
+ # if torch.rand(1) > 0.5:
452
+ # image_1 = image_2
453
+ # prompt = prompt2
454
+ img_path, prompt, type = ex
455
+ img_path = img_path.replace('changeit_detected_without_test', 'changeit_detected')
456
+ img_path = 'data/genhowto/' + img_path
457
+ full_img = Image.open(img_path).convert('RGB')
458
+ image_0 = full_img.crop((0, 0, full_img.width // 3, full_img.height))
459
+ if type == 'action':
460
+ image_1 = full_img.crop((full_img.width // 3, 0, full_img.width * 2 // 3, full_img.height))
461
+ else:
462
+ image_1 = full_img.crop((full_img.width * 2 // 3, 0, full_img.width, full_img.height))
463
+
464
+
465
+ reize_res = torch.randint(self.min_resize_res, self.max_resize_res + 1, ()).item()
466
+ image_0 = image_0.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
467
+ image_1 = image_1.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
468
+
469
+ image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
470
+ image_1 = rearrange(2 * torch.tensor(np.array(image_1)).float() / 255 - 1, "h w c -> c h w")
471
+
472
+ crop = torchvision.transforms.RandomCrop(self.crop_res)
473
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
474
+ image_0, image_1 = flip(crop(torch.cat((image_0, image_1)))).chunk(2)
475
+
476
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
477
+
478
+
479
+ class GenHowToDataset(Dataset):
480
+ def __init__(
481
+ self,
482
+ path: str = 'data/clip-filtered-dataset',
483
+ split: str = "train",
484
+ splits: tuple[float, float, float] = (0.9, 0.05, 0.05),
485
+ min_resize_res: int = 256,
486
+ max_resize_res: int = 256,
487
+ crop_res: int = 256,
488
+ flip_prob: float = 0.0,
489
+ ):
490
+ self.split = split
491
+ assert split in ("train", "val", "test")
492
+ assert sum(splits) == 1
493
+ self.path = path
494
+ self.min_resize_res = min_resize_res
495
+ self.max_resize_res = max_resize_res
496
+ self.crop_res = crop_res
497
+ self.flip_prob = flip_prob
498
+
499
+ self.genhowto = open('data/genhowto/genhowto_train.txt', 'r').readlines()
500
+ self.genhowto = [x.strip() for x in self.genhowto]
501
+
502
+ new_genhowto = []
503
+ for i in range(len(self.genhowto)):
504
+ img_path, prompt, prompt2 = self.genhowto[i].split(':')
505
+ new_genhowto.append((img_path, prompt, 'action'))
506
+ new_genhowto.append((img_path, prompt2, 'state'))
507
+ self.genhowto = new_genhowto
508
+ np.random.shuffle(self.genhowto)
509
+
510
+ # with open(Path(self.path, "seeds.json")) as f:
511
+ # self.seeds = json.load(f)
512
+
513
+ # split_0, split_1 = {
514
+ # "train": (0.0, splits[0]),
515
+ # "val": (splits[0], splits[0] + splits[1]),
516
+ # "test": (splits[0] + splits[1], 1.0),
517
+ # }[split]
518
+
519
+ # idx_0 = math.floor(split_0 * len(self.seeds))
520
+ # idx_1 = math.floor(split_1 * len(self.seeds))
521
+ # self.seeds = self.seeds[idx_0:idx_1]
522
+ # shuffle seeds and genhowto
523
+ # np.random.seed(42)
524
+ # np.random.shuffle(self.seeds)
525
+ # np.random.shuffle(self.genhowto)
526
+
527
+ def __len__(self) -> int:
528
+ return len(self.genhowto)
529
+
530
+ def __getitem__(self, i: int) -> dict[str, Any]:
531
+ ex = self.genhowto[i]
532
+ img_path, prompt, type = ex
533
+ img_path = img_path.replace('changeit_detected_without_test', 'changeit_detected')
534
+ img_path = 'data/genhowto/' + img_path
535
+ full_img = Image.open(img_path).convert('RGB')
536
+ image_0 = full_img.crop((0, 0, full_img.width // 3, full_img.height))
537
+ if type == 'action':
538
+ image_1 = full_img.crop((full_img.width // 3, 0, full_img.width * 2 // 3, full_img.height))
539
+ else:
540
+ image_1 = full_img.crop((full_img.width * 2 // 3, 0, full_img.width, full_img.height))
541
+
542
+
543
+ reize_res = torch.randint(self.min_resize_res, self.max_resize_res + 1, ()).item()
544
+ image_0 = image_0.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
545
+ image_1 = image_1.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
546
+
547
+ image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
548
+ image_1 = rearrange(2 * torch.tensor(np.array(image_1)).float() / 255 - 1, "h w c -> c h w")
549
+
550
+ crop = torchvision.transforms.RandomCrop(self.crop_res)
551
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
552
+ image_0, image_1 = flip(crop(torch.cat((image_0, image_1)))).chunk(2)
553
+
554
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
555
+
556
+
557
+ class EditDatasetEval(Dataset):
558
+ def __init__(
559
+ self,
560
+ path: str,
561
+ split: str = "train",
562
+ splits: tuple[float, float, float] = (0.9, 0.05, 0.05),
563
+ res: int = 256,
564
+ ):
565
+ assert split in ("train", "val", "test")
566
+ assert sum(splits) == 1
567
+ self.path = path
568
+ self.res = res
569
+
570
+ with open(Path(self.path, "seeds.json")) as f:
571
+ self.seeds = json.load(f)
572
+
573
+ split_0, split_1 = {
574
+ "train": (0.0, splits[0]),
575
+ "val": (splits[0], splits[0] + splits[1]),
576
+ "test": (splits[0] + splits[1], 1.0),
577
+ }[split]
578
+
579
+ idx_0 = math.floor(split_0 * len(self.seeds))
580
+ idx_1 = math.floor(split_1 * len(self.seeds))
581
+ self.seeds = self.seeds[idx_0:idx_1]
582
+
583
+ def __len__(self) -> int:
584
+ return len(self.seeds)
585
+
586
+ def __getitem__(self, i: int) -> dict[str, Any]:
587
+ name, seeds = self.seeds[i]
588
+ propt_dir = Path(self.path, name)
589
+ seed = seeds[torch.randint(0, len(seeds), ()).item()]
590
+ with open(propt_dir.joinpath("prompt.json")) as fp:
591
+ prompt = json.load(fp)
592
+ edit = prompt["edit"]
593
+ input_prompt = prompt["input"]
594
+ output_prompt = prompt["output"]
595
+
596
+ image_0 = Image.open(propt_dir.joinpath(f"{seed}_0.jpg"))
597
+
598
+ reize_res = torch.randint(self.res, self.res + 1, ()).item()
599
+ image_0 = image_0.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
600
+
601
+ image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
602
+
603
+ return dict(image_0=image_0, input_prompt=input_prompt, edit=edit, output_prompt=output_prompt)
eq-kubric/3d_data/GSO.json ADDED
The diff for this file is too large to render. See raw diff
 
eq-kubric/3d_data/GSO_dict_all.json ADDED
@@ -0,0 +1,1035 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "11pro_SL_TRX_FG": "11pro_SL_TRX_FG",
3
+ "2_of_Jenga_Classic_Game": "2_of_Jenga_Classic_Game",
4
+ "30_CONSTRUCTION_SET": "30_CONSTRUCTION_SET",
5
+ "3D_Dollhouse_Happy_Brother": "3D_Dollhouse_Happy_Brother",
6
+ "3D_Dollhouse_Lamp": "3D_Dollhouse_Lamp",
7
+ "3D_Dollhouse_Refrigerator": "green doll house wooden refrigerator",
8
+ "3D_Dollhouse_Sink": "3D_Dollhouse_Sink",
9
+ "3D_Dollhouse_Sofa": "purple doll house wooden sofa",
10
+ "3D_Dollhouse_Swing": "3D_Dollhouse_Swing",
11
+ "3D_Dollhouse_TablePurple": "3D_Dollhouse_TablePurple",
12
+ "3M_Antislip_Surfacing_Light_Duty_White": "3M_Antislip_Surfacing_Light_Duty_White",
13
+ "3M_Vinyl_Tape_Green_1_x_36_yd": "3M_Vinyl_Tape_Green_1_x_36_yd",
14
+ "45oz_RAMEKIN_ASST_DEEP_COLORS": "45oz_RAMEKIN_ASST_DEEP_COLORS",
15
+ "50_BLOCKS": "50_BLOCKS",
16
+ "5_HTP": "5_HTP",
17
+ "60_CONSTRUCTION_SET": "60_CONSTRUCTION_SET",
18
+ "ACE_Coffee_Mug_Kristen_16_oz_cup": "red coffee mug",
19
+ "ALPHABET_AZ_GRADIENT": "ALPHABET_AZ_GRADIENT",
20
+ "ALPHABET_AZ_GRADIENT_WQb1ufEycSj": "ALPHABET_AZ_GRADIENT_WQb1ufEycSj",
21
+ "AMBERLIGHT_UP_W": "AMBERLIGHT_UP_W",
22
+ "ASICS_GEL1140V_WhiteBlackSilver": "ASICS_GEL1140V_WhiteBlackSilver",
23
+ "ASICS_GEL1140V_WhiteRoyalSilver": "ASICS_GEL1140V_WhiteRoyalSilver",
24
+ "ASICS_GELAce_Pro_Pearl_WhitePink": "ASICS_GELAce_Pro_Pearl_WhitePink",
25
+ "ASICS_GELBlur33_20_GS_BlackWhiteSafety_Orange": "ASICS_GELBlur33_20_GS_BlackWhiteSafety_Orange",
26
+ "ASICS_GELBlur33_20_GS_Flash_YellowHot_PunchSilver": "ASICS_GELBlur33_20_GS_Flash_YellowHot_PunchSilver",
27
+ "ASICS_GELChallenger_9_Royal_BlueWhiteBlack": "ASICS_GELChallenger_9_Royal_BlueWhiteBlack",
28
+ "ASICS_GELDirt_Dog_4_SunFlameBlack": "ASICS_GELDirt_Dog_4_SunFlameBlack",
29
+ "ASICS_GELLinksmaster_WhiteCoffeeSand": "ASICS_GELLinksmaster_WhiteCoffeeSand",
30
+ "ASICS_GELLinksmaster_WhiteRasberryGunmetal": "ASICS_GELLinksmaster_WhiteRasberryGunmetal",
31
+ "ASICS_GELLinksmaster_WhiteSilverCarolina_Blue": "ASICS_GELLinksmaster_WhiteSilverCarolina_Blue",
32
+ "ASICS_GELResolution_5_Flash_YellowBlackSilver": "ASICS_GELResolution_5_Flash_YellowBlackSilver",
33
+ "ASICS_GELTour_Lyte_WhiteOrchidSilver": "ASICS_GELTour_Lyte_WhiteOrchidSilver",
34
+ "ASICS_HyperRocketgirl_SP_5_WhiteMalibu_BlueBlack": "ASICS_HyperRocketgirl_SP_5_WhiteMalibu_BlueBlack",
35
+ "ASSORTED_VEGETABLE_SET": "ASSORTED_VEGETABLE_SET",
36
+ "Adrenaline_GTS_13_Color_DrkDenimWhtBachlorBttnSlvr_Size_50_yfK40TNjq0V": "Adrenaline_GTS_13_Color_DrkDenimWhtBachlorBttnSlvr_Size_50_yfK40TNjq0V",
37
+ "Adrenaline_GTS_13_Color_WhtObsdianBlckOlmpcSlvr_Size_70": "Adrenaline_GTS_13_Color_WhtObsdianBlckOlmpcSlvr_Size_70",
38
+ "Air_Hogs_Wind_Flyers_Set_Airplane_Red": "Air_Hogs_Wind_Flyers_Set_Airplane_Red",
39
+ "AllergenFree_JarroDophilus": "AllergenFree_JarroDophilus",
40
+ "Android_Figure_Chrome": "Android_Figure_Chrome",
41
+ "Android_Figure_Orange": "Android_Figure_Orange",
42
+ "Android_Figure_Panda": "Android_Figure_Panda",
43
+ "Android_Lego": "Android_Lego",
44
+ "Animal_Crossing_New_Leaf_Nintendo_3DS_Game": "Animal_Crossing_New_Leaf_Nintendo_3DS_Game",
45
+ "Animal_Planet_Foam_2Headed_Dragon": "Animal_Planet_Foam_2Headed_Dragon",
46
+ "Apples_to_Apples_Kids_Edition": "Apples_to_Apples_Kids_Edition",
47
+ "Arm_Hammer_Diaper_Pail_Refills_12_Pack_MFWkmoweejt": "Arm_Hammer_Diaper_Pail_Refills_12_Pack_MFWkmoweejt",
48
+ "Aroma_Stainless_Steel_Milk_Frother_2_Cup": "stainless steel milk frother",
49
+ "Asus_80211ac_DualBand_Gigabit_Wireless_Router_RTAC68R": "Asus_80211ac_DualBand_Gigabit_Wireless_Router_RTAC68R",
50
+ "Asus_M5A78LMUSB3_Motherboard_Micro_ATX_Socket_AM3": "Asus_M5A78LMUSB3_Motherboard_Micro_ATX_Socket_AM3",
51
+ "Asus_M5A99FX_PRO_R20_Motherboard_ATX_Socket_AM3": "Asus_M5A99FX_PRO_R20_Motherboard_ATX_Socket_AM3",
52
+ "Asus_Sabertooth_990FX_20_Motherboard_ATX_Socket_AM3": "Asus_Sabertooth_990FX_20_Motherboard_ATX_Socket_AM3",
53
+ "Asus_Sabertooth_Z97_MARK_1_Motherboard_ATX_LGA1150_Socket": "Asus_Sabertooth_Z97_MARK_1_Motherboard_ATX_LGA1150_Socket",
54
+ "Asus_X99Deluxe_Motherboard_ATX_LGA2011v3_Socket": "Asus_X99Deluxe_Motherboard_ATX_LGA2011v3_Socket",
55
+ "Asus_Z87PRO_Motherboard_ATX_LGA1150_Socket": "Asus_Z87PRO_Motherboard_ATX_LGA1150_Socket",
56
+ "Asus_Z97AR_LGA_1150_Intel_ATX_Motherboard": "Asus_Z97AR_LGA_1150_Intel_ATX_Motherboard",
57
+ "Asus_Z97IPLUS_Motherboard_Mini_ITX_LGA1150_Socket": "Asus_Z97IPLUS_Motherboard_Mini_ITX_LGA1150_Socket",
58
+ "Avengers_Gamma_Green_Smash_Fists": "Avengers_Gamma_Green_Smash_Fists",
59
+ "Avengers_Thor_PLlrpYniaeB": "Avengers_Thor_PLlrpYniaeB",
60
+ "Azure_Snake_Tieks_Leather_Snake_Print_Ballet_Flats": "Azure_Snake_Tieks_Leather_Snake_Print_Ballet_Flats",
61
+ "BABY_CAR": "BABY_CAR",
62
+ "BAGEL_WITH_CHEESE": "BAGEL_WITH_CHEESE",
63
+ "BAKING_UTENSILS": "BAKING_UTENSILS",
64
+ "BALANCING_CACTUS": "BALANCING_CACTUS",
65
+ "BATHROOM_CLASSIC": "BATHROOM_CLASSIC",
66
+ "BATHROOM_FURNITURE_SET_1": "BATHROOM_FURNITURE_SET_1",
67
+ "BEDROOM_CLASSIC": "BEDROOM_CLASSIC",
68
+ "BEDROOM_CLASSIC_Gi22DjScTVS": "BEDROOM_CLASSIC_Gi22DjScTVS",
69
+ "BEDROOM_NEO": "BEDROOM_NEO",
70
+ "BIA_Cordon_Bleu_White_Porcelain_Utensil_Holder_900028": "BIA_Cordon_Bleu_White_Porcelain_Utensil_Holder_900028",
71
+ "BIA_Porcelain_Ramekin_With_Glazed_Rim_35_45_oz_cup": "BIA_Porcelain_Ramekin_With_Glazed_Rim_35_45_oz_cup",
72
+ "BIRD_RATTLE": "BIRD_RATTLE",
73
+ "BRAILLE_ALPHABET_AZ": "BRAILLE_ALPHABET_AZ",
74
+ "BREAKFAST_MENU": "BREAKFAST_MENU",
75
+ "BUILD_A_ROBOT": "BUILD_A_ROBOT",
76
+ "BUILD_A_ZOO": "BUILD_A_ZOO",
77
+ "BUNNY_RACER": "BUNNY_RACER",
78
+ "BUNNY_RATTLE": "BUNNY_RATTLE",
79
+ "Baby_Elements_Stacking_Cups": "Baby_Elements_Stacking_Cups",
80
+ "Balderdash_Game": "Balderdash_Game",
81
+ "Beetle_Adventure_Racing_Nintendo_64": "Beetle_Adventure_Racing_Nintendo_64",
82
+ "Beta_Glucan": "Beta_Glucan",
83
+ "Beyonc_Life_is_But_a_Dream_DVD": "Beyonc_Life_is_But_a_Dream_DVD",
84
+ "Bifidus_Balance_FOS": "Bifidus_Balance_FOS",
85
+ "Big_Dot_Aqua_Pencil_Case": "Big_Dot_Aqua_Pencil_Case",
86
+ "Big_Dot_Pink_Pencil_Case": "Big_Dot_Pink_Pencil_Case",
87
+ "Big_O_Sponges_Assorted_Cellulose_12_pack": "Big_O_Sponges_Assorted_Cellulose_12_pack",
88
+ "BlackBlack_Nintendo_3DSXL": "BlackBlack_Nintendo_3DSXL",
89
+ "Black_Decker_CM2035B_12Cup_Thermal_Coffeemaker": "Black_Decker_CM2035B_12Cup_Thermal_Coffeemaker",
90
+ "Black_Decker_Stainless_Steel_Toaster_4_Slice": "stainless steel toaster",
91
+ "Black_Elderberry_Syrup_54_oz_Gaia_Herbs": "Black_Elderberry_Syrup_54_oz_Gaia_Herbs",
92
+ "Black_Forest_Fruit_Snacks_28_Pack_Grape": "Black_Forest_Fruit_Snacks_28_Pack_Grape",
93
+ "Black_Forest_Fruit_Snacks_Juicy_Filled_Centers_10_pouches_9_oz_total": "Black_Forest_Fruit_Snacks_Juicy_Filled_Centers_10_pouches_9_oz_total",
94
+ "Black_and_Decker_PBJ2000_FusionBlade_Blender_Jars": "Black_and_Decker_PBJ2000_FusionBlade_Blender_Jars",
95
+ "Black_and_Decker_TR3500SD_2Slice_Toaster": "Black_and_Decker_TR3500SD_2Slice_Toaster",
96
+ "Blackcurrant_Lutein": "Blackcurrant_Lutein",
97
+ "BlueBlack_Nintendo_3DSXL": "BlueBlack_Nintendo_3DSXL",
98
+ "Blue_Jasmine_Includes_Digital_Copy_UltraViolet_DVD": "Blue_Jasmine_Includes_Digital_Copy_UltraViolet_DVD",
99
+ "Borage_GLA240Gamma_Tocopherol": "Borage_GLA240Gamma_Tocopherol",
100
+ "Bradshaw_International_11642_7_Qt_MP_Plastic_Bowl": "Bradshaw_International_11642_7_Qt_MP_Plastic_Bowl",
101
+ "Breyer_Horse_Of_The_Year_2015": "Breyer_Horse_Of_The_Year_2015",
102
+ "Brisk_Iced_Tea_Lemon_12_12_fl_oz_355_ml_cans_144_fl_oz_426_lt": "Brisk_Iced_Tea_Lemon_12_12_fl_oz_355_ml_cans_144_fl_oz_426_lt",
103
+ "Brother_Ink_Cartridge_Magenta_LC75M": "Brother_Ink_Cartridge_Magenta_LC75M",
104
+ "Brother_LC_1053PKS_Ink_Cartridge_CyanMagentaYellow_1pack": "Brother_LC_1053PKS_Ink_Cartridge_CyanMagentaYellow_1pack",
105
+ "Brother_Printing_Cartridge_PC501": "Brother_Printing_Cartridge_PC501",
106
+ "CARSII": "CARSII",
107
+ "CAR_CARRIER_TRAIN": "CAR_CARRIER_TRAIN",
108
+ "CASTLE_BLOCKS": "CASTLE_BLOCKS",
109
+ "CHICKEN_NESTING": "CHICKEN_NESTING",
110
+ "CHICKEN_RACER": "CHICKEN_RACER",
111
+ "CHILDRENS_ROOM_NEO": "CHILDRENS_ROOM_NEO",
112
+ "CHILDREN_BEDROOM_CLASSIC": "CHILDREN_BEDROOM_CLASSIC",
113
+ "CITY_TAXI_POLICE_CAR": "CITY_TAXI_POLICE_CAR",
114
+ "CLIMACOOL_BOAT_BREEZE_IE6CyqSaDwN": "CLIMACOOL_BOAT_BREEZE_IE6CyqSaDwN",
115
+ "COAST_GUARD_BOAT": "COAST_GUARD_BOAT",
116
+ "CONE_SORTING": "CONE_SORTING",
117
+ "CONE_SORTING_kg5fbARBwts": "CONE_SORTING_kg5fbARBwts",
118
+ "CREATIVE_BLOCKS_35_MM": "CREATIVE_BLOCKS_35_MM",
119
+ "California_Navy_Tieks_Italian_Leather_Ballet_Flats": "California_Navy_Tieks_Italian_Leather_Ballet_Flats",
120
+ "Calphalon_Kitchen_Essentials_12_Cast_Iron_Fry_Pan_Black": "Calphalon_Kitchen_Essentials_12_Cast_Iron_Fry_Pan_Black",
121
+ "Canon_225226_Ink_Cartridges_BlackColor_Cyan_Magenta_Yellow_6_count": "Canon_225226_Ink_Cartridges_BlackColor_Cyan_Magenta_Yellow_6_count",
122
+ "Canon_Ink_Cartridge_Green_6": "Canon_Ink_Cartridge_Green_6",
123
+ "Canon_Pixma_Chromalife_100_Magenta_8": "Canon_Pixma_Chromalife_100_Magenta_8",
124
+ "Canon_Pixma_Ink_Cartridge_251_M": "Canon_Pixma_Ink_Cartridge_251_M",
125
+ "Canon_Pixma_Ink_Cartridge_8": "Canon_Pixma_Ink_Cartridge_8",
126
+ "Canon_Pixma_Ink_Cartridge_8_Green": "Canon_Pixma_Ink_Cartridge_8_Green",
127
+ "Canon_Pixma_Ink_Cartridge_8_Red": "Canon_Pixma_Ink_Cartridge_8_Red",
128
+ "Canon_Pixma_Ink_Cartridge_Cyan_251": "Canon_Pixma_Ink_Cartridge_Cyan_251",
129
+ "Cascadia_8_Color_AquariusHibscsBearingSeaBlk_Size_50": "Cascadia_8_Color_AquariusHibscsBearingSeaBlk_Size_50",
130
+ "Central_Garden_Flower_Pot_Goo_425": "Central_Garden_Flower_Pot_Goo_425",
131
+ "Chef_Style_Round_Cake_Pan_9_inch_pan": "Chef_Style_Round_Cake_Pan_9_inch_pan",
132
+ "Chefmate_8_Frypan": "black frypan",
133
+ "Chelsea_BlkHeelPMP_DwxLtZNxLZZ": "Chelsea_BlkHeelPMP_DwxLtZNxLZZ",
134
+ "Chelsea_lo_fl_rdheel_nQ0LPNF1oMw": "red high heel",
135
+ "Chelsea_lo_fl_rdheel_zAQrnhlEfw8": "Chelsea_lo_fl_rdheel_zAQrnhlEfw8",
136
+ "Circo_Fish_Toothbrush_Holder_14995988": "Circo_Fish_Toothbrush_Holder_14995988",
137
+ "ClimaCool_Aerate_2_W_Wide": "ClimaCool_Aerate_2_W_Wide",
138
+ "Clorox_Premium_Choice_Gloves_SM_1_pair": "Clorox_Premium_Choice_Gloves_SM_1_pair",
139
+ "Closetmaid_Premium_Fabric_Cube_Red": "Closetmaid_Premium_Fabric_Cube_Red",
140
+ "Clue_Board_Game_Classic_Edition": "Clue_Board_Game_Classic_Edition",
141
+ "CoQ10": "white drug bottle",
142
+ "CoQ10_BjTLbuRVt1t": "CoQ10_BjTLbuRVt1t",
143
+ "CoQ10_wSSVoxVppVD": "CoQ10_wSSVoxVppVD",
144
+ "Cole_Hardware_Antislip_Surfacing_Material_White": "Cole_Hardware_Antislip_Surfacing_Material_White",
145
+ "Cole_Hardware_Antislip_Surfacing_White_2_x_60": "Cole_Hardware_Antislip_Surfacing_White_2_x_60",
146
+ "Cole_Hardware_Bowl_Scirocco_YellowBlue": "Cole_Hardware_Bowl_Scirocco_YellowBlue",
147
+ "Cole_Hardware_Butter_Dish_Square_Red": "Cole_Hardware_Butter_Dish_Square_Red",
148
+ "Cole_Hardware_Deep_Bowl_Good_Earth_1075": "Cole_Hardware_Deep_Bowl_Good_Earth_1075",
149
+ "Cole_Hardware_Dishtowel_Blue": "Cole_Hardware_Dishtowel_Blue",
150
+ "Cole_Hardware_Dishtowel_BlueWhite": "Cole_Hardware_Dishtowel_BlueWhite",
151
+ "Cole_Hardware_Dishtowel_Multicolors": "Cole_Hardware_Dishtowel_Multicolors",
152
+ "Cole_Hardware_Dishtowel_Red": "Cole_Hardware_Dishtowel_Red",
153
+ "Cole_Hardware_Dishtowel_Stripe": "Cole_Hardware_Dishtowel_Stripe",
154
+ "Cole_Hardware_Electric_Pot_Assortment_55": "Cole_Hardware_Electric_Pot_Assortment_55",
155
+ "Cole_Hardware_Electric_Pot_Cabana_55": "Cole_Hardware_Electric_Pot_Cabana_55",
156
+ "Cole_Hardware_Flower_Pot_1025": "Cole_Hardware_Flower_Pot_1025",
157
+ "Cole_Hardware_Hammer_Black": "black and yellow hammer",
158
+ "Cole_Hardware_Mini_Honey_Dipper": "Cole_Hardware_Mini_Honey_Dipper",
159
+ "Cole_Hardware_Mug_Classic_Blue": "Cole_Hardware_Mug_Classic_Blue",
160
+ "Cole_Hardware_Orchid_Pot_85": "Cole_Hardware_Orchid_Pot_85",
161
+ "Cole_Hardware_Plant_Saucer_Brown_125": "Cole_Hardware_Plant_Saucer_Brown_125",
162
+ "Cole_Hardware_Plant_Saucer_Glazed_9": "Cole_Hardware_Plant_Saucer_Glazed_9",
163
+ "Cole_Hardware_Saucer_Electric": "Cole_Hardware_Saucer_Electric",
164
+ "Cole_Hardware_Saucer_Glazed_6": "Cole_Hardware_Saucer_Glazed_6",
165
+ "Cole_Hardware_School_Bell_Solid_Brass_38": "Cole_Hardware_School_Bell_Solid_Brass_38",
166
+ "Colton_Wntr_Chukka_y4jO0I8JQFW": "Colton_Wntr_Chukka_y4jO0I8JQFW",
167
+ "Connect_4_Launchers": "Connect_4_Launchers",
168
+ "Cootie_Game": "Cootie_Game",
169
+ "Cootie_Game_tDhURNbfU5J": "Cootie_Game_tDhURNbfU5J",
170
+ "Copperhead_Snake_Tieks_Brown_Snake_Print_Ballet_Flats": "Copperhead_Snake_Tieks_Brown_Snake_Print_Ballet_Flats",
171
+ "Corningware_CW_by_Corningware_3qt_Oblong_Casserole_Dish_Blue": "Corningware_CW_by_Corningware_3qt_Oblong_Casserole_Dish_Blue",
172
+ "Court_Attitude": "Court_Attitude",
173
+ "Craftsman_Grip_Screwdriver_Phillips_Cushion": "Craftsman_Grip_Screwdriver_Phillips_Cushion",
174
+ "Crayola_Bonus_64_Crayons": "Crayola_Bonus_64_Crayons",
175
+ "Crayola_Crayons_120_crayons": "Crayola_Crayons_120_crayons",
176
+ "Crayola_Crayons_24_count": "Crayola_Crayons_24_count",
177
+ "Crayola_Crayons_Washable_24_crayons": "Crayola_Crayons_Washable_24_crayons",
178
+ "Crayola_Model_Magic_Modeling_Material_Single_Packs_6_pack_05_oz_packs": "Crayola_Model_Magic_Modeling_Material_Single_Packs_6_pack_05_oz_packs",
179
+ "Crayola_Model_Magic_Modeling_Material_White_3_oz": "Crayola_Model_Magic_Modeling_Material_White_3_oz",
180
+ "Crayola_Washable_Fingerpaint_Red_Blue_Yellow_3_count_8_fl_oz_bottes_each": "Crayola_Washable_Fingerpaint_Red_Blue_Yellow_3_count_8_fl_oz_bottes_each",
181
+ "Crayola_Washable_Sidewalk_Chalk_16_pack": "Crayola_Washable_Sidewalk_Chalk_16_pack",
182
+ "Crayola_Washable_Sidewalk_Chalk_16_pack_wDZECiw7J6s": "Crayola_Washable_Sidewalk_Chalk_16_pack_wDZECiw7J6s",
183
+ "Crazy_8": "Crazy_8",
184
+ "Crazy_Shadow_2": "Crazy_Shadow_2",
185
+ "Crazy_Shadow_2_oW4Jd10HFFr": "Crazy_Shadow_2_oW4Jd10HFFr",
186
+ "Cream_Tieks_Italian_Leather_Ballet_Flats": "Cream_Tieks_Italian_Leather_Ballet_Flats",
187
+ "Creatine_Monohydrate": "Creatine_Monohydrate",
188
+ "Crosley_Alarm_Clock_Vintage_Metal": "vintage metal alarm clock",
189
+ "Crunch_Girl_Scouts_Candy_Bars_Peanut_Butter_Creme_78_oz_box": "Crunch_Girl_Scouts_Candy_Bars_Peanut_Butter_Creme_78_oz_box",
190
+ "Curver_Storage_Bin_Black_Small": "Curver_Storage_Bin_Black_Small",
191
+ "DANCING_ALLIGATOR": "DANCING_ALLIGATOR",
192
+ "DANCING_ALLIGATOR_zoWBjc0jbTs": "DANCING_ALLIGATOR_zoWBjc0jbTs",
193
+ "DIM_CDG": "DIM_CDG",
194
+ "DINING_ROOM_CLASSIC": "DINING_ROOM_CLASSIC",
195
+ "DINING_ROOM_CLASSIC_UJuxQ0hv5XU": "DINING_ROOM_CLASSIC_UJuxQ0hv5XU",
196
+ "DINNING_ROOM_FURNITURE_SET_1": "DINNING_ROOM_FURNITURE_SET_1",
197
+ "DOLL_FAMILY": "DOLL_FAMILY",
198
+ "DPC_Handmade_Hat_Brown": "DPC_Handmade_Hat_Brown",
199
+ "DPC_Thinsulate_Isolate_Gloves_Brown": "DPC_Thinsulate_Isolate_Gloves_Brown",
200
+ "DPC_tropical_Trends_Hat": "DPC_tropical_Trends_Hat",
201
+ "DRAGON_W": "DRAGON_W",
202
+ "D_ROSE_45": "D_ROSE_45",
203
+ "D_ROSE_773_II_Kqclsph05pE": "D_ROSE_773_II_Kqclsph05pE",
204
+ "D_ROSE_773_II_hvInJwJ5HUD": "D_ROSE_773_II_hvInJwJ5HUD",
205
+ "D_ROSE_ENGLEWOOD_II": "D_ROSE_ENGLEWOOD_II",
206
+ "Dell_Ink_Cartridge": "Dell_Ink_Cartridge",
207
+ "Dell_Ink_Cartridge_Yellow_31": "Dell_Ink_Cartridge_Yellow_31",
208
+ "Dell_Series_9_Color_Ink_Cartridge_MK993_High_Yield": "Dell_Series_9_Color_Ink_Cartridge_MK993_High_Yield",
209
+ "Design_Ideas_Drawer_Store_Organizer": "Design_Ideas_Drawer_Store_Organizer",
210
+ "Deskstar_Desk_Top_Hard_Drive_1_TB": "Deskstar_Desk_Top_Hard_Drive_1_TB",
211
+ "Diamond_Visions_Scissors_Red": "red scissors",
212
+ "Diet_Pepsi_Soda_Cola12_Pack_12_oz_Cans": "Diet_Pepsi_Soda_Cola12_Pack_12_oz_Cans",
213
+ "Digital_Camo_Double_Decker_Lunch_Bag": "Digital_Camo_Double_Decker_Lunch_Bag",
214
+ "Dino_3": "Dino_3",
215
+ "Dino_4": "Dino_4",
216
+ "Dino_5": "Dino_5",
217
+ "Dixie_10_ounce_Bowls_35_ct": "Dixie_10_ounce_Bowls_35_ct",
218
+ "Dog": "Dog",
219
+ "Don_Franciscos_Gourmet_Coffee_Medium_Decaf_100_Colombian_12_oz_340_g": "Don_Franciscos_Gourmet_Coffee_Medium_Decaf_100_Colombian_12_oz_340_g",
220
+ "Down_To_Earth_Ceramic_Orchid_Pot_Asst_Blue": "Down_To_Earth_Ceramic_Orchid_Pot_Asst_Blue",
221
+ "Down_To_Earth_Orchid_Pot_Ceramic_Lime": "Down_To_Earth_Orchid_Pot_Ceramic_Lime",
222
+ "Down_To_Earth_Orchid_Pot_Ceramic_Red": "Down_To_Earth_Orchid_Pot_Ceramic_Red",
223
+ "ENFR_MID_ENFORCER": "ENFR_MID_ENFORCER",
224
+ "Eat_to_Live_The_Amazing_NutrientRich_Program_for_Fast_and_Sustained_Weight_Loss_Revised_Edition_Book": "Eat_to_Live_The_Amazing_NutrientRich_Program_for_Fast_and_Sustained_Weight_Loss_Revised_Edition_Book",
225
+ "Ecoforms_Cup_B4_SAN": "Ecoforms_Cup_B4_SAN",
226
+ "Ecoforms_Garden_Pot_GP16ATurquois": "Ecoforms_Garden_Pot_GP16ATurquois",
227
+ "Ecoforms_Plant_Bowl_Atlas_Low": "Ecoforms_Plant_Bowl_Atlas_Low",
228
+ "Ecoforms_Plant_Bowl_Turquoise_7": "Ecoforms_Plant_Bowl_Turquoise_7",
229
+ "Ecoforms_Plant_Container_12_Pot_Nova": "Ecoforms_Plant_Container_12_Pot_Nova",
230
+ "Ecoforms_Plant_Container_B4_Har": "Ecoforms_Plant_Container_B4_Har",
231
+ "Ecoforms_Plant_Container_FB6_Tur": "Ecoforms_Plant_Container_FB6_Tur",
232
+ "Ecoforms_Plant_Container_GP16AMOCHA": "Ecoforms_Plant_Container_GP16AMOCHA",
233
+ "Ecoforms_Plant_Container_GP16A_Coral": "Ecoforms_Plant_Container_GP16A_Coral",
234
+ "Ecoforms_Plant_Container_QP6CORAL": "Ecoforms_Plant_Container_QP6CORAL",
235
+ "Ecoforms_Plant_Container_QP6HARVEST": "Ecoforms_Plant_Container_QP6HARVEST",
236
+ "Ecoforms_Plant_Container_QP_Harvest": "Ecoforms_Plant_Container_QP_Harvest",
237
+ "Ecoforms_Plant_Container_QP_Turquoise": "Ecoforms_Plant_Container_QP_Turquoise",
238
+ "Ecoforms_Plant_Container_Quadra_Sand_QP6": "Ecoforms_Plant_Container_Quadra_Sand_QP6",
239
+ "Ecoforms_Plant_Container_Quadra_Turquoise_QP12": "Ecoforms_Plant_Container_Quadra_Turquoise_QP12",
240
+ "Ecoforms_Plant_Container_S14Turquoise": "Ecoforms_Plant_Container_S14Turquoise",
241
+ "Ecoforms_Plant_Container_S24NATURAL": "Ecoforms_Plant_Container_S24NATURAL",
242
+ "Ecoforms_Plant_Container_S24Turquoise": "Ecoforms_Plant_Container_S24Turquoise",
243
+ "Ecoforms_Plant_Container_SB9Turquoise": "Ecoforms_Plant_Container_SB9Turquoise",
244
+ "Ecoforms_Plant_Container_URN_NAT": "Ecoforms_Plant_Container_URN_NAT",
245
+ "Ecoforms_Plant_Container_URN_SAN": "Ecoforms_Plant_Container_URN_SAN",
246
+ "Ecoforms_Plant_Container_Urn_55_Avocado": "Ecoforms_Plant_Container_Urn_55_Avocado",
247
+ "Ecoforms_Plant_Container_Urn_55_Mocha": "Ecoforms_Plant_Container_Urn_55_Mocha",
248
+ "Ecoforms_Plant_Plate_S11Turquoise": "Ecoforms_Plant_Plate_S11Turquoise",
249
+ "Ecoforms_Plant_Pot_GP9AAvocado": "Ecoforms_Plant_Pot_GP9AAvocado",
250
+ "Ecoforms_Plant_Pot_GP9_SAND": "Ecoforms_Plant_Pot_GP9_SAND",
251
+ "Ecoforms_Plant_Saucer_S14MOCHA": "Ecoforms_Plant_Saucer_S14MOCHA",
252
+ "Ecoforms_Plant_Saucer_S14NATURAL": "Ecoforms_Plant_Saucer_S14NATURAL",
253
+ "Ecoforms_Plant_Saucer_S17MOCHA": "Ecoforms_Plant_Saucer_S17MOCHA",
254
+ "Ecoforms_Plant_Saucer_S20MOCHA": "Ecoforms_Plant_Saucer_S20MOCHA",
255
+ "Ecoforms_Plant_Saucer_SQ1HARVEST": "Ecoforms_Plant_Saucer_SQ1HARVEST",
256
+ "Ecoforms_Plant_Saucer_SQ8COR": "Ecoforms_Plant_Saucer_SQ8COR",
257
+ "Ecoforms_Planter_Bowl_Cole_Hardware": "Ecoforms_Planter_Bowl_Cole_Hardware",
258
+ "Ecoforms_Planter_Pot_GP12AAvocado": "Ecoforms_Planter_Pot_GP12AAvocado",
259
+ "Ecoforms_Planter_Pot_QP6Ebony": "Ecoforms_Planter_Pot_QP6Ebony",
260
+ "Ecoforms_Plate_S20Avocado": "Ecoforms_Plate_S20Avocado",
261
+ "Ecoforms_Pot_Nova_6_Turquoise": "Ecoforms_Pot_Nova_6_Turquoise",
262
+ "Ecoforms_Quadra_Saucer_SQ1_Avocado": "Ecoforms_Quadra_Saucer_SQ1_Avocado",
263
+ "Ecoforms_Saucer_SQ3_Turquoise": "Ecoforms_Saucer_SQ3_Turquoise",
264
+ "Elephant": "Elephant",
265
+ "Embark_Lunch_Cooler_Blue": "Embark_Lunch_Cooler_Blue",
266
+ "Envision_Home_Dish_Drying_Mat_Red_6_x_18": "Envision_Home_Dish_Drying_Mat_Red_6_x_18",
267
+ "Epson_273XL_Ink_Cartridge_Magenta": "Epson_273XL_Ink_Cartridge_Magenta",
268
+ "Epson_DURABrite_Ultra_786_Black_Ink_Cartridge_T786120S": "Epson_DURABrite_Ultra_786_Black_Ink_Cartridge_T786120S",
269
+ "Epson_Ink_Cartridge_126_Yellow": "Epson_Ink_Cartridge_126_Yellow",
270
+ "Epson_Ink_Cartridge_Black_200": "Epson_Ink_Cartridge_Black_200",
271
+ "Epson_LabelWorks_LC4WBN9_Tape_reel_labels_047_x_295_Roll_Black_on_White": "Epson_LabelWorks_LC4WBN9_Tape_reel_labels_047_x_295_Roll_Black_on_White",
272
+ "Epson_LabelWorks_LC5WBN9_Tape_reel_labels_071_x_295_Roll_Black_on_White": "Epson_LabelWorks_LC5WBN9_Tape_reel_labels_071_x_295_Roll_Black_on_White",
273
+ "Epson_T5803_Ink_Cartridge_Magenta_1pack": "Epson_T5803_Ink_Cartridge_Magenta_1pack",
274
+ "Epson_UltraChrome_T0543_Ink_Cartridge_Magenta_1pack": "Epson_UltraChrome_T0543_Ink_Cartridge_Magenta_1pack",
275
+ "Epson_UltraChrome_T0548_Ink_Cartridge_Matte_Black_1pack": "Epson_UltraChrome_T0548_Ink_Cartridge_Matte_Black_1pack",
276
+ "F10_TRX_FG_ssscuo9tGxb": "F10_TRX_FG_ssscuo9tGxb",
277
+ "F10_TRX_TF_rH7tmKCdUJq": "F10_TRX_TF_rH7tmKCdUJq",
278
+ "F5_TRX_FG": "F5_TRX_FG",
279
+ "FAIRY_TALE_BLOCKS": "FAIRY_TALE_BLOCKS",
280
+ "FARM_ANIMAL": "FARM_ANIMAL",
281
+ "FARM_ANIMAL_9GyfdcPyESK": "FARM_ANIMAL_9GyfdcPyESK",
282
+ "FIRE_ENGINE": "FIRE_ENGINE",
283
+ "FIRE_TRUCK": "FIRE_TRUCK",
284
+ "FISHING_GAME": "FISHING_GAME",
285
+ "FOOD_BEVERAGE_SET": "FOOD_BEVERAGE_SET",
286
+ "FRACTION_FUN_n4h4qte23QR": "FRACTION_FUN_n4h4qte23QR",
287
+ "FRUIT_VEGGIE_DOMINO_GRADIENT": "FRUIT_VEGGIE_DOMINO_GRADIENT",
288
+ "FRUIT_VEGGIE_MEMO_GRADIENT": "FRUIT_VEGGIE_MEMO_GRADIENT",
289
+ "FYW_ALTERNATION": "FYW_ALTERNATION",
290
+ "FYW_DIVISION": "FYW_DIVISION",
291
+ "FemDophilus": "FemDophilus",
292
+ "Final_Fantasy_XIV_A_Realm_Reborn_60Day_Subscription": "Final_Fantasy_XIV_A_Realm_Reborn_60Day_Subscription",
293
+ "Firefly_Clue_Board_Game": "Firefly_Clue_Board_Game",
294
+ "FisherPrice_Make_A_Match_Game_Thomas_Friends": "FisherPrice_Make_A_Match_Game_Thomas_Friends",
295
+ "Fisher_price_Classic_Toys_Buzzy_Bee": "Fisher_price_Classic_Toys_Buzzy_Bee",
296
+ "Focus_8643_Lime_Squeezer_10x35x188_Enamelled_Aluminum_Light": "Focus_8643_Lime_Squeezer_10x35x188_Enamelled_Aluminum_Light",
297
+ "Folic_Acid": "Folic_Acid",
298
+ "Footed_Bowl_Sand": "Footed_Bowl_Sand",
299
+ "Fresca_Peach_Citrus_Sparkling_Flavored_Soda_12_PK": "Fresca_Peach_Citrus_Sparkling_Flavored_Soda_12_PK",
300
+ "Frozen_Olafs_In_Trouble_PopOMatic_Game": "Frozen_Olafs_In_Trouble_PopOMatic_Game",
301
+ "Frozen_Olafs_In_Trouble_PopOMatic_Game_OEu83W9T8pD": "Frozen_Olafs_In_Trouble_PopOMatic_Game_OEu83W9T8pD",
302
+ "Frozen_Scrabble_Jr": "Frozen_Scrabble_Jr",
303
+ "Fruity_Friends": "Fruity_Friends",
304
+ "Fujifilm_instax_SHARE_SP1_10_photos": "Fujifilm_instax_SHARE_SP1_10_photos",
305
+ "Full_Circle_Happy_Scraps_Out_Collector_Gray": "Full_Circle_Happy_Scraps_Out_Collector_Gray",
306
+ "GARDEN_SWING": "GARDEN_SWING",
307
+ "GEARS_PUZZLES_STANDARD_gcYxhNHhKlI": "GEARS_PUZZLES_STANDARD_gcYxhNHhKlI",
308
+ "GEOMETRIC_PEG_BOARD": "GEOMETRIC_PEG_BOARD",
309
+ "GEOMETRIC_SORTING_BOARD": "GEOMETRIC_SORTING_BOARD",
310
+ "GEOMETRIC_SORTING_BOARD_MNi4Rbuz9vj": "GEOMETRIC_SORTING_BOARD_MNi4Rbuz9vj",
311
+ "GIRLS_DECKHAND": "GIRLS_DECKHAND",
312
+ "GRANDFATHER_DOLL": "GRANDFATHER_DOLL",
313
+ "GRANDMOTHER": "GRANDMOTHER",
314
+ "Germanium_GE132": "Germanium_GE132",
315
+ "Ghost_6_Color_BlckWhtLavaSlvrCitrus_Size_80": "Ghost_6_Color_BlckWhtLavaSlvrCitrus_Size_80",
316
+ "Ghost_6_Color_MdngtDenmPomBrtePnkSlvBlk_Size_50": "Ghost_6_Color_MdngtDenmPomBrtePnkSlvBlk_Size_50",
317
+ "Ghost_6_GTX_Color_AnthBlckSlvrFernSulphSprng_Size_80": "Ghost_6_GTX_Color_AnthBlckSlvrFernSulphSprng_Size_80",
318
+ "Gigabyte_GA78LMTUSB3_50_Motherboard_Micro_ATX_Socket_AM3": "Gigabyte_GA78LMTUSB3_50_Motherboard_Micro_ATX_Socket_AM3",
319
+ "Gigabyte_GA970AUD3P_10_Motherboard_ATX_Socket_AM3": "Gigabyte_GA970AUD3P_10_Motherboard_ATX_Socket_AM3",
320
+ "Gigabyte_GAZ97XSLI_10_motherboard_ATX_LGA1150_Socket_Z97": "Gigabyte_GAZ97XSLI_10_motherboard_ATX_LGA1150_Socket_Z97",
321
+ "Glycerin_11_Color_AqrsDrsdnBluBlkSlvShckOrng_Size_50": "Glycerin_11_Color_AqrsDrsdnBluBlkSlvShckOrng_Size_50",
322
+ "Glycerin_11_Color_BrllntBluSkydvrSlvrBlckWht_Size_80": "Glycerin_11_Color_BrllntBluSkydvrSlvrBlckWht_Size_80",
323
+ "GoPro_HERO3_Composite_Cable": "GoPro_HERO3_Composite_Cable",
324
+ "Google_Cardboard_Original_package": "Google_Cardboard_Original_package",
325
+ "Grand_Prix": "Grand_Prix",
326
+ "Granimals_20_Wooden_ABC_Blocks_Wagon": "Granimals_20_Wooden_ABC_Blocks_Wagon",
327
+ "Granimals_20_Wooden_ABC_Blocks_Wagon_85VdSftGsLi": "Granimals_20_Wooden_ABC_Blocks_Wagon_85VdSftGsLi",
328
+ "Granimals_20_Wooden_ABC_Blocks_Wagon_g2TinmUGGHI": "Granimals_20_Wooden_ABC_Blocks_Wagon_g2TinmUGGHI",
329
+ "Great_Dinos_Triceratops_Toy": "Great_Dinos_Triceratops_Toy",
330
+ "Great_Jones_Wingtip": "Great_Jones_Wingtip",
331
+ "Great_Jones_Wingtip_j5NV8GRnitM": "Great_Jones_Wingtip_j5NV8GRnitM",
332
+ "Great_Jones_Wingtip_kAqSg6EgG0I": "Great_Jones_Wingtip_kAqSg6EgG0I",
333
+ "Great_Jones_Wingtip_wxH3dbtlvBC": "Great_Jones_Wingtip_wxH3dbtlvBC",
334
+ "Grreat_Choice_Dog_Double_Dish_Plastic_Blue": "Grreat_Choice_Dog_Double_Dish_Plastic_Blue",
335
+ "Grreatv_Choice_Dog_Bowl_Gray_Bones_Plastic_20_fl_oz_total": "Grreatv_Choice_Dog_Bowl_Gray_Bones_Plastic_20_fl_oz_total",
336
+ "Guardians_of_the_Galaxy_Galactic_Battlers_Rocket_Raccoon_Figure": "Guardians_of_the_Galaxy_Galactic_Battlers_Rocket_Raccoon_Figure",
337
+ "HAMMER_BALL": "HAMMER_BALL",
338
+ "HAMMER_PEG": "HAMMER_PEG",
339
+ "HAPPY_ENGINE": "HAPPY_ENGINE",
340
+ "HELICOPTER": "HELICOPTER",
341
+ "HP_1800_Tablet_8GB_7": "HP_1800_Tablet_8GB_7",
342
+ "HP_Card_Invitation_Kit": "HP_Card_Invitation_Kit",
343
+ "Hasbro_Cranium_Performance_and_Acting_Game": "Hasbro_Cranium_Performance_and_Acting_Game",
344
+ "Hasbro_Dont_Wake_Daddy_Board_Game": "Hasbro_Dont_Wake_Daddy_Board_Game",
345
+ "Hasbro_Dont_Wake_Daddy_Board_Game_NJnjGna4u1a": "Hasbro_Dont_Wake_Daddy_Board_Game_NJnjGna4u1a",
346
+ "Hasbro_Life_Board_Game": "Hasbro_Life_Board_Game",
347
+ "Hasbro_Monopoly_Hotels_Game": "Hasbro_Monopoly_Hotels_Game",
348
+ "Hasbro_Trivial_Pursuit_Family_Edition_Game": "Hasbro_Trivial_Pursuit_Family_Edition_Game",
349
+ "HeavyDuty_Flashlight": "HeavyDuty_Flashlight",
350
+ "Hefty_Waste_Basket_Decorative_Bronze_85_liter": "Hefty_Waste_Basket_Decorative_Bronze_85_liter",
351
+ "Hey_You_Pikachu_Nintendo_64": "Hey_You_Pikachu_Nintendo_64",
352
+ "Hilary": "Hilary",
353
+ "Home_Fashions_Washcloth_Linen": "Home_Fashions_Washcloth_Linen",
354
+ "Home_Fashions_Washcloth_Olive_Green": "Home_Fashions_Washcloth_Olive_Green",
355
+ "Horse_Dreams_Pencil_Case": "Horse_Dreams_Pencil_Case",
356
+ "Horses_in_Pink_Pencil_Case": "Horses_in_Pink_Pencil_Case",
357
+ "House_of_Cards_The_Complete_First_Season_4_Discs_DVD": "House_of_Cards_The_Complete_First_Season_4_Discs_DVD",
358
+ "Hyaluronic_Acid": "Hyaluronic_Acid",
359
+ "HyperX_Cloud_II_Headset_Gun_Metal": "HyperX_Cloud_II_Headset_Gun_Metal",
360
+ "HyperX_Cloud_II_Headset_Red": "HyperX_Cloud_II_Headset_Red",
361
+ "INTERNATIONAL_PAPER_Willamette_4_Brown_Bag_500Count": "INTERNATIONAL_PAPER_Willamette_4_Brown_Bag_500Count",
362
+ "Imaginext_Castle_Ogre": "Imaginext_Castle_Ogre",
363
+ "In_Green_Company_Surface_Saver_Ring_10_Terra_Cotta": "In_Green_Company_Surface_Saver_Ring_10_Terra_Cotta",
364
+ "Inositol": "Inositol",
365
+ "InterDesign_Over_Door": "InterDesign_Over_Door",
366
+ "IsoRich_Soy": "IsoRich_Soy",
367
+ "JA_Henckels_International_Premio_Cutlery_Block_Set_14Piece": "JA_Henckels_International_Premio_Cutlery_Block_Set_14Piece",
368
+ "JBL_Charge_Speaker_portable_wireless_wired_Green": "JBL_Charge_Speaker_portable_wireless_wired_Green",
369
+ "JS_WINGS_20_BLACK_FLAG": "JS_WINGS_20_BLACK_FLAG",
370
+ "JUICER_SET": "JUICER_SET",
371
+ "JUNGLE_HEIGHT": "JUNGLE_HEIGHT",
372
+ "Jansport_School_Backpack_Blue_Streak": "blue and black backpack",
373
+ "JarroDophilusFOS_Value_Size": "JarroDophilusFOS_Value_Size",
374
+ "JarroSil_Activated_Silicon": "JarroSil_Activated_Silicon",
375
+ "JarroSil_Activated_Silicon_5exdZHIeLAp": "JarroSil_Activated_Silicon_5exdZHIeLAp",
376
+ "Jarrow_Formulas_Glucosamine_Hci_Mega_1000_100_ct": "Jarrow_Formulas_Glucosamine_Hci_Mega_1000_100_ct",
377
+ "Jarrow_Glucosamine_Chondroitin_Combination_120_Caps": "Jarrow_Glucosamine_Chondroitin_Combination_120_Caps",
378
+ "Jawbone_UP24_Wireless_Activity_Tracker_Pink_Coral_L": "Jawbone_UP24_Wireless_Activity_Tracker_Pink_Coral_L",
379
+ "Just_For_Men_Mustache_Beard_Brushin_Hair_Color_Gel_Kit_Jet_Black_M60": "Just_For_Men_Mustache_Beard_Brushin_Hair_Color_Gel_Kit_Jet_Black_M60",
380
+ "Just_For_Men_Mustache_Beard_Brushin_Hair_Color_Gel_MediumDark_Brown_M40": "Just_For_Men_Mustache_Beard_Brushin_Hair_Color_Gel_MediumDark_Brown_M40",
381
+ "Just_For_Men_ShampooIn_Haircolor_Jet_Black_60": "Just_For_Men_ShampooIn_Haircolor_Jet_Black_60",
382
+ "Just_For_Men_ShampooIn_Haircolor_Light_Brown_25": "Just_For_Men_ShampooIn_Haircolor_Light_Brown_25",
383
+ "Just_For_Men_Shampoo_In_Haircolor_Darkest_Brown_50": "Just_For_Men_Shampoo_In_Haircolor_Darkest_Brown_50",
384
+ "Justified_The_Complete_Fourth_Season_3_Discs_DVD": "Justified_The_Complete_Fourth_Season_3_Discs_DVD",
385
+ "KID_ROOM_FURNITURE_SET_1": "KID_ROOM_FURNITURE_SET_1",
386
+ "KITCHEN_FURNITURE_SET_1": "KITCHEN_FURNITURE_SET_1",
387
+ "KITCHEN_SET_CLASSIC_40HwCHfeG0H": "KITCHEN_SET_CLASSIC_40HwCHfeG0H",
388
+ "KS_Chocolate_Cube_Box_Assortment_By_Neuhaus_2010_Ounces": "white gift box with red straps",
389
+ "Kanex_MultiSync_Wireless_Keyboard": "Kanex_MultiSync_Wireless_Keyboard",
390
+ "Kid_Icarus_Uprising_Nintendo_3DS_Game": "Kid_Icarus_Uprising_Nintendo_3DS_Game",
391
+ "Kingston_DT4000MR_G2_Management_Ready_USB_64GB": "Kingston_DT4000MR_G2_Management_Ready_USB_64GB",
392
+ "Kong_Puppy_Teething_Rubber_Small_Pink": "Kong_Puppy_Teething_Rubber_Small_Pink",
393
+ "Kotex_U_Barely_There_Liners_Thin_60_count": "Kotex_U_Barely_There_Liners_Thin_60_count",
394
+ "Kotex_U_Tween_Pads_16_pads": "Kotex_U_Tween_Pads_16_pads",
395
+ "Kotobuki_Saucer_Dragon_Fly": "Kotobuki_Saucer_Dragon_Fly",
396
+ "Krill_Oil": "Krill_Oil",
397
+ "LACING_SHEEP": "LACING_SHEEP",
398
+ "LADYBUG_BEAD": "LADYBUG_BEAD",
399
+ "LEGO_5887_Dino_Defense_HQ": "LEGO_5887_Dino_Defense_HQ",
400
+ "LEGO_Bricks_More_Creative_Suitcase": "LEGO_Bricks_More_Creative_Suitcase",
401
+ "LEGO_City_Advent_Calendar": "LEGO_City_Advent_Calendar",
402
+ "LEGO_Creationary_Game": "LEGO_Creationary_Game",
403
+ "LEGO_Creationary_Game_ZJa163wlWp2": "LEGO_Creationary_Game_ZJa163wlWp2",
404
+ "LEGO_Duplo_Build_and_Play_Box_4629": "LEGO_Duplo_Build_and_Play_Box_4629",
405
+ "LEGO_Duplo_Creative_Animals_10573": "LEGO_Duplo_Creative_Animals_10573",
406
+ "LEGO_Fusion_Set_Town_Master": "LEGO_Fusion_Set_Town_Master",
407
+ "LEGO_Star_Wars_Advent_Calendar": "LEGO_Star_Wars_Advent_Calendar",
408
+ "LEUCIPPUS_ADIPURE": "LEUCIPPUS_ADIPURE",
409
+ "LTyrosine": "LTyrosine",
410
+ "Lactoferrin": "Lactoferrin",
411
+ "Lalaloopsy_Peanut_Big_Top_Tricycle": "Lalaloopsy_Peanut_Big_Top_Tricycle",
412
+ "Lavender_Snake_Tieks_Snake_Print_Ballet_Flats": "Lavender_Snake_Tieks_Snake_Print_Ballet_Flats",
413
+ "Leap_Frog_Paint_Dabber_Dot_Art_5_paint_bottles": "Leap_Frog_Paint_Dabber_Dot_Art_5_paint_bottles",
414
+ "Lego_Friends_Advent_Calendar": "Lego_Friends_Advent_Calendar",
415
+ "Lego_Friends_Mia": "Lego_Friends_Mia",
416
+ "Lenovo_Yoga_2_11": "Lenovo_Yoga_2_11",
417
+ "Little_Big_Planet_3_Plush_Edition": "Little_Big_Planet_3_Plush_Edition",
418
+ "Little_Debbie_Chocolate_Cupcakes_8_ct": "Little_Debbie_Chocolate_Cupcakes_8_ct",
419
+ "Little_Debbie_Cloud_Cakes_10_ct": "Little_Debbie_Cloud_Cakes_10_ct",
420
+ "Little_Debbie_Donut_Sticks_6_cake_donuts_10_oz_total": "Little_Debbie_Donut_Sticks_6_cake_donuts_10_oz_total",
421
+ "Little_House_on_the_Prairie_Season_Two_5_Discs_Includes_Digital": "Little_House_on_the_Prairie_Season_Two_5_Discs_Includes_Digital",
422
+ "Logitech_Ultimate_Ears_Boom_Wireless_Speaker_Night_Black": "Logitech_Ultimate_Ears_Boom_Wireless_Speaker_Night_Black",
423
+ "Lovable_Huggable_Cuddly_Boutique_Teddy_Bear_Beige": "Lovable_Huggable_Cuddly_Boutique_Teddy_Bear_Beige",
424
+ "Lovestruck_Tieks_Glittery_Rose_Gold_Italian_Leather_Ballet_Flats": "Lovestruck_Tieks_Glittery_Rose_Gold_Italian_Leather_Ballet_Flats",
425
+ "Luigis_Mansion_Dark_Moon_Nintendo_3DS_Game": "Luigis_Mansion_Dark_Moon_Nintendo_3DS_Game",
426
+ "Lutein": "Lutein",
427
+ "MARTIN_WEDGE_LACE_BOOT": "MARTIN_WEDGE_LACE_BOOT",
428
+ "MEAT_SET": "MEAT_SET",
429
+ "MINI_EXCAVATOR": "MINI_EXCAVATOR",
430
+ "MINI_FIRE_ENGINE": "MINI_FIRE_ENGINE",
431
+ "MINI_ROLLER": "MINI_ROLLER",
432
+ "MIRACLE_POUNDING": "MIRACLE_POUNDING",
433
+ "MK7": "MK7",
434
+ "MODERN_DOLL_FAMILY": "MODERN_DOLL_FAMILY",
435
+ "MONKEY_BOWLING": "MONKEY_BOWLING",
436
+ "MOSAIC": "MOSAIC",
437
+ "MOVING_MOUSE_PW_6PCSSET": "MOVING_MOUSE_PW_6PCSSET",
438
+ "MY_MOOD_MEMO": "MY_MOOD_MEMO",
439
+ "Mad_Gab_Refresh_Card_Game": "Mad_Gab_Refresh_Card_Game",
440
+ "Magnifying_Glassassrt": "Magnifying_Glassassrt",
441
+ "Marc_Anthony_Skip_Professional_Oil_of_Morocco_Conditioner_with_Argan_Oil": "Marc_Anthony_Skip_Professional_Oil_of_Morocco_Conditioner_with_Argan_Oil",
442
+ "Marc_Anthony_Strictly_Curls_Curl_Envy_Perfect_Curl_Cream_6_fl_oz_bottle": "Marc_Anthony_Strictly_Curls_Curl_Envy_Perfect_Curl_Cream_6_fl_oz_bottle",
443
+ "Marc_Anthony_True_Professional_Oil_of_Morocco_Argan_Oil_Treatment": "Marc_Anthony_True_Professional_Oil_of_Morocco_Argan_Oil_Treatment",
444
+ "Marc_Anthony_True_Professional_Strictly_Curls_Curl_Defining_Lotion": "Marc_Anthony_True_Professional_Strictly_Curls_Curl_Defining_Lotion",
445
+ "Mario_Luigi_Dream_Team_Nintendo_3DS_Game": "Mario_Luigi_Dream_Team_Nintendo_3DS_Game",
446
+ "Mario_Party_9_Wii_Game": "Mario_Party_9_Wii_Game",
447
+ "Markings_Desk_Caddy": "Markings_Desk_Caddy",
448
+ "Markings_Letter_Holder": "Markings_Letter_Holder",
449
+ "Marvel_Avengers_Titan_Hero_Series_Doctor_Doom": "Marvel_Avengers_Titan_Hero_Series_Doctor_Doom",
450
+ "Mastic_Gum": "Mastic_Gum",
451
+ "Matte_Black_Tieks_Italian_Leather_Ballet_Flats": "Matte_Black_Tieks_Italian_Leather_Ballet_Flats",
452
+ "Mattel_SKIP_BO_Card_Game": "Mattel_SKIP_BO_Card_Game",
453
+ "Melissa_Doug_Cart_Turtle_Block": "Melissa_Doug_Cart_Turtle_Block",
454
+ "Melissa_Doug_Chunky_Puzzle_Vehicles": "Melissa_Doug_Chunky_Puzzle_Vehicles",
455
+ "Melissa_Doug_Felt_Food_Pizza_Set": "Melissa_Doug_Felt_Food_Pizza_Set",
456
+ "Melissa_Doug_Jumbo_Knob_Puzzles_Barnyard_Animals": "Melissa_Doug_Jumbo_Knob_Puzzles_Barnyard_Animals",
457
+ "Melissa_Doug_Pattern_Blocks_and_Boards": "Melissa_Doug_Pattern_Blocks_and_Boards",
458
+ "Melissa_Doug_Pound_and_Roll": "Melissa_Doug_Pound_and_Roll",
459
+ "Melissa_Doug_See_Spell": "Melissa_Doug_See_Spell",
460
+ "Melissa_Doug_Shape_Sorting_Clock": "Melissa_Doug_Shape_Sorting_Clock",
461
+ "Melissa_Doug_Traffic_Signs_and_Vehicles": "Melissa_Doug_Traffic_Signs_and_Vehicles",
462
+ "Mens_ASV_Billfish_Boat_Shoe_in_Dark_Brown_Leather_zdHVHXueI3w": "Mens_ASV_Billfish_Boat_Shoe_in_Dark_Brown_Leather_zdHVHXueI3w",
463
+ "Mens_ASV_Billfish_Boat_Shoe_in_Tan_Leather_wmUJ5PbwANc": "Mens_ASV_Billfish_Boat_Shoe_in_Tan_Leather_wmUJ5PbwANc",
464
+ "Mens_ASV_Shock_Light_Bungee_in_Light_Grey_xGCOvtLDnQJ": "Mens_ASV_Shock_Light_Bungee_in_Light_Grey_xGCOvtLDnQJ",
465
+ "Mens_Authentic_Original_Boat_Shoe_in_Navy_Leather_NHHQddDLQys": "Mens_Authentic_Original_Boat_Shoe_in_Navy_Leather_NHHQddDLQys",
466
+ "Mens_Authentic_Original_Boat_Shoe_in_Navy_Leather_RpT4GvUXRRP": "Mens_Authentic_Original_Boat_Shoe_in_Navy_Leather_RpT4GvUXRRP",
467
+ "Mens_Authentic_Original_Boat_Shoe_in_Navy_Leather_xgoEcZtRNmH": "Mens_Authentic_Original_Boat_Shoe_in_Navy_Leather_xgoEcZtRNmH",
468
+ "Mens_Bahama_in_Black_b4ADzYywRHl": "Mens_Bahama_in_Black_b4ADzYywRHl",
469
+ "Mens_Bahama_in_Khaki_Oyster_xU2jeqYwhQJ": "Mens_Bahama_in_Khaki_Oyster_xU2jeqYwhQJ",
470
+ "Mens_Bahama_in_White_vSwvGMCo32f": "Mens_Bahama_in_White_vSwvGMCo32f",
471
+ "Mens_Billfish_3Eye_Boat_Shoe_in_Dark_Tan_wyns9HRcEuH": "Mens_Billfish_3Eye_Boat_Shoe_in_Dark_Tan_wyns9HRcEuH",
472
+ "Mens_Billfish_Slip_On_in_Coffee_e8bPKE9Lfgo": "Mens_Billfish_Slip_On_in_Coffee_e8bPKE9Lfgo",
473
+ "Mens_Billfish_Slip_On_in_Coffee_nK6AJJAHOae": "Mens_Billfish_Slip_On_in_Coffee_nK6AJJAHOae",
474
+ "Mens_Billfish_Slip_On_in_Tan_Beige_aaVUk0tNTv8": "Mens_Billfish_Slip_On_in_Tan_Beige_aaVUk0tNTv8",
475
+ "Mens_Billfish_Ultra_Lite_Boat_Shoe_in_Dark_Brown_Blue_c6zDZTtRJr6": "Mens_Billfish_Ultra_Lite_Boat_Shoe_in_Dark_Brown_Blue_c6zDZTtRJr6",
476
+ "Mens_Gold_Cup_ASV_2Eye_Boat_Shoe_in_Cognac_Leather": "Mens_Gold_Cup_ASV_2Eye_Boat_Shoe_in_Cognac_Leather",
477
+ "Mens_Gold_Cup_ASV_Capetown_Penny_Loafer_in_Black_EjPnk3E8fCs": "Mens_Gold_Cup_ASV_Capetown_Penny_Loafer_in_Black_EjPnk3E8fCs",
478
+ "Mens_Gold_Cup_ASV_Capetown_Penny_Loafer_in_Black_GkQBKqABeQN": "Mens_Gold_Cup_ASV_Capetown_Penny_Loafer_in_Black_GkQBKqABeQN",
479
+ "Mens_Gold_Cup_ASV_Dress_Casual_Venetian_in_Dark_Brown_Leather": "Mens_Gold_Cup_ASV_Dress_Casual_Venetian_in_Dark_Brown_Leather",
480
+ "Mens_Largo_Slip_On_in_Taupe_gooyS417q4R": "Mens_Largo_Slip_On_in_Taupe_gooyS417q4R",
481
+ "Mens_Mako_Canoe_Moc_2Eye_Boat_Shoe_in_Coffee_9d05GG33QQQ": "Mens_Mako_Canoe_Moc_2Eye_Boat_Shoe_in_Coffee_9d05GG33QQQ",
482
+ "Mens_Mako_Canoe_Moc_2Eye_Boat_Shoe_in_Coffee_K9e8FoV73uZ": "Mens_Mako_Canoe_Moc_2Eye_Boat_Shoe_in_Coffee_K9e8FoV73uZ",
483
+ "Mens_Mako_Canoe_Moc_2Eye_Boat_Shoe_in_OysterTaupe_otyRrfvPMiA": "Mens_Mako_Canoe_Moc_2Eye_Boat_Shoe_in_OysterTaupe_otyRrfvPMiA",
484
+ "Mens_RR_Moc_in_Navy_Suede_vmFfijhBzL3": "Mens_RR_Moc_in_Navy_Suede_vmFfijhBzL3",
485
+ "Mens_Santa_Cruz_Thong_in_Chocolate_La1fo2mAovE": "Mens_Santa_Cruz_Thong_in_Chocolate_La1fo2mAovE",
486
+ "Mens_Santa_Cruz_Thong_in_Chocolate_lvxYW7lek6B": "Mens_Santa_Cruz_Thong_in_Chocolate_lvxYW7lek6B",
487
+ "Mens_Santa_Cruz_Thong_in_Tan_r59C69daRPh": "Mens_Santa_Cruz_Thong_in_Tan_r59C69daRPh",
488
+ "Mens_Striper_Sneaker_in_White_rnp8HUli59Y": "Mens_Striper_Sneaker_in_White_rnp8HUli59Y",
489
+ "Mens_Tremont_Kiltie_Tassel_Loafer_in_Black_Amaretto": "Mens_Tremont_Kiltie_Tassel_Loafer_in_Black_Amaretto",
490
+ "Mens_Tremont_Kiltie_Tassel_Loafer_in_Black_Amaretto_FT0I9OjSA6O": "Mens_Tremont_Kiltie_Tassel_Loafer_in_Black_Amaretto_FT0I9OjSA6O",
491
+ "Mens_Tremont_Kiltie_Tassel_Loafer_in_Black_Amaretto_rCdzRZqgCnI": "Mens_Tremont_Kiltie_Tassel_Loafer_in_Black_Amaretto_rCdzRZqgCnI",
492
+ "Mens_Wave_Driver_Kiltie_Moc_in_Tan_Leather": "Mens_Wave_Driver_Kiltie_Moc_in_Tan_Leather",
493
+ "Metallic_Gold_Tieks_Italian_Leather_Ballet_Flats": "Metallic_Gold_Tieks_Italian_Leather_Ballet_Flats",
494
+ "Metallic_Pewter_Tieks_Italian_Leather_Ballet_Flats": "Metallic_Pewter_Tieks_Italian_Leather_Ballet_Flats",
495
+ "Mist_Wipe_Warmer": "Mist_Wipe_Warmer",
496
+ "My_First_Animal_Tower": "My_First_Animal_Tower",
497
+ "My_First_Rolling_Lion": "My_First_Rolling_Lion",
498
+ "My_First_Wiggle_Crocodile": "My_First_Wiggle_Crocodile",
499
+ "My_Little_Pony_Princess_Celestia": "My_Little_Pony_Princess_Celestia",
500
+ "My_Monopoly_Board_Game": "My_Monopoly_Board_Game",
501
+ "NAPA_VALLEY_NAVAJO_SANDAL": "NAPA_VALLEY_NAVAJO_SANDAL",
502
+ "NESCAFE_NESCAFE_TC_STKS_DECAF_6_CT": "NESCAFE_NESCAFE_TC_STKS_DECAF_6_CT",
503
+ "NUTS_BOLTS": "NUTS_BOLTS",
504
+ "NattoMax": "NattoMax",
505
+ "Neat_Solutions_Character_Bib_2_pack": "Neat_Solutions_Character_Bib_2_pack",
506
+ "Nescafe_16Count_Dolce_Gusto_Cappuccino_Capsules": "Nescafe_16Count_Dolce_Gusto_Cappuccino_Capsules",
507
+ "Nescafe_Memento_Latte_Caramel_8_08_oz_23_g_packets_64_oz_184_g": "Nescafe_Memento_Latte_Caramel_8_08_oz_23_g_packets_64_oz_184_g",
508
+ "Nescafe_Momento_Mocha_Specialty_Coffee_Mix_8_ct": "Nescafe_Momento_Mocha_Specialty_Coffee_Mix_8_ct",
509
+ "Nescafe_Tasters_Choice_Instant_Coffee_Decaf_House_Blend_Light_7_oz": "Nescafe_Tasters_Choice_Instant_Coffee_Decaf_House_Blend_Light_7_oz",
510
+ "Nestl_Crunch_Girl_Scouts_Cookie_Flavors_Caramel_Coconut_78_oz_box": "Nestl_Crunch_Girl_Scouts_Cookie_Flavors_Caramel_Coconut_78_oz_box",
511
+ "Nestl_Skinny_Cow_Heavenly_Crisp_Candy_Bar_Chocolate_Raspberry_6_pack_462_oz_total": "Nestl_Skinny_Cow_Heavenly_Crisp_Candy_Bar_Chocolate_Raspberry_6_pack_462_oz_total",
512
+ "Nestle_Candy_19_oz_Butterfinger_Singles_116567": "Nestle_Candy_19_oz_Butterfinger_Singles_116567",
513
+ "Nestle_Carnation_Cinnamon_Coffeecake_Kit_1913OZ": "Nestle_Carnation_Cinnamon_Coffeecake_Kit_1913OZ",
514
+ "Nestle_Nesquik_Chocolate_Powder_Flavored_Milk_Additive_109_Oz_Canister": "Nestle_Nesquik_Chocolate_Powder_Flavored_Milk_Additive_109_Oz_Canister",
515
+ "Nestle_Nips_Hard_Candy_Peanut_Butter": "Nestle_Nips_Hard_Candy_Peanut_Butter",
516
+ "Nestle_Pure_Life_Exotics_Sparkling_Water_Strawberry_Dragon_Fruit_8_count_12_fl_oz_can": "Nestle_Pure_Life_Exotics_Sparkling_Water_Strawberry_Dragon_Fruit_8_count_12_fl_oz_can",
517
+ "Nestle_Pure_Life_Exotics_Sparkling_Water_Strawberry_Dragon_Fruit_8_count_12_fl_oz_can_aX0ygjh3bxi": "Nestle_Pure_Life_Exotics_Sparkling_Water_Strawberry_Dragon_Fruit_8_count_12_fl_oz_can_aX0ygjh3bxi",
518
+ "Nestle_Raisinets_Milk_Chocolate_35_oz_992_g": "Nestle_Raisinets_Milk_Chocolate_35_oz_992_g",
519
+ "Nestle_Skinny_Cow_Dreamy_Clusters_Candy_Dark_Chocolate_6_pack_1_oz_pouches": "Nestle_Skinny_Cow_Dreamy_Clusters_Candy_Dark_Chocolate_6_pack_1_oz_pouches",
520
+ "Netgear_Ac1750_Router_Wireless_Dual_Band_Gigabit_Router": "Netgear_Ac1750_Router_Wireless_Dual_Band_Gigabit_Router",
521
+ "Netgear_N750_Wireless_Dual_Band_Gigabit_Router": "Netgear_N750_Wireless_Dual_Band_Gigabit_Router",
522
+ "Netgear_Nighthawk_X6_AC3200_TriBand_Gigabit_Wireless_Router": "Netgear_Nighthawk_X6_AC3200_TriBand_Gigabit_Wireless_Router",
523
+ "New_Super_Mario_BrosWii_Wii_Game": "New_Super_Mario_BrosWii_Wii_Game",
524
+ "Nickelodeon_Teenage_Mutant_Ninja_Turtles_Leonardo": "Nickelodeon_Teenage_Mutant_Ninja_Turtles_Leonardo",
525
+ "Nickelodeon_Teenage_Mutant_Ninja_Turtles_Michelangelo": "Nickelodeon_Teenage_Mutant_Ninja_Turtles_Michelangelo",
526
+ "Nickelodeon_Teenage_Mutant_Ninja_Turtles_Raphael": "Nickelodeon_Teenage_Mutant_Ninja_Turtles_Raphael",
527
+ "Nickelodeon_The_Spongebob_Movie_PopAPart_Spongebob": "Nickelodeon_The_Spongebob_Movie_PopAPart_Spongebob",
528
+ "Nightmare_Before_Christmas_Collectors_Edition_Operation": "Nightmare_Before_Christmas_Collectors_Edition_Operation",
529
+ "Nikon_1_AW1_w11275mm_Lens_Silver": "Nikon_1_AW1_w11275mm_Lens_Silver",
530
+ "Nintendo_2DS_Crimson_Red": "Nintendo_2DS_Crimson_Red",
531
+ "Nintendo_Mario_Action_Figure": "Nintendo_Mario_Action_Figure",
532
+ "Nintendo_Wii_Party_U_with_Controller_Wii_U_Game": "Nintendo_Wii_Party_U_with_Controller_Wii_U_Game",
533
+ "Nintendo_Yoshi_Action_Figure": "Nintendo_Yoshi_Action_Figure",
534
+ "Nips_Hard_Candy_Rich_Creamy_Butter_Rum_4_oz_1133_g": "Nips_Hard_Candy_Rich_Creamy_Butter_Rum_4_oz_1133_g",
535
+ "Nordic_Ware_Original_Bundt_Pan": "Nordic_Ware_Original_Bundt_Pan",
536
+ "Now_Designs_Bowl_Akita_Black": "Now_Designs_Bowl_Akita_Black",
537
+ "Now_Designs_Dish_Towel_Mojave_18_x_28": "Now_Designs_Dish_Towel_Mojave_18_x_28",
538
+ "Now_Designs_Snack_Bags_Bicycle_2_count": "Now_Designs_Snack_Bags_Bicycle_2_count",
539
+ "OVAL_XYLOPHONE": "OVAL_XYLOPHONE",
540
+ "OWL_SORTER": "OWL_SORTER",
541
+ "OXO_Cookie_Spatula": "OXO_Cookie_Spatula",
542
+ "OXO_Soft_Works_Can_Opener_SnapLock": "OXO_Soft_Works_Can_Opener_SnapLock",
543
+ "Object": "Object",
544
+ "Object_REmvBDJStub": "Object_REmvBDJStub",
545
+ "Ocedar_Snap_On_Dust_Pan_And_Brush_1_ct": "Ocedar_Snap_On_Dust_Pan_And_Brush_1_ct",
546
+ "Office_Depot_Canon_CL211XL_Remanufactured_Ink_Cartridge_TriColor": "Office_Depot_Canon_CL211XL_Remanufactured_Ink_Cartridge_TriColor",
547
+ "Office_Depot_Canon_CLI36_Remanufactured_Ink_Cartridge_TriColor": "Office_Depot_Canon_CLI36_Remanufactured_Ink_Cartridge_TriColor",
548
+ "Office_Depot_Canon_CLI_221BK_Ink_Cartridge_Black_2946B001": "Office_Depot_Canon_CLI_221BK_Ink_Cartridge_Black_2946B001",
549
+ "Office_Depot_Canon_CLI_8CMY_Remanufactured_Ink_Cartridges_Color_Cyan_Magenta_Yellow_3_count": "Office_Depot_Canon_CLI_8CMY_Remanufactured_Ink_Cartridges_Color_Cyan_Magenta_Yellow_3_count",
550
+ "Office_Depot_Canon_CLI_8Y_Ink_Cartridge_Yellow_0623B002": "Office_Depot_Canon_CLI_8Y_Ink_Cartridge_Yellow_0623B002",
551
+ "Office_Depot_Canon_CL_41_Remanufactured_Ink_Cartridge_TriColor": "Office_Depot_Canon_CL_41_Remanufactured_Ink_Cartridge_TriColor",
552
+ "Office_Depot_Canon_PG21XL_Remanufactured_Ink_Cartridge_Black": "Office_Depot_Canon_PG21XL_Remanufactured_Ink_Cartridge_Black",
553
+ "Office_Depot_Canon_PGI22_Remanufactured_Ink_Cartridge_Black": "Office_Depot_Canon_PGI22_Remanufactured_Ink_Cartridge_Black",
554
+ "Office_Depot_Canon_PGI35_Remanufactured_Ink_Cartridge_Black": "Office_Depot_Canon_PGI35_Remanufactured_Ink_Cartridge_Black",
555
+ "Office_Depot_Canon_PGI5BK_Remanufactured_Ink_Cartridge_Black": "Office_Depot_Canon_PGI5BK_Remanufactured_Ink_Cartridge_Black",
556
+ "Office_Depot_Canon_PG_240XL_Ink_Cartridge_Black_5206B001": "Office_Depot_Canon_PG_240XL_Ink_Cartridge_Black_5206B001",
557
+ "Office_Depot_Dell_Series_11_Remanufactured_Ink_Cartridge_Black": "Office_Depot_Dell_Series_11_Remanufactured_Ink_Cartridge_Black",
558
+ "Office_Depot_Dell_Series_11_Remanufactured_Ink_Cartridge_TriColor": "Office_Depot_Dell_Series_11_Remanufactured_Ink_Cartridge_TriColor",
559
+ "Office_Depot_Dell_Series_1_Remanufactured_Ink_Cartridge_Black": "Office_Depot_Dell_Series_1_Remanufactured_Ink_Cartridge_Black",
560
+ "Office_Depot_Dell_Series_1_Remanufactured_Ink_Cartridge_TriColor": "Office_Depot_Dell_Series_1_Remanufactured_Ink_Cartridge_TriColor",
561
+ "Office_Depot_Dell_Series_5_Remanufactured_Ink_Cartridge_Black": "Office_Depot_Dell_Series_5_Remanufactured_Ink_Cartridge_Black",
562
+ "Office_Depot_Dell_Series_9_Color_Ink_Ink_Cartridge_MK991_MK993": "Office_Depot_Dell_Series_9_Color_Ink_Ink_Cartridge_MK991_MK993",
563
+ "Office_Depot_Dell_Series_9_Ink_Cartridge_Black_MK992": "Office_Depot_Dell_Series_9_Ink_Cartridge_Black_MK992",
564
+ "Office_Depot_HP_2_Remanufactured_Ink_Cartridges_Color_Cyan_Magenta_Yellow_3_count": "Office_Depot_HP_2_Remanufactured_Ink_Cartridges_Color_Cyan_Magenta_Yellow_3_count",
565
+ "Office_Depot_HP_564XL_Ink_Cartridge_Black_CN684WN": "Office_Depot_HP_564XL_Ink_Cartridge_Black_CN684WN",
566
+ "Office_Depot_HP_564XL_Remanufactured_Ink_Cartridges_Color_Cyan_Magenta_Yellow_3_count": "Office_Depot_HP_564XL_Remanufactured_Ink_Cartridges_Color_Cyan_Magenta_Yellow_3_count",
567
+ "Office_Depot_HP_61Tricolor_Ink_Cartridge": "Office_Depot_HP_61Tricolor_Ink_Cartridge",
568
+ "Office_Depot_HP_71_Remanufactured_Ink_Cartridge_Black": "Office_Depot_HP_71_Remanufactured_Ink_Cartridge_Black",
569
+ "Office_Depot_HP_74XL75_Remanufactured_Ink_Cartridges_BlackTriColor_2_count": "Office_Depot_HP_74XL75_Remanufactured_Ink_Cartridges_BlackTriColor_2_count",
570
+ "Office_Depot_HP_75_Remanufactured_Ink_Cartridge_TriColor": "Office_Depot_HP_75_Remanufactured_Ink_Cartridge_TriColor",
571
+ "Office_Depot_HP_920XL_920_High_Yield_Black_and_Standard_CMY_Color_Ink_Cartridges": "Office_Depot_HP_920XL_920_High_Yield_Black_and_Standard_CMY_Color_Ink_Cartridges",
572
+ "Office_Depot_HP_932XL_Ink_Cartridge_Black_CN053A": "Office_Depot_HP_932XL_Ink_Cartridge_Black_CN053A",
573
+ "Office_Depot_HP_950XL_Ink_Cartridge_Black_CN045AN": "Office_Depot_HP_950XL_Ink_Cartridge_Black_CN045AN",
574
+ "Office_Depot_HP_96_Remanufactured_Ink_Cartridge_Black": "Office_Depot_HP_96_Remanufactured_Ink_Cartridge_Black",
575
+ "Office_Depot_HP_98_Remanufactured_Ink_Cartridge_Black": "Office_Depot_HP_98_Remanufactured_Ink_Cartridge_Black",
576
+ "Olive_Kids_Birdie_Lunch_Box": "Olive_Kids_Birdie_Lunch_Box",
577
+ "Olive_Kids_Birdie_Munch_n_Lunch": "Olive_Kids_Birdie_Munch_n_Lunch",
578
+ "Olive_Kids_Birdie_Pack_n_Snack": "Olive_Kids_Birdie_Pack_n_Snack",
579
+ "Olive_Kids_Birdie_Sidekick_Backpack": "Olive_Kids_Birdie_Sidekick_Backpack",
580
+ "Olive_Kids_Butterfly_Garden_Munch_n_Lunch_Bag": "Olive_Kids_Butterfly_Garden_Munch_n_Lunch_Bag",
581
+ "Olive_Kids_Butterfly_Garden_Pencil_Case": "Olive_Kids_Butterfly_Garden_Pencil_Case",
582
+ "Olive_Kids_Dinosaur_Land_Lunch_Box": "Olive_Kids_Dinosaur_Land_Lunch_Box",
583
+ "Olive_Kids_Dinosaur_Land_Munch_n_Lunch": "Olive_Kids_Dinosaur_Land_Munch_n_Lunch",
584
+ "Olive_Kids_Dinosaur_Land_Pack_n_Snack": "Olive_Kids_Dinosaur_Land_Pack_n_Snack",
585
+ "Olive_Kids_Dinosaur_Land_Sidekick_Backpack": "Olive_Kids_Dinosaur_Land_Sidekick_Backpack",
586
+ "Olive_Kids_Game_On_Lunch_Box": "Olive_Kids_Game_On_Lunch_Box",
587
+ "Olive_Kids_Game_On_Munch_n_Lunch": "Olive_Kids_Game_On_Munch_n_Lunch",
588
+ "Olive_Kids_Game_On_Pack_n_Snack": "Olive_Kids_Game_On_Pack_n_Snack",
589
+ "Olive_Kids_Mermaids_Pack_n_Snack_Backpack": "Olive_Kids_Mermaids_Pack_n_Snack_Backpack",
590
+ "Olive_Kids_Paisley_Pencil_Case": "Olive_Kids_Paisley_Pencil_Case",
591
+ "Olive_Kids_Robots_Pencil_Case": "Olive_Kids_Robots_Pencil_Case",
592
+ "Olive_Kids_Trains_Planes_Trucks_Bogo_Backpack": "Olive_Kids_Trains_Planes_Trucks_Bogo_Backpack",
593
+ "Olive_Kids_Trains_Planes_Trucks_Munch_n_Lunch_Bag": "Olive_Kids_Trains_Planes_Trucks_Munch_n_Lunch_Bag",
594
+ "Orbit_Bubblemint_Mini_Bottle_6_ct": "Orbit_Bubblemint_Mini_Bottle_6_ct",
595
+ "Organic_Whey_Protein_Unflavored": "Organic_Whey_Protein_Unflavored",
596
+ "Organic_Whey_Protein_Vanilla": "Organic_Whey_Protein_Vanilla",
597
+ "Ortho_Forward_Facing": "Ortho_Forward_Facing",
598
+ "Ortho_Forward_Facing_3Q6J2oKJD92": "Ortho_Forward_Facing_3Q6J2oKJD92",
599
+ "Ortho_Forward_Facing_CkAW6rL25xH": "Ortho_Forward_Facing_CkAW6rL25xH",
600
+ "Ortho_Forward_Facing_QCaor9ImJ2G": "Ortho_Forward_Facing_QCaor9ImJ2G",
601
+ "PARENT_ROOM_FURNITURE_SET_1": "PARENT_ROOM_FURNITURE_SET_1",
602
+ "PARENT_ROOM_FURNITURE_SET_1_DLKEy8H4mwK": "PARENT_ROOM_FURNITURE_SET_1_DLKEy8H4mwK",
603
+ "PEEKABOO_ROLLER": "PEEKABOO_ROLLER",
604
+ "PEPSI_NEXT_CACRV": "PEPSI_NEXT_CACRV",
605
+ "PETS_ACCESSORIES": "PETS_ACCESSORIES",
606
+ "PHEEHAN_RUN": "PHEEHAN_RUN",
607
+ "PINEAPPLE_MARACA_6_PCSSET": "PINEAPPLE_MARACA_6_PCSSET",
608
+ "POUNDING_MUSHROOMS": "POUNDING_MUSHROOMS",
609
+ "PUNCH_DROP": "PUNCH_DROP",
610
+ "PUNCH_DROP_TjicLPMqLvz": "PUNCH_DROP_TjicLPMqLvz",
611
+ "Paint_Maker": "Paint_Maker",
612
+ "Paper_Mario_Sticker_Star_Nintendo_3DS_Game": "Paper_Mario_Sticker_Star_Nintendo_3DS_Game",
613
+ "Pass_The_Popcorn_Movie_Guessing_Game": "Pass_The_Popcorn_Movie_Guessing_Game",
614
+ "Paul_Frank_Dot_Lunch_Box": "Paul_Frank_Dot_Lunch_Box",
615
+ "Pennington_Electric_Pot_Cabana_4": "Pennington_Electric_Pot_Cabana_4",
616
+ "Pepsi_Caffeine_Free_Diet_12_CT": "Pepsi_Caffeine_Free_Diet_12_CT",
617
+ "Pepsi_Cola_Caffeine_Free_12_12_fl_oz_355_ml_cans_144_fl_oz_426_lt": "Pepsi_Cola_Caffeine_Free_12_12_fl_oz_355_ml_cans_144_fl_oz_426_lt",
618
+ "Pepsi_Cola_Wild_Cherry_Diet_12_12_fl_oz_355_ml_cans_144_fl_oz_426_lt": "Pepsi_Cola_Wild_Cherry_Diet_12_12_fl_oz_355_ml_cans_144_fl_oz_426_lt",
619
+ "Pepsi_Max_Cola_Zero_Calorie_12_12_fl_oz_355_ml_cans_144_fl_oz_426_lt": "Pepsi_Max_Cola_Zero_Calorie_12_12_fl_oz_355_ml_cans_144_fl_oz_426_lt",
620
+ "Perricoen_MD_No_Concealer_Concealer": "Perricoen_MD_No_Concealer_Concealer",
621
+ "Perricone_MD_AcylGlutathione_Deep_Crease_Serum": "Perricone_MD_AcylGlutathione_Deep_Crease_Serum",
622
+ "Perricone_MD_AcylGlutathione_Eye_Lid_Serum": "Perricone_MD_AcylGlutathione_Eye_Lid_Serum",
623
+ "Perricone_MD_Best_of_Perricone_7Piece_Collection_MEGsO6GIsyL": "Perricone_MD_Best_of_Perricone_7Piece_Collection_MEGsO6GIsyL",
624
+ "Perricone_MD_Blue_Plasma_Orbital": "Perricone_MD_Blue_Plasma_Orbital",
625
+ "Perricone_MD_Chia_Serum": "Perricone_MD_Chia_Serum",
626
+ "Perricone_MD_Cold_Plasma": "Perricone_MD_Cold_Plasma",
627
+ "Perricone_MD_Cold_Plasma_Body": "Perricone_MD_Cold_Plasma_Body",
628
+ "Perricone_MD_Face_Finishing_Moisturizer": "Perricone_MD_Face_Finishing_Moisturizer",
629
+ "Perricone_MD_Face_Finishing_Moisturizer_4_oz": "Perricone_MD_Face_Finishing_Moisturizer_4_oz",
630
+ "Perricone_MD_Firming_Neck_Therapy_Treatment": "Perricone_MD_Firming_Neck_Therapy_Treatment",
631
+ "Perricone_MD_Health_Weight_Management_Supplements": "Perricone_MD_Health_Weight_Management_Supplements",
632
+ "Perricone_MD_High_Potency_Evening_Repair": "Perricone_MD_High_Potency_Evening_Repair",
633
+ "Perricone_MD_Hypoallergenic_Firming_Eye_Cream_05_oz": "Perricone_MD_Hypoallergenic_Firming_Eye_Cream_05_oz",
634
+ "Perricone_MD_Hypoallergenic_Gentle_Cleanser": "Perricone_MD_Hypoallergenic_Gentle_Cleanser",
635
+ "Perricone_MD_Neuropeptide_Facial_Conformer": "Perricone_MD_Neuropeptide_Facial_Conformer",
636
+ "Perricone_MD_Neuropeptide_Firming_Moisturizer": "Perricone_MD_Neuropeptide_Firming_Moisturizer",
637
+ "Perricone_MD_No_Bronzer_Bronzer": "Perricone_MD_No_Bronzer_Bronzer",
638
+ "Perricone_MD_No_Foundation_Foundation_No_1": "Perricone_MD_No_Foundation_Foundation_No_1",
639
+ "Perricone_MD_No_Foundation_Serum": "Perricone_MD_No_Foundation_Serum",
640
+ "Perricone_MD_No_Lipstick_Lipstick": "Perricone_MD_No_Lipstick_Lipstick",
641
+ "Perricone_MD_No_Mascara_Mascara": "Perricone_MD_No_Mascara_Mascara",
642
+ "Perricone_MD_Nutritive_Cleanser": "Perricone_MD_Nutritive_Cleanser",
643
+ "Perricone_MD_OVM": "Perricone_MD_OVM",
644
+ "Perricone_MD_Omega_3_Supplements": "Perricone_MD_Omega_3_Supplements",
645
+ "Perricone_MD_Photo_Plasma": "Perricone_MD_Photo_Plasma",
646
+ "Perricone_MD_Skin_Clear_Supplements": "Perricone_MD_Skin_Clear_Supplements",
647
+ "Perricone_MD_Skin_Total_Body_Supplements": "Perricone_MD_Skin_Total_Body_Supplements",
648
+ "Perricone_MD_Super_Berry_Powder_with_Acai_Supplements": "Perricone_MD_Super_Berry_Powder_with_Acai_Supplements",
649
+ "Perricone_MD_The_Cold_Plasma_Face_Eyes_Duo": "Perricone_MD_The_Cold_Plasma_Face_Eyes_Duo",
650
+ "Perricone_MD_The_Crease_Cure_Duo": "Perricone_MD_The_Crease_Cure_Duo",
651
+ "Perricone_MD_The_Metabolic_Formula_Supplements": "Perricone_MD_The_Metabolic_Formula_Supplements",
652
+ "Perricone_MD_The_Power_Treatments": "Perricone_MD_The_Power_Treatments",
653
+ "Perricone_MD_Vitamin_C_Ester_15": "Perricone_MD_Vitamin_C_Ester_15",
654
+ "Perricone_MD_Vitamin_C_Ester_Serum": "Perricone_MD_Vitamin_C_Ester_Serum",
655
+ "Persona_Q_Shadow_of_the_Labyrinth_Nintendo_3DS": "Persona_Q_Shadow_of_the_Labyrinth_Nintendo_3DS",
656
+ "Pet_Dophilus_powder": "Pet_Dophilus_powder",
657
+ "Philips_60ct_Warm_White_LED_Smooth_Mini_String_Lights": "Philips_60ct_Warm_White_LED_Smooth_Mini_String_Lights",
658
+ "Philips_EcoVantage_43_W_Light_Bulbs_Natural_Light_2_pack": "Philips_EcoVantage_43_W_Light_Bulbs_Natural_Light_2_pack",
659
+ "Philips_Sonicare_Tooth_Brush_2_count": "Philips_Sonicare_Tooth_Brush_2_count",
660
+ "Phillips_Caplets_Size_24": "Phillips_Caplets_Size_24",
661
+ "Phillips_Colon_Health_Probiotic_Capsule": "Phillips_Colon_Health_Probiotic_Capsule",
662
+ "Phillips_Milk_of_Magnesia_Saline_Laxative_Liquid_Original": "Phillips_Milk_of_Magnesia_Saline_Laxative_Liquid_Original",
663
+ "Phillips_Stool_Softener_Liquid_Gels_30_liquid_gels": "Phillips_Stool_Softener_Liquid_Gels_30_liquid_gels",
664
+ "PhosphOmega": "PhosphOmega",
665
+ "Pinwheel_Pencil_Case": "Pinwheel_Pencil_Case",
666
+ "Playmates_Industrial_CoSplinter_Teenage_Mutant_Ninja_Turtle_Action_Figure": "Playmates_Industrial_CoSplinter_Teenage_Mutant_Ninja_Turtle_Action_Figure",
667
+ "Playmates_nickelodeon_teenage_mutant_ninja_turtles_shredder": "Playmates_nickelodeon_teenage_mutant_ninja_turtles_shredder",
668
+ "Poise_Ultimate_Pads_Long": "Poise_Ultimate_Pads_Long",
669
+ "Pokmon_Conquest_Nintendo_DS_Game": "Pokmon_Conquest_Nintendo_DS_Game",
670
+ "Pokmon_X_Nintendo_3DS_Game": "Pokmon_X_Nintendo_3DS_Game",
671
+ "Pokmon_Y_Nintendo_3DS_Game": "Pokmon_Y_Nintendo_3DS_Game",
672
+ "Pok\u00e9mon_Omega_Ruby_Alpha_Sapphire_Dual_Pack_Nintendo_3DS": "Pok\u00e9mon_Omega_Ruby_Alpha_Sapphire_Dual_Pack_Nintendo_3DS",
673
+ "Pok\u00e9mon_Yellow_Special_Pikachu_Edition_Nintendo_Game_Boy_Color": "Pok\u00e9mon_Yellow_Special_Pikachu_Edition_Nintendo_Game_Boy_Color",
674
+ "Polar_Herring_Fillets_Smoked_Peppered_705_oz_total": "Polar_Herring_Fillets_Smoked_Peppered_705_oz_total",
675
+ "Pony_C_Clamp_1440": "Pony_C_Clamp_1440",
676
+ "Poppin_File_Sorter_Blue": "Poppin_File_Sorter_Blue",
677
+ "Poppin_File_Sorter_Pink": "Poppin_File_Sorter_Pink",
678
+ "Poppin_File_Sorter_White": "Poppin_File_Sorter_White",
679
+ "Predator_LZ_TRX_FG": "Predator_LZ_TRX_FG",
680
+ "Predito_LZ_TRX_FG_W": "Predito_LZ_TRX_FG_W",
681
+ "ProSport_Harness_to_Booster_Seat": "ProSport_Harness_to_Booster_Seat",
682
+ "Progressive_Rubber_Spatulas_3_count": "Progressive_Rubber_Spatulas_3_count",
683
+ "Prostate_Optimizer": "Prostate_Optimizer",
684
+ "Provence_Bath_Towel_Royal_Blue": "Provence_Bath_Towel_Royal_Blue",
685
+ "PureCadence_2_Color_HiRskRedNghtlfeSlvrBlckWht_Size_70": "PureCadence_2_Color_HiRskRedNghtlfeSlvrBlckWht_Size_70",
686
+ "PureCadence_2_Color_TleBluLmePnchSlvMoodIndgWh_Size_50_EEzAfcBfHHO": "PureCadence_2_Color_TleBluLmePnchSlvMoodIndgWh_Size_50_EEzAfcBfHHO",
687
+ "PureConnect_2_Color_AnthrcteKnckoutPnkGrnGecko_Size_50": "PureConnect_2_Color_AnthrcteKnckoutPnkGrnGecko_Size_50",
688
+ "PureConnect_2_Color_BlckBrllntBluNghtlfeAnthrct_Size_70": "PureConnect_2_Color_BlckBrllntBluNghtlfeAnthrct_Size_70",
689
+ "PureConnect_2_Color_FernNightlifeSilverBlack_Size_70_5w0BYsiogeV": "PureConnect_2_Color_FernNightlifeSilverBlack_Size_70_5w0BYsiogeV",
690
+ "PureFlow_2_Color_RylPurHibiscusBlkSlvrWht_Size_50": "PureFlow_2_Color_RylPurHibiscusBlkSlvrWht_Size_50",
691
+ "QAbsorb_CoQ10": "QAbsorb_CoQ10",
692
+ "QAbsorb_CoQ10_53iUqjWjW3O": "QAbsorb_CoQ10_53iUqjWjW3O",
693
+ "QHPomegranate": "QHPomegranate",
694
+ "Quercetin_500": "Quercetin_500",
695
+ "REEF_BANTU": "black boot",
696
+ "REEF_BRAIDED_CUSHION": "REEF_BRAIDED_CUSHION",
697
+ "REEF_ZENFUN": "REEF_ZENFUN",
698
+ "RESCUE_CREW": "RESCUE_CREW",
699
+ "RJ_Rabbit_Easter_Basket_Blue": "RJ_Rabbit_Easter_Basket_Blue",
700
+ "ROAD_CONSTRUCTION_SET": "ROAD_CONSTRUCTION_SET",
701
+ "Racoon": "Racoon",
702
+ "Ravenna_4_Color_WhtOlyBluBlkShkOrngSlvRdO_Size_70": "Ravenna_4_Color_WhtOlyBluBlkShkOrngSlvRdO_Size_70",
703
+ "Rayna_BootieWP": "Rayna_BootieWP",
704
+ "Razer_Abyssus_Ambidextrous_Gaming_Mouse": "Razer_Abyssus_Ambidextrous_Gaming_Mouse",
705
+ "Razer_BlackWidow_Stealth_2014_Keyboard_07VFzIVabgh": "black keyboard",
706
+ "Razer_BlackWidow_Ultimate_2014_Mechanical_Gaming_Keyboard": "Razer_BlackWidow_Ultimate_2014_Mechanical_Gaming_Keyboard",
707
+ "Razer_Blackwidow_Tournament_Edition_Keyboard": "Razer_Blackwidow_Tournament_Edition_Keyboard",
708
+ "Razer_Goliathus_Control_Edition_Small_Soft_Gaming_Mouse_Mat": "Razer_Goliathus_Control_Edition_Small_Soft_Gaming_Mouse_Mat",
709
+ "Razer_Kraken_71_Chroma_headset_Full_size_Black": "Razer_Kraken_71_Chroma_headset_Full_size_Black",
710
+ "Razer_Kraken_Pro_headset_Full_size_Black": "Razer_Kraken_Pro_headset_Full_size_Black",
711
+ "Razer_Naga_MMO_Gaming_Mouse": "Razer_Naga_MMO_Gaming_Mouse",
712
+ "Razer_Taipan_Black_Ambidextrous_Gaming_Mouse": "black gaming mouse",
713
+ "Razer_Taipan_White_Ambidextrous_Gaming_Mouse": "white gaming mouse",
714
+ "ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box": "ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box",
715
+ "Real_Deal_1nIwCHX1MTh": "Real_Deal_1nIwCHX1MTh",
716
+ "RedBlack_Nintendo_3DSXL": "black and red gameboy",
717
+ "Reebok_ALLYLYNN": "Reebok_ALLYLYNN",
718
+ "Reebok_BREAKPOINT_LO_2V": "Reebok_BREAKPOINT_LO_2V",
719
+ "Reebok_BREAKPOINT_MID": "Reebok_BREAKPOINT_MID",
720
+ "Reebok_CLASSIC_JOGGER": "Reebok_CLASSIC_JOGGER",
721
+ "Reebok_CLASSIC_LEGACY_II": "Reebok_CLASSIC_LEGACY_II",
722
+ "Reebok_CL_DIBELLO_II": "Reebok_CL_DIBELLO_II",
723
+ "Reebok_CL_LTHR_R12": "Reebok_CL_LTHR_R12",
724
+ "Reebok_CL_RAYEN": "Reebok_CL_RAYEN",
725
+ "Reebok_COMFORT_REEFRESH_FLIP": "Reebok_COMFORT_REEFRESH_FLIP",
726
+ "Reebok_DMX_MAX_MANIA_WD_D": "Reebok_DMX_MAX_MANIA_WD_D",
727
+ "Reebok_DMX_MAX_PLUS_ATHLETIC": "Reebok_DMX_MAX_PLUS_ATHLETIC",
728
+ "Reebok_DMX_MAX_PLUS_RAINWALKER": "Reebok_DMX_MAX_PLUS_RAINWALKER",
729
+ "Reebok_EASYTONE_CL_LEATHER": "Reebok_EASYTONE_CL_LEATHER",
730
+ "Reebok_FS_HI_INT_R12": "Reebok_FS_HI_INT_R12",
731
+ "Reebok_FS_HI_MINI": "Reebok_FS_HI_MINI",
732
+ "Reebok_FUELTRAIN": "Reebok_FUELTRAIN",
733
+ "Reebok_GL_6000": "Reebok_GL_6000",
734
+ "Reebok_HIMARA_LTR": "Reebok_HIMARA_LTR",
735
+ "Reebok_JR_ZIG_COOPERSTOWN_MR": "Reebok_JR_ZIG_COOPERSTOWN_MR",
736
+ "Reebok_KAMIKAZE_II_MID": "Reebok_KAMIKAZE_II_MID",
737
+ "Reebok_PUMP_OMNI_LITE_HLS": "Reebok_PUMP_OMNI_LITE_HLS",
738
+ "Reebok_REALFLEX_SELECT": "Reebok_REALFLEX_SELECT",
739
+ "Reebok_REESCULPT_TRAINER_II": "Reebok_REESCULPT_TRAINER_II",
740
+ "Reebok_RETRO_RUSH_2V": "Reebok_RETRO_RUSH_2V",
741
+ "Reebok_R_CROSSFIT_OLY_UFORM": "Reebok_R_CROSSFIT_OLY_UFORM",
742
+ "Reebok_R_DANCE_FLASH": "Reebok_R_DANCE_FLASH",
743
+ "Reebok_SH_COURT_MID_II": "Reebok_SH_COURT_MID_II",
744
+ "Reebok_SH_NEWPORT_LOW": "Reebok_SH_NEWPORT_LOW",
745
+ "Reebok_SH_PRIME_COURT_LOW": "Reebok_SH_PRIME_COURT_LOW",
746
+ "Reebok_SH_PRIME_COURT_MID": "Reebok_SH_PRIME_COURT_MID",
747
+ "Reebok_SL_FLIP_UPDATE": "Reebok_SL_FLIP_UPDATE",
748
+ "Reebok_SMOOTHFLEX_CUSHRUN_20": "Reebok_SMOOTHFLEX_CUSHRUN_20",
749
+ "Reebok_SOMERSET_RUN": "Reebok_SOMERSET_RUN",
750
+ "Reebok_STUDIO_BEAT_LOW_V": "Reebok_STUDIO_BEAT_LOW_V",
751
+ "Reebok_TRIPLE_BREAK_LITE": "Reebok_TRIPLE_BREAK_LITE",
752
+ "Reebok_TURBO_RC": "Reebok_TURBO_RC",
753
+ "Reebok_ULTIMATIC_2V": "Reebok_ULTIMATIC_2V",
754
+ "Reebok_VERSA_TRAIN": "Reebok_VERSA_TRAIN",
755
+ "Reebok_ZIGCOOPERSTOWN_QUAG": "Reebok_ZIGCOOPERSTOWN_QUAG",
756
+ "Reebok_ZIGLITE_RUSH": "Reebok_ZIGLITE_RUSH",
757
+ "Reebok_ZIGLITE_RUSH_AC": "Reebok_ZIGLITE_RUSH_AC",
758
+ "Reebok_ZIGSTORM": "Reebok_ZIGSTORM",
759
+ "Reebok_ZIGTECH_SHARK_MAYHEM360": "Reebok_ZIGTECH_SHARK_MAYHEM360",
760
+ "Reef_Star_Cushion_Flipflops_Size_8_Black": "Reef_Star_Cushion_Flipflops_Size_8_Black",
761
+ "Remington_1_12_inch_Hair_Straightener": "Remington_1_12_inch_Hair_Straightener",
762
+ "Remington_TStudio_Hair_Dryer": "Remington_TStudio_Hair_Dryer",
763
+ "Remington_TStudio_Silk_Ceramic_Hair_Straightener_2_Inch_Floating_Plates": "Remington_TStudio_Silk_Ceramic_Hair_Straightener_2_Inch_Floating_Plates",
764
+ "Retail_Leadership_Summit": "brown hat",
765
+ "Retail_Leadership_Summit_eCT3zqHYIkX": "Retail_Leadership_Summit_eCT3zqHYIkX",
766
+ "Retail_Leadership_Summit_tQFCizMt6g0": "Retail_Leadership_Summit_tQFCizMt6g0",
767
+ "Rexy_Glove_Heavy_Duty_Gloves_Medium": "blue gloves",
768
+ "Rexy_Glove_Heavy_Duty_Large": "Rexy_Glove_Heavy_Duty_Large",
769
+ "Romantic_Blush_Tieks_Metallic_Italian_Leather_Ballet_Flats": "Romantic_Blush_Tieks_Metallic_Italian_Leather_Ballet_Flats",
770
+ "Room_Essentials_Bowl_Turquiose": "Room_Essentials_Bowl_Turquiose",
771
+ "Room_Essentials_Dish_Drainer_Collapsible_White": "Room_Essentials_Dish_Drainer_Collapsible_White",
772
+ "Room_Essentials_Fabric_Cube_Lavender": "Room_Essentials_Fabric_Cube_Lavender",
773
+ "Room_Essentials_Kitchen_Towels_16_x_26_2_count": "Room_Essentials_Kitchen_Towels_16_x_26_2_count",
774
+ "Room_Essentials_Mug_White_Yellow": "Room_Essentials_Mug_White_Yellow",
775
+ "Room_Essentials_Salad_Plate_Turquoise": "Room_Essentials_Salad_Plate_Turquoise",
776
+ "Rose_Garden_Tieks_Leather_Ballet_Flats_with_Floral_Rosettes": "Rose_Garden_Tieks_Leather_Ballet_Flats_with_Floral_Rosettes",
777
+ "Rubbermaid_Large_Drainer": "Rubbermaid_Large_Drainer",
778
+ "SAMBA_HEMP": "SAMBA_HEMP",
779
+ "SAMOA": "SAMOA",
780
+ "SAMe_200": "SAMe_200",
781
+ "SAMe_200_KX7ZmOw47co": "SAMe_200_KX7ZmOw47co",
782
+ "SANDWICH_MEAL": "SANDWICH_MEAL",
783
+ "SAPPHIRE_R7_260X_OC": "SAPPHIRE_R7_260X_OC",
784
+ "SCHOOL_BUS": "SCHOOL_BUS",
785
+ "SHAPE_MATCHING": "SHAPE_MATCHING",
786
+ "SHAPE_MATCHING_NxacpAY9jDt": "SHAPE_MATCHING_NxacpAY9jDt",
787
+ "SHAPE_SORTER": "SHAPE_SORTER",
788
+ "SIT_N_WALK_PUPPY": "SIT_N_WALK_PUPPY",
789
+ "SLACK_CRUISER": "SLACK_CRUISER",
790
+ "SNAIL_MEASURING_TAPE": "SNAIL_MEASURING_TAPE",
791
+ "SORTING_BUS": "SORTING_BUS",
792
+ "SORTING_TRAIN": "SORTING_TRAIN",
793
+ "SPEED_BOAT": "SPEED_BOAT",
794
+ "STACKING_BEAR": "STACKING_BEAR",
795
+ "STACKING_BEAR_V04KKgGBn2A": "STACKING_BEAR_V04KKgGBn2A",
796
+ "STACKING_RING": "STACKING_RING",
797
+ "STEAK_SET": "STEAK_SET",
798
+ "SUPERSTAR_CLR": "SUPERSTAR_CLR",
799
+ "Saccharomyces_Boulardii_MOS_Value_Size": "Saccharomyces_Boulardii_MOS_Value_Size",
800
+ "Samoa_onepiece": "Samoa_onepiece",
801
+ "Samsung_CLTC406S_Toner_Cartridge_Cyan_1pack": "Samsung_CLTC406S_Toner_Cartridge_Cyan_1pack",
802
+ "Santa_Cruz_Mens": "Santa_Cruz_Mens",
803
+ "Santa_Cruz_Mens_G7kQXK7cIky": "Santa_Cruz_Mens_G7kQXK7cIky",
804
+ "Santa_Cruz_Mens_YmsMDkFf11Z": "Santa_Cruz_Mens_YmsMDkFf11Z",
805
+ "Santa_Cruz_Mens_umxTczr1Ygg": "Santa_Cruz_Mens_umxTczr1Ygg",
806
+ "Santa_Cruz_Mens_vnbiTDDt5xH": "Santa_Cruz_Mens_vnbiTDDt5xH",
807
+ "Sapota_Threshold_4_Ceramic_Round_Planter_Red": "Sapota_Threshold_4_Ceramic_Round_Planter_Red",
808
+ "Schleich_African_Black_Rhino": "Schleich_African_Black_Rhino",
809
+ "Schleich_Allosaurus": "Schleich_Allosaurus",
810
+ "Schleich_Bald_Eagle": "bald eagle toy",
811
+ "Schleich_Hereford_Bull": "brown bull",
812
+ "Schleich_Lion_Action_Figure": "Schleich_Lion_Action_Figure",
813
+ "Schleich_S_Bayala_Unicorn_70432": "Schleich_S_Bayala_Unicorn_70432",
814
+ "Schleich_Spinosaurus_Action_Figure": "Schleich_Spinosaurus_Action_Figure",
815
+ "Schleich_Therizinosaurus_ln9cruulPqc": "Schleich_Therizinosaurus_ln9cruulPqc",
816
+ "Sea_to_Summit_Xl_Bowl": "Sea_to_Summit_Xl_Bowl",
817
+ "Seagate_1TB_Backup_Plus_portable_drive_Blue": "Seagate_1TB_Backup_Plus_portable_drive_Blue",
818
+ "Seagate_1TB_Backup_Plus_portable_drive_Silver": "Seagate_1TB_Backup_Plus_portable_drive_Silver",
819
+ "Seagate_1TB_Backup_Plus_portable_drive_for_Mac": "Seagate_1TB_Backup_Plus_portable_drive_for_Mac",
820
+ "Seagate_1TB_Wireless_Plus_mobile_device_storage": "Seagate_1TB_Wireless_Plus_mobile_device_storage",
821
+ "Seagate_3TB_Central_shared_storage": "Seagate_3TB_Central_shared_storage",
822
+ "Seagate_Archive_HDD_8_TB_Internal_hard_drive_SATA_6Gbs_35_ST8000AS0002": "Seagate_Archive_HDD_8_TB_Internal_hard_drive_SATA_6Gbs_35_ST8000AS0002",
823
+ "Shark": "Shark",
824
+ "Shaxon_100_Molded_Category_6_RJ45RJ45_Shielded_Patch_Cord_White": "Shaxon_100_Molded_Category_6_RJ45RJ45_Shielded_Patch_Cord_White",
825
+ "Shurtape_30_Day_Removal_UV_Delct_15": "Shurtape_30_Day_Removal_UV_Delct_15",
826
+ "Shurtape_Gaffers_Tape_Silver_2_x_60_yd": "Shurtape_Gaffers_Tape_Silver_2_x_60_yd",
827
+ "Shurtape_Tape_Purple_CP28": "Shurtape_Tape_Purple_CP28",
828
+ "Sienna_Brown_Croc_Tieks_Patent_Leather_Crocodile_Print_Ballet_Flats": "Sienna_Brown_Croc_Tieks_Patent_Leather_Crocodile_Print_Ballet_Flats",
829
+ "Simon_Swipe_Game": "Simon_Swipe_Game",
830
+ "Sleep_Optimizer": "Sleep_Optimizer",
831
+ "Smith_Hawken_Woven_BasketTray_Organizer_with_3_Compartments_95_x_9_x_13": "Smith_Hawken_Woven_BasketTray_Organizer_with_3_Compartments_95_x_9_x_13",
832
+ "Snack_Catcher_Snack_Dispenser": "Snack_Catcher_Snack_Dispenser",
833
+ "Sonicare_2_Series_Toothbrush_Plaque_Control": "Sonicare_2_Series_Toothbrush_Plaque_Control",
834
+ "Sonny_School_Bus": "school bus toy",
835
+ "Sony_Acid_Music_Studio": "Sony_Acid_Music_Studio",
836
+ "Sony_Downloadable_Loops": "Sony_Downloadable_Loops",
837
+ "Sootheze_Cold_Therapy_Elephant": "grey elephant toy",
838
+ "Sootheze_Toasty_Orca": "Sootheze_Toasty_Orca",
839
+ "Sorry_Sliders_Board_Game": "Sorry_Sliders_Board_Game",
840
+ "Spectrum_Wall_Mount": "Spectrum_Wall_Mount",
841
+ "Sperry_TopSider_pSUFPWQXPp3": "Sperry_TopSider_pSUFPWQXPp3",
842
+ "Sperry_TopSider_tNB9t6YBUf3": "Sperry_TopSider_tNB9t6YBUf3",
843
+ "SpiderMan_Titan_Hero_12Inch_Action_Figure_5Hnn4mtkFsP": "SpiderMan_Titan_Hero_12Inch_Action_Figure_5Hnn4mtkFsP",
844
+ "SpiderMan_Titan_Hero_12Inch_Action_Figure_oo1qph4wwiW": "SpiderMan_Titan_Hero_12Inch_Action_Figure_oo1qph4wwiW",
845
+ "Spritz_Easter_Basket_Plastic_Teal": "Spritz_Easter_Basket_Plastic_Teal",
846
+ "Squirrel": "Squirrel",
847
+ "Squirt_Strain_Fruit_Basket": "Squirt_Strain_Fruit_Basket",
848
+ "Squirtin_Barnyard_Friends_4pk": "Squirtin_Barnyard_Friends_4pk",
849
+ "Star_Wars_Rogue_Squadron_Nintendo_64": "Star_Wars_Rogue_Squadron_Nintendo_64",
850
+ "Starstruck_Tieks_Glittery_Gold_Italian_Leather_Ballet_Flats": "Starstruck_Tieks_Glittery_Gold_Italian_Leather_Ballet_Flats",
851
+ "Sterilite_Caddy_Blue_Sky_17_58_x_12_58_x_9_14": "Sterilite_Caddy_Blue_Sky_17_58_x_12_58_x_9_14",
852
+ "Super_Mario_3D_World_Deluxe_Set": "Super_Mario_3D_World_Deluxe_Set",
853
+ "Super_Mario_3D_World_Deluxe_Set_yThuvW9vZed": "Super_Mario_3D_World_Deluxe_Set_yThuvW9vZed",
854
+ "Super_Mario_3D_World_Wii_U_Game": "Super_Mario_3D_World_Wii_U_Game",
855
+ "Super_Mario_Kart_Super_Nintendo_Entertainment_System": "Super_Mario_Kart_Super_Nintendo_Entertainment_System",
856
+ "Superman_Battle_of_Smallville": "Superman_Battle_of_Smallville",
857
+ "Supernatural_Ouija_Board_Game": "Supernatural_Ouija_Board_Game",
858
+ "Sushi_Mat": "Sushi_Mat",
859
+ "Swiss_Miss_Hot_Cocoa_KCups_Milk_Chocolate_12_count": "Swiss_Miss_Hot_Cocoa_KCups_Milk_Chocolate_12_count",
860
+ "TABLEWARE_SET": "TABLEWARE_SET",
861
+ "TABLEWARE_SET_5CHkPjjxVpp": "TABLEWARE_SET_5CHkPjjxVpp",
862
+ "TABLEWARE_SET_5ww1UFLuCJG": "TABLEWARE_SET_5ww1UFLuCJG",
863
+ "TEA_SET": "TEA_SET",
864
+ "TERREX_FAST_R": "TERREX_FAST_R",
865
+ "TERREX_FAST_X_GTX": "TERREX_FAST_X_GTX",
866
+ "TOOL_BELT": "TOOL_BELT",
867
+ "TOP_TEN_HI": "TOP_TEN_HI",
868
+ "TOP_TEN_HI_60KlbRbdoJA": "TOP_TEN_HI_60KlbRbdoJA",
869
+ "TOWER_TUMBLING": "TOWER_TUMBLING",
870
+ "TROCHILUS_BOOST": "TROCHILUS_BOOST",
871
+ "TURBOPROP_AIRPLANE_WITH_PILOT": "TURBOPROP_AIRPLANE_WITH_PILOT",
872
+ "TWISTED_PUZZLE": "TWISTED_PUZZLE",
873
+ "TWISTED_PUZZLE_twb4AyFtu8Q": "TWISTED_PUZZLE_twb4AyFtu8Q",
874
+ "TWIST_SHAPE": "TWIST_SHAPE",
875
+ "TZX_Runner": "TZX_Runner",
876
+ "Tag_Dishtowel_18_x_26": "Tag_Dishtowel_18_x_26",
877
+ "Tag_Dishtowel_Basket_Weave_Red_18_x_26": "Tag_Dishtowel_Basket_Weave_Red_18_x_26",
878
+ "Tag_Dishtowel_Dobby_Stripe_Blue_18_x_26": "Tag_Dishtowel_Dobby_Stripe_Blue_18_x_26",
879
+ "Tag_Dishtowel_Green": "Tag_Dishtowel_Green",
880
+ "Tag_Dishtowel_Waffle_Gray_Checks_18_x_26": "Tag_Dishtowel_Waffle_Gray_Checks_18_x_26",
881
+ "Target_Basket_Medium": "Target_Basket_Medium",
882
+ "Teenage_Mutant_Ninja_Turtles_Rahzar_Action_Figure": "Teenage_Mutant_Ninja_Turtles_Rahzar_Action_Figure",
883
+ "Tena_Pads_Heavy_Long_42_pads": "Tena_Pads_Heavy_Long_42_pads",
884
+ "Tetris_Link_Game": "Tetris_Link_Game",
885
+ "The_Coffee_Bean_Tea_Leaf_KCup_Packs_Jasmine_Green_Tea_16_count": "The_Coffee_Bean_Tea_Leaf_KCup_Packs_Jasmine_Green_Tea_16_count",
886
+ "The_Scooper_Hooper": "The_Scooper_Hooper",
887
+ "Theanine": "Theanine",
888
+ "Thomas_Friends_Woodan_Railway_Henry": "Thomas_Friends_Woodan_Railway_Henry",
889
+ "Thomas_Friends_Wooden_Railway_Ascending_Track_Riser_Pack": "Thomas_Friends_Wooden_Railway_Ascending_Track_Riser_Pack",
890
+ "Thomas_Friends_Wooden_Railway_Deluxe_Track_Accessory_Pack": "Thomas_Friends_Wooden_Railway_Deluxe_Track_Accessory_Pack",
891
+ "Thomas_Friends_Wooden_Railway_Porter_5JzRhMm3a9o": "Thomas_Friends_Wooden_Railway_Porter_5JzRhMm3a9o",
892
+ "Thomas_Friends_Wooden_Railway_Talking_Thomas_z7yi7UFHJRj": "Thomas_Friends_Wooden_Railway_Talking_Thomas_z7yi7UFHJRj",
893
+ "Threshold_Bamboo_Ceramic_Soap_Dish": "Threshold_Bamboo_Ceramic_Soap_Dish",
894
+ "Threshold_Basket_Natural_Finish_Fabric_Liner_Small": "fabric basket",
895
+ "Threshold_Bead_Cereal_Bowl_White": "Threshold_Bead_Cereal_Bowl_White",
896
+ "Threshold_Bistro_Ceramic_Dinner_Plate_Ruby_Ring": "Threshold_Bistro_Ceramic_Dinner_Plate_Ruby_Ring",
897
+ "Threshold_Dinner_Plate_Square_Rim_White_Porcelain": "Threshold_Dinner_Plate_Square_Rim_White_Porcelain",
898
+ "Threshold_Hand_Towel_Blue_Medallion_16_x_27": "Threshold_Hand_Towel_Blue_Medallion_16_x_27",
899
+ "Threshold_Performance_Bath_Sheet_Sandoval_Blue_33_x_63": "Threshold_Performance_Bath_Sheet_Sandoval_Blue_33_x_63",
900
+ "Threshold_Porcelain_Coffee_Mug_All_Over_Bead_White": "Threshold_Porcelain_Coffee_Mug_All_Over_Bead_White",
901
+ "Threshold_Porcelain_Pitcher_White": "Threshold_Porcelain_Pitcher_White",
902
+ "Threshold_Porcelain_Serving_Bowl_Coupe_White": "Threshold_Porcelain_Serving_Bowl_Coupe_White",
903
+ "Threshold_Porcelain_Spoon_Rest_White": "Threshold_Porcelain_Spoon_Rest_White",
904
+ "Threshold_Porcelain_Teapot_White": "white porcelain teapot",
905
+ "Threshold_Ramekin_White_Porcelain": "Threshold_Ramekin_White_Porcelain",
906
+ "Threshold_Salad_Plate_Square_Rim_Porcelain": "Threshold_Salad_Plate_Square_Rim_Porcelain",
907
+ "Threshold_Textured_Damask_Bath_Towel_Pink": "pink damask bath towel",
908
+ "Threshold_Tray_Rectangle_Porcelain": "Threshold_Tray_Rectangle_Porcelain",
909
+ "Tiek_Blue_Patent_Tieks_Italian_Leather_Ballet_Flats": "Tiek_Blue_Patent_Tieks_Italian_Leather_Ballet_Flats",
910
+ "Tieks_Ballet_Flats_Diamond_White_Croc": "Tieks_Ballet_Flats_Diamond_White_Croc",
911
+ "Tieks_Ballet_Flats_Electric_Snake": "Tieks_Ballet_Flats_Electric_Snake",
912
+ "Timberland_Mens_Classic_2Eye_Boat_Shoe": "Timberland_Mens_Classic_2Eye_Boat_Shoe",
913
+ "Timberland_Mens_Earthkeepers_Casco_Bay_Canvas_Oxford": "Timberland_Mens_Earthkeepers_Casco_Bay_Canvas_Oxford",
914
+ "Timberland_Mens_Earthkeepers_Casco_Bay_Canvas_SlipOn": "Timberland_Mens_Earthkeepers_Casco_Bay_Canvas_SlipOn",
915
+ "Timberland_Mens_Earthkeepers_Casco_Bay_Suede_1Eye": "Timberland_Mens_Earthkeepers_Casco_Bay_Suede_1Eye",
916
+ "Timberland_Mens_Earthkeepers_Heritage_2Eye_Boat_Shoe": "Timberland_Mens_Earthkeepers_Heritage_2Eye_Boat_Shoe",
917
+ "Timberland_Mens_Earthkeepers_Newmarket_6Inch_Cupsole_Boot": "Timberland_Mens_Earthkeepers_Newmarket_6Inch_Cupsole_Boot",
918
+ "Timberland_Mens_Earthkeepers_Stormbuck_Chukka": "Timberland_Mens_Earthkeepers_Stormbuck_Chukka",
919
+ "Timberland_Mens_Earthkeepers_Stormbuck_Lite_Plain_Toe_Oxford": "Timberland_Mens_Earthkeepers_Stormbuck_Lite_Plain_Toe_Oxford",
920
+ "Timberland_Mens_Earthkeepers_Stormbuck_Plain_Toe_Oxford": "Timberland_Mens_Earthkeepers_Stormbuck_Plain_Toe_Oxford",
921
+ "Timberland_Womens_Classic_Amherst_2Eye_Boat_Shoe": "Timberland_Womens_Classic_Amherst_2Eye_Boat_Shoe",
922
+ "Timberland_Womens_Earthkeepers_Classic_Unlined_Boat_Shoe": "Timberland_Womens_Earthkeepers_Classic_Unlined_Boat_Shoe",
923
+ "Timberland_Womens_Waterproof_Nellie_Chukka_Double": "Timberland_Womens_Waterproof_Nellie_Chukka_Double",
924
+ "Top_Paw_Dog_Bow_Bone_Ceramic_13_fl_oz_total": "Top_Paw_Dog_Bow_Bone_Ceramic_13_fl_oz_total",
925
+ "Top_Paw_Dog_Bowl_Blue_Paw_Bone_Ceramic_25_fl_oz_total": "Top_Paw_Dog_Bowl_Blue_Paw_Bone_Ceramic_25_fl_oz_total",
926
+ "Tory_Burch_Kaitlin_Ballet_Mestico_in_BlackGold": "Tory_Burch_Kaitlin_Ballet_Mestico_in_BlackGold",
927
+ "Tory_Burch_Kiernan_Riding_Boot": "Tory_Burch_Kiernan_Riding_Boot",
928
+ "Tory_Burch_Reva_Metal_Logo_Litus_Snake_Print_in_dark_BranchGold": "Tory_Burch_Reva_Metal_Logo_Litus_Snake_Print_in_dark_BranchGold",
929
+ "Tory_Burch_Sabe_65mm_Bootie_Split_Suede_in_Caramel": "Tory_Burch_Sabe_65mm_Bootie_Split_Suede_in_Caramel",
930
+ "Toys_R_Us_Treat_Dispenser_Smart_Puzzle_Foobler": "Toys_R_Us_Treat_Dispenser_Smart_Puzzle_Foobler",
931
+ "Toysmith_Windem_Up_Flippin_Animals_Dog": "white animal dog toy",
932
+ "Transformers_Age_of_Extinction_Mega_1Step_Bumblebee_Figure": "Transformers_Age_of_Extinction_Mega_1Step_Bumblebee_Figure",
933
+ "Transformers_Age_of_Extinction_Stomp_and_Chomp_Grimlock_Figure": "Transformers_Age_of_Extinction_Stomp_and_Chomp_Grimlock_Figure",
934
+ "Travel_Mate_P_series_Notebook": "black laptop",
935
+ "Travel_Smart_Neck_Rest_Inflatable": "Travel_Smart_Neck_Rest_Inflatable",
936
+ "TriStar_Products_PPC_Power_Pressure_Cooker_XL_in_Black": "black power pressure cooker",
937
+ "Tune_Belt_Sport_Armband_For_Samsung_Galaxy_S3": "Tune_Belt_Sport_Armband_For_Samsung_Galaxy_S3",
938
+ "Twinlab_100_Whey_Protein_Fuel_Chocolate": "Twinlab_100_Whey_Protein_Fuel_Chocolate",
939
+ "Twinlab_100_Whey_Protein_Fuel_Cookies_and_Cream": "Twinlab_100_Whey_Protein_Fuel_Cookies_and_Cream",
940
+ "Twinlab_100_Whey_Protein_Fuel_Vanilla": "Twinlab_100_Whey_Protein_Fuel_Vanilla",
941
+ "Twinlab_Nitric_Fuel": "Twinlab_Nitric_Fuel",
942
+ "Twinlab_Premium_Creatine_Fuel_Powder": "Twinlab_Premium_Creatine_Fuel_Powder",
943
+ "UGG_Bailey_Bow_Womens_Clogs_Black_7": "UGG_Bailey_Bow_Womens_Clogs_Black_7",
944
+ "UGG_Bailey_Button_Triplet_Womens_Boots_Black_7": "UGG_Bailey_Button_Triplet_Womens_Boots_Black_7",
945
+ "UGG_Bailey_Button_Womens_Boots_Black_7": "UGG_Bailey_Button_Womens_Boots_Black_7",
946
+ "UGG_Cambridge_Womens_Black_7": "UGG_Cambridge_Womens_Black_7",
947
+ "UGG_Classic_Tall_Womens_Boots_Chestnut_7": "UGG_Classic_Tall_Womens_Boots_Chestnut_7",
948
+ "UGG_Classic_Tall_Womens_Boots_Grey_7": "UGG_Classic_Tall_Womens_Boots_Grey_7",
949
+ "UGG_Jena_Womens_Java_7": "UGG_Jena_Womens_Java_7",
950
+ "US_Army_Stash_Lunch_Bag": "US_Army_Stash_Lunch_Bag",
951
+ "U_By_Kotex_Cleanwear_Heavy_Flow_Pads_32_Ct": "U_By_Kotex_Cleanwear_Heavy_Flow_Pads_32_Ct",
952
+ "U_By_Kotex_Sleek_Regular_Unscented_Tampons_36_Ct_Box": "U_By_Kotex_Sleek_Regular_Unscented_Tampons_36_Ct_Box",
953
+ "Ubisoft_RockSmith_Real_Tone_Cable_Xbox_360": "Ubisoft_RockSmith_Real_Tone_Cable_Xbox_360",
954
+ "Ultra_JarroDophilus": "Ultra_JarroDophilus",
955
+ "Unmellow_Yellow_Tieks_Neon_Patent_Leather_Ballet_Flats": "Unmellow_Yellow_Tieks_Neon_Patent_Leather_Ballet_Flats",
956
+ "Utana_5_Porcelain_Ramekin_Large": "white ramekin porcelain",
957
+ "VANS_FIRE_ROASTED_VEGGIE_CRACKERS_GLUTEN_FREE": "VANS_FIRE_ROASTED_VEGGIE_CRACKERS_GLUTEN_FREE",
958
+ "VEGETABLE_GARDEN": "VEGETABLE_GARDEN",
959
+ "Vans_Cereal_Honey_Nut_Crunch_11_oz_box": "Vans_Cereal_Honey_Nut_Crunch_11_oz_box",
960
+ "Victor_Reversible_Bookend": "Victor_Reversible_Bookend",
961
+ "Vtech_Cruise_Learn_Car_25_Years": "Vtech_Cruise_Learn_Car_25_Years",
962
+ "Vtech_Roll_Learn_Turtle": "green turtle toy",
963
+ "Vtech_Stack_Sing_Rings_636_Months": "Vtech_Stack_Sing_Rings_636_Months",
964
+ "WATER_LANDING_NET": "WATER_LANDING_NET",
965
+ "WHALE_WHISTLE_6PCS_SET": "WHALE_WHISTLE_6PCS_SET",
966
+ "W_Lou_z0dkC78niiZ": "W_Lou_z0dkC78niiZ",
967
+ "Weisshai_Great_White_Shark": "great white shark model",
968
+ "Weston_No_22_Cajun_Jerky_Tonic_12_fl_oz_nLj64ZnGwDh": "Weston_No_22_Cajun_Jerky_Tonic_12_fl_oz_nLj64ZnGwDh",
969
+ "Weston_No_33_Signature_Sausage_Tonic_12_fl_oz": "Weston_No_33_Signature_Sausage_Tonic_12_fl_oz",
970
+ "Whey_Protein_3_Flavor_Variety_Pack_12_Packets": "Whey_Protein_3_Flavor_Variety_Pack_12_Packets",
971
+ "Whey_Protein_Chocolate_12_Packets": "Whey_Protein_Chocolate_12_Packets",
972
+ "Whey_Protein_Vanilla": "Whey_Protein_Vanilla",
973
+ "Whey_Protein_Vanilla_12_Packets": "Whey_Protein_Vanilla_12_Packets",
974
+ "White_Rose_Tieks_Leather_Ballet_Flats_with_Floral_Rosettes": "White_Rose_Tieks_Leather_Ballet_Flats_with_Floral_Rosettes",
975
+ "Wild_Copper_Tieks_Metallic_Italian_Leather_Ballet_Flats": "Wild_Copper_Tieks_Metallic_Italian_Leather_Ballet_Flats",
976
+ "Wilton_Easy_Layers_Cake_Pan_Set": "Wilton_Easy_Layers_Cake_Pan_Set",
977
+ "Wilton_Pearlized_Sugar_Sprinkles_525_oz_Gold": "Wilton_Pearlized_Sugar_Sprinkles_525_oz_Gold",
978
+ "Wilton_PreCut_Parchment_Sheets_10_x_15_24_sheets": "Wilton_PreCut_Parchment_Sheets_10_x_15_24_sheets",
979
+ "Winning_Moves_1180_Aggravation_Board_Game": "Winning_Moves_1180_Aggravation_Board_Game",
980
+ "Wishbone_Pencil_Case": "Wishbone_Pencil_Case",
981
+ "Womens_Angelfish_Boat_Shoe_in_Linen_Leopard_Sequin_NJDwosWNeZz": "Womens_Angelfish_Boat_Shoe_in_Linen_Leopard_Sequin_NJDwosWNeZz",
982
+ "Womens_Angelfish_Boat_Shoe_in_Linen_Oat": "Womens_Angelfish_Boat_Shoe_in_Linen_Oat",
983
+ "Womens_Audrey_Slip_On_Boat_Shoe_in_Graphite_Nubuck_xWVkCJ5vxZe": "Womens_Audrey_Slip_On_Boat_Shoe_in_Graphite_Nubuck_xWVkCJ5vxZe",
984
+ "Womens_Authentic_Original_Boat_Shoe_in_Classic_Brown_Leather": "Womens_Authentic_Original_Boat_Shoe_in_Classic_Brown_Leather",
985
+ "Womens_Authentic_Original_Boat_Shoe_in_Classic_Brown_Leather_48Nh7VuMwW6": "Womens_Authentic_Original_Boat_Shoe_in_Classic_Brown_Leather_48Nh7VuMwW6",
986
+ "Womens_Authentic_Original_Boat_Shoe_in_Classic_Brown_Leather_cJSCWiH7QmB": "Womens_Authentic_Original_Boat_Shoe_in_Classic_Brown_Leather_cJSCWiH7QmB",
987
+ "Womens_Authentic_Original_Boat_Shoe_in_Navy_Deerskin_50lWJaLWG8R": "Womens_Authentic_Original_Boat_Shoe_in_Navy_Deerskin_50lWJaLWG8R",
988
+ "Womens_Betty_Chukka_Boot_in_Grey_Jersey_Sequin": "Womens_Betty_Chukka_Boot_in_Grey_Jersey_Sequin",
989
+ "Womens_Betty_Chukka_Boot_in_Navy_Jersey_Sequin_y0SsHk7dKUX": "Womens_Betty_Chukka_Boot_in_Navy_Jersey_Sequin_y0SsHk7dKUX",
990
+ "Womens_Betty_Chukka_Boot_in_Navy_aEE8OqvMII4": "Womens_Betty_Chukka_Boot_in_Navy_aEE8OqvMII4",
991
+ "Womens_Betty_Chukka_Boot_in_Salt_Washed_Red_AL2YrOt9CRy": "Womens_Betty_Chukka_Boot_in_Salt_Washed_Red_AL2YrOt9CRy",
992
+ "Womens_Bluefish_2Eye_Boat_Shoe_in_Brown_Deerskin_JJ2pfEHTZG7": "Womens_Bluefish_2Eye_Boat_Shoe_in_Brown_Deerskin_JJ2pfEHTZG7",
993
+ "Womens_Bluefish_2Eye_Boat_Shoe_in_Brown_Deerskin_i1TgjjO0AKY": "Womens_Bluefish_2Eye_Boat_Shoe_in_Brown_Deerskin_i1TgjjO0AKY",
994
+ "Womens_Bluefish_2Eye_Boat_Shoe_in_Linen_Natural_Sparkle_Suede_kqi81aojcOR": "Womens_Bluefish_2Eye_Boat_Shoe_in_Linen_Natural_Sparkle_Suede_kqi81aojcOR",
995
+ "Womens_Bluefish_2Eye_Boat_Shoe_in_Linen_Natural_Sparkle_Suede_w34KNQ41csH": "Womens_Bluefish_2Eye_Boat_Shoe_in_Linen_Natural_Sparkle_Suede_w34KNQ41csH",
996
+ "Womens_Bluefish_2Eye_Boat_Shoe_in_Linen_Oat": "Womens_Bluefish_2Eye_Boat_Shoe_in_Linen_Oat",
997
+ "Womens_Bluefish_2Eye_Boat_Shoe_in_Linen_Oat_IbrSyJdpT3h": "Womens_Bluefish_2Eye_Boat_Shoe_in_Linen_Oat_IbrSyJdpT3h",
998
+ "Womens_Bluefish_2Eye_Boat_Shoe_in_Linen_Oat_niKJKeWsmxY": "Womens_Bluefish_2Eye_Boat_Shoe_in_Linen_Oat_niKJKeWsmxY",
999
+ "Womens_Bluefish_2Eye_Boat_Shoe_in_Tan": "Womens_Bluefish_2Eye_Boat_Shoe_in_Tan",
1000
+ "Womens_Bluefish_2Eye_Boat_Shoe_in_White_Tumbled_YG44xIePRHw": "Womens_Bluefish_2Eye_Boat_Shoe_in_White_Tumbled_YG44xIePRHw",
1001
+ "Womens_Canvas_Bahama_in_Black": "Womens_Canvas_Bahama_in_Black",
1002
+ "Womens_Canvas_Bahama_in_Black_vnJULsDVyq5": "Womens_Canvas_Bahama_in_Black_vnJULsDVyq5",
1003
+ "Womens_Canvas_Bahama_in_White_4UyOhP6rYGO": "white canvas shoe",
1004
+ "Womens_Canvas_Bahama_in_White_UfZPHGQpvz0": "Womens_Canvas_Bahama_in_White_UfZPHGQpvz0",
1005
+ "Womens_Cloud_Logo_Authentic_Original_Boat_Shoe_in_Black_Supersoft_8LigQYwf4gr": "Womens_Cloud_Logo_Authentic_Original_Boat_Shoe_in_Black_Supersoft_8LigQYwf4gr",
1006
+ "Womens_Cloud_Logo_Authentic_Original_Boat_Shoe_in_Black_Supersoft_cZR022qFI4k": "Womens_Cloud_Logo_Authentic_Original_Boat_Shoe_in_Black_Supersoft_cZR022qFI4k",
1007
+ "Womens_Hikerfish_Boot_in_Black_Leopard_bVSNY1Le1sm": "Womens_Hikerfish_Boot_in_Black_Leopard_bVSNY1Le1sm",
1008
+ "Womens_Hikerfish_Boot_in_Black_Leopard_ridcCWsv8rW": "Womens_Hikerfish_Boot_in_Black_Leopard_ridcCWsv8rW",
1009
+ "Womens_Hikerfish_Boot_in_Linen_Leather_Sparkle_Suede_QktIyAkonrU": "Womens_Hikerfish_Boot_in_Linen_Leather_Sparkle_Suede_QktIyAkonrU",
1010
+ "Womens_Hikerfish_Boot_in_Linen_Leather_Sparkle_Suede_imlP8VkwqIH": "Womens_Hikerfish_Boot_in_Linen_Leather_Sparkle_Suede_imlP8VkwqIH",
1011
+ "Womens_Multi_13": "Womens_Multi_13",
1012
+ "Womens_Sequin_Bahama_in_White_Sequin_V9K1hf24Oxe": "Womens_Sequin_Bahama_in_White_Sequin_V9K1hf24Oxe",
1013
+ "Womens_Sequin_Bahama_in_White_Sequin_XoR8xTlxj1g": "Womens_Sequin_Bahama_in_White_Sequin_XoR8xTlxj1g",
1014
+ "Womens_Sequin_Bahama_in_White_Sequin_yGVsSA4tOwJ": "Womens_Sequin_Bahama_in_White_Sequin_yGVsSA4tOwJ",
1015
+ "Womens_Sparkle_Suede_Angelfish_in_Grey_Sparkle_Suede_Silver": "Womens_Sparkle_Suede_Angelfish_in_Grey_Sparkle_Suede_Silver",
1016
+ "Womens_Sparkle_Suede_Bahama_in_Silver_Sparkle_Suede_Grey_Patent_tYrIBLMhSTN": "Womens_Sparkle_Suede_Bahama_in_Silver_Sparkle_Suede_Grey_Patent_tYrIBLMhSTN",
1017
+ "Womens_Sparkle_Suede_Bahama_in_Silver_Sparkle_Suede_Grey_Patent_x9rclU7EJXx": "Womens_Sparkle_Suede_Bahama_in_Silver_Sparkle_Suede_Grey_Patent_x9rclU7EJXx",
1018
+ "Womens_Suede_Bahama_in_Graphite_Suede_cUAjIMhWSO9": "Womens_Suede_Bahama_in_Graphite_Suede_cUAjIMhWSO9",
1019
+ "Womens_Suede_Bahama_in_Graphite_Suede_p1KUwoWbw7R": "Womens_Suede_Bahama_in_Graphite_Suede_p1KUwoWbw7R",
1020
+ "Womens_Suede_Bahama_in_Graphite_Suede_t22AJSRjBOX": "Womens_Suede_Bahama_in_Graphite_Suede_t22AJSRjBOX",
1021
+ "Womens_Teva_Capistrano_Bootie": "Womens_Teva_Capistrano_Bootie",
1022
+ "Womens_Teva_Capistrano_Bootie_ldjRT9yZ5Ht": "Womens_Teva_Capistrano_Bootie_ldjRT9yZ5Ht",
1023
+ "Wooden_ABC_123_Blocks_50_pack": "Wooden_ABC_123_Blocks_50_pack",
1024
+ "Wrigley_Orbit_Mint_Variety_18_Count": "Wrigley_Orbit_Mint_Variety_18_Count",
1025
+ "Xyli_Pure_Xylitol": "Xyli_Pure_Xylitol",
1026
+ "YumYum_D3_Liquid": "YumYum_D3_Liquid",
1027
+ "ZX700_lYiwcTIekXk": "ZX700_lYiwcTIekXk",
1028
+ "ZX700_mf9Pc06uL06": "ZX700_mf9Pc06uL06",
1029
+ "ZX700_mzGbdP3u6JB": "ZX700_mzGbdP3u6JB",
1030
+ "ZigKick_Hoops": "ZigKick_Hoops",
1031
+ "adiZero_Slide_2_SC": "adiZero_Slide_2_SC",
1032
+ "adistar_boost_m": "black sneaker",
1033
+ "adizero_5Tool_25": "adizero_5Tool_25",
1034
+ "adizero_F50_TRX_FG_LEA": "adizero_F50_TRX_FG_LEA"
1035
+ }
eq-kubric/3d_data/GSO_dict_filtered.json ADDED
@@ -0,0 +1,583 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "purple-white lamp": [
3
+ "3D_Dollhouse_Lamp"
4
+ ],
5
+ "green wooden refrigerator": [
6
+ "3D_Dollhouse_Refrigerator"
7
+ ],
8
+ "purple wooden sofa": [
9
+ "3D_Dollhouse_Sofa"
10
+ ],
11
+ "purple wooden table": [
12
+ "3D_Dollhouse_TablePurple"
13
+ ],
14
+ "light-gray tape": [
15
+ "3M_Antislip_Surfacing_Light_Duty_White"
16
+ ],
17
+ "green tape": [
18
+ "3M_Vinyl_Tape_Green_1_x_36_yd"
19
+ ],
20
+ "green shiny bowl": [
21
+ "45oz_RAMEKIN_ASST_DEEP_COLORS"
22
+ ],
23
+ "blue medicine bottle": [
24
+ "5_HTP"
25
+ ],
26
+ "red coffee mug": [
27
+ "ACE_Coffee_Mug_Kristen_16_oz_cup"
28
+ ],
29
+ "blue sneakers": [
30
+ "AMBERLIGHT_UP_W"
31
+ ],
32
+ "white-black shoes": [
33
+ "ASICS_GEL1140V_WhiteBlackSilver",
34
+ "ASICS_GEL1140V_WhiteRoyalSilver"
35
+ ],
36
+ "white-pink shoes": [
37
+ "ASICS_GELAce_Pro_Pearl_WhitePink"
38
+ ],
39
+ "black-orange shoes": [
40
+ "ASICS_GELBlur33_20_GS_BlackWhiteSafety_Orange"
41
+ ],
42
+ "yellow-orange shoes": [
43
+ "ASICS_GELBlur33_20_GS_Flash_YellowHot_PunchSilver"
44
+ ],
45
+ "blue-white shoes": [
46
+ "ASICS_GELChallenger_9_Royal_BlueWhiteBlack"
47
+ ],
48
+ "red toy airplane": [
49
+ "Air_Hogs_Wind_Flyers_Set_Airplane_Red"
50
+ ],
51
+ "yellow medicine bottle": [
52
+ "AllergenFree_JarroDophilus"
53
+ ],
54
+ "silver android figure": [
55
+ "Android_Figure_Chrome"
56
+ ],
57
+ "orange android figure": [
58
+ "Android_Figure_Orange"
59
+ ],
60
+ "green-yellow boardgame": [
61
+ "Apples_to_Apples_Kids_Edition"
62
+ ],
63
+ "steel milk frother": [
64
+ "Aroma_Stainless_Steel_Milk_Frother_2_Cup"
65
+ ],
66
+ "green hulk toy fists": [
67
+ "Avengers_Gamma_Green_Smash_Fists"
68
+ ],
69
+ "white porcelain utensil holder": [
70
+ "BIA_Cordon_Bleu_White_Porcelain_Utensil_Holder_900028"
71
+ ],
72
+ "white porcelain ramekin": [
73
+ "BIA_Porcelain_Ramekin_With_Glazed_Rim_35_45_oz_cup",
74
+ "Threshold_Ramekin_White_Porcelain",
75
+ "Utana_5_Porcelain_Ramekin_Large"
76
+ ],
77
+ "stack of colorful cups": [
78
+ "Baby_Elements_Stacking_Cups"
79
+ ],
80
+ "black DVD": [
81
+ "Beyonc_Life_is_But_a_Dream_DVD"
82
+ ],
83
+ "purple medicine bottle": [
84
+ "Bifidus_Balance_FOS"
85
+ ],
86
+ "green-purple pencil case": [
87
+ "Big_Dot_Aqua_Pencil_Case"
88
+ ],
89
+ "pink-black pencil case": [
90
+ "Big_Dot_Pink_Pencil_Case"
91
+ ],
92
+ "purple sponge": [
93
+ "Big_O_Sponges_Assorted_Cellulose_12_pack"
94
+ ],
95
+ "black metal coffee maker": [
96
+ "Black_Decker_CM2035B_12Cup_Thermal_Coffeemaker"
97
+ ],
98
+ "stainless steel toaster": [
99
+ "Black_Decker_Stainless_Steel_Toaster_4_Slice"
100
+ ],
101
+ "Nintendo gaming console": [
102
+ "BlueBlack_Nintendo_3DSXL"
103
+ ],
104
+ "white DVD": [
105
+ "Blue_Jasmine_Includes_Digital_Copy_UltraViolet_DVD"
106
+ ],
107
+ "red bowl": [
108
+ "Bradshaw_International_11642_7_Qt_MP_Plastic_Bowl"
109
+ ],
110
+ "toy horse": [
111
+ "Breyer_Horse_Of_The_Year_2015"
112
+ ],
113
+ "CARSII": [
114
+ "CARSII"
115
+ ],
116
+ "black toy train loaded with cars": [
117
+ "CAR_CARRIER_TRAIN"
118
+ ],
119
+ "black ballet shoe": [
120
+ "California_Navy_Tieks_Italian_Leather_Ballet_Flats"
121
+ ],
122
+ "white bowl": [
123
+ "Calphalon_Kitchen_Essentials_12_Cast_Iron_Fry_Pan_Black",
124
+ "Threshold_Bead_Cereal_Bowl_White",
125
+ "Threshold_Porcelain_Serving_Bowl_Coupe_White"
126
+ ],
127
+ "round cake pan": [
128
+ "Chef_Style_Round_Cake_Pan_9_inch_pan"
129
+ ],
130
+ "black frypan": [
131
+ "Chefmate_8_Frypan"
132
+ ],
133
+ "golden-black high heel": [
134
+ "Chelsea_BlkHeelPMP_DwxLtZNxLZZ"
135
+ ],
136
+ "red high heel": [
137
+ "Chelsea_lo_fl_rdheel_nQ0LPNF1oMw"
138
+ ],
139
+ "pink high heel": [
140
+ "Chelsea_lo_fl_rdheel_zAQrnhlEfw8"
141
+ ],
142
+ "white drug bottle": [
143
+ "CoQ10"
144
+ ],
145
+ "toilet paper": [
146
+ "Cole_Hardware_Antislip_Surfacing_Material_White"
147
+ ],
148
+ "yellow round bowl": [
149
+ "Cole_Hardware_Bowl_Scirocco_YellowBlue"
150
+ ],
151
+ "brown bowl": [
152
+ "Cole_Hardware_Deep_Bowl_Good_Earth_1075"
153
+ ],
154
+ "blue-white dish towel": [
155
+ "Cole_Hardware_Dishtowel_BlueWhite"
156
+ ],
157
+ "red towel": [
158
+ "Cole_Hardware_Dishtowel_Red"
159
+ ],
160
+ "red-white striped towel": [
161
+ "Cole_Hardware_Dishtowel_Stripe",
162
+ "Tag_Dishtowel_Basket_Weave_Red_18_x_26"
163
+ ],
164
+ "red flower pot": [
165
+ "Cole_Hardware_Electric_Pot_Assortment_55",
166
+ "Sapota_Threshold_4_Ceramic_Round_Planter_Red"
167
+ ],
168
+ "orange flower pot": [
169
+ "Cole_Hardware_Electric_Pot_Cabana_55",
170
+ "Cole_Hardware_Orchid_Pot_85"
171
+ ],
172
+ "gray flower pot": [
173
+ "Cole_Hardware_Flower_Pot_1025"
174
+ ],
175
+ "black and yellow hammer": [
176
+ "Cole_Hardware_Hammer_Black"
177
+ ],
178
+ "brown round plate": [
179
+ "Cole_Hardware_Plant_Saucer_Brown_125",
180
+ "Cole_Hardware_Plant_Saucer_Glazed_9"
181
+ ],
182
+ "pink saucer": [
183
+ "Cole_Hardware_Saucer_Electric"
184
+ ],
185
+ "school bell": [
186
+ "Cole_Hardware_School_Bell_Solid_Brass_38"
187
+ ],
188
+ "leather boot": [
189
+ "Colton_Wntr_Chukka_y4jO0I8JQFW"
190
+ ],
191
+ "rectangular blue casserol dish": [
192
+ "Corningware_CW_by_Corningware_3qt_Oblong_Casserole_Dish_Blue"
193
+ ],
194
+ "screwdriver": [
195
+ "Craftsman_Grip_Screwdriver_Phillips_Cushion"
196
+ ],
197
+ "vintage metal alarm clock": [
198
+ "Crosley_Alarm_Clock_Vintage_Metal"
199
+ ],
200
+ "black net basket": [
201
+ "Curver_Storage_Bin_Black_Small"
202
+ ],
203
+ "black hat": [
204
+ "DPC_Handmade_Hat_Brown",
205
+ "Retail_Leadership_Summit_tQFCizMt6g0"
206
+ ],
207
+ "brown straw hat": [
208
+ "DPC_tropical_Trends_Hat"
209
+ ],
210
+ "red scissors": [
211
+ "Diamond_Visions_Scissors_Red"
212
+ ],
213
+ "toy T-Rex": [
214
+ "Dino_3"
215
+ ],
216
+ "toy triceratops": [
217
+ "Dino_4"
218
+ ],
219
+ "toy dicynodont dinosaur": [
220
+ "Dino_5"
221
+ ],
222
+ "white bowl with purple pattern": [
223
+ "Dixie_10_ounce_Bowls_35_ct"
224
+ ],
225
+ "Dog": [
226
+ "Dog"
227
+ ],
228
+ "white book": [
229
+ "Eat_to_Live_The_Amazing_NutrientRich_Program_for_Fast_and_Sustained_Weight_Loss_Revised_Edition_Book"
230
+ ],
231
+ "turquoise flower pot": [
232
+ "Ecoforms_Garden_Pot_GP16ATurquois"
233
+ ],
234
+ "green flower pot": [
235
+ "Ecoforms_Plant_Container_12_Pot_Nova"
236
+ ],
237
+ "red plant container": [
238
+ "Ecoforms_Plant_Container_QP6CORAL"
239
+ ],
240
+ "brown flower pot": [
241
+ "Ecoforms_Plant_Container_URN_NAT"
242
+ ],
243
+ "dark brown saucer": [
244
+ "Ecoforms_Plant_Saucer_S20MOCHA"
245
+ ],
246
+ "gray elephant toy": [
247
+ "Elephant"
248
+ ],
249
+ "blue cooler bag": [
250
+ "Embark_Lunch_Cooler_Blue"
251
+ ],
252
+ "blue-red soccer cleats": [
253
+ "F10_TRX_FG_ssscuo9tGxb"
254
+ ],
255
+ "yellow soccer cleats": [
256
+ "F5_TRX_FG"
257
+ ],
258
+ "FemDophilus": [
259
+ "FemDophilus"
260
+ ],
261
+ "garden swing": [
262
+ "GARDEN_SWING"
263
+ ],
264
+ "wooden doll": [
265
+ "GRANDFATHER_DOLL",
266
+ "GRANDMOTHER"
267
+ ],
268
+ "composite cable": [
269
+ "GoPro_HERO3_Composite_Cable"
270
+ ],
271
+ "green android mascot": [
272
+ "Great_Dinos_Triceratops_Toy"
273
+ ],
274
+ "blue dog dish": [
275
+ "Grreat_Choice_Dog_Double_Dish_Plastic_Blue"
276
+ ],
277
+ "red flashlight": [
278
+ "HeavyDuty_Flashlight"
279
+ ],
280
+ "black basket": [
281
+ "Hefty_Waste_Basket_Decorative_Bronze_85_liter"
282
+ ],
283
+ "brown leather boot": [
284
+ "Hilary",
285
+ "MARTIN_WEDGE_LACE_BOOT",
286
+ "Rayna_BootieWP",
287
+ "Sperry_TopSider_pSUFPWQXPp3",
288
+ "Sperry_TopSider_tNB9t6YBUf3",
289
+ "Tory_Burch_Sabe_65mm_Bootie_Split_Suede_in_Caramel",
290
+ "W_Lou_z0dkC78niiZ"
291
+ ],
292
+ "linen cloth": [
293
+ "Home_Fashions_Washcloth_Linen"
294
+ ],
295
+ "olive green cloth": [
296
+ "Home_Fashions_Washcloth_Olive_Green"
297
+ ],
298
+ "pink pencil case": [
299
+ "Horses_in_Pink_Pencil_Case"
300
+ ],
301
+ "green toy ogre": [
302
+ "Imaginext_Castle_Ogre"
303
+ ],
304
+ "Inositol": [
305
+ "Inositol"
306
+ ],
307
+ "green JBL portable speaker": [
308
+ "JBL_Charge_Speaker_portable_wireless_wired_Green"
309
+ ],
310
+ "blue and black backpack": [
311
+ "Jansport_School_Backpack_Blue_Streak"
312
+ ],
313
+ "white gift box with red straps": [
314
+ "KS_Chocolate_Cube_Box_Assortment_By_Neuhaus_2010_Ounces"
315
+ ],
316
+ "white keyboard": [
317
+ "Kanex_MultiSync_Wireless_Keyboard"
318
+ ],
319
+ "pale green saucer": [
320
+ "Kotobuki_Saucer_Dragon_Fly"
321
+ ],
322
+ "toy sheep": [
323
+ "LACING_SHEEP"
324
+ ],
325
+ "gray laptop": [
326
+ "Lenovo_Yoga_2_11"
327
+ ],
328
+ "brown teddy bear": [
329
+ "Lovable_Huggable_Cuddly_Boutique_Teddy_Bear_Beige"
330
+ ],
331
+ "green-orange magnifying glass": [
332
+ "Magnifying_Glassassrt"
333
+ ],
334
+ "blue conditioner bottle": [
335
+ "Marc_Anthony_Skip_Professional_Oil_of_Morocco_Conditioner_with_Argan_Oil"
336
+ ],
337
+ "brown leather shoe": [
338
+ "Mens_ASV_Billfish_Boat_Shoe_in_Dark_Brown_Leather_zdHVHXueI3w",
339
+ "Mens_Billfish_3Eye_Boat_Shoe_in_Dark_Tan_wyns9HRcEuH",
340
+ "Mens_Billfish_Slip_On_in_Tan_Beige_aaVUk0tNTv8"
341
+ ],
342
+ "sandal": [
343
+ "NAPA_VALLEY_NAVAJO_SANDAL"
344
+ ],
345
+ "white square bowl": [
346
+ "Neat_Solutions_Character_Bib_2_pack"
347
+ ],
348
+ "yellow nesquik chocolate powder canister": [
349
+ "Nestle_Nesquik_Chocolate_Powder_Flavored_Milk_Additive_109_Oz_Canister"
350
+ ],
351
+ "teenage mutant ninja turtle figure": [
352
+ "Nickelodeon_Teenage_Mutant_Ninja_Turtles_Leonardo",
353
+ "Nickelodeon_Teenage_Mutant_Ninja_Turtles_Michelangelo",
354
+ "Nickelodeon_Teenage_Mutant_Ninja_Turtles_Raphael"
355
+ ],
356
+ "nikon camera lens": [
357
+ "Nikon_1_AW1_w11275mm_Lens_Silver"
358
+ ],
359
+ "black-red nintendo 2ds console": [
360
+ "Nintendo_2DS_Crimson_Red"
361
+ ],
362
+ "mario action figure": [
363
+ "Nintendo_Mario_Action_Figure"
364
+ ],
365
+ "green yoshi action figure": [
366
+ "Nintendo_Yoshi_Action_Figure"
367
+ ],
368
+ "black-white bowl": [
369
+ "Now_Designs_Bowl_Akita_Black"
370
+ ],
371
+ "green towel": [
372
+ "Now_Designs_Dish_Towel_Mojave_18_x_28"
373
+ ],
374
+ "colorful xylophone": [
375
+ "OVAL_XYLOPHONE"
376
+ ],
377
+ "black-purple spatula": [
378
+ "OXO_Cookie_Spatula"
379
+ ],
380
+ "black can opener": [
381
+ "OXO_Soft_Works_Can_Opener_SnapLock"
382
+ ],
383
+ "green hat with feather": [
384
+ "Object_REmvBDJStub"
385
+ ],
386
+ "white dust pan with brush": [
387
+ "Ocedar_Snap_On_Dust_Pan_And_Brush_1_ct"
388
+ ],
389
+ "turquoise backpack": [
390
+ "Olive_Kids_Birdie_Sidekick_Backpack"
391
+ ],
392
+ "yellow tow giraffe": [
393
+ "Ortho_Forward_Facing"
394
+ ],
395
+ "black helmet": [
396
+ "Ortho_Forward_Facing_CkAW6rL25xH"
397
+ ],
398
+ "toy koala": [
399
+ "Ortho_Forward_Facing_QCaor9ImJ2G"
400
+ ],
401
+ "yellow flower pot": [
402
+ "Pennington_Electric_Pot_Cabana_4"
403
+ ],
404
+ "colorful pencil case": [
405
+ "Pinwheel_Pencil_Case"
406
+ ],
407
+ "white soccer cleats": [
408
+ "Predator_LZ_TRX_FG",
409
+ "Predito_LZ_TRX_FG_W"
410
+ ],
411
+ "white plate with salad": [
412
+ "ProSport_Harness_to_Booster_Seat"
413
+ ],
414
+ "dark blue towel": [
415
+ "Provence_Bath_Towel_Royal_Blue"
416
+ ],
417
+ "black boot": [
418
+ "REEF_BANTU"
419
+ ],
420
+ "black flip-flop sandal": [
421
+ "REEF_BRAIDED_CUSHION",
422
+ "Reef_Star_Cushion_Flipflops_Size_8_Black"
423
+ ],
424
+ "white-blue basket": [
425
+ "RJ_Rabbit_Easter_Basket_Blue"
426
+ ],
427
+ "plush racoon": [
428
+ "Racoon"
429
+ ],
430
+ "black gaming mouse": [
431
+ "Razer_Abyssus_Ambidextrous_Gaming_Mouse",
432
+ "Razer_Naga_MMO_Gaming_Mouse",
433
+ "Razer_Taipan_Black_Ambidextrous_Gaming_Mouse"
434
+ ],
435
+ "black keyboard": [
436
+ "Razer_BlackWidow_Stealth_2014_Keyboard_07VFzIVabgh",
437
+ "Razer_BlackWidow_Ultimate_2014_Mechanical_Gaming_Keyboard",
438
+ "Razer_Blackwidow_Tournament_Edition_Keyboard"
439
+ ],
440
+ "white gaming mouse": [
441
+ "Razer_Taipan_White_Ambidextrous_Gaming_Mouse"
442
+ ],
443
+ "black and red gameboy": [
444
+ "RedBlack_Nintendo_3DSXL"
445
+ ],
446
+ "red hair dryer": [
447
+ "Remington_TStudio_Hair_Dryer"
448
+ ],
449
+ "brown hat": [
450
+ "Retail_Leadership_Summit"
451
+ ],
452
+ "gray hat": [
453
+ "Retail_Leadership_Summit_eCT3zqHYIkX"
454
+ ],
455
+ "blue gloves": [
456
+ "Rexy_Glove_Heavy_Duty_Gloves_Medium"
457
+ ],
458
+ "turquoise bowl": [
459
+ "Room_Essentials_Bowl_Turquiose"
460
+ ],
461
+ "white-yellow mug": [
462
+ "Room_Essentials_Mug_White_Yellow"
463
+ ],
464
+ "turquoise plate": [
465
+ "Room_Essentials_Salad_Plate_Turquoise"
466
+ ],
467
+ "dish drainer": [
468
+ "Rubbermaid_Large_Drainer"
469
+ ],
470
+ "brown shoe": [
471
+ "SAMBA_HEMP"
472
+ ],
473
+ "sandwich on plate": [
474
+ "SANDWICH_MEAL"
475
+ ],
476
+ "yellow school bus": [
477
+ "SCHOOL_BUS"
478
+ ],
479
+ "wooden ring stacker toy": [
480
+ "STACKING_RING"
481
+ ],
482
+ "rhino": [
483
+ "Schleich_African_Black_Rhino"
484
+ ],
485
+ "bald eagle": [
486
+ "Schleich_Bald_Eagle"
487
+ ],
488
+ "brown bull": [
489
+ "Schleich_Hereford_Bull"
490
+ ],
491
+ "lion": [
492
+ "Schleich_Lion_Action_Figure"
493
+ ],
494
+ "unicorn": [
495
+ "Schleich_S_Bayala_Unicorn_70432"
496
+ ],
497
+ "metal hard drive storage": [
498
+ "Seagate_Archive_HDD_8_TB_Internal_hard_drive_SATA_6Gbs_35_ST8000AS0002"
499
+ ],
500
+ "shark": [
501
+ "Shark",
502
+ "Weisshai_Great_White_Shark"
503
+ ],
504
+ "purple tape": [
505
+ "Shurtape_30_Day_Removal_UV_Delct_15"
506
+ ],
507
+ "gray tape": [
508
+ "Shurtape_Gaffers_Tape_Silver_2_x_60_yd"
509
+ ],
510
+ "grey elephant toy": [
511
+ "Sootheze_Cold_Therapy_Elephant"
512
+ ],
513
+ "orca toy": [
514
+ "Sootheze_Toasty_Orca"
515
+ ],
516
+ "spider man action figure": [
517
+ "SpiderMan_Titan_Hero_12Inch_Action_Figure_5Hnn4mtkFsP",
518
+ "SpiderMan_Titan_Hero_12Inch_Action_Figure_oo1qph4wwiW"
519
+ ],
520
+ "toy squirrel": [
521
+ "Squirrel"
522
+ ],
523
+ "bamboo sushi mat": [
524
+ "Sushi_Mat"
525
+ ],
526
+ "blue-white striped towel": [
527
+ "Tag_Dishtowel_Dobby_Stripe_Blue_18_x_26"
528
+ ],
529
+ "green-white striped towel": [
530
+ "Tag_Dishtowel_Green"
531
+ ],
532
+ "green toy train": [
533
+ "Thomas_Friends_Woodan_Railway_Henry"
534
+ ],
535
+ "woven storage basket": [
536
+ "Threshold_Basket_Natural_Finish_Fabric_Liner_Small"
537
+ ],
538
+ "white-red plate": [
539
+ "Threshold_Bistro_Ceramic_Dinner_Plate_Ruby_Ring"
540
+ ],
541
+ "white mug": [
542
+ "Threshold_Porcelain_Coffee_Mug_All_Over_Bead_White"
543
+ ],
544
+ "white porcelain teapot": [
545
+ "Threshold_Porcelain_Teapot_White"
546
+ ],
547
+ "white square saucer": [
548
+ "Threshold_Salad_Plate_Square_Rim_Porcelain"
549
+ ],
550
+ "pink bath towel": [
551
+ "Threshold_Textured_Damask_Bath_Towel_Pink"
552
+ ],
553
+ "rectangular porcelain tray": [
554
+ "Threshold_Tray_Rectangle_Porcelain"
555
+ ],
556
+ "white-pink dog bowl": [
557
+ "Top_Paw_Dog_Bow_Bone_Ceramic_13_fl_oz_total"
558
+ ],
559
+ "blue dog bowl": [
560
+ "Top_Paw_Dog_Bowl_Blue_Paw_Bone_Ceramic_25_fl_oz_total"
561
+ ],
562
+ "white animal dog toy": [
563
+ "Toysmith_Windem_Up_Flippin_Animals_Dog"
564
+ ],
565
+ "black laptop": [
566
+ "Travel_Mate_P_series_Notebook"
567
+ ],
568
+ "black power pressure cooker": [
569
+ "TriStar_Products_PPC_Power_Pressure_Cooker_XL_in_Black"
570
+ ],
571
+ "yellow ballet shoe": [
572
+ "Unmellow_Yellow_Tieks_Neon_Patent_Leather_Ballet_Flats"
573
+ ],
574
+ "green turtle toy": [
575
+ "Vtech_Roll_Learn_Turtle"
576
+ ],
577
+ "white shoe": [
578
+ "Womens_Canvas_Bahama_in_White_4UyOhP6rYGO"
579
+ ],
580
+ "black sneaker": [
581
+ "adistar_boost_m"
582
+ ]
583
+ }
eq-kubric/create_scene.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+
3
+ def create_scene(index: int, dataset_type="location", max_num_objects=1, retries=10, log_file="logs/error_log.txt", verbose=False) -> int:
4
+ """
5
+ Attempts to create a data entry point in a dataset by running a Docker container that executes a Python script.
6
+
7
+ This function tries to execute a command to create a scene up to a specified number of retries. It logs the attempts and errors to a specified file. If successful, it returns 1; if it fails after all retries, it returns 0.
8
+
9
+ Args:
10
+ index (int): The index of the scene to generate, which affects the generate_idx parameter in the command.
11
+ dataset_type (str): The type of the dataset, which customizes the Python script to be executed.
12
+ max_num_objects (int): The maximum number of objects to include in the scene.
13
+ retries (int): The number of attempts to make in case of failure.
14
+ log_file (str): Path to the file where error logs are appended.
15
+
16
+ Returns:
17
+ int: 0 if the scene was successfully created, 1 otherwise.
18
+
19
+ Raises:
20
+ None directly by the function, but subprocess.run may raise an exception if the command execution fails critically.
21
+
22
+ Side Effects:
23
+ Writes to a log file at `log_file` path if any errors occur during the execution.
24
+ Tries to execute a Docker command which can affect system resources and Docker state.
25
+ """
26
+ command = f"""
27
+ sudo docker run --rm --interactive \
28
+ --user $(id -u):$(id -g) \
29
+ --volume "$(pwd):/kubric" kubricdockerhub/kubruntu \
30
+ /usr/bin/python3 eq-kubric/my_kubric_twoframe_{dataset_type}.py \
31
+ --sub_outputdir {dataset_type} \
32
+ --generate_idx {index+1} \
33
+ --max_num_objects {max_num_objects}
34
+ """
35
+
36
+ attempt = 0
37
+ while attempt < retries:
38
+ result = subprocess.run(command, shell=True, capture_output=True, text=True)
39
+ if result.returncode == 0 and ("INFO:root:Done!" in result.stderr or "INFO:root:Done!" in result.stdout):
40
+ return 0
41
+ attempt += 1
42
+ if verbose:
43
+ print(f"Attempt {attempt} failed with return code {result.returncode}.")
44
+ print(result.stderr)
45
+
46
+ error_message = f"Failed to create a scene after {attempt} attempts: Index: {index+1}, Dataset Type: '{dataset_type}'."
47
+ with open(log_file, "a") as file:
48
+ file.write(f"{error_message}\n")
49
+ return 1
eq-kubric/main.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from create_dataset import create_dataset
3
+
4
+ def main():
5
+ parser = argparse.ArgumentParser(description='Create a dataset.')
6
+ parser.add_argument('dataset_length', type=int, help='The length of the dataset')
7
+ parser.add_argument('--dataset_type', type=str, default='location', help='Type of dataset to create (default: location)')
8
+ parser.add_argument('--max_num_objects', type=int, default=4, help='Maximum number of objects in the scene (default: 4)')
9
+ parser.add_argument('--n_jobs', type=int, default=1, help='Number of parallel jobs to run (default: 1)')
10
+ parser.add_argument('--verbose', action='store_true', help='Print verbose output')
11
+
12
+ args = parser.parse_args()
13
+ create_dataset(args.dataset_length, args.dataset_type, args.max_num_objects, args.n_jobs, args.verbose)
14
+
15
+ if __name__ == '__main__':
16
+ main()
eq-kubric/my_kubric_twoframe_attribute.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The Kubric Authors
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Worker file for the Multi-Object Video (MOVi) C (and CC) datasets.
16
+ * The number of objects is randomly chosen between
17
+ --min_num_objects (3) and --max_num_objects (10)
18
+ * The objects are randomly chosen from the Google Scanned Objects dataset
19
+
20
+ * Background is an random HDRI from the HDRI Haven dataset,
21
+ projected onto a Dome (half-sphere).
22
+ The HDRI is also used for lighting the scene.
23
+ """
24
+
25
+ import logging
26
+
27
+ import bpy
28
+ import copy
29
+ import os
30
+ import kubric as kb
31
+ from kubric.simulator import PyBullet
32
+ from kubric.renderer import Blender
33
+ import numpy as np
34
+ import random
35
+ import shutil
36
+
37
+ from GSO_transfer import GSO_dict, GSO_dict_attr
38
+ from utils import save_scene_instruction, dataset_dir
39
+
40
+ # --- Some configuration values
41
+ DATASET_TYPE = "attribute"
42
+ # the region in which to place objects [(min), (max)]
43
+ SPAWN_REGION = [(-8, -8, 0), (8, 8, 5)]
44
+ SPAWN_REGION_OBJ = [[-6, -6, 0.5], [6, 6, 0.5]]
45
+ VELOCITY_RANGE = [(-4., -4., 0.), (4., 4., 0.)]
46
+
47
+ # --- CLI arguments
48
+ parser = kb.ArgumentParser()
49
+ parser.add_argument("--objects_split", choices=["train", "test"],
50
+ default="train")
51
+ # Configuration for the objects of the scene
52
+ parser.add_argument("--min_num_objects", type=int, default=1,
53
+ help="minimum number of objects")
54
+ parser.add_argument("--max_num_objects", type=int, default=4,
55
+ help="maximum number of objects")
56
+ # Configuration for the floor and background
57
+ parser.add_argument("--floor_friction", type=float, default=0.3)
58
+ parser.add_argument("--floor_restitution", type=float, default=0.5)
59
+ parser.add_argument("--backgrounds_split", choices=["train", "test"],
60
+ default="train")
61
+
62
+ parser.add_argument("--camera", choices=["fixed_random", "linear_movement"],
63
+ default="fixed_random")
64
+ parser.add_argument("--max_camera_movement", type=float, default=4.0)
65
+ parser.add_argument("--smallest_scale", type=float, default=1.5)
66
+ parser.add_argument("--largest_scale", type=float, default=4.)
67
+
68
+ # Configuration for the source of the assets
69
+ parser.add_argument("--kubasic_assets", type=str,
70
+ default="gs://kubric-public/assets/KuBasic/KuBasic.json")
71
+ parser.add_argument("--hdri_assets", type=str,
72
+ default="gs://kubric-public/assets/HDRI_haven/HDRI_haven.json")
73
+ parser.add_argument("--gso_assets", type=str,
74
+ default="gs://kubric-public/assets/GSO/GSO.json")
75
+ parser.add_argument("--save_state", dest="save_state", action="store_true")
76
+ parser.set_defaults(save_state=False, frame_end=24, frame_rate=12,
77
+ resolution=512)
78
+ parser.add_argument("--sub_outputdir", type=str, default="test sub output dir")
79
+ parser.add_argument("--generate_idx", type=int, default=-1, help="generation idx")
80
+ FLAGS = parser.parse_args()
81
+
82
+
83
+ import pyquaternion as pyquat
84
+ def default_rng():
85
+ return np.random.RandomState()
86
+
87
+
88
+ # def random_rotation(axis=None, rng=default_rng()):
89
+ # """ Compute a random rotation as a quaternion.
90
+ # If axis is None the rotation is sampled uniformly over all possible orientations.
91
+ # Otherwise it corresponds to a random rotation around the given axis."""
92
+
93
+ # if axis is None:
94
+ # # uniform across rotation space
95
+ # # copied from pyquat.Quaternion.random to be able to use a custom rng
96
+ # r1, r2, r3 = rng.random(3)
97
+
98
+ # q1 = np.sqrt(1.0 - r1) * (np.sin(2 * np.pi * r2))
99
+ # q2 = np.sqrt(1.0 - r1) * (np.cos(2 * np.pi * r2))
100
+ # q3 = np.sqrt(r1) * (np.sin(2 * np.pi * r3))
101
+ # q4 = np.sqrt(r1) * (np.cos(2 * np.pi * r3))
102
+
103
+ # return q1, q2, q3, q4
104
+
105
+ # else:
106
+ # if isinstance(axis, str) and axis.upper() in ["X", "Y", "Z"]:
107
+ # axis = {"X": (1., 0., 0.),
108
+ # "Y": (0., 1., 0.),
109
+ # "Z": (0., 0., 1.)}[axis.upper()]
110
+
111
+ # # quat = pyquat.Quaternion(axis=axis, angle=rng.uniform(0, 2*np.pi))
112
+ # quat = pyquat.Quaternion(axis=axis, angle=rng.uniform(-0.5*np.pi, 0.5*np.pi)) # -0.5pi -- 0.5pi
113
+ # return tuple(quat)
114
+
115
+
116
+ # from kubric.core import objects
117
+ # def rotation_sampler(axis=None):
118
+ # def _sampler(obj: objects.PhysicalObject, rng):
119
+ # obj.quaternion = random_rotation(axis=axis, rng=rng)
120
+ # return _sampler
121
+
122
+
123
+ def move_until_no_overlap(asset, simulator, spawn_region=((-1, -1, -1), (1, 1, 1)), max_trials=100,
124
+ rng=default_rng()):
125
+ return kb.randomness.resample_while(asset,
126
+ samplers=[kb.randomness.position_sampler(spawn_region)],
127
+ condition=simulator.check_overlap,
128
+ max_trials=max_trials,
129
+ rng=rng)
130
+
131
+
132
+ def check_ok(obj, pos, region):
133
+ # import pdb; pdb.set_trace()
134
+ x, y, z = pos
135
+ if pos[0]<region[0][0] or pos[0]>region[1][0] or pos[1]<region[0][1] or pos[1]>region[1][1]: #or pos[2]<region[0][2] or pos[2]>region[1][2]:
136
+ return False
137
+
138
+ if simulator.check_overlap(obj):
139
+ return False
140
+
141
+ return True
142
+
143
+
144
+ def get_obj_x_left(bound, scale):
145
+ return -bound[0][0] * scale[0]
146
+
147
+ def get_obj_x_right(bound, scale):
148
+ return bound[1][0] * scale[0]
149
+
150
+ def get_obj_y_front(bound, scale):
151
+ return -bound[0][1] * scale[1]
152
+
153
+ def get_obj_y_behind(bound, scale):
154
+ return bound[1][1] * scale[1]
155
+
156
+ def get_obj_z(bound, scale):
157
+ return bound[0][2] * scale[2]
158
+
159
+ def get_obj_z_up(bound, scale):
160
+ return bound[1][2] * scale[2]
161
+
162
+
163
+ def get_new_pos(bounds, scale, ref_location, ref_pos, ref_z_up, ref_object, rng):
164
+
165
+ obj_z = - get_obj_z(bounds, scale)
166
+ # import pdb; pdb.set_trace()
167
+ ref_x_left, ref_x_right, ref_y_front, ref_y_behind = get_obj_x_left(ref_object.bounds, ref_object.scale), get_obj_x_right(ref_object.bounds, ref_object.scale), get_obj_y_front(ref_object.bounds, ref_object.scale), get_obj_y_behind(ref_object.bounds, ref_object.scale)
168
+ ref_x, ref_y, ref_z = ref_pos
169
+ if ref_location == 'front':
170
+ return [rng.uniform(ref_x-0.5, ref_x+0.5), rng.uniform(ref_y-ref_y_front-6, ref_y-ref_y_front-2), obj_z+0.02]
171
+ elif ref_location == 'behind':
172
+ return [rng.uniform(ref_x-0.5, ref_x+0.5), rng.uniform(ref_y+ref_y_behind+3, ref_y+ref_y_behind+7), obj_z+0.02]
173
+ elif ref_location == 'left':
174
+ return [rng.uniform(ref_x-ref_x_left-6, ref_x-ref_x_left-2), rng.uniform(ref_y-0.5, ref_y+0.5), obj_z+0.02]
175
+ elif ref_location == 'right':
176
+ return [rng.uniform(ref_x+ref_x_right+2, ref_x+ref_x_right+6), rng.uniform(ref_y-0.5, ref_y+0.5), obj_z+0.02]
177
+ elif ref_location == 'on':
178
+ return [ref_x, ref_y, ref_z+ref_z_up+obj_z+1]
179
+
180
+ def get_second_pos(bounds, scale, ref_location, ref_pos, ref_z_up, ref_object, rng):
181
+ obj_z = -get_obj_z(bounds, scale)
182
+ ref_x, ref_y, ref_z = ref_pos
183
+
184
+ if ref_location == 'on':
185
+ return [ref_x, ref_y, ref_z]
186
+ else:
187
+ return [ref_x, ref_y, obj_z + 0.02]
188
+
189
+
190
+ def add_new_obj(scene, new_obj, ref_location, ref_object, rng, max_trails=50, second_obj=False):
191
+
192
+ ref_obj_pos = ref_object.position
193
+ # import pdb; pdb.set_trace()
194
+ ref_obj_z_up = get_obj_z_up(ref_object.bounds, ref_object.scale)
195
+ if not second_obj:
196
+ new_obj_pos = get_new_pos(new_obj.bounds, new_obj.scale, ref_location, ref_obj_pos, ref_obj_z_up, ref_object, rng)
197
+ else:
198
+ new_obj_pos = get_second_pos(new_obj.bounds, new_obj.scale, ref_location, ref_obj_pos, ref_obj_z_up, ref_object, rng)
199
+ new_obj.position = new_obj_pos
200
+ scene += new_obj
201
+
202
+ # import pdb; pdb.set_trace()
203
+ trails = 0
204
+ while not check_ok(new_obj, new_obj.position, SPAWN_REGION_OBJ):
205
+ trails += 1
206
+ # import pdb; pdb.set_trace()
207
+ # new_obj.position = get_new_pos(new_obj.bounds, new_obj.scale, ref_location, ref_obj_pos, ref_obj_z_up, ref_object, rng)
208
+ if not second_obj:
209
+ new_obj_pos = get_new_pos(new_obj.bounds, new_obj.scale, ref_location, ref_obj_pos, ref_obj_z_up, ref_object, rng)
210
+ else:
211
+ new_obj_pos = get_second_pos(new_obj.bounds, new_obj.scale, ref_location, ref_obj_pos, ref_obj_z_up, ref_object, rng)
212
+ new_obj.position = new_obj_pos
213
+ # new_obj.quaternion = random_rotation(axis="Z", rng=rng)
214
+ if trails > max_trails:
215
+ print('cannot put the object, break')
216
+ # import pdb; pdb.set_trace()
217
+ return None
218
+ print('try {} times'.format(trails))
219
+ return scene
220
+
221
+ def gen_caption(obj_name, obj_scale, ref_obj_name, ref_obj_scale, use_attr):
222
+ def get_change_size_exp(obj_scale, ref_obj_scale):
223
+ if obj_scale < ref_obj_scale:
224
+ return random.choice(["smaller", "small"])
225
+ elif obj_scale > ref_obj_scale:
226
+ return random.choice(["larger", "bigger", "large", "big"])
227
+ else:
228
+ return "same size"
229
+
230
+ ref_obj_size_exp = get_change_size_exp(obj_scale, ref_obj_scale)
231
+
232
+ if use_attr != "scale":
233
+ edit_instruction = random.choice(["transform", "convert", "turn"])
234
+ caption = f'{edit_instruction} the {ref_obj_name} into a {obj_name}'
235
+ else:
236
+ edit_instruction = random.choice(["make", "turn"])
237
+ caption = f'{edit_instruction} the {ref_obj_name} {ref_obj_size_exp}'
238
+ return caption
239
+
240
+ def sample_unique_items(GSO_dict, num_samples):
241
+ unique_items = {}
242
+ sampled_values = set()
243
+ active_keys = list(GSO_dict.keys())
244
+
245
+ while len(unique_items) < num_samples:
246
+ key = random.choice(active_keys)
247
+ value = GSO_dict[key]
248
+
249
+ if value not in sampled_values:
250
+ sampled_values.add(value)
251
+ unique_items[key] = value
252
+
253
+ active_keys.remove(key)
254
+ if not active_keys:
255
+ break
256
+
257
+ return list(unique_items.keys())
258
+
259
+ # --- Common setups & resources
260
+ print('Generate {} Sample'.format(FLAGS.generate_idx))
261
+ scene, rng, output_dir, scratch_dir = kb.setup(FLAGS)
262
+ output_dir = output_dir / FLAGS.sub_outputdir
263
+
264
+ simulator = PyBullet(scene, scratch_dir)
265
+ renderer = Blender(scene, scratch_dir, samples_per_pixel=64)
266
+ kubasic = kb.AssetSource.from_manifest(FLAGS.kubasic_assets)
267
+ gso = kb.AssetSource.from_manifest(FLAGS.gso_assets)
268
+ hdri_source = kb.AssetSource.from_manifest(FLAGS.hdri_assets)
269
+
270
+ # --- Populate the scene
271
+ # background HDRI
272
+ train_backgrounds, test_backgrounds = hdri_source.get_test_split(fraction=0.)
273
+ logging.info("Choosing one of the %d training backgrounds...", len(train_backgrounds))
274
+ hdri_id = rng.choice(train_backgrounds)
275
+
276
+ background_hdri = hdri_source.create(asset_id=hdri_id)
277
+ #assert isinstance(background_hdri, kb.Texture)
278
+ logging.info("Using background %s", hdri_id)
279
+ scene.metadata["background"] = hdri_id
280
+ renderer._set_ambient_light_hdri(background_hdri.filename)
281
+
282
+
283
+ # Dome
284
+ dome = kubasic.create(asset_id="dome", name="dome",
285
+ friction=FLAGS.floor_friction,
286
+ restitution=FLAGS.floor_restitution,
287
+ static=True, background=True)
288
+ assert isinstance(dome, kb.FileBasedObject)
289
+ scene += dome
290
+ dome_blender = dome.linked_objects[renderer]
291
+ texture_node = dome_blender.data.materials[0].node_tree.nodes["Image Texture"]
292
+ texture_node.image = bpy.data.images.load(background_hdri.filename)
293
+
294
+ def get_linear_camera_motion_start_end(
295
+ movement_speed: float,
296
+ inner_radius: float = 8.,
297
+ outer_radius: float = 12.,
298
+ z_offset: float = 0.1,
299
+ ):
300
+ """Sample a linear path which starts and ends within a half-sphere shell."""
301
+ while True:
302
+ camera_start = np.array(kb.sample_point_in_half_sphere_shell(inner_radius,
303
+ outer_radius,
304
+ z_offset))
305
+ direction = rng.rand(3) - 0.5
306
+ movement = direction / np.linalg.norm(direction) * movement_speed
307
+ camera_end = camera_start + movement
308
+ if (inner_radius <= np.linalg.norm(camera_end) <= outer_radius and
309
+ camera_end[2] > z_offset):
310
+ return camera_start, camera_end
311
+
312
+
313
+ # Camera
314
+ logging.info("Setting up the Camera...")
315
+ scene.camera = kb.PerspectiveCamera(focal_length=35., sensor_width=36)
316
+ if FLAGS.camera == "fixed_random":
317
+ # scene.camera.position = kb.sample_point_in_half_sphere_shell(
318
+ # inner_radius=7., outer_radius=9., offset=4)
319
+ scene.camera.position = (0, -10, 12)
320
+ scene.camera.look_at((0, 0, 0))
321
+ elif FLAGS.camera == "linear_movement":
322
+ camera_start, camera_end = get_linear_camera_motion_start_end(
323
+ movement_speed=rng.uniform(low=0., high=FLAGS.max_camera_movement)
324
+ )
325
+ # linearly interpolate the camera position between these two points
326
+ # while keeping it focused on the center of the scene
327
+ # we start one frame early and end one frame late to ensure that
328
+ # forward and backward flow are still consistent for the last and first frames
329
+ for frame in range(FLAGS.frame_start - 1, FLAGS.frame_end + 2):
330
+ interp = ((frame - FLAGS.frame_start + 1) /
331
+ (FLAGS.frame_end - FLAGS.frame_start + 3))
332
+ scene.camera.position = (interp * np.array(camera_start) +
333
+ (1 - interp) * np.array(camera_end))
334
+ scene.camera.look_at((0, 0, 0))
335
+ scene.camera.keyframe_insert("position", frame)
336
+ scene.camera.keyframe_insert("quaternion", frame)
337
+
338
+
339
+ # Add random objects
340
+ active_split = list(GSO_dict_attr['base_set'].keys())
341
+ num_objects = rng.randint(FLAGS.min_num_objects,
342
+ FLAGS.max_num_objects+1)
343
+
344
+ logging.info("Step 1: Randomly placing %d objects:", num_objects)
345
+ object_state_save_dict = {}
346
+ object_state_ref_dict = {}
347
+
348
+
349
+ # not resample objects
350
+ # object_id_list = random.sample(active_split, num_objects)
351
+ object_id_list = sample_unique_items(GSO_dict, num_objects+1)
352
+
353
+ for i in range(num_objects):
354
+ # object_id = rng.choice(active_split)
355
+ object_id = object_id_list[i]
356
+ obj = gso.create(asset_id=object_id)
357
+
358
+
359
+ assert isinstance(obj, kb.FileBasedObject)
360
+ scale = rng.uniform(FLAGS.smallest_scale, FLAGS.largest_scale)
361
+ obj.scale = scale / np.max(obj.bounds[1] - obj.bounds[0])
362
+
363
+
364
+ obj_pos_z = - get_obj_z(obj.bounds, obj.scale)
365
+ SPAWN_REGION_OBJ[0][2], SPAWN_REGION_OBJ[1][2] = obj_pos_z, obj_pos_z
366
+ obj.position = rng.uniform(*SPAWN_REGION_OBJ)
367
+
368
+ obj.metadata["scale"] = scale
369
+ scene += obj
370
+ move_until_no_overlap(obj, simulator, spawn_region=SPAWN_REGION_OBJ, rng=rng)
371
+ # initialize velocity randomly but biased towards center
372
+ # obj.velocity = (rng.uniform(*VELOCITY_RANGE) -
373
+ # [obj.position[0], obj.position[1], 0])
374
+ # print(obj.position)
375
+ obj.velocity = [0, 0, 0]
376
+ logging.info(" Added %s at %s", obj.asset_id, obj.position)
377
+ object_state_save_dict[i] = {'object_id': object_id,
378
+ 'object_scale': obj.scale,
379
+ 'object_quaternion': obj.quaternion,
380
+ 'object_bounds': obj.bounds}
381
+ object_state_ref_dict[i] = {'object': obj}
382
+
383
+
384
+
385
+ # # choose the object to change the attribute
386
+ # active_split_choose = random.choice(list(GSO_dict_attr['choose_set'].keys()))
387
+ # object_choose1, object_choose2 = random.sample(list(GSO_dict_attr['choose_set'][active_split_choose].keys()), 2)
388
+ # # choose the ref object and the location
389
+ # ref_object = object_state_ref_dict[rng.choice(list(object_state_ref_dict.keys()))]['object'] # random choose an reference object
390
+ # ref_object_name = GSO_dict[ref_object.asset_id]
391
+ # ref_location = ref_object.position
392
+
393
+ # random choose two location
394
+ LOC_SET = ['front', 'behind', 'left', 'right', 'on']
395
+ use_location = random.sample(LOC_SET, 1)[0]
396
+ ATTR_SET = [use_location, 'scale']
397
+ use_attr = random.sample(ATTR_SET, 1)[0]
398
+
399
+ if use_attr != 'scale':
400
+ # choose the object to change the attribute
401
+ active_split_choose = random.choice(list(GSO_dict_attr['choose_set'].keys()))
402
+ object_choose1, object_choose2 = random.sample(list(GSO_dict_attr['choose_set'][active_split_choose].keys()), 2)
403
+ # choose the ref object and the location
404
+ ref_object = object_state_ref_dict[rng.choice(list(object_state_ref_dict.keys()))]['object'] # random choose an reference object
405
+ ref_object_name = GSO_dict[ref_object.asset_id]
406
+ ref_location = ref_object.position
407
+
408
+ # 1st
409
+ print('Generate the first scene.')
410
+ # object_id = rng.choice(active_split)
411
+ object_id = object_choose1
412
+ obj = gso.create(asset_id=object_id)
413
+ scale = rng.uniform(FLAGS.smallest_scale, FLAGS.largest_scale)
414
+ obj.scale = scale / np.max(obj.bounds[1] - obj.bounds[0])
415
+ obj.metadata["scale"] = scale
416
+
417
+ new_object_name = GSO_dict_attr['choose_set'][active_split_choose][object_id]
418
+ print('Add new object {}'.format(new_object_name))
419
+
420
+
421
+ # obj 2
422
+ object2_id = object_choose2
423
+ obj2 = gso.create(asset_id=object2_id)
424
+ # scale2 = rng.uniform(FLAGS.smallest_scale, FLAGS.largest_scale)
425
+ # obj2.scale = scale2 / np.max(obj2.bounds[1] - obj2.bounds[0])
426
+ # obj2.metadata["scale"] = scale2
427
+ obj2.scale = scale / np.max(obj2.bounds[1] - obj2.bounds[0])
428
+ obj2.metadata["scale"] = scale
429
+
430
+ new_object2_name = GSO_dict_attr['choose_set'][active_split_choose][object2_id] # Updated to use object2_id
431
+ print('Add second object {}'.format(new_object2_name)) # Refers to new_object2_name
432
+ #obj 2
433
+
434
+ scene = add_new_obj(scene, obj, use_attr, ref_object, rng, max_trails=500)
435
+ if scene is None:
436
+ exit()
437
+ frame = renderer.render_still()
438
+
439
+ os.makedirs(output_dir/'{}'.format(FLAGS.generate_idx), exist_ok=True)
440
+ kb.write_png(frame["rgba"], output_dir/"{}/image0.png".format(FLAGS.generate_idx))
441
+ caption_1 = gen_caption(new_object_name, obj.metadata["scale"], new_object2_name, obj2.metadata["scale"], use_attr)
442
+ print(caption_1)
443
+
444
+ # 2nd
445
+ print('Generate the second scene.')
446
+ scene.remove(obj)
447
+ scene = add_new_obj(scene, obj2, use_attr, obj, rng, max_trails=500, second_obj=True)
448
+
449
+ if scene is None:
450
+ print('cannot put the object, break')
451
+ shutil.rmtree(output_dir / '{}'.format(FLAGS.generate_idx))
452
+ exit()
453
+
454
+ frame = renderer.render_still()
455
+ kb.write_png(frame["rgba"], output_dir/"{}/image1.png".format(FLAGS.generate_idx))
456
+ caption_2 = gen_caption(new_object2_name, obj2.metadata["scale"], new_object_name, obj.metadata["scale"], use_attr)
457
+ print(caption_2)
458
+ else:
459
+ # choose the object to change the attribute
460
+ # active_split_choose = random.choice(list(GSO_dict_attr['choose_set'].keys()))
461
+ # object_choose1, object_choose2 = random.sample(list(GSO_dict_attr['choose_set'][active_split_choose].keys()), 2)
462
+ object_choose1 = random.choice(list(GSO_dict.keys()))
463
+
464
+ # choose the ref object and the location
465
+ ref_object = object_state_ref_dict[rng.choice(list(object_state_ref_dict.keys()))]['object'] # random choose an reference object
466
+ ref_object_name = GSO_dict[ref_object.asset_id]
467
+ ref_location = ref_object.position
468
+
469
+ # 1st
470
+ print('Generate the first scene.')
471
+ # object_id = rng.choice(active_split)
472
+ object_id = object_choose1
473
+ obj = gso.create(asset_id=object_id)
474
+ scale = rng.uniform(FLAGS.smallest_scale, FLAGS.largest_scale)
475
+ obj.scale = scale / np.max(obj.bounds[1] - obj.bounds[0])
476
+ obj.metadata["scale"] = scale
477
+
478
+ new_object_name = GSO_dict[object_id]
479
+ print('Add new object {}'.format(new_object_name))
480
+
481
+
482
+ # obj 2
483
+ object2_id = object_choose1
484
+ obj2 = gso.create(asset_id=object2_id)
485
+ scale2 = rng.uniform(FLAGS.smallest_scale-1, FLAGS.largest_scale+2)
486
+ obj2.scale = scale2 / np.max(obj2.bounds[1] - obj2.bounds[0])
487
+ obj2.metadata["scale"] = scale2
488
+
489
+ new_object2_name = GSO_dict[object2_id] # Updated to use object2_id
490
+ print('Add second object {}'.format(new_object2_name)) # Refers to new_object2_name
491
+ #obj 2
492
+
493
+ scene = add_new_obj(scene, obj, use_location, ref_object, rng, max_trails=500)
494
+ if scene is None:
495
+ exit()
496
+ frame = renderer.render_still()
497
+
498
+ os.makedirs(output_dir/'{}'.format(FLAGS.generate_idx), exist_ok=True)
499
+ kb.write_png(frame["rgba"], output_dir/"{}/image0.png".format(FLAGS.generate_idx))
500
+ caption_1 = gen_caption(new_object_name, obj.metadata["scale"], new_object2_name, obj2.metadata["scale"], use_attr)
501
+ print(caption_1)
502
+
503
+ # 2nd
504
+ print('Generate the second scene.')
505
+ scene.remove(obj)
506
+ scene = add_new_obj(scene, obj2, use_location, obj, rng, max_trails=500, second_obj=True)
507
+
508
+ if scene is None:
509
+ print('cannot put the object, break')
510
+ shutil.rmtree(output_dir / '{}'.format(FLAGS.generate_idx))
511
+ exit()
512
+
513
+ frame = renderer.render_still()
514
+ kb.write_png(frame["rgba"], output_dir/"{}/image1.png".format(FLAGS.generate_idx))
515
+ caption_2 = gen_caption(new_object2_name, obj2.metadata["scale"], new_object_name, obj.metadata["scale"], use_attr)
516
+ print(caption_2)
517
+
518
+ local_ann = [
519
+ {
520
+ 'input': dataset_dir(DATASET_TYPE) + "{}/image0.png".format(FLAGS.generate_idx),
521
+ 'output': dataset_dir(DATASET_TYPE) + "{}/image1.png".format(FLAGS.generate_idx),
522
+ 'instruction': caption_2,
523
+ },
524
+ {
525
+ 'input': dataset_dir(DATASET_TYPE) + "{}/image1.png".format(FLAGS.generate_idx),
526
+ 'output': dataset_dir(DATASET_TYPE) + "{}/image0.png".format(FLAGS.generate_idx),
527
+ 'instruction': caption_1,
528
+ }
529
+ ]
530
+ save_scene_instruction(f"{output_dir}/eq_kubric_{DATASET_TYPE}.json", local_ann, DATASET_TYPE, FLAGS.generate_idx)
531
+
532
+ kb.done()
533
+
534
+ # if FLAGS.save_state:
535
+ # logging.info("Saving the simulator state to '%s' prior to the simulation.",
536
+ # output_dir / "scene.bullet")
537
+ # simulator.save_state(output_dir / "scene.bullet")
538
+ #
539
+ # # Run dynamic objects simulation
540
+ # logging.info("Running the simulation ...")
541
+ # animation, collisions = simulator.run(frame_start=0,
542
+ # frame_end=scene.frame_end+1)
543
+ #
544
+ # # --- Rendering
545
+ # if FLAGS.save_state:
546
+ # logging.info("Saving the renderer state to '%s' ",
547
+ # output_dir / "scene.blend")
548
+ # renderer.save_state(output_dir / "scene.blend")
549
+ #
550
+ #
551
+ # logging.info("Rendering the scene ...")
552
+ # data_stack = renderer.render()
553
+ #
554
+ # # --- Postprocessing
555
+ # kb.compute_visibility(data_stack["segmentation"], scene.assets)
556
+ # visible_foreground_assets = [asset for asset in scene.foreground_assets
557
+ # if np.max(asset.metadata["visibility"]) > 0]
558
+ # visible_foreground_assets = sorted( # sort assets by their visibility
559
+ # visible_foreground_assets,
560
+ # key=lambda asset: np.sum(asset.metadata["visibility"]),
561
+ # reverse=True)
562
+ #
563
+ # data_stack["segmentation"] = kb.adjust_segmentation_idxs(
564
+ # data_stack["segmentation"],
565
+ # scene.assets,
566
+ # visible_foreground_assets)
567
+ # scene.metadata["num_instances"] = len(visible_foreground_assets)
568
+ #
569
+ # # Save to image files
570
+ # kb.write_image_dict(data_stack, output_dir)
571
+ # kb.post_processing.compute_bboxes(data_stack["segmentation"],
572
+ # visible_foreground_assets)
573
+ #
574
+ # # --- Metadata
575
+ # logging.info("Collecting and storing metadata for each object.")
576
+ # kb.write_json(filename=output_dir / "metadata.json", data={
577
+ # "flags": vars(FLAGS),
578
+ # "metadata": kb.get_scene_metadata(scene),
579
+ # "camera": kb.get_camera_info(scene.camera),
580
+ # "instances": kb.get_instance_info(scene, visible_foreground_assets),
581
+ # })
582
+ # kb.write_json(filename=output_dir / "events.json", data={
583
+ # "collisions": kb.process_collisions(
584
+ # collisions, scene, assets_subset=visible_foreground_assets),
585
+ # })
586
+ #
587
+ # kb.done()
eq-kubric/my_kubric_twoframe_closer.py ADDED
@@ -0,0 +1,479 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The Kubric Authors
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Worker file for the Multi-Object Video (MOVi) C (and CC) datasets.
16
+ * The number of objects is randomly chosen between
17
+ --min_num_objects (3) and --max_num_objects (10)
18
+ * The objects are randomly chosen from the Google Scanned Objects dataset
19
+
20
+ * Background is an random HDRI from the HDRI Haven dataset,
21
+ projected onto a Dome (half-sphere).
22
+ The HDRI is also used for lighting the scene.
23
+ """
24
+
25
+ import logging
26
+
27
+ import bpy
28
+ import copy
29
+ import os
30
+ import kubric as kb
31
+ from kubric.simulator import PyBullet
32
+ from kubric.renderer import Blender
33
+ import numpy as np
34
+ import random
35
+ import shutil
36
+
37
+ from GSO_transfer import GSO_dict
38
+ from utils import save_scene_instruction, dataset_dir
39
+
40
+ # --- Some configuration values
41
+ DATASET_TYPE = "closer"
42
+ # the region in which to place objects [(min), (max)]
43
+ SPAWN_REGION = [(-8, -8, 0), (8, 8, 5)]
44
+ SPAWN_REGION_OBJ = [[-6, -6, 0.5], [6, 6, 0.5]]
45
+ VELOCITY_RANGE = [(-4., -4., 0.), (4., 4., 0.)]
46
+
47
+ # --- CLI arguments
48
+ parser = kb.ArgumentParser()
49
+ parser.add_argument("--objects_split", choices=["train", "test"],
50
+ default="train")
51
+ # Configuration for the objects of the scene
52
+ parser.add_argument("--min_num_objects", type=int, default=1,
53
+ help="minimum number of objects")
54
+ parser.add_argument("--max_num_objects", type=int, default=5,
55
+ help="maximum number of objects")
56
+ # Configuration for the floor and background
57
+ parser.add_argument("--floor_friction", type=float, default=0.3)
58
+ parser.add_argument("--floor_restitution", type=float, default=0.5)
59
+ parser.add_argument("--backgrounds_split", choices=["train", "test"],
60
+ default="train")
61
+
62
+ parser.add_argument("--camera", choices=["fixed_random", "linear_movement"],
63
+ default="fixed_random")
64
+ parser.add_argument("--max_camera_movement", type=float, default=4.0)
65
+ parser.add_argument("--smallest_scale", type=float, default=2.)
66
+ parser.add_argument("--largest_scale", type=float, default=4.)
67
+
68
+ # Configuration for the source of the assets
69
+ parser.add_argument("--kubasic_assets", type=str,
70
+ default="gs://kubric-public/assets/KuBasic/KuBasic.json")
71
+ parser.add_argument("--hdri_assets", type=str,
72
+ default="gs://kubric-public/assets/HDRI_haven/HDRI_haven.json")
73
+ parser.add_argument("--gso_assets", type=str,
74
+ default="gs://kubric-public/assets/GSO/GSO.json")
75
+ parser.add_argument("--save_state", dest="save_state", action="store_true")
76
+ parser.set_defaults(save_state=False, frame_end=24, frame_rate=12,
77
+ resolution=512)
78
+ parser.add_argument("--sub_outputdir", type=str, default="test sub output dir")
79
+ parser.add_argument("--generate_idx", type=int, default=-1, help="generation idx")
80
+ FLAGS = parser.parse_args()
81
+
82
+
83
+ import pyquaternion as pyquat
84
+ def default_rng():
85
+ return np.random.RandomState()
86
+
87
+ def random_rotation(axis=None, rng=default_rng()):
88
+ """ Compute a random rotation as a quaternion.
89
+ If axis is None the rotation is sampled uniformly over all possible orientations.
90
+ Otherwise it corresponds to a random rotation around the given axis."""
91
+
92
+ if axis is None:
93
+ # uniform across rotation space
94
+ # copied from pyquat.Quaternion.random to be able to use a custom rng
95
+ r1, r2, r3 = rng.random(3)
96
+
97
+ q1 = np.sqrt(1.0 - r1) * (np.sin(2 * np.pi * r2))
98
+ q2 = np.sqrt(1.0 - r1) * (np.cos(2 * np.pi * r2))
99
+ q3 = np.sqrt(r1) * (np.sin(2 * np.pi * r3))
100
+ q4 = np.sqrt(r1) * (np.cos(2 * np.pi * r3))
101
+
102
+ return q1, q2, q3, q4
103
+
104
+ else:
105
+ if isinstance(axis, str) and axis.upper() in ["X", "Y", "Z"]:
106
+ axis = {"X": (1., 0., 0.),
107
+ "Y": (0., 1., 0.),
108
+ "Z": (0., 0., 1.)}[axis.upper()]
109
+
110
+ # quat = pyquat.Quaternion(axis=axis, angle=rng.uniform(0, 2*np.pi))
111
+ quat = pyquat.Quaternion(axis=axis, angle=rng.uniform(-0.5*np.pi, 0.5*np.pi)) # -0.5pi -- 0.5pi
112
+ return tuple(quat)
113
+
114
+
115
+ from kubric.core import objects
116
+ def rotation_sampler(axis=None):
117
+ def _sampler(obj: objects.PhysicalObject, rng):
118
+ obj.quaternion = random_rotation(axis=axis, rng=rng)
119
+ return _sampler
120
+
121
+
122
+ def move_until_no_overlap(asset, simulator, spawn_region=((-1, -1, -1), (1, 1, 1)), max_trials=100,
123
+ rng=default_rng()):
124
+ return kb.randomness.resample_while(asset,
125
+ # samplers=[rotation_sampler(axis='Z'), kb.randomness.position_sampler(spawn_region)],
126
+ samplers=[kb.randomness.position_sampler(spawn_region)],
127
+ condition=simulator.check_overlap,
128
+ max_trials=max_trials,
129
+ rng=rng)
130
+
131
+
132
+ def check_ok(obj, pos, region):
133
+ # import pdb; pdb.set_trace()
134
+ x, y, z = pos
135
+ if pos[0]<region[0][0] or pos[0]>region[1][0] or pos[1]<region[0][1] or pos[1]>region[1][1]: #or pos[2]<region[0][2] or pos[2]>region[1][2]:
136
+ return False
137
+
138
+ if simulator.check_overlap(obj):
139
+ return False
140
+
141
+ return True
142
+
143
+
144
+ def get_obj_x_left(bound, scale):
145
+ return -bound[0][0] * scale[0]
146
+
147
+ def get_obj_x_right(bound, scale):
148
+ return bound[1][0] * scale[0]
149
+
150
+ def get_obj_y_front(bound, scale):
151
+ return -bound[0][1] * scale[1]
152
+
153
+ def get_obj_y_behind(bound, scale):
154
+ return bound[1][1] * scale[1]
155
+
156
+ def get_obj_z(bound, scale):
157
+ return bound[0][2] * scale[2]
158
+
159
+ def get_obj_z_up(bound, scale):
160
+ return bound[1][2] * scale[2]
161
+
162
+
163
+ # def get_new_pos(bounds, scale, ref_location, ref_pos, ref_z_up, ref_object, rng):
164
+ # obj_z = - get_obj_z(bounds, scale)
165
+ # # import pdb; pdb.set_trace()
166
+ # ref_x_left, ref_x_right, ref_y_front, ref_y_behind = get_obj_x_left(ref_object.bounds, ref_object.scale), get_obj_x_right(ref_object.bounds, ref_object.scale), get_obj_y_front(ref_object.bounds, ref_object.scale), get_obj_y_behind(ref_object.bounds, ref_object.scale)
167
+ # ref_x, ref_y, ref_z = ref_pos
168
+ # if ref_location == 'front':
169
+ # return [rng.uniform(ref_x-0.5, ref_x+0.5), rng.uniform(ref_y-ref_y_front-6, ref_y-ref_y_front-2), obj_z+0.02]
170
+ # elif ref_location == 'behind':
171
+ # return [rng.uniform(ref_x-0.5, ref_x+0.5), rng.uniform(ref_y+ref_y_behind+2, ref_y+ref_y_behind+6), obj_z+0.02]
172
+ # elif ref_location == 'left':
173
+ # return [rng.uniform(ref_x-ref_x_left-6, ref_x-ref_x_left-2), rng.uniform(ref_y-0.5, ref_y+0.5), obj_z+0.02]
174
+ # elif ref_location == 'right':
175
+ # return [rng.uniform(ref_x+ref_x_right+2, ref_x+ref_x_right+6), rng.uniform(ref_y-0.5, ref_y+0.5), obj_z+0.02]
176
+ # elif ref_location == 'on':
177
+ # return [ref_x, ref_y, ref_z+ref_z_up+obj_z+1]
178
+
179
+ def get_new_pos(bounds, scale, ref_location, ref_pos, ref_z_up, ref_object, rng):
180
+ # Calculate the z-position based on the object's bounds and scale
181
+ obj_z = -get_obj_z(bounds, scale) + 0.2 # Ensuring the object is slightly above the ground
182
+
183
+ # Extract the bounds from the SPAWN_REGION_OBJ variable
184
+ spawn_x_min, spawn_y_min, _ = SPAWN_REGION_OBJ[0]
185
+ spawn_x_max, spawn_y_max, _ = SPAWN_REGION_OBJ[1]
186
+
187
+ # Calculate the maximum offsets within the given spawn bounds
188
+ max_offset_x = spawn_x_max - spawn_x_min + 1
189
+ max_offset_y = spawn_y_max - spawn_y_min + 1
190
+
191
+ # Define absolute positions for each location using straightforward calculations
192
+ import random
193
+
194
+ # Return the position for the specified location
195
+ return locations.get(ref_location, [ref_pos[0], ref_pos[1], obj_z]) # Default position if location is not specified
196
+
197
+ def add_new_obj(scene, new_obj, ref_location, ref_object, rng, max_trails=50):
198
+
199
+ ref_obj_pos = ref_object.position
200
+ # import pdb; pdb.set_trace()
201
+ ref_obj_z_up = get_obj_z_up(ref_object.bounds, ref_object.scale)
202
+ new_obj_pos = get_new_pos(new_obj.bounds, new_obj.scale, ref_location, ref_obj_pos, ref_obj_z_up, ref_object, rng)
203
+ new_obj.position = new_obj_pos
204
+ scene += new_obj
205
+
206
+ # import pdb; pdb.set_trace()
207
+ trails = 0
208
+ while not check_ok(new_obj, new_obj.position, SPAWN_REGION_OBJ):
209
+ trails += 1
210
+ # import pdb; pdb.set_trace()
211
+ new_obj.position = get_new_pos(new_obj.bounds, new_obj.scale, ref_location, ref_obj_pos, ref_obj_z_up, ref_object, rng)
212
+ # new_obj.quaternion = random_rotation(axis="Z", rng=rng)
213
+ if trails > max_trails:
214
+ print('cannot put the object, break')
215
+ # import pdb; pdb.set_trace()
216
+ return None
217
+ print('try {} times'.format(trails))
218
+ return scene
219
+
220
+ def gen_caption(obj_name, obj_scale, ref_obj_name, ref_obj_scale, type='closer'):
221
+ if type == 'closer':
222
+ captions = [f'Move the {obj_name} and the {ref_obj_name} closer together.', f'Move the {obj_name} and the {ref_obj_name} closer.', f'Move the {obj_name} and the {ref_obj_name} closer to each other.', f'Move both objects closer', f'Move the two objects closer together.', f'Move the two objects closer to each other.']
223
+ elif type == 'further':
224
+ captions = [f'Move the {obj_name} further away from the {ref_obj_name}.', f'Move the {obj_name} and the {ref_obj_name} further apart.', f'Move the {obj_name} and the {ref_obj_name} further away from each other.', f'Move both objects further apart', f'Move the two objects further away from each other.', f'Move the two objects further apart.']
225
+ elif type == 'swap':
226
+ captions = [f'Swap the positions of the {obj_name} and the {ref_obj_name}.', f'Swap the positions of the {ref_obj_name} and the {obj_name}.', f'Swap the positions of the two objects.', f'Swap positions of both items.']
227
+ return random.choice(captions)
228
+
229
+
230
+ # --- Common setups & resources
231
+ print('Generate {} Sample'.format(FLAGS.generate_idx))
232
+ scene, rng, output_dir, scratch_dir = kb.setup(FLAGS)
233
+ output_dir = output_dir / FLAGS.sub_outputdir
234
+
235
+
236
+
237
+ simulator = PyBullet(scene, scratch_dir)
238
+ renderer = Blender(scene, scratch_dir, samples_per_pixel=64)
239
+ kubasic = kb.AssetSource.from_manifest(FLAGS.kubasic_assets)
240
+ gso = kb.AssetSource.from_manifest(FLAGS.gso_assets)
241
+ hdri_source = kb.AssetSource.from_manifest(FLAGS.hdri_assets)
242
+
243
+
244
+ # --- Populate the scene
245
+ # background HDRI
246
+ train_backgrounds, test_backgrounds = hdri_source.get_test_split(fraction=0.)
247
+ logging.info("Choosing one of the %d training backgrounds...", len(train_backgrounds))
248
+ hdri_id = rng.choice(train_backgrounds)
249
+
250
+ background_hdri = hdri_source.create(asset_id=hdri_id)
251
+ #assert isinstance(background_hdri, kb.Texture)
252
+ logging.info("Using background %s", hdri_id)
253
+ scene.metadata["background"] = hdri_id
254
+ renderer._set_ambient_light_hdri(background_hdri.filename)
255
+
256
+
257
+ # Dome
258
+ dome = kubasic.create(asset_id="dome", name="dome",
259
+ friction=FLAGS.floor_friction,
260
+ restitution=FLAGS.floor_restitution,
261
+ static=True, background=True)
262
+ assert isinstance(dome, kb.FileBasedObject)
263
+ scene += dome
264
+ dome_blender = dome.linked_objects[renderer]
265
+ texture_node = dome_blender.data.materials[0].node_tree.nodes["Image Texture"]
266
+ texture_node.image = bpy.data.images.load(background_hdri.filename)
267
+
268
+
269
+
270
+ def get_linear_camera_motion_start_end(
271
+ movement_speed: float,
272
+ inner_radius: float = 8.,
273
+ outer_radius: float = 12.,
274
+ z_offset: float = 0.1,
275
+ ):
276
+ """Sample a linear path which starts and ends within a half-sphere shell."""
277
+ while True:
278
+ camera_start = np.array(kb.sample_point_in_half_sphere_shell(inner_radius,
279
+ outer_radius,
280
+ z_offset))
281
+ direction = rng.rand(3) - 0.5
282
+ movement = direction / np.linalg.norm(direction) * movement_speed
283
+ camera_end = camera_start + movement
284
+ if (inner_radius <= np.linalg.norm(camera_end) <= outer_radius and
285
+ camera_end[2] > z_offset):
286
+ return camera_start, camera_end
287
+
288
+
289
+ # Camera
290
+ logging.info("Setting up the Camera...")
291
+ scene.camera = kb.PerspectiveCamera(focal_length=35., sensor_width=36)
292
+ if FLAGS.camera == "fixed_random":
293
+ # scene.camera.position = kb.sample_point_in_half_sphere_shell(
294
+ # inner_radius=7., outer_radius=9., offset=4)
295
+ scene.camera.position = (0, -10, 15)
296
+ scene.camera.look_at((0, 0, 0))
297
+ elif FLAGS.camera == "linear_movement":
298
+ camera_start, camera_end = get_linear_camera_motion_start_end(
299
+ movement_speed=rng.uniform(low=0., high=FLAGS.max_camera_movement)
300
+ )
301
+ # linearly interpolate the camera position between these two points
302
+ # while keeping it focused on the center of the scene
303
+ # we start one frame early and end one frame late to ensure that
304
+ # forward and backward flow are still consistent for the last and first frames
305
+ for frame in range(FLAGS.frame_start - 1, FLAGS.frame_end + 2):
306
+ interp = ((frame - FLAGS.frame_start + 1) /
307
+ (FLAGS.frame_end - FLAGS.frame_start + 3))
308
+ scene.camera.position = (interp * np.array(camera_start) +
309
+ (1 - interp) * np.array(camera_end))
310
+ scene.camera.look_at((0, 0, 0))
311
+ scene.camera.keyframe_insert("position", frame)
312
+ scene.camera.keyframe_insert("quaternion", frame)
313
+
314
+
315
+ # Add random objects
316
+ train_split, test_split = gso.get_test_split(fraction=0.)
317
+ # if FLAGS.objects_split == "train":
318
+ logging.info("Choosing one of the %d training objects...", len(train_split))
319
+ # active_split = train_split
320
+ active_split = list(GSO_dict.keys())
321
+
322
+ # num_objects = rng.randint(FLAGS.min_num_objects,
323
+ # FLAGS.max_num_objects+1)
324
+ num_objects = 2
325
+
326
+ logging.info("Step 1: Randomly placing %d objects:", num_objects)
327
+ object_state_save_dict = {}
328
+ object_state_ref_dict = {}
329
+
330
+
331
+ # not resample objects
332
+ object_id_list = random.sample(active_split, num_objects+1)
333
+
334
+ for i in range(num_objects):
335
+ # object_id = rng.choice(active_split)
336
+ object_id = object_id_list[i]
337
+ obj = gso.create(asset_id=object_id)
338
+
339
+
340
+ assert isinstance(obj, kb.FileBasedObject)
341
+ scale = rng.uniform(FLAGS.smallest_scale, FLAGS.largest_scale)
342
+ obj.scale = scale / np.max(obj.bounds[1] - obj.bounds[0])
343
+
344
+
345
+ obj_pos_z = - get_obj_z(obj.bounds, obj.scale)
346
+ SPAWN_REGION_OBJ[0][2], SPAWN_REGION_OBJ[1][2] = obj_pos_z, obj_pos_z
347
+ obj.position = rng.uniform(*SPAWN_REGION_OBJ)
348
+
349
+ obj.metadata["scale"] = scale
350
+ scene += obj
351
+ move_until_no_overlap(obj, simulator, spawn_region=SPAWN_REGION_OBJ, rng=rng)
352
+ # initialize velocity randomly but biased towards center
353
+ # obj.velocity = (rng.uniform(*VELOCITY_RANGE) -
354
+ # [obj.position[0], obj.position[1], 0])
355
+ # print(obj.position)
356
+ obj.velocity = [0, 0, 0]
357
+ logging.info(" Added %s at %s", obj.asset_id, obj.position)
358
+ object_state_save_dict[i] = {'object_id': object_id,
359
+ 'object_scale': obj.scale,
360
+ 'object_quaternion': obj.quaternion,
361
+ 'object_bounds': obj.bounds}
362
+ object_state_ref_dict[i] = {'object': obj}
363
+
364
+
365
+ ref_object = object_state_ref_dict[list(object_state_ref_dict.keys())[0]]['object']
366
+ ref_object_name = GSO_dict[ref_object.asset_id]
367
+ ref_location = ref_object.position
368
+
369
+ obj = object_state_ref_dict[list(object_state_ref_dict.keys())[1]]['object']
370
+ new_object_name = GSO_dict[obj.asset_id]
371
+
372
+ # 1st
373
+ print('Generate the first scene.')
374
+ # object_id = rng.choice(active_split)
375
+ # object_id = object_id_list[-1]
376
+ # obj = gso.create(asset_id=object_id)
377
+ # scale = rng.uniform(FLAGS.smallest_scale, FLAGS.largest_scale)
378
+ # obj.scale = scale / np.max(obj.bounds[1] - obj.bounds[0])
379
+ # obj.metadata["scale"] = scale
380
+
381
+ # new_object_name = GSO_dict[obj.asset_id]
382
+ # print('Add new object {}'.format(new_object_name))
383
+
384
+
385
+ # scene = add_new_obj(scene, obj, ref_location1, ref_object, rng, max_trails=500)
386
+ if scene is None:
387
+ exit()
388
+ frame = renderer.render_still()
389
+
390
+ edits = ['close', 'swap']
391
+ edit = random.choice(edits)
392
+
393
+ os.makedirs(output_dir/'{}'.format(FLAGS.generate_idx), exist_ok=True)
394
+ kb.write_png(frame["rgba"], output_dir/"{}/image0.png".format(FLAGS.generate_idx))
395
+ caption_1 = gen_caption(new_object_name, obj.metadata["scale"], ref_object_name, ref_object.metadata["scale"], type="further" if edit == 'close' else 'swap')
396
+ print(caption_1)
397
+
398
+
399
+ # save meta ann
400
+ object_state_save_dict[i+1] = {'object_id': object_id,
401
+ 'object_scale': obj.scale,
402
+ 'object_pos': obj.position,
403
+ 'object_quaternion': obj.quaternion,
404
+ 'object_bounds': obj.bounds}
405
+ # import json
406
+ # json.dump(object_state_save_dict, open(output_dir/'{}/meta_ann1.json'.format(FLAGS.generate_idx), 'w'))
407
+ # np.save(output_dir/'{}/meta_ann1.npy'.format(FLAGS.generate_idx), object_state_save_dict)
408
+ # renderer.save_state(output_dir/'{}/image1.blend'.format(FLAGS.generate_idx))
409
+
410
+
411
+
412
+ # 2nd
413
+ print('Generate the second scene.')
414
+ # delete the last object to generate the second frame
415
+ # import pdb; pdb.set_trace()
416
+ # scene.remove(obj)
417
+ # scene= add_new_obj(scene, obj, ref_location2, ref_object, rng, max_trails=100)
418
+ ref_obj_pos = ref_object.position
419
+ ref_obj_z_up = get_obj_z_up(ref_object.bounds, ref_object.scale)
420
+ logging.info(f'Object position: {obj.position}')
421
+
422
+ obj1_pos = obj.position
423
+ obj2_pos = ref_location
424
+ if edit == 'close':
425
+ direction = obj2_pos - obj1_pos
426
+ factor1, factor2 = random.uniform(0.1, 0.3), random.uniform(0.1, 0.3)
427
+ obj.position = obj1_pos + direction * factor1
428
+ ref_object.position = obj2_pos - direction * factor2
429
+ else:
430
+ obj.position = obj2_pos
431
+ ref_object.position = obj1_pos
432
+
433
+ frame = renderer.render_still()
434
+ kb.write_png(frame["rgba"], output_dir/"{}/image1.png".format(FLAGS.generate_idx))
435
+ caption_2 = gen_caption(new_object_name, obj.metadata["scale"], ref_object_name, ref_object.metadata["scale"], type="closer" if edit == 'close' else 'swap')
436
+ print(caption_2)
437
+
438
+ # save meta ann
439
+ object_state_save_dict[i+1] = {'object_id': object_id,
440
+ 'object_scale': obj.scale,
441
+ 'object_pos': obj.position,
442
+ 'object_quaternion': obj.quaternion,
443
+ 'object_bounds': obj.bounds}
444
+ # import json
445
+ # json.dump(object_state_save_dict, open(output_dir/'{}/meta_ann2.json'.format(FLAGS.generate_idx), 'w'))
446
+ # np.save(output_dir/'{}/meta_ann2.npy'.format(FLAGS.generate_idx), object_state_save_dict)
447
+ # renderer.save_state(output_dir/'{}/image2.blend'.format(FLAGS.generate_idx))
448
+
449
+
450
+ # save json
451
+ # local_ann = {'image0':"{}/image0.png".format(FLAGS.generate_idx), 'caption0':caption_1,
452
+ # 'image1':"{}/image1.png".format(FLAGS.generate_idx), 'caption1':caption_2,
453
+ # 'ann_path':"{}/ann.json".format(FLAGS.generate_idx),
454
+ # 'obj_num':num_objects+1}
455
+ # json.dump(local_ann, open("{}/{}/ann.json".format(str(output_dir), FLAGS.generate_idx), 'w'))
456
+
457
+ # import pdb; pdb.set_trace()
458
+ # if not os.path.exists("{}/global_ann.json".format(str(output_dir))):
459
+ # json.dump([], open("{}/global_ann.json".format(str(output_dir)), 'w'))
460
+ # with open("{}/global_ann.json".format(str(output_dir)), 'r') as f:
461
+ # old_data = json.load(f)
462
+ # old_data.append(local_ann)
463
+ # with open("{}/global_ann.json".format(str(output_dir)), "w") as f:
464
+ # json.dump(old_data, f)
465
+
466
+ local_ann = [{
467
+ 'input': dataset_dir(DATASET_TYPE) + "{}/image0.png".format(FLAGS.generate_idx),
468
+ 'output': dataset_dir(DATASET_TYPE) + "{}/image1.png".format(FLAGS.generate_idx),
469
+ 'instruction': caption_2,
470
+ },
471
+ {
472
+ 'input': dataset_dir(DATASET_TYPE) + "{}/image1.png".format(FLAGS.generate_idx),
473
+ 'output': dataset_dir(DATASET_TYPE) + "{}/image0.png".format(FLAGS.generate_idx),
474
+ 'instruction': caption_1,
475
+ }
476
+ ]
477
+ save_scene_instruction(f"{output_dir}/eq_kubric_{DATASET_TYPE}.json", local_ann, DATASET_TYPE, FLAGS.generate_idx)
478
+
479
+ kb.done()
eq-kubric/my_kubric_twoframe_rotate.py ADDED
@@ -0,0 +1,590 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The Kubric Authors
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Worker file for the Multi-Object Video (MOVi) C (and CC) datasets.
16
+ * The number of objects is randomly chosen between
17
+ --min_num_objects (3) and --max_num_objects (10)
18
+ * The objects are randomly chosen from the Google Scanned Objects dataset
19
+
20
+ * Background is an random HDRI from the HDRI Haven dataset,
21
+ projected onto a Dome (half-sphere).
22
+ The HDRI is also used for lighting the scene.
23
+ """
24
+
25
+ import logging
26
+
27
+ import bpy
28
+ import copy
29
+ import os
30
+ import kubric as kb
31
+ from kubric.simulator import PyBullet
32
+ from kubric.renderer import Blender
33
+ import numpy as np
34
+ import random
35
+ import shutil
36
+
37
+ from GSO_transfer import GSO_dict
38
+ from utils import save_scene_instruction, dataset_dir
39
+
40
+ # --- Some configuration values
41
+ DATASET_TYPE = "rotate"
42
+ # the region in which to place objects [(min), (max)]
43
+ SPAWN_REGION = [(-8, -8, 0), (8, 8, 5)]
44
+ SPAWN_REGION_OBJ = [[-6, -6, 0.5], [6, 6, 0.5]]
45
+ VELOCITY_RANGE = [(-4., -4., 0.), (4., 4., 0.)]
46
+
47
+ # --- CLI arguments
48
+ parser = kb.ArgumentParser()
49
+ parser.add_argument("--objects_split", choices=["train", "test"],
50
+ default="train")
51
+ # Configuration for the objects of the scene
52
+ parser.add_argument("--min_num_objects", type=int, default=1,
53
+ help="minimum number of objects")
54
+ parser.add_argument("--max_num_objects", type=int, default=5,
55
+ help="maximum number of objects")
56
+ # Configuration for the floor and background
57
+ parser.add_argument("--floor_friction", type=float, default=0.3)
58
+ parser.add_argument("--floor_restitution", type=float, default=0.5)
59
+ parser.add_argument("--backgrounds_split", choices=["train", "test"],
60
+ default="train")
61
+
62
+ parser.add_argument("--camera", choices=["fixed_random", "linear_movement"],
63
+ default="fixed_random")
64
+ parser.add_argument("--max_camera_movement", type=float, default=4.0)
65
+ parser.add_argument("--smallest_scale", type=float, default=2.)
66
+ parser.add_argument("--largest_scale", type=float, default=4.)
67
+
68
+ # Configuration for the source of the assets
69
+ parser.add_argument("--kubasic_assets", type=str,
70
+ default="gs://kubric-public/assets/KuBasic/KuBasic.json")
71
+ parser.add_argument("--hdri_assets", type=str,
72
+ default="gs://kubric-public/assets/HDRI_haven/HDRI_haven.json")
73
+ parser.add_argument("--gso_assets", type=str,
74
+ default="gs://kubric-public/assets/GSO/GSO.json")
75
+ parser.add_argument("--save_state", dest="save_state", action="store_true")
76
+ parser.set_defaults(save_state=False, frame_end=24, frame_rate=12,
77
+ resolution=512)
78
+ parser.add_argument("--sub_outputdir", type=str, default="test sub output dir")
79
+ parser.add_argument("--generate_idx", type=int, default=-1, help="generation idx")
80
+ FLAGS = parser.parse_args()
81
+
82
+
83
+ import pyquaternion as pyquat
84
+ def default_rng():
85
+ return np.random.RandomState()
86
+
87
+ import numpy as np
88
+
89
+ def rotation(axis='Z', degrees=0):
90
+ """ Compute a specific rotation as a quaternion along a given axis by a specified degree.
91
+
92
+ Args:
93
+ axis (str): Axis to rotate around ('X', 'Y', 'Z').
94
+ degrees (float): Angle in degrees to rotate around the specified axis.
95
+
96
+ Returns:
97
+ tuple: Quaternion representing the rotation.
98
+ """
99
+ # Convert degrees to radians
100
+ degrees = degrees + random.uniform(-10, 10)
101
+ radians = np.radians(degrees)
102
+
103
+ # Define axes
104
+ axis_vectors = {
105
+ 'X': (1., 0., 0.),
106
+ 'Y': (0., 1., 0.),
107
+ 'Z': (0., 0., 1.)
108
+ }
109
+
110
+ # Get the axis vector
111
+ axis_vector = axis_vectors.get(axis.upper(), (0., 0., 1.)) # Default to Z-axis if unspecified
112
+
113
+ # Create the quaternion for the rotation
114
+ quat = pyquat.Quaternion(axis=axis_vector, angle=radians)
115
+ return tuple(quat)
116
+
117
+ def random_rotation(axis=None, rng=default_rng()):
118
+ """ Compute a random rotation as a quaternion.
119
+ If axis is None the rotation is sampled uniformly over all possible orientations.
120
+ Otherwise it corresponds to a random rotation around the given axis."""
121
+
122
+ if axis is None:
123
+ # uniform across rotation space
124
+ # copied from pyquat.Quaternion.random to be able to use a custom rng
125
+ r1, r2, r3 = rng.random(3)
126
+
127
+ q1 = np.sqrt(1.0 - r1) * (np.sin(2 * np.pi * r2))
128
+ q2 = np.sqrt(1.0 - r1) * (np.cos(2 * np.pi * r2))
129
+ q3 = np.sqrt(r1) * (np.sin(2 * np.pi * r3))
130
+ q4 = np.sqrt(r1) * (np.cos(2 * np.pi * r3))
131
+
132
+ return q1, q2, q3, q4
133
+
134
+ else:
135
+ if isinstance(axis, str) and axis.upper() in ["X", "Y", "Z"]:
136
+ axis = {"X": (1., 0., 0.),
137
+ "Y": (0., 1., 0.),
138
+ "Z": (0., 0., 1.)}[axis.upper()]
139
+
140
+ # quat = pyquat.Quaternion(axis=axis, angle=rng.uniform(0, 2*np.pi))
141
+ quat = pyquat.Quaternion(axis=axis, angle=rng.uniform(-0.5*np.pi, 0.5*np.pi)) # -0.5pi -- 0.5pi
142
+ return tuple(quat)
143
+
144
+
145
+ from kubric.core import objects
146
+ def rotation_sampler(axis=None):
147
+ def _sampler(obj: objects.PhysicalObject, rng):
148
+ obj.quaternion = random_rotation(axis=axis, rng=rng)
149
+ return _sampler
150
+
151
+
152
+ def move_until_no_overlap(asset, simulator, spawn_region=((-1, -1, -1), (1, 1, 1)), max_trials=100,
153
+ rng=default_rng()):
154
+ return kb.randomness.resample_while(asset,
155
+ # samplers=[rotation_sampler(axis='Z'), kb.randomness.position_sampler(spawn_region)],
156
+ samplers=[kb.randomness.position_sampler(spawn_region)],
157
+ condition=simulator.check_overlap,
158
+ max_trials=max_trials,
159
+ rng=rng)
160
+
161
+
162
+ def check_ok(obj, pos, region):
163
+ # import pdb; pdb.set_trace()
164
+ x, y, z = pos
165
+ if pos[0]<region[0][0] or pos[0]>region[1][0] or pos[1]<region[0][1] or pos[1]>region[1][1]: #or pos[2]<region[0][2] or pos[2]>region[1][2]:
166
+ return False
167
+
168
+ if simulator.check_overlap(obj):
169
+ return False
170
+
171
+ return True
172
+
173
+
174
+ def get_obj_x_left(bound, scale):
175
+ return -bound[0][0] * scale[0]
176
+
177
+ def get_obj_x_right(bound, scale):
178
+ return bound[1][0] * scale[0]
179
+
180
+ def get_obj_y_front(bound, scale):
181
+ return -bound[0][1] * scale[1]
182
+
183
+ def get_obj_y_behind(bound, scale):
184
+ return bound[1][1] * scale[1]
185
+
186
+ def get_obj_z(bound, scale):
187
+ return bound[0][2] * scale[2]
188
+
189
+ def get_obj_z_up(bound, scale):
190
+ return bound[1][2] * scale[2]
191
+
192
+
193
+ # def get_new_pos(bounds, scale, ref_location, ref_pos, ref_z_up, ref_object, rng):
194
+ # obj_z = - get_obj_z(bounds, scale)
195
+ # # import pdb; pdb.set_trace()
196
+ # ref_x_left, ref_x_right, ref_y_front, ref_y_behind = get_obj_x_left(ref_object.bounds, ref_object.scale), get_obj_x_right(ref_object.bounds, ref_object.scale), get_obj_y_front(ref_object.bounds, ref_object.scale), get_obj_y_behind(ref_object.bounds, ref_object.scale)
197
+ # ref_x, ref_y, ref_z = ref_pos
198
+ # if ref_location == 'front':
199
+ # return [rng.uniform(ref_x-0.5, ref_x+0.5), rng.uniform(ref_y-ref_y_front-6, ref_y-ref_y_front-2), obj_z+0.02]
200
+ # elif ref_location == 'behind':
201
+ # return [rng.uniform(ref_x-0.5, ref_x+0.5), rng.uniform(ref_y+ref_y_behind+2, ref_y+ref_y_behind+6), obj_z+0.02]
202
+ # elif ref_location == 'left':
203
+ # return [rng.uniform(ref_x-ref_x_left-6, ref_x-ref_x_left-2), rng.uniform(ref_y-0.5, ref_y+0.5), obj_z+0.02]
204
+ # elif ref_location == 'right':
205
+ # return [rng.uniform(ref_x+ref_x_right+2, ref_x+ref_x_right+6), rng.uniform(ref_y-0.5, ref_y+0.5), obj_z+0.02]
206
+ # elif ref_location == 'on':
207
+ # return [ref_x, ref_y, ref_z+ref_z_up+obj_z+1]
208
+
209
+ def sample_unique_items(GSO_dict, num_samples):
210
+ unique_items = {}
211
+ sampled_values = set()
212
+ active_keys = list(GSO_dict.keys())
213
+
214
+ while len(unique_items) < num_samples:
215
+ key = random.choice(active_keys)
216
+ value = GSO_dict[key]
217
+
218
+ if value not in sampled_values:
219
+ sampled_values.add(value)
220
+ unique_items[key] = value
221
+
222
+ active_keys.remove(key)
223
+ if not active_keys:
224
+ break
225
+
226
+ return list(unique_items.keys())
227
+
228
+
229
+ def get_new_pos(bounds, scale, ref_location, ref_pos, ref_z_up, ref_object, rng):
230
+ # Calculate the z-position based on the object's bounds and scale
231
+ obj_z = -get_obj_z(bounds, scale) + 0.2 # Ensuring the object is slightly above the ground
232
+
233
+ # Extract the bounds from the SPAWN_REGION_OBJ variable
234
+ spawn_x_min, spawn_y_min, _ = SPAWN_REGION_OBJ[0]
235
+ spawn_x_max, spawn_y_max, _ = SPAWN_REGION_OBJ[1]
236
+
237
+ # Calculate the maximum offsets within the given spawn bounds
238
+ max_offset_x = spawn_x_max - spawn_x_min + 1
239
+ max_offset_y = spawn_y_max - spawn_y_min + 1
240
+
241
+ # Define absolute positions for each location using straightforward calculations
242
+ import random
243
+
244
+ locations = {
245
+ 'closer': [ref_pos[0], max(spawn_y_min, ref_pos[1] - max_offset_y) * random.uniform(0.5, 1.2), obj_z],
246
+ 'further away': [ref_pos[0], min(spawn_y_max, ref_pos[1] + max_offset_y) * random.uniform(0.5, 1.2), obj_z],
247
+ 'further left': [max(spawn_x_min, ref_pos[0] - max_offset_x) * random.uniform(0.5, 1.2), ref_pos[1], obj_z],
248
+ 'further right': [min(spawn_x_max, ref_pos[0] + max_offset_x) * random.uniform(0.5, 1.2), ref_pos[1], obj_z],
249
+ }
250
+
251
+ # Return the position for the specified location
252
+ return locations.get(ref_location, [ref_pos[0], ref_pos[1], obj_z]) # Default position if location is not specified
253
+
254
+ def add_new_obj(scene, new_obj, ref_location, ref_object, rng, max_trails=50):
255
+
256
+ ref_obj_pos = ref_object.position
257
+ # import pdb; pdb.set_trace()
258
+ ref_obj_z_up = get_obj_z_up(ref_object.bounds, ref_object.scale)
259
+ new_obj_pos = get_new_pos(new_obj.bounds, new_obj.scale, ref_location, ref_obj_pos, ref_obj_z_up, ref_object, rng)
260
+ new_obj.position = new_obj_pos
261
+ scene += new_obj
262
+
263
+ # import pdb; pdb.set_trace()
264
+ trails = 0
265
+ while not check_ok(new_obj, new_obj.position, SPAWN_REGION_OBJ):
266
+ trails += 1
267
+ # import pdb; pdb.set_trace()
268
+ new_obj.position = get_new_pos(new_obj.bounds, new_obj.scale, ref_location, ref_obj_pos, ref_obj_z_up, ref_object, rng)
269
+ # new_obj.quaternion = random_rotation(axis="Z", rng=rng)
270
+ if trails > max_trails:
271
+ print('cannot put the object, break')
272
+ # import pdb; pdb.set_trace()
273
+ return None
274
+ print('try {} times'.format(trails))
275
+ return scene
276
+
277
+ def gen_caption(obj_name, obj_scale, ref_obj_name, ref_obj_scale, rotation):
278
+
279
+ if rotation == "flipped upside down":
280
+ captions = [f'the {obj_name} is flipped upside down', f'flip the {obj_name} upside down', f'Turn the {obj_name} upside down']
281
+ elif rotation == "turn around":
282
+ captions = [f'turn the {obj_name} around']
283
+ elif rotation == "turn left":
284
+ captions = [f'turn the {obj_name} 90 degrees', f'rotate the {obj_name} 90 degrees']
285
+ elif rotation == "turn right":
286
+ captions = [f'turn the {obj_name} 90 degrees', f'rotate the {obj_name} 90 degrees']
287
+ elif rotation == "fall down":
288
+ captions = [f'let the {obj_name} fall down', f'push the {obj_name} down', f'let the {obj_name} drop']
289
+ else:
290
+ captions = ['Fail']
291
+
292
+ # edit_verb = random.choice(['put', 'shift', 'move'])
293
+ # # caption = f'the{obj_size_exp} {obj_name} {verb_exp} {location_exp} the{ref_obj_size_exp} {ref_obj_name}'
294
+ # caption = f'{edit_verb} the {obj_name} {location_exp}'
295
+
296
+ return captions[random.randint(0, len(captions)-1)]
297
+
298
+
299
+
300
+ # --- Common setups & resources
301
+ print('Generate {} Sample'.format(FLAGS.generate_idx))
302
+ scene, rng, output_dir, scratch_dir = kb.setup(FLAGS)
303
+ output_dir = output_dir / FLAGS.sub_outputdir
304
+
305
+
306
+
307
+ simulator = PyBullet(scene, scratch_dir)
308
+ renderer = Blender(scene, scratch_dir, samples_per_pixel=64)
309
+ kubasic = kb.AssetSource.from_manifest(FLAGS.kubasic_assets)
310
+ gso = kb.AssetSource.from_manifest(FLAGS.gso_assets)
311
+ hdri_source = kb.AssetSource.from_manifest(FLAGS.hdri_assets)
312
+
313
+
314
+ # --- Populate the scene
315
+ # background HDRI
316
+ train_backgrounds, test_backgrounds = hdri_source.get_test_split(fraction=0.)
317
+ logging.info("Choosing one of the %d training backgrounds...", len(train_backgrounds))
318
+ hdri_id = rng.choice(train_backgrounds)
319
+
320
+ background_hdri = hdri_source.create(asset_id=hdri_id)
321
+ #assert isinstance(background_hdri, kb.Texture)
322
+ logging.info("Using background %s", hdri_id)
323
+ scene.metadata["background"] = hdri_id
324
+ renderer._set_ambient_light_hdri(background_hdri.filename)
325
+
326
+
327
+ # Dome
328
+ dome = kubasic.create(asset_id="dome", name="dome",
329
+ friction=FLAGS.floor_friction,
330
+ restitution=FLAGS.floor_restitution,
331
+ static=True, background=True)
332
+ assert isinstance(dome, kb.FileBasedObject)
333
+ scene += dome
334
+ dome_blender = dome.linked_objects[renderer]
335
+ texture_node = dome_blender.data.materials[0].node_tree.nodes["Image Texture"]
336
+ texture_node.image = bpy.data.images.load(background_hdri.filename)
337
+
338
+
339
+
340
+ def get_linear_camera_motion_start_end(
341
+ movement_speed: float,
342
+ inner_radius: float = 8.,
343
+ outer_radius: float = 12.,
344
+ z_offset: float = 0.1,
345
+ ):
346
+ """Sample a linear path which starts and ends within a half-sphere shell."""
347
+ while True:
348
+ camera_start = np.array(kb.sample_point_in_half_sphere_shell(inner_radius,
349
+ outer_radius,
350
+ z_offset))
351
+ direction = rng.rand(3) - 0.5
352
+ movement = direction / np.linalg.norm(direction) * movement_speed
353
+ camera_end = camera_start + movement
354
+ if (inner_radius <= np.linalg.norm(camera_end) <= outer_radius and
355
+ camera_end[2] > z_offset):
356
+ return camera_start, camera_end
357
+
358
+
359
+ # Camera
360
+ logging.info("Setting up the Camera...")
361
+ scene.camera = kb.PerspectiveCamera(focal_length=35., sensor_width=36)
362
+ if FLAGS.camera == "fixed_random":
363
+ # scene.camera.position = kb.sample_point_in_half_sphere_shell(
364
+ # inner_radius=7., outer_radius=9., offset=4)
365
+ y = 10 + rng.uniform(-1, 1)
366
+ z = 12 + rng.uniform(-3, 3)
367
+ scene.camera.position = (0, y, z)
368
+ scene.camera.look_at((0, 0, 0))
369
+ elif FLAGS.camera == "linear_movement":
370
+ camera_start, camera_end = get_linear_camera_motion_start_end(
371
+ movement_speed=rng.uniform(low=0., high=FLAGS.max_camera_movement)
372
+ )
373
+ # linearly interpolate the camera position between these two points
374
+ # while keeping it focused on the center of the scene
375
+ # we start one frame early and end one frame late to ensure that
376
+ # forward and backward flow are still consistent for the last and first frames
377
+ for frame in range(FLAGS.frame_start - 1, FLAGS.frame_end + 2):
378
+ interp = ((frame - FLAGS.frame_start + 1) /
379
+ (FLAGS.frame_end - FLAGS.frame_start + 3))
380
+ scene.camera.position = (interp * np.array(camera_start) +
381
+ (1 - interp) * np.array(camera_end))
382
+ scene.camera.look_at((0, 0, 0))
383
+ scene.camera.keyframe_insert("position", frame)
384
+ scene.camera.keyframe_insert("quaternion", frame)
385
+
386
+
387
+ # Add random objects
388
+ train_split, test_split = gso.get_test_split(fraction=0.)
389
+ # if FLAGS.objects_split == "train":
390
+ logging.info("Choosing one of the %d training objects...", len(train_split))
391
+ # active_split = train_split
392
+ active_split = list(GSO_dict.keys())
393
+
394
+ num_objects = rng.randint(FLAGS.min_num_objects,
395
+ FLAGS.max_num_objects+1 - 2)
396
+
397
+ logging.info("Step 1: Randomly placing %d objects:", num_objects)
398
+ object_state_save_dict = {}
399
+ object_state_ref_dict = {}
400
+
401
+
402
+ # not resample objects
403
+ # object_id_list = random.sample(active_split, num_objects+1)
404
+ object_id_list = sample_unique_items(GSO_dict, num_objects+1)
405
+
406
+
407
+ for i in range(num_objects):
408
+ # object_id = rng.choice(active_split)
409
+ object_id = object_id_list[i]
410
+ obj = gso.create(asset_id=object_id)
411
+
412
+
413
+ assert isinstance(obj, kb.FileBasedObject)
414
+ scale = rng.uniform(FLAGS.smallest_scale, FLAGS.largest_scale)
415
+ obj.scale = scale / np.max(obj.bounds[1] - obj.bounds[0])
416
+
417
+
418
+ obj_pos_z = - get_obj_z(obj.bounds, obj.scale)
419
+ SPAWN_REGION_OBJ[0][2], SPAWN_REGION_OBJ[1][2] = obj_pos_z, obj_pos_z
420
+ obj.position = rng.uniform(*SPAWN_REGION_OBJ)
421
+
422
+ obj.metadata["scale"] = scale
423
+ scene += obj
424
+ move_until_no_overlap(obj, simulator, spawn_region=SPAWN_REGION_OBJ, rng=rng)
425
+ # initialize velocity randomly but biased towards center
426
+ # obj.velocity = (rng.uniform(*VELOCITY_RANGE) -
427
+ # [obj.position[0], obj.position[1], 0])
428
+ # print(obj.position)
429
+ obj.velocity = [0, 0, 0]
430
+ logging.info(" Added %s at %s", obj.asset_id, obj.position)
431
+ object_state_save_dict[i] = {'object_id': object_id,
432
+ 'object_scale': obj.scale,
433
+ 'object_quaternion': obj.quaternion,
434
+ 'object_bounds': obj.bounds}
435
+ object_state_ref_dict[i] = {'object': obj}
436
+
437
+
438
+ ref_object = object_state_ref_dict[rng.choice(list(object_state_ref_dict.keys()))]['object'] # random choose an reference object
439
+ ref_object_name = GSO_dict[ref_object.asset_id]
440
+ ref_location = ref_object.position
441
+ # random choose two location
442
+ # LOC_SET = ['front', 'behind', 'left', 'right', 'on']
443
+ LOC_SET = ['further right', 'further left', 'further away', 'closer']
444
+ ref_location1 = random.sample(LOC_SET, 1)[0]
445
+ if ref_location1 == 'further right':
446
+ ref_location2 = 'further left'
447
+ elif ref_location1 == 'further left':
448
+ ref_location2 = 'further right'
449
+ elif ref_location1 == 'further away':
450
+ ref_location2 = 'closer'
451
+ elif ref_location1 == 'closer':
452
+ ref_location2 = 'further away'
453
+
454
+ # 1st
455
+ print('Generate the first scene.')
456
+ # object_id = rng.choice(active_split)
457
+ object_id = object_id_list[-1]
458
+ obj = gso.create(asset_id=object_id)
459
+ scale = rng.uniform(FLAGS.smallest_scale, FLAGS.largest_scale)
460
+ obj.scale = scale / np.max(obj.bounds[1] - obj.bounds[0])
461
+ obj.metadata["scale"] = scale
462
+
463
+ new_object_name = GSO_dict[obj.asset_id]
464
+ print('Add new object {}'.format(new_object_name))
465
+
466
+
467
+ scene = add_new_obj(scene, obj, ref_location1, ref_object, rng, max_trails=500)
468
+ if scene is None:
469
+ exit()
470
+ frame = renderer.render_still()
471
+
472
+ os.makedirs(output_dir/'{}'.format(FLAGS.generate_idx), exist_ok=True)
473
+ kb.write_png(frame["rgba"], output_dir/"{}/image0.png".format(FLAGS.generate_idx))
474
+ # caption_1 = gen_caption(new_object_name, obj.metadata["scale"], ref_object_name, ref_object.metadata["scale"], ref_location1)
475
+ # print(caption_1)
476
+
477
+
478
+ # save meta ann
479
+ object_state_save_dict[i+1] = {'object_id': object_id,
480
+ 'object_scale': obj.scale,
481
+ 'object_pos': obj.position,
482
+ 'object_quaternion': obj.quaternion,
483
+ 'object_bounds': obj.bounds}
484
+ # import json
485
+ # json.dump(object_state_save_dict, open(output_dir/'{}/meta_ann1.json'.format(FLAGS.generate_idx), 'w'))
486
+ # np.save(output_dir/'{}/meta_ann1.npy'.format(FLAGS.generate_idx), object_state_save_dict)
487
+ # renderer.save_state(output_dir/'{}/image1.blend'.format(FLAGS.generate_idx))
488
+
489
+
490
+
491
+ # 2nd
492
+ print('Generate the second scene.')
493
+ # delete the last object to generate the second frame
494
+ # import pdb; pdb.set_trace()
495
+ # scene.remove(obj)
496
+ # scene= add_new_obj(scene, obj, ref_location2, ref_object, rng, max_trails=100)
497
+ ref_obj_pos = ref_object.position
498
+ ref_obj_z_up = get_obj_z_up(ref_object.bounds, ref_object.scale)
499
+ logging.info(f'Object position: {obj.position}')
500
+ # new_obj_pos = get_new_pos(obj.bounds, obj.scale, ref_location2, obj.position, ref_obj_z_up, ref_object, rng)
501
+ # logging.info(f'New object position: {new_obj_pos}')
502
+ # obj.position = new_obj_pos
503
+
504
+ text2rotation = {
505
+ "flipped upside down": [rotation(axis='X', degrees=180), rotation(axis='Y', degrees=180)],
506
+ # "turn around": [rotation(axis='Z', degrees=180)],
507
+ # "turn left": [rotation(axis='Z', degrees=-90)],
508
+ # "turn righ": [rotation(axis='Z', degrees=90)],
509
+ # "fall down": [rotation(axis='X', degrees=90), rotation(axis='Y', degrees=90), rotation(axis='X', degrees=90), rotation(axis='Y', degrees=90)]
510
+ }
511
+
512
+ nope = ['towel', 'cloth', 'tape']
513
+ round_words = ['mug', 'bowl', 'plate', 'pot', 'saucer', 'hat', 'tape', 'mat', 'bottle', 'pan', 'ramekin']
514
+ can_fall = ['pot', 'mug', 'figure', 'toy', 'boot', 'bottle', 'lamp', 'refrigerator']
515
+
516
+ nope_cond, round_cond, fall_cond = False, False, False
517
+ for token in new_object_name.split():
518
+ if token in nope:
519
+ nope_cond = True
520
+ if token in round_words:
521
+ round_cond = True
522
+ if token in can_fall:
523
+ fall_cond = True
524
+
525
+ if nope_cond:
526
+ exit()
527
+
528
+ if not round_cond:
529
+ text2rotation.update({
530
+ "turn around": [rotation(axis='Z', degrees=180)],
531
+ "turn left": [rotation(axis='Z', degrees=-90)],
532
+ "turn right": [rotation(axis='Z', degrees=90)]
533
+ })
534
+
535
+ if fall_cond:
536
+ text2rotation.update({
537
+ "fall down": [rotation(axis='X', degrees=90), rotation(axis='Y', degrees=90), rotation(axis='X', degrees=90), rotation(axis='Y', degrees=90)]
538
+ })
539
+
540
+ sampled = random.sample(list(text2rotation.keys()), 1)
541
+ rotation_func = text2rotation[sampled[0]][random.randint(0, len(sampled)-1)]
542
+ obj.quaternion = rotation_func
543
+
544
+ frame = renderer.render_still()
545
+ kb.write_png(frame["rgba"], output_dir/"{}/image1.png".format(FLAGS.generate_idx))
546
+ caption_2 = gen_caption(new_object_name, obj.metadata["scale"], ref_object_name, ref_object.metadata["scale"], sampled[0])
547
+ print(caption_2)
548
+
549
+ # save meta ann
550
+ object_state_save_dict[i+1] = {'object_id': object_id,
551
+ 'object_scale': obj.scale,
552
+ 'object_pos': obj.position,
553
+ 'object_quaternion': obj.quaternion,
554
+ 'object_bounds': obj.bounds}
555
+ # import json
556
+ # json.dump(object_state_save_dict, open(output_dir/'{}/meta_ann2.json'.format(FLAGS.generate_idx), 'w'))
557
+ # np.save(output_dir/'{}/meta_ann2.npy'.format(FLAGS.generate_idx), object_state_save_dict)
558
+ # renderer.save_state(output_dir/'{}/image2.blend'.format(FLAGS.generate_idx))
559
+
560
+
561
+ # save json
562
+ # local_ann = {'image0':"{}/image0.png".format(FLAGS.generate_idx), 'caption0':caption_1,
563
+ # 'image1':"{}/image1.png".format(FLAGS.generate_idx), 'caption1':caption_2,
564
+ # 'ann_path':"{}/ann.json".format(FLAGS.generate_idx),
565
+ # 'obj_num':num_objects+1}
566
+ # json.dump(local_ann, open("{}/{}/ann.json".format(str(output_dir), FLAGS.generate_idx), 'w'))
567
+
568
+ # import pdb; pdb.set_trace()
569
+ # if not os.path.exists("{}/global_ann.json".format(str(output_dir))):
570
+ # json.dump([], open("{}/global_ann.json".format(str(output_dir)), 'w'))
571
+ # with open("{}/global_ann.json".format(str(output_dir)), 'r') as f:
572
+ # old_data = json.load(f)
573
+ # old_data.append(local_ann)
574
+ # with open("{}/global_ann.json".format(str(output_dir)), "w") as f:
575
+ # json.dump(old_data, f)
576
+
577
+ local_ann = [{
578
+ 'input': dataset_dir(DATASET_TYPE) + "{}/image0.png".format(FLAGS.generate_idx),
579
+ 'output': dataset_dir(DATASET_TYPE) + "{}/image1.png".format(FLAGS.generate_idx),
580
+ 'instruction': caption_2,
581
+ }
582
+ # {
583
+ # 'input': dataset_dir(DATASET_TYPE) + "{}/image1.png".format(FLAGS.generate_idx),
584
+ # 'output': dataset_dir(DATASET_TYPE) + "{}/image0.png".format(FLAGS.generate_idx),
585
+ # 'instruction': caption_1,
586
+ # }
587
+ ]
588
+ save_scene_instruction(f"{output_dir}/eq_kubric_{DATASET_TYPE}.json", local_ann, DATASET_TYPE, FLAGS.generate_idx)
589
+
590
+ kb.done()
eq-kubric/utils/__init__.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import json
4
+
5
+ def setup_output_files(dataset_type: str) -> None:
6
+ """
7
+ Sets up the necessary directories and files for the script to run.
8
+ """
9
+ setup_logs()
10
+ start_output_file(dataset_type)
11
+
12
+ def setup_logs(log_dir="logs") -> None:
13
+ """
14
+ Sets up the logging directory by removing it if it exists and then recreating it.
15
+
16
+ Args:
17
+ log_dir (str): The path to the log directory to set up.
18
+ """
19
+ if os.path.exists(log_dir):
20
+ shutil.rmtree(log_dir)
21
+ os.makedirs(log_dir, exist_ok=True)
22
+
23
+ def start_output_file(dataset_type: str) -> None:
24
+ output_json = f"output/{dataset_type}/eq_kubric_{dataset_type}.json"
25
+ os.makedirs(f"output/{dataset_type}", exist_ok=True)
26
+ with open(output_json, "w") as response_file:
27
+ response_file.write("[\n")
28
+
29
+ def end_output_file(dataset_type: str) -> None:
30
+ output_json = f"output/{dataset_type}/eq_kubric_{dataset_type}.json"
31
+ with open(output_json, "ab+") as response_file:
32
+ response_file.seek(-2, os.SEEK_END)
33
+ response_file.truncate()
34
+ response_file.write(b"\n]")
35
+
36
+ def dataset_dir(dataset_type: str) -> str:
37
+ return f"../../change_descriptions/eqmod/{dataset_type}/"
38
+
39
+ def save_scene_instruction(output_file_path: str, entries: list, dataset_type: str, index: int, log_file="logs/error_log.txt") -> None:
40
+ try:
41
+ for entry in entries:
42
+ with open(output_file_path, "a") as file:
43
+ json_string = json.dumps(entry, indent=4)
44
+ indented_json_string = "\n ".join(json_string.splitlines())
45
+ file.write(f" {indented_json_string},\n")
46
+ except Exception as e:
47
+ error_message = f"{e}\nFailed to save a scene text: Index: {index+1}, Dataset Type: '{dataset_type}'."
48
+ with open(log_file, "a") as file:
49
+ file.write(f"{error_message}\n")
eval_disc_edit.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import math
3
+
4
+ tasks = ['whatsup', 'something', 'ag', 'kubric', 'clevr']
5
+ ckpts = [
6
+ 'checkpoints_magic_reproduce_epoch=000047-step=000012999.ckpt_results.json',
7
+ 'logs_logs_finetune_magicbrush_ag_something_kubric_15-15-1-1_init-magic_first_checkpoints_trainstep_checkpoints_step=000041999.ckpt_results.json'
8
+ ]
9
+
10
+ for ckpt in ckpts:
11
+ print(ckpt)
12
+ skill_scores_latent_l2 = {task: [] for task in tasks}
13
+ for task in tasks:
14
+ results = json.load(open(f'itm_evaluation/test/{task}/{ckpt}'))
15
+ samples = 4
16
+
17
+ for idx, result in results.items():
18
+ pos_latent_l2s = result['pos']['latent_l2']
19
+ neg_latent_l2s = result['neg']['latent_l2']
20
+ if task == 'flickr_edit':
21
+ skills = result['task'].split(',')
22
+ skills = [skill.strip() for skill in skills]
23
+ for skill in skills:
24
+ skill_scores_latent_l2[skill] += [1 if pos_latent_l2s[i] < neg_latent_l2s[i] else 0 for i in range(len(pos_latent_l2s))]
25
+ skill_scores_latent_l2[task] += [1 if pos_latent_l2s[i] < neg_latent_l2s[i] else 0 for i in range(len(pos_latent_l2s))]
26
+
27
+ # make latex row with each task's score
28
+ row = ''
29
+ for k, v in skill_scores_latent_l2.items():
30
+ final_score = sum(v) / len(v)
31
+ se = math.sqrt(final_score * (1 - final_score) / len(v))
32
+ row += f' & {final_score:.3f} \pm {se:.3f}'
33
+ print(row)
hf_push.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import HfApi
2
+
3
+ model_name = "AURORA"
4
+
5
+ api = HfApi()
6
+ #api.create_repo("yfqiu-nlp/"+model_name.replace('+', '-'), repo_type="model")
7
+
8
+ from huggingface_hub import HfApi
9
+
10
+ api = HfApi()
11
+ api.upload_large_folder(
12
+ folder_path='./',
13
+ repo_id="yfqiu-nlp/AURORA",
14
+ repo_type="dataset",
15
+ )
main.py ADDED
@@ -0,0 +1,800 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse, os, sys, datetime, glob
2
+ import numpy as np
3
+ import time
4
+ import torch
5
+ import torchvision
6
+ import pytorch_lightning as pl
7
+ import json
8
+ import pickle
9
+
10
+ from packaging import version
11
+ from omegaconf import OmegaConf
12
+ from torch.utils.data import DataLoader, Dataset
13
+ from functools import partial
14
+ from PIL import Image
15
+
16
+ import torch.distributed as dist
17
+ from pytorch_lightning import seed_everything
18
+ from pytorch_lightning.trainer import Trainer
19
+ from pytorch_lightning.callbacks import ModelCheckpoint, Callback, LearningRateMonitor
20
+ from pytorch_lightning.utilities.distributed import rank_zero_only
21
+ from pytorch_lightning.utilities import rank_zero_info
22
+ from pytorch_lightning.plugins import DDPPlugin
23
+
24
+ sys.path.append("./stable_diffusion")
25
+
26
+ from ldm.data.base import Txt2ImgIterableBaseDataset
27
+ from ldm.util import instantiate_from_config
28
+
29
+
30
+ def get_parser(**parser_kwargs):
31
+ def str2bool(v):
32
+ if isinstance(v, bool):
33
+ return v
34
+ if v.lower() in ("yes", "true", "t", "y", "1"):
35
+ return True
36
+ elif v.lower() in ("no", "false", "f", "n", "0"):
37
+ return False
38
+ else:
39
+ raise argparse.ArgumentTypeError("Boolean value expected.")
40
+
41
+ parser = argparse.ArgumentParser(**parser_kwargs)
42
+ parser.add_argument(
43
+ "-n",
44
+ "--name",
45
+ type=str,
46
+ const=True,
47
+ default="train",
48
+ nargs="?",
49
+ help="postfix for logdir",
50
+ )
51
+ parser.add_argument(
52
+ "-r",
53
+ "--resume",
54
+ type=str,
55
+ const=True,
56
+ default="",
57
+ nargs="?",
58
+ help="resume from logdir or checkpoint in logdir",
59
+ )
60
+ parser.add_argument(
61
+ "-b",
62
+ "--base",
63
+ nargs="*",
64
+ default='configs/finetune_magicbrush_ag_something_kubric_15-15-1-1_init-magic.yaml',
65
+ help="paths to base configs. Loaded from left-to-right."
66
+ "Parameters can be overwritten or added with command-line options of the form `--key value`.",
67
+ )
68
+ parser.add_argument(
69
+ "-t",
70
+ "--train",
71
+ type=str2bool,
72
+ const=True,
73
+ default=True,
74
+ nargs="?",
75
+ help="train",
76
+ )
77
+ parser.add_argument(
78
+ "--no-test",
79
+ type=str2bool,
80
+ const=True,
81
+ default=False,
82
+ nargs="?",
83
+ help="disable test",
84
+ )
85
+ parser.add_argument(
86
+ "-p",
87
+ "--project",
88
+ help="name of new or path to existing project"
89
+ )
90
+ parser.add_argument(
91
+ "-d",
92
+ "--debug",
93
+ type=str2bool,
94
+ nargs="?",
95
+ const=True,
96
+ default=False,
97
+ help="enable post-mortem debugging",
98
+ )
99
+ parser.add_argument(
100
+ "-s",
101
+ "--seed",
102
+ type=int,
103
+ default=23,
104
+ help="seed for seed_everything",
105
+ )
106
+ parser.add_argument(
107
+ "-f",
108
+ "--postfix",
109
+ type=str,
110
+ default="",
111
+ help="post-postfix for default name",
112
+ )
113
+ parser.add_argument(
114
+ "-l",
115
+ "--logdir",
116
+ type=str,
117
+ default="/mnt/research/scratch/bkroje/logs",
118
+ help="directory for logging dat shit",
119
+ )
120
+ parser.add_argument(
121
+ "--scale_lr",
122
+ action="store_true",
123
+ default=False,
124
+ help="scale base-lr by ngpu * batch_size * n_accumulate",
125
+ )
126
+ return parser
127
+
128
+
129
+ def nondefault_trainer_args(opt):
130
+ parser = argparse.ArgumentParser()
131
+ parser = Trainer.add_argparse_args(parser)
132
+ args = parser.parse_args([])
133
+ return sorted(k for k in vars(args) if getattr(opt, k) != getattr(args, k))
134
+
135
+
136
+ class WrappedDataset(Dataset):
137
+ """Wraps an arbitrary object with __len__ and __getitem__ into a pytorch dataset"""
138
+
139
+ def __init__(self, dataset):
140
+ self.data = dataset
141
+
142
+ def __len__(self):
143
+ return len(self.data)
144
+
145
+ def __getitem__(self, idx):
146
+ return self.data[idx]
147
+
148
+
149
+ def worker_init_fn(_):
150
+ worker_info = torch.utils.data.get_worker_info()
151
+
152
+ dataset = worker_info.dataset
153
+ worker_id = worker_info.id
154
+
155
+ if isinstance(dataset, Txt2ImgIterableBaseDataset):
156
+ split_size = dataset.num_records // worker_info.num_workers
157
+ # reset num_records to the true number to retain reliable length information
158
+ dataset.sample_ids = dataset.valid_ids[worker_id * split_size:(worker_id + 1) * split_size]
159
+ current_id = np.random.choice(len(np.random.get_state()[1]), 1)
160
+ return np.random.seed(np.random.get_state()[1][current_id] + worker_id)
161
+ else:
162
+ return np.random.seed(np.random.get_state()[1][0] + worker_id)
163
+
164
+
165
+ class DataModuleFromConfig(pl.LightningDataModule):
166
+ def __init__(self, batch_size, train=None, validation=None, test=None, predict=None,
167
+ wrap=False, num_workers=None, shuffle_test_loader=False, use_worker_init_fn=False,
168
+ shuffle_val_dataloader=False):
169
+ super().__init__()
170
+ self.batch_size = batch_size
171
+ self.dataset_configs = dict()
172
+ self.num_workers = num_workers if num_workers is not None else batch_size * 2
173
+ self.use_worker_init_fn = use_worker_init_fn
174
+ if train is not None:
175
+ self.dataset_configs["train"] = train
176
+ self.train_dataloader = self._train_dataloader
177
+ if validation is not None:
178
+ self.dataset_configs["validation"] = validation
179
+ self.val_dataloader = partial(self._val_dataloader, shuffle=shuffle_val_dataloader)
180
+ if test is not None:
181
+ self.dataset_configs["test"] = test
182
+ self.test_dataloader = partial(self._test_dataloader, shuffle=shuffle_test_loader)
183
+ if predict is not None:
184
+ self.dataset_configs["predict"] = predict
185
+ self.predict_dataloader = self._predict_dataloader
186
+ self.wrap = wrap
187
+
188
+ def prepare_data(self):
189
+ for data_cfg in self.dataset_configs.values():
190
+ instantiate_from_config(data_cfg)
191
+
192
+ def setup(self, stage=None):
193
+ self.datasets = dict(
194
+ (k, instantiate_from_config(self.dataset_configs[k]))
195
+ for k in self.dataset_configs)
196
+ if self.wrap:
197
+ for k in self.datasets:
198
+ self.datasets[k] = WrappedDataset(self.datasets[k])
199
+
200
+ def _train_dataloader(self):
201
+ is_iterable_dataset = isinstance(self.datasets['train'], Txt2ImgIterableBaseDataset)
202
+ if is_iterable_dataset or self.use_worker_init_fn:
203
+ init_fn = worker_init_fn
204
+ else:
205
+ init_fn = None
206
+ return DataLoader(self.datasets["train"], batch_size=self.batch_size,
207
+ num_workers=self.num_workers, shuffle=False if is_iterable_dataset else True,
208
+ worker_init_fn=init_fn, persistent_workers=True)
209
+
210
+ def _val_dataloader(self, shuffle=False):
211
+ if isinstance(self.datasets['validation'], Txt2ImgIterableBaseDataset) or self.use_worker_init_fn:
212
+ init_fn = worker_init_fn
213
+ else:
214
+ init_fn = None
215
+ return DataLoader(self.datasets["validation"],
216
+ batch_size=self.batch_size,
217
+ num_workers=self.num_workers,
218
+ worker_init_fn=init_fn,
219
+ shuffle=shuffle, persistent_workers=True)
220
+
221
+ def _test_dataloader(self, shuffle=False):
222
+ is_iterable_dataset = isinstance(self.datasets['train'], Txt2ImgIterableBaseDataset)
223
+ if is_iterable_dataset or self.use_worker_init_fn:
224
+ init_fn = worker_init_fn
225
+ else:
226
+ init_fn = None
227
+
228
+ # do not shuffle dataloader for iterable dataset
229
+ shuffle = shuffle and (not is_iterable_dataset)
230
+
231
+ return DataLoader(self.datasets["test"], batch_size=self.batch_size,
232
+ num_workers=self.num_workers, worker_init_fn=init_fn, shuffle=shuffle, persistent_workers=True)
233
+
234
+ def _predict_dataloader(self, shuffle=False):
235
+ if isinstance(self.datasets['predict'], Txt2ImgIterableBaseDataset) or self.use_worker_init_fn:
236
+ init_fn = worker_init_fn
237
+ else:
238
+ init_fn = None
239
+ return DataLoader(self.datasets["predict"], batch_size=self.batch_size,
240
+ num_workers=self.num_workers, worker_init_fn=init_fn, persistent_workers=True)
241
+
242
+
243
+ class SetupCallback(Callback):
244
+ def __init__(self, resume, now, logdir, ckptdir, cfgdir, config, lightning_config):
245
+ super().__init__()
246
+ self.resume = resume
247
+ self.now = now
248
+ self.logdir = logdir
249
+ self.ckptdir = ckptdir
250
+ self.cfgdir = cfgdir
251
+ self.config = config
252
+ self.lightning_config = lightning_config
253
+
254
+ def on_keyboard_interrupt(self, trainer, pl_module):
255
+ if trainer.global_rank == 0:
256
+ print("Summoning checkpoint.")
257
+ ckpt_path = os.path.join(self.ckptdir, "last.ckpt")
258
+ trainer.save_checkpoint(ckpt_path)
259
+
260
+ def on_pretrain_routine_start(self, trainer, pl_module):
261
+ if trainer.global_rank == 0:
262
+ # Create logdirs and save configs
263
+ # os.makedirs(self.logdir, exist_ok=True)
264
+ # os.makedirs(self.ckptdir, exist_ok=True)
265
+ # os.makedirs(self.cfgdir, exist_ok=True)
266
+
267
+ if "callbacks" in self.lightning_config:
268
+ if 'metrics_over_trainsteps_checkpoint' in self.lightning_config['callbacks']:
269
+ os.makedirs(os.path.join(self.ckptdir, 'trainstep_checkpoints'), exist_ok=True)
270
+ print("Project config")
271
+ print(OmegaConf.to_yaml(self.config))
272
+ OmegaConf.save(self.config,
273
+ os.path.join(self.cfgdir, "{}-project.yaml".format(self.now)))
274
+
275
+ print("Lightning config")
276
+ print(OmegaConf.to_yaml(self.lightning_config))
277
+ OmegaConf.save(OmegaConf.create({"lightning": self.lightning_config}),
278
+ os.path.join(self.cfgdir, "{}-lightning.yaml".format(self.now)))
279
+
280
+ def get_world_size():
281
+ if not dist.is_available():
282
+ return 1
283
+ if not dist.is_initialized():
284
+ return 1
285
+ return dist.get_world_size()
286
+
287
+ def all_gather(data):
288
+ """
289
+ Run all_gather on arbitrary picklable data (not necessarily tensors)
290
+ Args:
291
+ data: any picklable object
292
+ Returns:
293
+ list[data]: list of data gathered from each rank
294
+ """
295
+ world_size = get_world_size()
296
+ if world_size == 1:
297
+ return [data]
298
+
299
+ # serialized to a Tensor
300
+ origin_size = None
301
+ if not isinstance(data, torch.Tensor):
302
+ buffer = pickle.dumps(data)
303
+ storage = torch.ByteStorage.from_buffer(buffer)
304
+ tensor = torch.ByteTensor(storage).to("cuda")
305
+ else:
306
+ origin_size = data.size()
307
+ tensor = data.reshape(-1)
308
+
309
+ tensor_type = tensor.dtype
310
+
311
+ # obtain Tensor size of each rank
312
+ local_size = torch.LongTensor([tensor.numel()]).to("cuda")
313
+ size_list = [torch.LongTensor([0]).to("cuda") for _ in range(world_size)]
314
+ dist.all_gather(size_list, local_size)
315
+ size_list = [int(size.item()) for size in size_list]
316
+ max_size = max(size_list)
317
+
318
+ # receiving Tensor from all ranks
319
+ # we pad the tensor because torch all_gather does not support
320
+ # gathering tensors of different shapes
321
+ tensor_list = []
322
+ for _ in size_list:
323
+ tensor_list.append(torch.FloatTensor(size=(max_size,)).cuda().to(tensor_type))
324
+ if local_size != max_size:
325
+ padding = torch.FloatTensor(size=(max_size - local_size,)).cuda().to(tensor_type)
326
+ tensor = torch.cat((tensor, padding), dim=0)
327
+ dist.all_gather(tensor_list, tensor)
328
+
329
+ data_list = []
330
+ for size, tensor in zip(size_list, tensor_list):
331
+ if origin_size is None:
332
+ buffer = tensor.cpu().numpy().tobytes()[:size]
333
+ data_list.append(pickle.loads(buffer))
334
+ else:
335
+ buffer = tensor[:size]
336
+ data_list.append(buffer)
337
+
338
+ if origin_size is not None:
339
+ new_shape = [-1] + list(origin_size[1:])
340
+ resized_list = []
341
+ for data in data_list:
342
+ # suppose the difference of tensor size exist in first dimension
343
+ data = data.reshape(new_shape)
344
+ resized_list.append(data)
345
+
346
+ return resized_list
347
+ else:
348
+ return data_list
349
+
350
+ class ImageLogger(Callback):
351
+ def __init__(self, batch_frequency, max_images, clamp=True, increase_log_steps=True,
352
+ rescale=True, disabled=False, log_on_batch_idx=False, log_first_step=False,
353
+ log_images_kwargs=None):
354
+ super().__init__()
355
+ self.rescale = rescale
356
+ self.batch_freq = batch_frequency
357
+ self.max_images = max_images
358
+ self.logger_log_images = {
359
+ pl.loggers.TestTubeLogger: self._testtube,
360
+ }
361
+ self.log_steps = [2 ** n for n in range(6, int(np.log2(self.batch_freq)) + 1)]
362
+ if not increase_log_steps:
363
+ self.log_steps = [self.batch_freq]
364
+ self.clamp = clamp
365
+ self.disabled = disabled
366
+ self.log_on_batch_idx = log_on_batch_idx
367
+ self.log_images_kwargs = log_images_kwargs if log_images_kwargs else {}
368
+ self.log_first_step = log_first_step
369
+
370
+ @rank_zero_only
371
+ def _testtube(self, pl_module, images, batch_idx, split):
372
+ for k in images:
373
+ grid = torchvision.utils.make_grid(images[k])
374
+ grid = (grid + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w
375
+
376
+ tag = f"{split}/{k}"
377
+ pl_module.logger.experiment.add_image(
378
+ tag, grid,
379
+ global_step=pl_module.global_step)
380
+
381
+ @rank_zero_only
382
+ def log_local(self, save_dir, split, images, prompts,
383
+ global_step, current_epoch, batch_idx):
384
+ root = os.path.join(save_dir, "images", split)
385
+ names = {"reals": "before", "inputs": "after", "reconstruction": "before-vq", "samples": "after-gen"}
386
+ # print(root)
387
+ for k in images:
388
+ grid = torchvision.utils.make_grid(images[k], nrow=8)
389
+ if self.rescale:
390
+ grid = (grid + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w
391
+ grid = grid.transpose(0, 1).transpose(1, 2).squeeze(-1)
392
+ grid = grid.numpy()
393
+ grid = (grid * 255).astype(np.uint8)
394
+ filename = "global_step-{:06}_epoch-{:06}_batch-{:06}_{}.png".format(
395
+ global_step,
396
+ current_epoch,
397
+ batch_idx,
398
+ names[k])
399
+ path = os.path.join(root, filename)
400
+ os.makedirs(os.path.split(path)[0], exist_ok=True)
401
+ # print(path)
402
+ Image.fromarray(grid).save(path)
403
+
404
+ filename = "global_step-{:06}_epoch-{:06}_batch-{:06}_prompt.json".format(
405
+ global_step,
406
+ current_epoch,
407
+ batch_idx)
408
+ path = os.path.join(root, filename)
409
+ with open(path, "w") as f:
410
+ for p in prompts:
411
+ f.write(f"{json.dumps(p)}\n")
412
+
413
+ def log_img(self, pl_module, batch, batch_idx, split="train"):
414
+ check_idx = batch_idx if self.log_on_batch_idx else pl_module.global_step
415
+ if (self.check_frequency(check_idx) and # batch_idx % self.batch_freq == 0
416
+ hasattr(pl_module, "log_images") and
417
+ callable(pl_module.log_images) and
418
+ self.max_images > 0) or (split == "val" and batch_idx == 0):
419
+ logger = type(pl_module.logger)
420
+
421
+ is_train = pl_module.training
422
+ if is_train:
423
+ pl_module.eval()
424
+
425
+ with torch.no_grad():
426
+ images = pl_module.log_images(batch, split=split, **self.log_images_kwargs)
427
+
428
+ prompts = batch["edit"]["c_crossattn"][:self.max_images]
429
+ prompts = [p for ps in all_gather(prompts) for p in ps]
430
+
431
+ for k in images:
432
+ N = min(images[k].shape[0], self.max_images)
433
+ images[k] = images[k][:N]
434
+ images[k] = torch.cat(all_gather(images[k][:N]))
435
+ if isinstance(images[k], torch.Tensor):
436
+ images[k] = images[k].detach().cpu()
437
+ if self.clamp:
438
+ images[k] = torch.clamp(images[k], -1., 1.)
439
+
440
+ self.log_local(pl_module.logger.save_dir, split, images, prompts,
441
+ pl_module.global_step, pl_module.current_epoch, batch_idx)
442
+
443
+ logger_log_images = self.logger_log_images.get(logger, lambda *args, **kwargs: None)
444
+ logger_log_images(pl_module, images, pl_module.global_step, split)
445
+
446
+ if is_train:
447
+ pl_module.train()
448
+
449
+ def check_frequency(self, check_idx):
450
+ if ((check_idx % self.batch_freq) == 0 or (check_idx in self.log_steps)) and (
451
+ check_idx > 0 or self.log_first_step):
452
+ if len(self.log_steps) > 0:
453
+ self.log_steps.pop(0)
454
+ return True
455
+ return False
456
+
457
+ # def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
458
+ # if not self.disabled and (pl_module.global_step > 0 or self.log_first_step):
459
+ # self.log_img(pl_module, batch, batch_idx, split="train")
460
+
461
+ # def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
462
+ # if not self.disabled and pl_module.global_step > 0:
463
+ # self.log_img(pl_module, batch, batch_idx, split="val")
464
+ # if hasattr(pl_module, 'calibrate_grad_norm'):
465
+ # if (pl_module.calibrate_grad_norm and batch_idx % 25 == 0) and batch_idx > 0:
466
+ # self.log_gradients(trainer, pl_module, batch_idx=batch_idx)
467
+
468
+
469
+ class CUDACallback(Callback):
470
+ # see https://github.com/SeanNaren/minGPT/blob/master/mingpt/callback.py
471
+ def on_train_epoch_start(self, trainer, pl_module):
472
+ # Reset the memory use counter
473
+ torch.cuda.reset_peak_memory_stats(trainer.root_gpu)
474
+ torch.cuda.synchronize(trainer.root_gpu)
475
+ self.start_time = time.time()
476
+
477
+ def on_train_epoch_end(self, trainer, pl_module, outputs):
478
+ torch.cuda.synchronize(trainer.root_gpu)
479
+ max_memory = torch.cuda.max_memory_allocated(trainer.root_gpu) / 2 ** 20
480
+ epoch_time = time.time() - self.start_time
481
+
482
+ try:
483
+ max_memory = trainer.training_type_plugin.reduce(max_memory)
484
+ epoch_time = trainer.training_type_plugin.reduce(epoch_time)
485
+
486
+ rank_zero_info(f"Average Epoch time: {epoch_time:.2f} seconds")
487
+ rank_zero_info(f"Average Peak memory {max_memory:.2f}MiB")
488
+ except AttributeError:
489
+ pass
490
+
491
+
492
+ if __name__ == "__main__":
493
+ # custom parser to specify config files, train, test and debug mode,
494
+ # postfix, resume.
495
+ # `--key value` arguments are interpreted as arguments to the trainer.
496
+ # `nested.key=value` arguments are interpreted as config parameters.
497
+ # configs are merged from left-to-right followed by command line parameters.
498
+
499
+ # model:
500
+ # base_learning_rate: float
501
+ # target: path to lightning module
502
+ # params:
503
+ # key: value
504
+ # data:
505
+ # target: main.DataModuleFromConfig
506
+ # params:
507
+ # batch_size: int
508
+ # wrap: bool
509
+ # train:
510
+ # target: path to train dataset
511
+ # params:
512
+ # key: value
513
+ # validation:
514
+ # target: path to validation dataset
515
+ # params:
516
+ # key: value
517
+ # test:
518
+ # target: path to test dataset
519
+ # params:
520
+ # key: value
521
+ # lightning: (optional, has sane defaults and can be specified on cmdline)
522
+ # trainer:
523
+ # additional arguments to trainer
524
+ # logger:
525
+ # logger to instantiate
526
+ # modelcheckpoint:
527
+ # modelcheckpoint to instantiate
528
+ # callbacks:
529
+ # callback1:
530
+ # target: importpath
531
+ # params:
532
+ # key: value
533
+
534
+ now = datetime.datetime.now().strftime("%Y-%m-%dT%H-%M-%S")
535
+
536
+ # add cwd for convenience and to make classes in this file available when
537
+ # running as `python main.py`
538
+ # (in particular `main.DataModuleFromConfig`)
539
+ sys.path.append(os.getcwd())
540
+
541
+ parser = get_parser()
542
+ parser = Trainer.add_argparse_args(parser)
543
+
544
+ opt, unknown = parser.parse_known_args()
545
+
546
+ assert opt.name
547
+ cfg_fname = os.path.split(opt.base[0])[-1]
548
+ cfg_name = os.path.splitext(cfg_fname)[0]
549
+ nowname = f"{cfg_name}_{opt.name}"
550
+ logdir = os.path.join(opt.logdir, nowname)
551
+ ckpt = os.path.join(logdir, "checkpoints", "last.ckpt")
552
+ resume = False
553
+
554
+ if os.path.isfile(ckpt):
555
+ opt.resume_from_checkpoint = ckpt
556
+ base_configs = sorted(glob.glob(os.path.join(logdir, "configs/*.yaml")))
557
+ opt.base = base_configs + opt.base
558
+ _tmp = logdir.split("/")
559
+ nowname = _tmp[-1]
560
+ resume = True
561
+
562
+ ckptdir = os.path.join(logdir, "checkpoints")
563
+ cfgdir = os.path.join(logdir, "configs")
564
+
565
+ os.makedirs(logdir, exist_ok=True)
566
+ os.makedirs(ckptdir, exist_ok=True)
567
+ os.makedirs(cfgdir, exist_ok=True)
568
+
569
+ try:
570
+ # init and save configs
571
+ configs = [OmegaConf.load(opt.base)]
572
+ cli = OmegaConf.from_dotlist(unknown)
573
+ config = OmegaConf.merge(*configs, cli)
574
+
575
+ if resume:
576
+ # By default, when finetuning from Stable Diffusion, we load the EMA-only checkpoint to initialize all weights.
577
+ # If resuming InstructPix2Pix from a finetuning checkpoint, instead load both EMA and non-EMA weights.
578
+ config.model.params.load_ema = True
579
+
580
+ lightning_config = config.pop("lightning", OmegaConf.create())
581
+ # merge trainer cli with config
582
+ trainer_config = lightning_config.get("trainer", OmegaConf.create())
583
+ # default to ddp
584
+ trainer_config["accelerator"] = "ddp"
585
+ for k in nondefault_trainer_args(opt):
586
+ trainer_config[k] = getattr(opt, k)
587
+ if not "gpus" in trainer_config:
588
+ del trainer_config["accelerator"]
589
+ cpu = True
590
+ else:
591
+ gpuinfo = trainer_config["gpus"]
592
+ print(f"Running on GPUs {gpuinfo}")
593
+ cpu = False
594
+ trainer_opt = argparse.Namespace(**trainer_config)
595
+ lightning_config.trainer = trainer_config
596
+
597
+ # model
598
+ model = instantiate_from_config(config.model)
599
+
600
+ # trainer and callbacks
601
+ trainer_kwargs = dict()
602
+
603
+ # default logger configs
604
+ default_logger_cfgs = {
605
+ "wandb": {
606
+ "target": "pytorch_lightning.loggers.WandbLogger",
607
+ "params": {
608
+ "name": nowname,
609
+ "save_dir": logdir,
610
+ "id": nowname,
611
+ }
612
+ },
613
+ "testtube": {
614
+ "target": "pytorch_lightning.loggers.TestTubeLogger",
615
+ "params": {
616
+ "name": "testtube",
617
+ "save_dir": logdir,
618
+ }
619
+ },
620
+ }
621
+ default_logger_cfg = default_logger_cfgs["wandb"]
622
+ if "logger" in lightning_config:
623
+ logger_cfg = lightning_config.logger
624
+ else:
625
+ logger_cfg = OmegaConf.create()
626
+ logger_cfg = OmegaConf.merge(default_logger_cfg, logger_cfg)
627
+ trainer_kwargs["logger"] = instantiate_from_config(logger_cfg)
628
+
629
+ # modelcheckpoint - use TrainResult/EvalResult(checkpoint_on=metric) to
630
+ # specify which metric is used to determine best models
631
+ default_modelckpt_cfg = {
632
+ "target": "pytorch_lightning.callbacks.ModelCheckpoint",
633
+ "params": {
634
+ "dirpath": ckptdir,
635
+ "filename": "{epoch:06}",
636
+ 'filename': 'last',
637
+ "verbose": True,
638
+ "save_last": True,
639
+ "save_top_k": 0,
640
+ }
641
+ }
642
+
643
+ if "modelcheckpoint" in lightning_config:
644
+ modelckpt_cfg = lightning_config.modelcheckpoint
645
+ else:
646
+ modelckpt_cfg = OmegaConf.create()
647
+ modelckpt_cfg = OmegaConf.merge(default_modelckpt_cfg, modelckpt_cfg)
648
+ print(f"Merged modelckpt-cfg: \n{modelckpt_cfg}")
649
+ if version.parse(pl.__version__) < version.parse('1.4.0'):
650
+ trainer_kwargs["checkpoint_callback"] = instantiate_from_config(modelckpt_cfg)
651
+
652
+ # add callback which sets up log directory
653
+ default_callbacks_cfg = {
654
+ "setup_callback": {
655
+ "target": "main.SetupCallback",
656
+ "params": {
657
+ "resume": opt.resume,
658
+ "now": now,
659
+ "logdir": logdir,
660
+ "ckptdir": ckptdir,
661
+ "cfgdir": cfgdir,
662
+ "config": config,
663
+ "lightning_config": lightning_config,
664
+ }
665
+ },
666
+ "image_logger": {
667
+ "target": "main.ImageLogger",
668
+ "params": {
669
+ "batch_frequency": 750,
670
+ "max_images": 8,
671
+ "clamp": True
672
+ }
673
+ },
674
+ "learning_rate_logger": {
675
+ "target": "main.LearningRateMonitor",
676
+ "params": {
677
+ "logging_interval": "step",
678
+ # "log_momentum": True
679
+ }
680
+ },
681
+ "cuda_callback": {
682
+ "target": "main.CUDACallback"
683
+ },
684
+ }
685
+ if version.parse(pl.__version__) >= version.parse('1.4.0'):
686
+ default_callbacks_cfg.update({'checkpoint_callback': modelckpt_cfg})
687
+
688
+ if "callbacks" in lightning_config:
689
+ callbacks_cfg = lightning_config.callbacks
690
+ else:
691
+ callbacks_cfg = OmegaConf.create()
692
+
693
+ print(
694
+ 'Caution: Saving checkpoints every n train steps without deleting. This might require some free space.')
695
+ default_metrics_over_trainsteps_ckpt_dict = {
696
+ 'metrics_over_trainsteps_checkpoint': {
697
+ "target": 'pytorch_lightning.callbacks.ModelCheckpoint',
698
+ 'params': {
699
+ "dirpath": os.path.join(ckptdir, 'trainstep_checkpoints'),
700
+ "filename": "{epoch:06}-{step:09}",
701
+ "verbose": True,
702
+ 'save_top_k': -1,
703
+ 'every_n_train_steps': 1000,
704
+ 'save_weights_only': True
705
+ }
706
+ }
707
+ }
708
+ default_callbacks_cfg.update(default_metrics_over_trainsteps_ckpt_dict)
709
+
710
+ callbacks_cfg = OmegaConf.merge(default_callbacks_cfg, callbacks_cfg)
711
+ if 'ignore_keys_callback' in callbacks_cfg and hasattr(trainer_opt, 'resume_from_checkpoint'):
712
+ callbacks_cfg.ignore_keys_callback.params['ckpt_path'] = trainer_opt.resume_from_checkpoint
713
+ elif 'ignore_keys_callback' in callbacks_cfg:
714
+ del callbacks_cfg['ignore_keys_callback']
715
+
716
+ trainer_kwargs["callbacks"] = [instantiate_from_config(callbacks_cfg[k]) for k in callbacks_cfg]
717
+
718
+ trainer = Trainer.from_argparse_args(trainer_opt, plugins=DDPPlugin(find_unused_parameters=False), **trainer_kwargs)
719
+ trainer.logdir = logdir ###
720
+
721
+ # data
722
+ data = instantiate_from_config(config.data)
723
+ # NOTE according to https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html
724
+ # calling these ourselves should not be necessary but it is.
725
+ # lightning still takes care of proper multiprocessing though
726
+ data.prepare_data()
727
+ data.setup()
728
+ print("#### Data #####")
729
+ for k in data.datasets:
730
+ print(f"{k}, {data.datasets[k].__class__.__name__}, {len(data.datasets[k])}")
731
+
732
+ # configure learning rate
733
+ bs, base_lr = config.data.params.batch_size, config.model.base_learning_rate
734
+ if not cpu:
735
+ ngpu = len(lightning_config.trainer.gpus.strip(",").split(','))
736
+ else:
737
+ ngpu = 1
738
+ if 'accumulate_grad_batches' in lightning_config.trainer:
739
+ accumulate_grad_batches = lightning_config.trainer.accumulate_grad_batches
740
+ else:
741
+ accumulate_grad_batches = 1
742
+ print(f"accumulate_grad_batches = {accumulate_grad_batches}")
743
+ lightning_config.trainer.accumulate_grad_batches = accumulate_grad_batches
744
+ if opt.scale_lr:
745
+ model.learning_rate = accumulate_grad_batches * ngpu * bs * base_lr
746
+ print(
747
+ "Setting learning rate to {:.2e} = {} (accumulate_grad_batches) * {} (num_gpus) * {} (batchsize) * {:.2e} (base_lr)".format(
748
+ model.learning_rate, accumulate_grad_batches, ngpu, bs, base_lr))
749
+ else:
750
+ model.learning_rate = base_lr
751
+ print("++++ NOT USING LR SCALING ++++")
752
+ print(f"Setting learning rate to {model.learning_rate:.2e}")
753
+
754
+
755
+ # allow checkpointing via USR1
756
+ def melk(*args, **kwargs):
757
+ # run all checkpoint hooks
758
+ if trainer.global_rank == 0:
759
+ print("Summoning checkpoint.")
760
+ ckpt_path = os.path.join(ckptdir, "last.ckpt")
761
+ trainer.save_checkpoint(ckpt_path)
762
+
763
+
764
+ def divein(*args, **kwargs):
765
+ if trainer.global_rank == 0:
766
+ import pudb;
767
+ pudb.set_trace()
768
+
769
+
770
+ import signal
771
+
772
+ signal.signal(signal.SIGUSR1, melk)
773
+ signal.signal(signal.SIGUSR2, divein)
774
+
775
+ # run
776
+ if opt.train:
777
+ try:
778
+ trainer.fit(model, data)
779
+ except Exception:
780
+ melk()
781
+ raise
782
+ if not opt.no_test and not trainer.interrupted:
783
+ trainer.test(model, data)
784
+ except Exception:
785
+ if opt.debug and trainer.global_rank == 0:
786
+ try:
787
+ import pudb as debugger
788
+ except ImportError:
789
+ import pdb as debugger
790
+ debugger.post_mortem()
791
+ raise
792
+ finally:
793
+ # move newly created debug project to debug_runs
794
+ if opt.debug and not opt.resume and trainer.global_rank == 0:
795
+ dst, name = os.path.split(logdir)
796
+ dst = os.path.join(dst, "debug_runs", name)
797
+ os.makedirs(os.path.split(dst)[0], exist_ok=True)
798
+ os.rename(logdir, dst)
799
+ if trainer.global_rank == 0:
800
+ print(trainer.profiler.summary())
requirements.txt ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==2.0.0
2
+ accelerate==0.26.1
3
+ addict==2.4.0
4
+ aiofiles==23.2.1
5
+ aiohttp==3.9.1
6
+ aiosignal==1.3.1
7
+ albumentations==0.4.3
8
+ altair==5.2.0
9
+ annotated-types==0.6.0
10
+ antlr4-python3-runtime==4.8
11
+ anyio==4.2.0
12
+ appdirs==1.4.4
13
+ asttokens==2.4.1
14
+ async-timeout==4.0.3
15
+ attrs==23.2.0
16
+ beautifulsoup4==4.12.2
17
+ blinker==1.7.0
18
+ cachetools==5.3.2
19
+ certifi==2023.11.17
20
+ charset-normalizer==3.3.2
21
+ clean-fid==0.1.35
22
+ click==8.1.7
23
+ -e git+https://github.com/openai/CLIP.git@a1d071733d7111c9c014f024669f959182114e33#egg=clip
24
+ clip-anytorch==2.5.2
25
+ cmake==3.28.1
26
+ colorama==0.4.6
27
+ contourpy==1.2.0
28
+ cycler==0.12.1
29
+ datasets==2.17.1
30
+ dctorch==0.1.2
31
+ diffusers==0.25.0
32
+ dill==0.3.6
33
+ distro==1.9.0
34
+ docker-pycreds==0.4.0
35
+ easydict==1.12
36
+ einops==0.3.0
37
+ exceptiongroup==1.2.0
38
+ executing==2.0.1
39
+ facexlib==0.3.0
40
+ fancycompleter==0.9.1
41
+ fastapi==0.109.0
42
+ ffmpy==0.3.1
43
+ filelock==3.13.1
44
+ filterpy==1.4.5
45
+ fonttools==4.47.2
46
+ frozenlist==1.4.1
47
+ fschat==0.2.35
48
+ fsspec==2023.10.0
49
+ ftfy==6.1.3
50
+ future==0.18.3
51
+ gdown==4.7.1
52
+ gitdb==4.0.11
53
+ GitPython==3.1.41
54
+ google-auth==2.26.2
55
+ google-auth-oauthlib==1.2.0
56
+ gradio==3.50.2
57
+ gradio_client==0.6.1
58
+ grpcio==1.60.0
59
+ h11==0.14.0
60
+ httpcore==1.0.2
61
+ httpx==0.26.0
62
+ huggingface-hub==0.20.2
63
+ icecream==2.1.3
64
+ idna==3.6
65
+ imageio==2.9.0
66
+ imageio-ffmpeg==0.4.2
67
+ imgaug==0.2.6
68
+ importlib-metadata==7.0.1
69
+ importlib-resources==6.1.1
70
+ inquirerpy==0.3.4
71
+ invisible-watermark==0.2.0
72
+ Jinja2==3.1.3
73
+ joblib==1.4.2
74
+ jsonmerge==1.9.2
75
+ jsonschema==4.20.0
76
+ jsonschema-specifications==2023.12.1
77
+ k-diffusion @ git+https://github.com/crowsonkb/k-diffusion.git@cc49cf6182284e577e896943f8e29c7c9d1a7f2c
78
+ kiwisolver==1.4.5
79
+ kornia==0.6.0
80
+ lazy_loader==0.3
81
+ lit==17.0.6
82
+ llvmlite==0.42.0
83
+ lmdb==1.4.1
84
+ Markdown==3.5.2
85
+ markdown-it-py==3.0.0
86
+ markdown2==2.4.12
87
+ MarkupSafe==2.1.3
88
+ matplotlib==3.8.2
89
+ mdurl==0.1.2
90
+ mpmath==1.3.0
91
+ multidict==6.0.4
92
+ multiprocess==0.70.14
93
+ networkx==3.2.1
94
+ nh3==0.2.15
95
+ numba==0.59.1
96
+ numpy==1.24.4
97
+ nvidia-cublas-cu11==11.10.3.66
98
+ nvidia-cublas-cu12==12.1.3.1
99
+ nvidia-cuda-cupti-cu11==11.7.101
100
+ nvidia-cuda-cupti-cu12==12.1.105
101
+ nvidia-cuda-nvrtc-cu11==11.7.99
102
+ nvidia-cuda-nvrtc-cu12==12.1.105
103
+ nvidia-cuda-runtime-cu11==11.7.99
104
+ nvidia-cuda-runtime-cu12==12.1.105
105
+ nvidia-cudnn-cu11==8.5.0.96
106
+ nvidia-cudnn-cu12==8.9.2.26
107
+ nvidia-cufft-cu11==10.9.0.58
108
+ nvidia-cufft-cu12==11.0.2.54
109
+ nvidia-curand-cu11==10.2.10.91
110
+ nvidia-curand-cu12==10.3.2.106
111
+ nvidia-cusolver-cu11==11.4.0.1
112
+ nvidia-cusolver-cu12==11.4.5.107
113
+ nvidia-cusparse-cu11==11.7.4.91
114
+ nvidia-cusparse-cu12==12.1.0.106
115
+ nvidia-nccl-cu11==2.14.3
116
+ nvidia-nccl-cu12==2.18.1
117
+ nvidia-nvjitlink-cu12==12.3.101
118
+ nvidia-nvtx-cu11==11.7.91
119
+ nvidia-nvtx-cu12==12.1.105
120
+ oauthlib==3.2.2
121
+ omegaconf==2.1.1
122
+ open-clip-torch==2.24.0
123
+ openai==1.7.0
124
+ openai-clip==1.0.1
125
+ opencv-python==4.9.0.80
126
+ opencv-python-headless==4.9.0.80
127
+ orjson==3.9.10
128
+ packaging==23.2
129
+ pandas==2.1.4
130
+ patsy==0.5.6
131
+ peft==0.8.1
132
+ pfzy==0.3.4
133
+ pillow==10.2.0
134
+ platformdirs==4.2.1
135
+ prompt-toolkit==3.0.43
136
+ protobuf==4.23.4
137
+ psutil==5.9.7
138
+ pudb==2019.2
139
+ pyarrow==14.0.2
140
+ pyarrow-hotfix==0.6
141
+ pyasn1==0.5.1
142
+ pyasn1-modules==0.3.0
143
+ pydantic==1.10.14
144
+ pydantic_core==2.14.6
145
+ pydeck==0.8.1b0
146
+ pyDeprecate==0.3.1
147
+ pydub==0.25.1
148
+ Pygments==2.17.2
149
+ pyiqa==0.1.11
150
+ pyparsing==3.1.1
151
+ pyrepl==0.9.0
152
+ PySocks==1.7.1
153
+ python-dateutil==2.8.2
154
+ python-multipart==0.0.6
155
+ pytorch-lightning==1.4.2
156
+ pytube==15.0.0
157
+ pytz==2023.3.post1
158
+ PyWavelets==1.5.0
159
+ PyYAML==6.0.1
160
+ referencing==0.32.1
161
+ regex==2023.12.25
162
+ requests==2.31.0
163
+ requests-oauthlib==1.3.1
164
+ responses==0.18.0
165
+ rich==13.7.0
166
+ rpds-py==0.16.2
167
+ rsa==4.9
168
+ safetensors==0.4.1
169
+ scikit-image==0.20.0
170
+ scipy==1.9.1
171
+ seaborn==0.13.1
172
+ semantic-version==2.10.0
173
+ sentencepiece==0.1.99
174
+ sentry-sdk==1.39.2
175
+ setproctitle==1.3.3
176
+ shellingham==1.5.4
177
+ shortuuid==1.0.11
178
+ six==1.16.0
179
+ smmap==5.0.1
180
+ sniffio==1.3.0
181
+ soupsieve==2.5
182
+ starlette==0.35.1
183
+ statsmodels==0.14.2
184
+ streamlit==1.30.0
185
+ svgwrite==1.4.3
186
+ sympy==1.12
187
+ -e git+https://github.com/CompVis/taming-transformers.git@master#egg=taming-transformers
188
+ tenacity==8.2.3
189
+ tensorboard==2.15.1
190
+ tensorboard-data-server==0.7.2
191
+ test_tube==0.7.5
192
+ tifffile==2023.12.9
193
+ tiktoken==0.5.2
194
+ timm==0.9.12
195
+ tokenizers==0.15.1
196
+ toml==0.10.2
197
+ tomli==2.0.1
198
+ tomlkit==0.12.0
199
+ toolz==0.12.0
200
+ torch==2.0.1
201
+ torch-fidelity==0.3.0
202
+ torchdiffeq==0.2.3
203
+ torchmetrics==0.6.0
204
+ torchsde==0.2.6
205
+ torchvision==0.15.2
206
+ tornado==6.4
207
+ tqdm==4.66.1
208
+ trampoline==0.1.2
209
+ transformers==4.37.2
210
+ triton==2.0.0
211
+ typer==0.9.0
212
+ typing_extensions==4.9.0
213
+ tzdata==2023.4
214
+ tzlocal==5.2
215
+ urllib3==2.1.0
216
+ urwid==2.4.2
217
+ uvicorn==0.25.0
218
+ validators==0.22.0
219
+ wandb==0.16.3
220
+ watchdog==3.0.0
221
+ wavedrom==2.0.3.post3
222
+ wcwidth==0.2.13
223
+ websockets==11.0.3
224
+ Werkzeug==3.0.1
225
+ wmctrl==0.5
226
+ xxhash==3.4.1
227
+ yapf==0.40.2
228
+ yarl==1.9.4
229
+ zipp==3.17.0
stable_diffusion/LICENSE ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2022 Robin Rombach and Patrick Esser and contributors
2
+
3
+ CreativeML Open RAIL-M
4
+ dated August 22, 2022
5
+
6
+ Section I: PREAMBLE
7
+
8
+ Multimodal generative models are being widely adopted and used, and have the potential to transform the way artists, among other individuals, conceive and benefit from AI or ML technologies as a tool for content creation.
9
+
10
+ Notwithstanding the current and potential benefits that these artifacts can bring to society at large, there are also concerns about potential misuses of them, either due to their technical limitations or ethical considerations.
11
+
12
+ In short, this license strives for both the open and responsible downstream use of the accompanying model. When it comes to the open character, we took inspiration from open source permissive licenses regarding the grant of IP rights. Referring to the downstream responsible use, we added use-based restrictions not permitting the use of the Model in very specific scenarios, in order for the licensor to be able to enforce the license in case potential misuses of the Model may occur. At the same time, we strive to promote open and responsible research on generative models for art and content generation.
13
+
14
+ Even though downstream derivative versions of the model could be released under different licensing terms, the latter will always have to include - at minimum - the same use-based restrictions as the ones in the original license (this license). We believe in the intersection between open and responsible AI development; thus, this License aims to strike a balance between both in order to enable responsible open-science in the field of AI.
15
+
16
+ This License governs the use of the model (and its derivatives) and is informed by the model card associated with the model.
17
+
18
+ NOW THEREFORE, You and Licensor agree as follows:
19
+
20
+ 1. Definitions
21
+
22
+ - "License" means the terms and conditions for use, reproduction, and Distribution as defined in this document.
23
+ - "Data" means a collection of information and/or content extracted from the dataset used with the Model, including to train, pretrain, or otherwise evaluate the Model. The Data is not licensed under this License.
24
+ - "Output" means the results of operating a Model as embodied in informational content resulting therefrom.
25
+ - "Model" means any accompanying machine-learning based assemblies (including checkpoints), consisting of learnt weights, parameters (including optimizer states), corresponding to the model architecture as embodied in the Complementary Material, that have been trained or tuned, in whole or in part on the Data, using the Complementary Material.
26
+ - "Derivatives of the Model" means all modifications to the Model, works based on the Model, or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or output of the Model, to the other model, in order to cause the other model to perform similarly to the Model, including - but not limited to - distillation methods entailing the use of intermediate data representations or methods based on the generation of synthetic data by the Model for training the other model.
27
+ - "Complementary Material" means the accompanying source code and scripts used to define, run, load, benchmark or evaluate the Model, and used to prepare data for training or evaluation, if any. This includes any accompanying documentation, tutorials, examples, etc, if any.
28
+ - "Distribution" means any transmission, reproduction, publication or other sharing of the Model or Derivatives of the Model to a third party, including providing the Model as a hosted service made available by electronic or other remote means - e.g. API-based or web access.
29
+ - "Licensor" means the copyright owner or entity authorized by the copyright owner that is granting the License, including the persons or entities that may have rights in the Model and/or distributing the Model.
30
+ - "You" (or "Your") means an individual or Legal Entity exercising permissions granted by this License and/or making use of the Model for whichever purpose and in any field of use, including usage of the Model in an end-use application - e.g. chatbot, translator, image generator.
31
+ - "Third Parties" means individuals or legal entities that are not under common control with Licensor or You.
32
+ - "Contribution" means any work of authorship, including the original version of the Model and any modifications or additions to that Model or Derivatives of the Model thereof, that is intentionally submitted to Licensor for inclusion in the Model by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Model, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
33
+ - "Contributor" means Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Model.
34
+
35
+ Section II: INTELLECTUAL PROPERTY RIGHTS
36
+
37
+ Both copyright and patent grants apply to the Model, Derivatives of the Model and Complementary Material. The Model and Derivatives of the Model are subject to additional terms as described in Section III.
38
+
39
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare, publicly display, publicly perform, sublicense, and distribute the Complementary Material, the Model, and Derivatives of the Model.
40
+ 3. Grant of Patent License. Subject to the terms and conditions of this License and where and as applicable, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this paragraph) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Model and the Complementary Material, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Model to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Model and/or Complementary Material or a Contribution incorporated within the Model and/or Complementary Material constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for the Model and/or Work shall terminate as of the date such litigation is asserted or filed.
41
+
42
+ Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION
43
+
44
+ 4. Distribution and Redistribution. You may host for Third Party remote access purposes (e.g. software-as-a-service), reproduce and distribute copies of the Model or Derivatives of the Model thereof in any medium, with or without modifications, provided that You meet the following conditions:
45
+ Use-based restrictions as referenced in paragraph 5 MUST be included as an enforceable provision by You in any type of legal agreement (e.g. a license) governing the use and/or distribution of the Model or Derivatives of the Model, and You shall give notice to subsequent users You Distribute to, that the Model or Derivatives of the Model are subject to paragraph 5. This provision does not apply to the use of Complementary Material.
46
+ You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License;
47
+ You must cause any modified files to carry prominent notices stating that You changed the files;
48
+ You must retain all copyright, patent, trademark, and attribution notices excluding those notices that do not pertain to any part of the Model, Derivatives of the Model.
49
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions - respecting paragraph 4.a. - for use, reproduction, or Distribution of Your modifications, or for any such Derivatives of the Model as a whole, provided Your use, reproduction, and Distribution of the Model otherwise complies with the conditions stated in this License.
50
+ 5. Use-based restrictions. The restrictions set forth in Attachment A are considered Use-based restrictions. Therefore You cannot use the Model and the Derivatives of the Model for the specified restricted uses. You may use the Model subject to this License, including only for lawful purposes and in accordance with the License. Use may include creating any content with, finetuning, updating, running, training, evaluating and/or reparametrizing the Model. You shall require all of Your users who use the Model or a Derivative of the Model to comply with the terms of this paragraph (paragraph 5).
51
+ 6. The Output You Generate. Except as set forth herein, Licensor claims no rights in the Output You generate using the Model. You are accountable for the Output you generate and its subsequent uses. No use of the output can contravene any provision as stated in the License.
52
+
53
+ Section IV: OTHER PROVISIONS
54
+
55
+ 7. Updates and Runtime Restrictions. To the maximum extent permitted by law, Licensor reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License, update the Model through electronic means, or modify the Output of the Model based on updates. You shall undertake reasonable efforts to use the latest version of the Model.
56
+ 8. Trademarks and related. Nothing in this License permits You to make use of Licensors’ trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by the Licensors.
57
+ 9. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Model and the Complementary Material (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Model, Derivatives of the Model, and the Complementary Material and assume any risks associated with Your exercise of permissions under this License.
58
+ 10. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Model and the Complementary Material (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
59
+ 11. Accepting Warranty or Additional Liability. While redistributing the Model, Derivatives of the Model and the Complementary Material thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
60
+ 12. If any provision of this License is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.
61
+
62
+ END OF TERMS AND CONDITIONS
63
+
64
+
65
+
66
+
67
+ Attachment A
68
+
69
+ Use Restrictions
70
+
71
+ You agree not to use the Model or Derivatives of the Model:
72
+ - In any way that violates any applicable national, federal, state, local or international law or regulation;
73
+ - For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;
74
+ - To generate or disseminate verifiably false information and/or content with the purpose of harming others;
75
+ - To generate or disseminate personal identifiable information that can be used to harm an individual;
76
+ - To defame, disparage or otherwise harass others;
77
+ - For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation;
78
+ - For any use intended to or which has the effect of discriminating against or harming individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics;
79
+ - To exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;
80
+ - For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories;
81
+ - To provide medical advice and medical results interpretation;
82
+ - To generate or disseminate information for the purpose to be used for administration of justice, law enforcement, immigration or asylum processes, such as predicting an individual will commit fraud/crime commitment (e.g. by text profiling, drawing causal relationships between assertions made in documents, indiscriminate and arbitrarily-targeted use).
stable_diffusion/README.md ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stable Diffusion
2
+ *Stable Diffusion was made possible thanks to a collaboration with [Stability AI](https://stability.ai/) and [Runway](https://runwayml.com/) and builds upon our previous work:*
3
+
4
+ [**High-Resolution Image Synthesis with Latent Diffusion Models**](https://ommer-lab.com/research/latent-diffusion-models/)<br/>
5
+ [Robin Rombach](https://github.com/rromb)\*,
6
+ [Andreas Blattmann](https://github.com/ablattmann)\*,
7
+ [Dominik Lorenz](https://github.com/qp-qp)\,
8
+ [Patrick Esser](https://github.com/pesser),
9
+ [Björn Ommer](https://hci.iwr.uni-heidelberg.de/Staff/bommer)<br/>
10
+ _[CVPR '22 Oral](https://openaccess.thecvf.com/content/CVPR2022/html/Rombach_High-Resolution_Image_Synthesis_With_Latent_Diffusion_Models_CVPR_2022_paper.html) |
11
+ [GitHub](https://github.com/CompVis/latent-diffusion) | [arXiv](https://arxiv.org/abs/2112.10752) | [Project page](https://ommer-lab.com/research/latent-diffusion-models/)_
12
+
13
+ ![txt2img-stable2](assets/stable-samples/txt2img/merged-0006.png)
14
+ [Stable Diffusion](#stable-diffusion-v1) is a latent text-to-image diffusion
15
+ model.
16
+ Thanks to a generous compute donation from [Stability AI](https://stability.ai/) and support from [LAION](https://laion.ai/), we were able to train a Latent Diffusion Model on 512x512 images from a subset of the [LAION-5B](https://laion.ai/blog/laion-5b/) database.
17
+ Similar to Google's [Imagen](https://arxiv.org/abs/2205.11487),
18
+ this model uses a frozen CLIP ViT-L/14 text encoder to condition the model on text prompts.
19
+ With its 860M UNet and 123M text encoder, the model is relatively lightweight and runs on a GPU with at least 10GB VRAM.
20
+ See [this section](#stable-diffusion-v1) below and the [model card](https://huggingface.co/CompVis/stable-diffusion).
21
+
22
+
23
+ ## Requirements
24
+ A suitable [conda](https://conda.io/) environment named `ldm` can be created
25
+ and activated with:
26
+
27
+ ```
28
+ conda env create -f environment.yaml
29
+ conda activate ldm
30
+ ```
31
+
32
+ You can also update an existing [latent diffusion](https://github.com/CompVis/latent-diffusion) environment by running
33
+
34
+ ```
35
+ conda install pytorch torchvision -c pytorch
36
+ pip install transformers==4.19.2 diffusers invisible-watermark
37
+ pip install -e .
38
+ ```
39
+
40
+
41
+ ## Stable Diffusion v1
42
+
43
+ Stable Diffusion v1 refers to a specific configuration of the model
44
+ architecture that uses a downsampling-factor 8 autoencoder with an 860M UNet
45
+ and CLIP ViT-L/14 text encoder for the diffusion model. The model was pretrained on 256x256 images and
46
+ then finetuned on 512x512 images.
47
+
48
+ *Note: Stable Diffusion v1 is a general text-to-image diffusion model and therefore mirrors biases and (mis-)conceptions that are present
49
+ in its training data.
50
+ Details on the training procedure and data, as well as the intended use of the model can be found in the corresponding [model card](Stable_Diffusion_v1_Model_Card.md).*
51
+
52
+ The weights are available via [the CompVis organization at Hugging Face](https://huggingface.co/CompVis) under [a license which contains specific use-based restrictions to prevent misuse and harm as informed by the model card, but otherwise remains permissive](LICENSE). While commercial use is permitted under the terms of the license, **we do not recommend using the provided weights for services or products without additional safety mechanisms and considerations**, since there are [known limitations and biases](Stable_Diffusion_v1_Model_Card.md#limitations-and-bias) of the weights, and research on safe and ethical deployment of general text-to-image models is an ongoing effort. **The weights are research artifacts and should be treated as such.**
53
+
54
+ [The CreativeML OpenRAIL M license](LICENSE) is an [Open RAIL M license](https://www.licenses.ai/blog/2022/8/18/naming-convention-of-responsible-ai-licenses), adapted from the work that [BigScience](https://bigscience.huggingface.co/) and [the RAIL Initiative](https://www.licenses.ai/) are jointly carrying in the area of responsible AI licensing. See also [the article about the BLOOM Open RAIL license](https://bigscience.huggingface.co/blog/the-bigscience-rail-license) on which our license is based.
55
+
56
+ ### Weights
57
+
58
+ We currently provide the following checkpoints:
59
+
60
+ - `sd-v1-1.ckpt`: 237k steps at resolution `256x256` on [laion2B-en](https://huggingface.co/datasets/laion/laion2B-en).
61
+ 194k steps at resolution `512x512` on [laion-high-resolution](https://huggingface.co/datasets/laion/laion-high-resolution) (170M examples from LAION-5B with resolution `>= 1024x1024`).
62
+ - `sd-v1-2.ckpt`: Resumed from `sd-v1-1.ckpt`.
63
+ 515k steps at resolution `512x512` on [laion-aesthetics v2 5+](https://laion.ai/blog/laion-aesthetics/) (a subset of laion2B-en with estimated aesthetics score `> 5.0`, and additionally
64
+ filtered to images with an original size `>= 512x512`, and an estimated watermark probability `< 0.5`. The watermark estimate is from the [LAION-5B](https://laion.ai/blog/laion-5b/) metadata, the aesthetics score is estimated using the [LAION-Aesthetics Predictor V2](https://github.com/christophschuhmann/improved-aesthetic-predictor)).
65
+ - `sd-v1-3.ckpt`: Resumed from `sd-v1-2.ckpt`. 195k steps at resolution `512x512` on "laion-aesthetics v2 5+" and 10\% dropping of the text-conditioning to improve [classifier-free guidance sampling](https://arxiv.org/abs/2207.12598).
66
+ - `sd-v1-4.ckpt`: Resumed from `sd-v1-2.ckpt`. 225k steps at resolution `512x512` on "laion-aesthetics v2 5+" and 10\% dropping of the text-conditioning to improve [classifier-free guidance sampling](https://arxiv.org/abs/2207.12598).
67
+
68
+ Evaluations with different classifier-free guidance scales (1.5, 2.0, 3.0, 4.0,
69
+ 5.0, 6.0, 7.0, 8.0) and 50 PLMS sampling
70
+ steps show the relative improvements of the checkpoints:
71
+ ![sd evaluation results](assets/v1-variants-scores.jpg)
72
+
73
+
74
+
75
+ ### Text-to-Image with Stable Diffusion
76
+ ![txt2img-stable2](assets/stable-samples/txt2img/merged-0005.png)
77
+ ![txt2img-stable2](assets/stable-samples/txt2img/merged-0007.png)
78
+
79
+ Stable Diffusion is a latent diffusion model conditioned on the (non-pooled) text embeddings of a CLIP ViT-L/14 text encoder.
80
+ We provide a [reference script for sampling](#reference-sampling-script), but
81
+ there also exists a [diffusers integration](#diffusers-integration), which we
82
+ expect to see more active community development.
83
+
84
+ #### Reference Sampling Script
85
+
86
+ We provide a reference sampling script, which incorporates
87
+
88
+ - a [Safety Checker Module](https://github.com/CompVis/stable-diffusion/pull/36),
89
+ to reduce the probability of explicit outputs,
90
+ - an [invisible watermarking](https://github.com/ShieldMnt/invisible-watermark)
91
+ of the outputs, to help viewers [identify the images as machine-generated](scripts/tests/test_watermark.py).
92
+
93
+ After [obtaining the `stable-diffusion-v1-*-original` weights](#weights), link them
94
+ ```
95
+ mkdir -p models/ldm/stable-diffusion-v1/
96
+ ln -s <path/to/model.ckpt> models/ldm/stable-diffusion-v1/model.ckpt
97
+ ```
98
+ and sample with
99
+ ```
100
+ python scripts/txt2img.py --prompt "a photograph of an astronaut riding a horse" --plms
101
+ ```
102
+
103
+ By default, this uses a guidance scale of `--scale 7.5`, [Katherine Crowson's implementation](https://github.com/CompVis/latent-diffusion/pull/51) of the [PLMS](https://arxiv.org/abs/2202.09778) sampler,
104
+ and renders images of size 512x512 (which it was trained on) in 50 steps. All supported arguments are listed below (type `python scripts/txt2img.py --help`).
105
+
106
+
107
+ ```commandline
108
+ usage: txt2img.py [-h] [--prompt [PROMPT]] [--outdir [OUTDIR]] [--skip_grid] [--skip_save] [--ddim_steps DDIM_STEPS] [--plms] [--laion400m] [--fixed_code] [--ddim_eta DDIM_ETA]
109
+ [--n_iter N_ITER] [--H H] [--W W] [--C C] [--f F] [--n_samples N_SAMPLES] [--n_rows N_ROWS] [--scale SCALE] [--from-file FROM_FILE] [--config CONFIG] [--ckpt CKPT]
110
+ [--seed SEED] [--precision {full,autocast}]
111
+
112
+ optional arguments:
113
+ -h, --help show this help message and exit
114
+ --prompt [PROMPT] the prompt to render
115
+ --outdir [OUTDIR] dir to write results to
116
+ --skip_grid do not save a grid, only individual samples. Helpful when evaluating lots of samples
117
+ --skip_save do not save individual samples. For speed measurements.
118
+ --ddim_steps DDIM_STEPS
119
+ number of ddim sampling steps
120
+ --plms use plms sampling
121
+ --laion400m uses the LAION400M model
122
+ --fixed_code if enabled, uses the same starting code across samples
123
+ --ddim_eta DDIM_ETA ddim eta (eta=0.0 corresponds to deterministic sampling
124
+ --n_iter N_ITER sample this often
125
+ --H H image height, in pixel space
126
+ --W W image width, in pixel space
127
+ --C C latent channels
128
+ --f F downsampling factor
129
+ --n_samples N_SAMPLES
130
+ how many samples to produce for each given prompt. A.k.a. batch size
131
+ --n_rows N_ROWS rows in the grid (default: n_samples)
132
+ --scale SCALE unconditional guidance scale: eps = eps(x, empty) + scale * (eps(x, cond) - eps(x, empty))
133
+ --from-file FROM_FILE
134
+ if specified, load prompts from this file
135
+ --config CONFIG path to config which constructs model
136
+ --ckpt CKPT path to checkpoint of model
137
+ --seed SEED the seed (for reproducible sampling)
138
+ --precision {full,autocast}
139
+ evaluate at this precision
140
+ ```
141
+ Note: The inference config for all v1 versions is designed to be used with EMA-only checkpoints.
142
+ For this reason `use_ema=False` is set in the configuration, otherwise the code will try to switch from
143
+ non-EMA to EMA weights. If you want to examine the effect of EMA vs no EMA, we provide "full" checkpoints
144
+ which contain both types of weights. For these, `use_ema=False` will load and use the non-EMA weights.
145
+
146
+
147
+ #### Diffusers Integration
148
+
149
+ A simple way to download and sample Stable Diffusion is by using the [diffusers library](https://github.com/huggingface/diffusers/tree/main#new--stable-diffusion-is-now-fully-compatible-with-diffusers):
150
+ ```py
151
+ # make sure you're logged in with `huggingface-cli login`
152
+ from torch import autocast
153
+ from diffusers import StableDiffusionPipeline
154
+
155
+ pipe = StableDiffusionPipeline.from_pretrained(
156
+ "CompVis/stable-diffusion-v1-4",
157
+ use_auth_token=True
158
+ ).to("cuda")
159
+
160
+ prompt = "a photo of an astronaut riding a horse on mars"
161
+ with autocast("cuda"):
162
+ image = pipe(prompt)["sample"][0]
163
+
164
+ image.save("astronaut_rides_horse.png")
165
+ ```
166
+
167
+
168
+ ### Image Modification with Stable Diffusion
169
+
170
+ By using a diffusion-denoising mechanism as first proposed by [SDEdit](https://arxiv.org/abs/2108.01073), the model can be used for different
171
+ tasks such as text-guided image-to-image translation and upscaling. Similar to the txt2img sampling script,
172
+ we provide a script to perform image modification with Stable Diffusion.
173
+
174
+ The following describes an example where a rough sketch made in [Pinta](https://www.pinta-project.com/) is converted into a detailed artwork.
175
+ ```
176
+ python scripts/img2img.py --prompt "A fantasy landscape, trending on artstation" --init-img <path-to-img.jpg> --strength 0.8
177
+ ```
178
+ Here, strength is a value between 0.0 and 1.0, that controls the amount of noise that is added to the input image.
179
+ Values that approach 1.0 allow for lots of variations but will also produce images that are not semantically consistent with the input. See the following example.
180
+
181
+ **Input**
182
+
183
+ ![sketch-in](assets/stable-samples/img2img/sketch-mountains-input.jpg)
184
+
185
+ **Outputs**
186
+
187
+ ![out3](assets/stable-samples/img2img/mountains-3.png)
188
+ ![out2](assets/stable-samples/img2img/mountains-2.png)
189
+
190
+ This procedure can, for example, also be used to upscale samples from the base model.
191
+
192
+
193
+ ## Comments
194
+
195
+ - Our codebase for the diffusion models builds heavily on [OpenAI's ADM codebase](https://github.com/openai/guided-diffusion)
196
+ and [https://github.com/lucidrains/denoising-diffusion-pytorch](https://github.com/lucidrains/denoising-diffusion-pytorch).
197
+ Thanks for open-sourcing!
198
+
199
+ - The implementation of the transformer encoder is from [x-transformers](https://github.com/lucidrains/x-transformers) by [lucidrains](https://github.com/lucidrains?tab=repositories).
200
+
201
+
202
+ ## BibTeX
203
+
204
+ ```
205
+ @misc{rombach2021highresolution,
206
+ title={High-Resolution Image Synthesis with Latent Diffusion Models},
207
+ author={Robin Rombach and Andreas Blattmann and Dominik Lorenz and Patrick Esser and Björn Ommer},
208
+ year={2021},
209
+ eprint={2112.10752},
210
+ archivePrefix={arXiv},
211
+ primaryClass={cs.CV}
212
+ }
213
+ ```
214
+
215
+
stable_diffusion/Stable_Diffusion_v1_Model_Card.md ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stable Diffusion v1 Model Card
2
+ This model card focuses on the model associated with the Stable Diffusion model, available [here](https://github.com/CompVis/stable-diffusion).
3
+
4
+ ## Model Details
5
+ - **Developed by:** Robin Rombach, Patrick Esser
6
+ - **Model type:** Diffusion-based text-to-image generation model
7
+ - **Language(s):** English
8
+ - **License:** [Proprietary](LICENSE)
9
+ - **Model Description:** This is a model that can be used to generate and modify images based on text prompts. It is a [Latent Diffusion Model](https://arxiv.org/abs/2112.10752) that uses a fixed, pretrained text encoder ([CLIP ViT-L/14](https://arxiv.org/abs/2103.00020)) as suggested in the [Imagen paper](https://arxiv.org/abs/2205.11487).
10
+ - **Resources for more information:** [GitHub Repository](https://github.com/CompVis/stable-diffusion), [Paper](https://arxiv.org/abs/2112.10752).
11
+ - **Cite as:**
12
+
13
+ @InProceedings{Rombach_2022_CVPR,
14
+ author = {Rombach, Robin and Blattmann, Andreas and Lorenz, Dominik and Esser, Patrick and Ommer, Bj\"orn},
15
+ title = {High-Resolution Image Synthesis With Latent Diffusion Models},
16
+ booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)},
17
+ month = {June},
18
+ year = {2022},
19
+ pages = {10684-10695}
20
+ }
21
+
22
+ # Uses
23
+
24
+ ## Direct Use
25
+ The model is intended for research purposes only. Possible research areas and
26
+ tasks include
27
+
28
+ - Safe deployment of models which have the potential to generate harmful content.
29
+ - Probing and understanding the limitations and biases of generative models.
30
+ - Generation of artworks and use in design and other artistic processes.
31
+ - Applications in educational or creative tools.
32
+ - Research on generative models.
33
+
34
+ Excluded uses are described below.
35
+
36
+ ### Misuse, Malicious Use, and Out-of-Scope Use
37
+ _Note: This section is taken from the [DALLE-MINI model card](https://huggingface.co/dalle-mini/dalle-mini), but applies in the same way to Stable Diffusion v1_.
38
+
39
+ The model should not be used to intentionally create or disseminate images that create hostile or alienating environments for people. This includes generating images that people would foreseeably find disturbing, distressing, or offensive; or content that propagates historical or current stereotypes.
40
+
41
+ #### Out-of-Scope Use
42
+ The model was not trained to be factual or true representations of people or events, and therefore using the model to generate such content is out-of-scope for the abilities of this model.
43
+
44
+ #### Misuse and Malicious Use
45
+ Using the model to generate content that is cruel to individuals is a misuse of this model. This includes, but is not limited to:
46
+
47
+ - Generating demeaning, dehumanizing, or otherwise harmful representations of people or their environments, cultures, religions, etc.
48
+ - Intentionally promoting or propagating discriminatory content or harmful stereotypes.
49
+ - Impersonating individuals without their consent.
50
+ - Sexual content without consent of the people who might see it.
51
+ - Mis- and disinformation
52
+ - Representations of egregious violence and gore
53
+ - Sharing of copyrighted or licensed material in violation of its terms of use.
54
+ - Sharing content that is an alteration of copyrighted or licensed material in violation of its terms of use.
55
+
56
+ ## Limitations and Bias
57
+
58
+ ### Limitations
59
+
60
+ - The model does not achieve perfect photorealism
61
+ - The model cannot render legible text
62
+ - The model does not perform well on more difficult tasks which involve compositionality, such as rendering an image corresponding to “A red cube on top of a blue sphere”
63
+ - Faces and people in general may not be generated properly.
64
+ - The model was trained mainly with English captions and will not work as well in other languages.
65
+ - The autoencoding part of the model is lossy
66
+ - The model was trained on a large-scale dataset
67
+ [LAION-5B](https://laion.ai/blog/laion-5b/) which contains adult material
68
+ and is not fit for product use without additional safety mechanisms and
69
+ considerations.
70
+ - No additional measures were used to deduplicate the dataset. As a result, we observe some degree of memorization for images that are duplicated in the training data.
71
+ The training data can be searched at [https://rom1504.github.io/clip-retrieval/](https://rom1504.github.io/clip-retrieval/) to possibly assist in the detection of memorized images.
72
+
73
+ ### Bias
74
+ While the capabilities of image generation models are impressive, they can also reinforce or exacerbate social biases.
75
+ Stable Diffusion v1 was primarily trained on subsets of [LAION-2B(en)](https://laion.ai/blog/laion-5b/),
76
+ which consists of images that are limited to English descriptions.
77
+ Texts and images from communities and cultures that use other languages are likely to be insufficiently accounted for.
78
+ This affects the overall output of the model, as white and western cultures are often set as the default. Further, the
79
+ ability of the model to generate content with non-English prompts is significantly worse than with English-language prompts.
80
+ Stable Diffusion v1 mirrors and exacerbates biases to such a degree that viewer discretion must be advised irrespective of the input or its intent.
81
+
82
+
83
+ ## Training
84
+
85
+ **Training Data**
86
+ The model developers used the following dataset for training the model:
87
+
88
+ - LAION-5B and subsets thereof (see next section)
89
+
90
+ **Training Procedure**
91
+ Stable Diffusion v1 is a latent diffusion model which combines an autoencoder with a diffusion model that is trained in the latent space of the autoencoder. During training,
92
+
93
+ - Images are encoded through an encoder, which turns images into latent representations. The autoencoder uses a relative downsampling factor of 8 and maps images of shape H x W x 3 to latents of shape H/f x W/f x 4
94
+ - Text prompts are encoded through a ViT-L/14 text-encoder.
95
+ - The non-pooled output of the text encoder is fed into the UNet backbone of the latent diffusion model via cross-attention.
96
+ - The loss is a reconstruction objective between the noise that was added to the latent and the prediction made by the UNet.
97
+
98
+ We currently provide the following checkpoints:
99
+
100
+ - `sd-v1-1.ckpt`: 237k steps at resolution `256x256` on [laion2B-en](https://huggingface.co/datasets/laion/laion2B-en).
101
+ 194k steps at resolution `512x512` on [laion-high-resolution](https://huggingface.co/datasets/laion/laion-high-resolution) (170M examples from LAION-5B with resolution `>= 1024x1024`).
102
+ - `sd-v1-2.ckpt`: Resumed from `sd-v1-1.ckpt`.
103
+ 515k steps at resolution `512x512` on [laion-aesthetics v2 5+](https://laion.ai/blog/laion-aesthetics/) (a subset of laion2B-en with estimated aesthetics score `> 5.0`, and additionally
104
+ filtered to images with an original size `>= 512x512`, and an estimated watermark probability `< 0.5`. The watermark estimate is from the [LAION-5B](https://laion.ai/blog/laion-5b/) metadata, the aesthetics score is estimated using the [LAION-Aesthetics Predictor V2](https://github.com/christophschuhmann/improved-aesthetic-predictor)).
105
+ - `sd-v1-3.ckpt`: Resumed from `sd-v1-2.ckpt`. 195k steps at resolution `512x512` on "laion-aesthetics v2 5+" and 10\% dropping of the text-conditioning to improve [classifier-free guidance sampling](https://arxiv.org/abs/2207.12598).
106
+ - `sd-v1-4.ckpt`: Resumed from `sd-v1-2.ckpt`. 225k steps at resolution `512x512` on "laion-aesthetics v2 5+" and 10\% dropping of the text-conditioning to improve [classifier-free guidance sampling](https://arxiv.org/abs/2207.12598).
107
+
108
+ - **Hardware:** 32 x 8 x A100 GPUs
109
+ - **Optimizer:** AdamW
110
+ - **Gradient Accumulations**: 2
111
+ - **Batch:** 32 x 8 x 2 x 4 = 2048
112
+ - **Learning rate:** warmup to 0.0001 for 10,000 steps and then kept constant
113
+
114
+ ## Evaluation Results
115
+ Evaluations with different classifier-free guidance scales (1.5, 2.0, 3.0, 4.0,
116
+ 5.0, 6.0, 7.0, 8.0) and 50 PLMS sampling
117
+ steps show the relative improvements of the checkpoints:
118
+
119
+ ![pareto](assets/v1-variants-scores.jpg)
120
+
121
+ Evaluated using 50 PLMS steps and 10000 random prompts from the COCO2017 validation set, evaluated at 512x512 resolution. Not optimized for FID scores.
122
+
123
+ ## Environmental Impact
124
+
125
+ **Stable Diffusion v1** **Estimated Emissions**
126
+ Based on that information, we estimate the following CO2 emissions using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700). The hardware, runtime, cloud provider, and compute region were utilized to estimate the carbon impact.
127
+
128
+ - **Hardware Type:** A100 PCIe 40GB
129
+ - **Hours used:** 150000
130
+ - **Cloud Provider:** AWS
131
+ - **Compute Region:** US-east
132
+ - **Carbon Emitted (Power consumption x Time x Carbon produced based on location of power grid):** 11250 kg CO2 eq.
133
+
134
+ ## Citation
135
+ @InProceedings{Rombach_2022_CVPR,
136
+ author = {Rombach, Robin and Blattmann, Andreas and Lorenz, Dominik and Esser, Patrick and Ommer, Bj\"orn},
137
+ title = {High-Resolution Image Synthesis With Latent Diffusion Models},
138
+ booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)},
139
+ month = {June},
140
+ year = {2022},
141
+ pages = {10684-10695}
142
+ }
143
+
144
+ *This model card was written by: Robin Rombach and Patrick Esser and is based on the [DALL-E Mini model card](https://huggingface.co/dalle-mini/dalle-mini).*
stable_diffusion/assets/stable-samples/txt2img/merged-0006.png.REMOVED.git-id ADDED
@@ -0,0 +1 @@
 
 
1
+ 999f3703230580e8c89e9081abd6a1f8f50896d4
stable_diffusion/assets/stable-samples/txt2img/merged-0007.png.REMOVED.git-id ADDED
@@ -0,0 +1 @@
 
 
1
+ af390acaf601283782d6f479d4cade4d78e30b26
stable_diffusion/assets/txt2img-preview.png.REMOVED.git-id ADDED
@@ -0,0 +1 @@
 
 
1
+ 51ee1c235dfdc63d4c41de7d303d03730e43c33c
stable_diffusion/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
stable_diffusion/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
stable_diffusion/data/example_conditioning/text_conditional/sample_0.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ A basket of cerries
stable_diffusion/ldm/data/__init__.py ADDED
File without changes
stable_diffusion/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
stable_diffusion/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)
stable_diffusion/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)
stable_diffusion/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
+
stable_diffusion/ldm/models/diffusion/__init__.py ADDED
File without changes
stable_diffusion/ldm/models/diffusion/ddim.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SAMPLING ONLY."""
2
+
3
+ import torch
4
+ import numpy as np
5
+ from tqdm import tqdm
6
+ from functools import partial
7
+
8
+ from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, \
9
+ extract_into_tensor
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
+ to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
31
+
32
+ self.register_buffer('betas', to_torch(self.model.betas))
33
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
34
+ self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
35
+
36
+ # calculations for diffusion q(x_t | x_{t-1}) and others
37
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
38
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
39
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
40
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
41
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
42
+
43
+ # ddim sampling parameters
44
+ ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
45
+ ddim_timesteps=self.ddim_timesteps,
46
+ eta=ddim_eta,verbose=verbose)
47
+ self.register_buffer('ddim_sigmas', ddim_sigmas)
48
+ self.register_buffer('ddim_alphas', ddim_alphas)
49
+ self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
50
+ self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
51
+ sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
52
+ (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
53
+ 1 - self.alphas_cumprod / self.alphas_cumprod_prev))
54
+ self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
55
+
56
+ @torch.no_grad()
57
+ def sample(self,
58
+ S,
59
+ batch_size,
60
+ shape,
61
+ conditioning=None,
62
+ callback=None,
63
+ normals_sequence=None,
64
+ img_callback=None,
65
+ quantize_x0=False,
66
+ eta=0.,
67
+ mask=None,
68
+ x0=None,
69
+ temperature=1.,
70
+ noise_dropout=0.,
71
+ score_corrector=None,
72
+ corrector_kwargs=None,
73
+ verbose=True,
74
+ x_T=None,
75
+ log_every_t=100,
76
+ unconditional_guidance_scale=1.,
77
+ unconditional_conditioning=None,
78
+ # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
79
+ **kwargs
80
+ ):
81
+ if conditioning is not None:
82
+ if isinstance(conditioning, dict):
83
+ cbs = conditioning[list(conditioning.keys())[0]].shape[0]
84
+ if cbs != batch_size:
85
+ print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
86
+ else:
87
+ if conditioning.shape[0] != batch_size:
88
+ print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
89
+
90
+ self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
91
+ # sampling
92
+ C, H, W = shape
93
+ size = (batch_size, C, H, W)
94
+ print(f'Data shape for DDIM sampling is {size}, eta {eta}')
95
+
96
+ samples, intermediates = self.ddim_sampling(conditioning, size,
97
+ callback=callback,
98
+ img_callback=img_callback,
99
+ quantize_denoised=quantize_x0,
100
+ mask=mask, x0=x0,
101
+ ddim_use_original_steps=False,
102
+ noise_dropout=noise_dropout,
103
+ temperature=temperature,
104
+ score_corrector=score_corrector,
105
+ corrector_kwargs=corrector_kwargs,
106
+ x_T=x_T,
107
+ log_every_t=log_every_t,
108
+ unconditional_guidance_scale=unconditional_guidance_scale,
109
+ unconditional_conditioning=unconditional_conditioning,
110
+ )
111
+ return samples, intermediates
112
+
113
+ @torch.no_grad()
114
+ def ddim_sampling(self, cond, shape,
115
+ x_T=None, ddim_use_original_steps=False,
116
+ callback=None, timesteps=None, quantize_denoised=False,
117
+ mask=None, x0=None, img_callback=None, log_every_t=100,
118
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
119
+ unconditional_guidance_scale=1., unconditional_conditioning=None,):
120
+ device = self.model.betas.device
121
+ b = shape[0]
122
+ if x_T is None:
123
+ img = torch.randn(shape, device=device)
124
+ else:
125
+ img = x_T
126
+
127
+ if timesteps is None:
128
+ timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
129
+ elif timesteps is not None and not ddim_use_original_steps:
130
+ subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
131
+ timesteps = self.ddim_timesteps[:subset_end]
132
+
133
+ intermediates = {'x_inter': [img], 'pred_x0': [img]}
134
+ time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
135
+ total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
136
+ print(f"Running DDIM Sampling with {total_steps} timesteps")
137
+
138
+ iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
139
+
140
+ for i, step in enumerate(iterator):
141
+ index = total_steps - i - 1
142
+ ts = torch.full((b,), step, device=device, dtype=torch.long)
143
+
144
+ if mask is not None:
145
+ assert x0 is not None
146
+ img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
147
+ img = img_orig * mask + (1. - mask) * img
148
+
149
+ outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
150
+ quantize_denoised=quantize_denoised, temperature=temperature,
151
+ noise_dropout=noise_dropout, score_corrector=score_corrector,
152
+ corrector_kwargs=corrector_kwargs,
153
+ unconditional_guidance_scale=unconditional_guidance_scale,
154
+ unconditional_conditioning=unconditional_conditioning)
155
+ img, pred_x0 = outs
156
+ if callback: callback(i)
157
+ if img_callback: img_callback(pred_x0, i)
158
+
159
+ if index % log_every_t == 0 or index == total_steps - 1:
160
+ intermediates['x_inter'].append(img)
161
+ intermediates['pred_x0'].append(pred_x0)
162
+
163
+ return img, intermediates
164
+
165
+ @torch.no_grad()
166
+ def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
167
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
168
+ unconditional_guidance_scale=1., unconditional_conditioning=None):
169
+ b, *_, device = *x.shape, x.device
170
+
171
+ if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
172
+ e_t = self.model.apply_model(x, t, c)
173
+ else:
174
+ x_in = torch.cat([x] * 2)
175
+ t_in = torch.cat([t] * 2)
176
+ c_in = torch.cat([unconditional_conditioning, c])
177
+ e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)
178
+ e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)
179
+
180
+ if score_corrector is not None:
181
+ assert self.model.parameterization == "eps"
182
+ e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
183
+
184
+ alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
185
+ alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
186
+ sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
187
+ sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
188
+ # select parameters corresponding to the currently considered timestep
189
+ a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
190
+ a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
191
+ sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
192
+ sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
193
+
194
+ # current prediction for x_0
195
+ pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
196
+ if quantize_denoised:
197
+ pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
198
+ # direction pointing to x_t
199
+ dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
200
+ noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
201
+ if noise_dropout > 0.:
202
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
203
+ x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
204
+ return x_prev, pred_x0
205
+
206
+ @torch.no_grad()
207
+ def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):
208
+ # fast, but does not allow for exact reconstruction
209
+ # t serves as an index to gather the correct alphas
210
+ if use_original_steps:
211
+ sqrt_alphas_cumprod = self.sqrt_alphas_cumprod
212
+ sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod
213
+ else:
214
+ sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)
215
+ sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas
216
+
217
+ if noise is None:
218
+ noise = torch.randn_like(x0)
219
+ return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +
220
+ extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)
221
+
222
+ @torch.no_grad()
223
+ def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,
224
+ use_original_steps=False):
225
+
226
+ timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
227
+ timesteps = timesteps[:t_start]
228
+
229
+ time_range = np.flip(timesteps)
230
+ total_steps = timesteps.shape[0]
231
+ print(f"Running DDIM Sampling with {total_steps} timesteps")
232
+
233
+ iterator = tqdm(time_range, desc='Decoding image', total=total_steps)
234
+ x_dec = x_latent
235
+ for i, step in enumerate(iterator):
236
+ index = total_steps - i - 1
237
+ ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)
238
+ x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,
239
+ unconditional_guidance_scale=unconditional_guidance_scale,
240
+ unconditional_conditioning=unconditional_conditioning)
241
+ return x_dec
stable_diffusion/ldm/models/diffusion/ddpm.py ADDED
@@ -0,0 +1,1445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 pytorch_lightning.utilities.distributed import rank_zero_only
20
+
21
+ from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config
22
+ from ldm.modules.ema import LitEma
23
+ from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution
24
+ from ldm.models.autoencoder import VQModelInterface, IdentityFirstStage, AutoencoderKL
25
+ from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like
26
+ from ldm.models.diffusion.ddim import DDIMSampler
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 uniform_on_device(r1, r2, shape, device):
41
+ return (r1 - r2) * torch.rand(*shape, device=device) + r2
42
+
43
+
44
+ class DDPM(pl.LightningModule):
45
+ # classic DDPM with Gaussian diffusion, in image space
46
+ def __init__(self,
47
+ unet_config,
48
+ timesteps=1000,
49
+ beta_schedule="linear",
50
+ loss_type="l2",
51
+ ckpt_path=None,
52
+ ignore_keys=[],
53
+ load_only_unet=False,
54
+ monitor="val/loss",
55
+ use_ema=True,
56
+ first_stage_key="image",
57
+ image_size=256,
58
+ channels=3,
59
+ log_every_t=100,
60
+ clip_denoised=True,
61
+ linear_start=1e-4,
62
+ linear_end=2e-2,
63
+ cosine_s=8e-3,
64
+ given_betas=None,
65
+ original_elbo_weight=0.,
66
+ v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
67
+ l_simple_weight=1.,
68
+ conditioning_key=None,
69
+ parameterization="eps", # all assuming fixed variance schedules
70
+ scheduler_config=None,
71
+ use_positional_encodings=False,
72
+ learn_logvar=False,
73
+ logvar_init=0.,
74
+ ):
75
+ super().__init__()
76
+ assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"'
77
+ self.parameterization = parameterization
78
+ print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
79
+ self.cond_stage_model = None
80
+ self.clip_denoised = clip_denoised
81
+ self.log_every_t = log_every_t
82
+ self.first_stage_key = first_stage_key
83
+ self.image_size = image_size # try conv?
84
+ self.channels = channels
85
+ self.use_positional_encodings = use_positional_encodings
86
+ self.model = DiffusionWrapper(unet_config, conditioning_key)
87
+ count_params(self.model, verbose=True)
88
+ self.use_ema = use_ema
89
+ if self.use_ema:
90
+ self.model_ema = LitEma(self.model)
91
+ print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
92
+
93
+ self.use_scheduler = scheduler_config is not None
94
+ if self.use_scheduler:
95
+ self.scheduler_config = scheduler_config
96
+
97
+ self.v_posterior = v_posterior
98
+ self.original_elbo_weight = original_elbo_weight
99
+ self.l_simple_weight = l_simple_weight
100
+
101
+ if monitor is not None:
102
+ self.monitor = monitor
103
+ if ckpt_path is not None:
104
+ self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet)
105
+
106
+ self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
107
+ linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
108
+
109
+ self.loss_type = loss_type
110
+
111
+ self.learn_logvar = learn_logvar
112
+ self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
113
+ if self.learn_logvar:
114
+ self.logvar = nn.Parameter(self.logvar, requires_grad=True)
115
+
116
+
117
+ def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
118
+ linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
119
+ if exists(given_betas):
120
+ betas = given_betas
121
+ else:
122
+ betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
123
+ cosine_s=cosine_s)
124
+ alphas = 1. - betas
125
+ alphas_cumprod = np.cumprod(alphas, axis=0)
126
+ alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
127
+
128
+ timesteps, = betas.shape
129
+ self.num_timesteps = int(timesteps)
130
+ self.linear_start = linear_start
131
+ self.linear_end = linear_end
132
+ assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
133
+
134
+ to_torch = partial(torch.tensor, dtype=torch.float32)
135
+
136
+ self.register_buffer('betas', to_torch(betas))
137
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
138
+ self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
139
+
140
+ # calculations for diffusion q(x_t | x_{t-1}) and others
141
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
142
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
143
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
144
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
145
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
146
+
147
+ # calculations for posterior q(x_{t-1} | x_t, x_0)
148
+ posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / (
149
+ 1. - alphas_cumprod) + self.v_posterior * betas
150
+ # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
151
+ self.register_buffer('posterior_variance', to_torch(posterior_variance))
152
+ # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
153
+ self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
154
+ self.register_buffer('posterior_mean_coef1', to_torch(
155
+ betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
156
+ self.register_buffer('posterior_mean_coef2', to_torch(
157
+ (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
158
+
159
+ if self.parameterization == "eps":
160
+ lvlb_weights = self.betas ** 2 / (
161
+ 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))
162
+ elif self.parameterization == "x0":
163
+ lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod))
164
+ else:
165
+ raise NotImplementedError("mu not supported")
166
+ # TODO how to choose this term
167
+ lvlb_weights[0] = lvlb_weights[1]
168
+ self.register_buffer('lvlb_weights', lvlb_weights, persistent=False)
169
+ assert not torch.isnan(self.lvlb_weights).all()
170
+
171
+ @contextmanager
172
+ def ema_scope(self, context=None):
173
+ if self.use_ema:
174
+ self.model_ema.store(self.model.parameters())
175
+ self.model_ema.copy_to(self.model)
176
+ if context is not None:
177
+ print(f"{context}: Switched to EMA weights")
178
+ try:
179
+ yield None
180
+ finally:
181
+ if self.use_ema:
182
+ self.model_ema.restore(self.model.parameters())
183
+ if context is not None:
184
+ print(f"{context}: Restored training weights")
185
+
186
+ def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
187
+ sd = torch.load(path, map_location="cpu")
188
+ if "state_dict" in list(sd.keys()):
189
+ sd = sd["state_dict"]
190
+ keys = list(sd.keys())
191
+ for k in keys:
192
+ for ik in ignore_keys:
193
+ if k.startswith(ik):
194
+ print("Deleting key {} from state_dict.".format(k))
195
+ del sd[k]
196
+ missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
197
+ sd, strict=False)
198
+ print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
199
+ if len(missing) > 0:
200
+ print(f"Missing Keys: {missing}")
201
+ if len(unexpected) > 0:
202
+ print(f"Unexpected Keys: {unexpected}")
203
+
204
+ def q_mean_variance(self, x_start, t):
205
+ """
206
+ Get the distribution q(x_t | x_0).
207
+ :param x_start: the [N x C x ...] tensor of noiseless inputs.
208
+ :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
209
+ :return: A tuple (mean, variance, log_variance), all of x_start's shape.
210
+ """
211
+ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
212
+ variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
213
+ log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
214
+ return mean, variance, log_variance
215
+
216
+ def predict_start_from_noise(self, x_t, t, noise):
217
+ return (
218
+ extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
219
+ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
220
+ )
221
+
222
+ def q_posterior(self, x_start, x_t, t):
223
+ posterior_mean = (
224
+ extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start +
225
+ extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
226
+ )
227
+ posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape)
228
+ posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
229
+ return posterior_mean, posterior_variance, posterior_log_variance_clipped
230
+
231
+ def p_mean_variance(self, x, t, clip_denoised: bool):
232
+ model_out = self.model(x, t)
233
+ if self.parameterization == "eps":
234
+ x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
235
+ elif self.parameterization == "x0":
236
+ x_recon = model_out
237
+ if clip_denoised:
238
+ x_recon.clamp_(-1., 1.)
239
+
240
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
241
+ return model_mean, posterior_variance, posterior_log_variance
242
+
243
+ @torch.no_grad()
244
+ def p_sample(self, x, t, clip_denoised=True, repeat_noise=False):
245
+ b, *_, device = *x.shape, x.device
246
+ model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
247
+ noise = noise_like(x.shape, device, repeat_noise)
248
+ # no noise when t == 0
249
+ nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
250
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
251
+
252
+ @torch.no_grad()
253
+ def p_sample_loop(self, shape, return_intermediates=False):
254
+ device = self.betas.device
255
+ b = shape[0]
256
+ img = torch.randn(shape, device=device)
257
+ intermediates = [img]
258
+ for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps):
259
+ img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long),
260
+ clip_denoised=self.clip_denoised)
261
+ if i % self.log_every_t == 0 or i == self.num_timesteps - 1:
262
+ intermediates.append(img)
263
+ if return_intermediates:
264
+ return img, intermediates
265
+ return img
266
+
267
+ @torch.no_grad()
268
+ def sample(self, batch_size=16, return_intermediates=False):
269
+ image_size = self.image_size
270
+ channels = self.channels
271
+ return self.p_sample_loop((batch_size, channels, image_size, image_size),
272
+ return_intermediates=return_intermediates)
273
+
274
+ def q_sample(self, x_start, t, noise=None):
275
+ noise = default(noise, lambda: torch.randn_like(x_start))
276
+ return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
277
+ extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
278
+
279
+ def get_loss(self, pred, target, mean=True):
280
+ if self.loss_type == 'l1':
281
+ loss = (target - pred).abs()
282
+ if mean:
283
+ loss = loss.mean()
284
+ elif self.loss_type == 'l2':
285
+ if mean:
286
+ loss = torch.nn.functional.mse_loss(target, pred)
287
+ else:
288
+ loss = torch.nn.functional.mse_loss(target, pred, reduction='none')
289
+ else:
290
+ raise NotImplementedError("unknown loss type '{loss_type}'")
291
+
292
+ return loss
293
+
294
+ def p_losses(self, x_start, t, noise=None):
295
+ noise = default(noise, lambda: torch.randn_like(x_start))
296
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
297
+ model_out = self.model(x_noisy, t)
298
+
299
+ loss_dict = {}
300
+ if self.parameterization == "eps":
301
+ target = noise
302
+ elif self.parameterization == "x0":
303
+ target = x_start
304
+ else:
305
+ raise NotImplementedError(f"Paramterization {self.parameterization} not yet supported")
306
+
307
+ loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3])
308
+
309
+ log_prefix = 'train' if self.training else 'val'
310
+
311
+ loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()})
312
+ loss_simple = loss.mean() * self.l_simple_weight
313
+
314
+ loss_vlb = (self.lvlb_weights[t] * loss).mean()
315
+ loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb})
316
+
317
+ loss = loss_simple + self.original_elbo_weight * loss_vlb
318
+
319
+ loss_dict.update({f'{log_prefix}/loss': loss})
320
+
321
+ return loss, loss_dict
322
+
323
+ def forward(self, x, *args, **kwargs):
324
+ # b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size
325
+ # assert h == img_size and w == img_size, f'height and width of image must be {img_size}'
326
+ t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
327
+ return self.p_losses(x, t, *args, **kwargs)
328
+
329
+ def get_input(self, batch, k):
330
+ x = batch[k]
331
+ if len(x.shape) == 3:
332
+ x = x[..., None]
333
+ x = rearrange(x, 'b h w c -> b c h w')
334
+ x = x.to(memory_format=torch.contiguous_format).float()
335
+ return x
336
+
337
+ def shared_step(self, batch):
338
+ x = self.get_input(batch, self.first_stage_key)
339
+ loss, loss_dict = self(x)
340
+ return loss, loss_dict
341
+
342
+ def training_step(self, batch, batch_idx):
343
+ loss, loss_dict = self.shared_step(batch)
344
+
345
+ self.log_dict(loss_dict, prog_bar=True,
346
+ logger=True, on_step=True, on_epoch=True)
347
+
348
+ self.log("global_step", self.global_step,
349
+ prog_bar=True, logger=True, on_step=True, on_epoch=False)
350
+
351
+ if self.use_scheduler:
352
+ lr = self.optimizers().param_groups[0]['lr']
353
+ self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False)
354
+
355
+ return loss
356
+
357
+ @torch.no_grad()
358
+ def validation_step(self, batch, batch_idx):
359
+ _, loss_dict_no_ema = self.shared_step(batch)
360
+ with self.ema_scope():
361
+ _, loss_dict_ema = self.shared_step(batch)
362
+ loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema}
363
+ self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
364
+ self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
365
+
366
+ def on_train_batch_end(self, *args, **kwargs):
367
+ if self.use_ema:
368
+ self.model_ema(self.model)
369
+
370
+ def _get_rows_from_list(self, samples):
371
+ n_imgs_per_row = len(samples)
372
+ denoise_grid = rearrange(samples, 'n b c h w -> b n c h w')
373
+ denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
374
+ denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
375
+ return denoise_grid
376
+
377
+ @torch.no_grad()
378
+ def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
379
+ log = dict()
380
+ x = self.get_input(batch, self.first_stage_key)
381
+ N = min(x.shape[0], N)
382
+ n_row = min(x.shape[0], n_row)
383
+ x = x.to(self.device)[:N]
384
+ log["inputs"] = x
385
+
386
+ # get diffusion row
387
+ diffusion_row = list()
388
+ x_start = x[:n_row]
389
+
390
+ for t in range(self.num_timesteps):
391
+ if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
392
+ t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
393
+ t = t.to(self.device).long()
394
+ noise = torch.randn_like(x_start)
395
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
396
+ diffusion_row.append(x_noisy)
397
+
398
+ log["diffusion_row"] = self._get_rows_from_list(diffusion_row)
399
+
400
+ if sample:
401
+ # get denoise row
402
+ with self.ema_scope("Plotting"):
403
+ samples, denoise_row = self.sample(batch_size=N, return_intermediates=True)
404
+
405
+ log["samples"] = samples
406
+ log["denoise_row"] = self._get_rows_from_list(denoise_row)
407
+
408
+ if return_keys:
409
+ if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
410
+ return log
411
+ else:
412
+ return {key: log[key] for key in return_keys}
413
+ return log
414
+
415
+ def configure_optimizers(self):
416
+ lr = self.learning_rate
417
+ params = list(self.model.parameters())
418
+ if self.learn_logvar:
419
+ params = params + [self.logvar]
420
+ opt = torch.optim.AdamW(params, lr=lr)
421
+ return opt
422
+
423
+
424
+ class LatentDiffusion(DDPM):
425
+ """main class"""
426
+ def __init__(self,
427
+ first_stage_config,
428
+ cond_stage_config,
429
+ num_timesteps_cond=None,
430
+ cond_stage_key="image",
431
+ cond_stage_trainable=False,
432
+ concat_mode=True,
433
+ cond_stage_forward=None,
434
+ conditioning_key=None,
435
+ scale_factor=1.0,
436
+ scale_by_std=False,
437
+ *args, **kwargs):
438
+ self.num_timesteps_cond = default(num_timesteps_cond, 1)
439
+ self.scale_by_std = scale_by_std
440
+ assert self.num_timesteps_cond <= kwargs['timesteps']
441
+ # for backwards compatibility after implementation of DiffusionWrapper
442
+ if conditioning_key is None:
443
+ conditioning_key = 'concat' if concat_mode else 'crossattn'
444
+ if cond_stage_config == '__is_unconditional__':
445
+ conditioning_key = None
446
+ ckpt_path = kwargs.pop("ckpt_path", None)
447
+ ignore_keys = kwargs.pop("ignore_keys", [])
448
+ super().__init__(conditioning_key=conditioning_key, *args, **kwargs)
449
+ self.concat_mode = concat_mode
450
+ self.cond_stage_trainable = cond_stage_trainable
451
+ self.cond_stage_key = cond_stage_key
452
+ try:
453
+ self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
454
+ except:
455
+ self.num_downs = 0
456
+ if not scale_by_std:
457
+ self.scale_factor = scale_factor
458
+ else:
459
+ self.register_buffer('scale_factor', torch.tensor(scale_factor))
460
+ self.instantiate_first_stage(first_stage_config)
461
+ self.instantiate_cond_stage(cond_stage_config)
462
+ self.cond_stage_forward = cond_stage_forward
463
+ self.clip_denoised = False
464
+ self.bbox_tokenizer = None
465
+
466
+ self.restarted_from_ckpt = False
467
+ if ckpt_path is not None:
468
+ self.init_from_ckpt(ckpt_path, ignore_keys)
469
+ self.restarted_from_ckpt = True
470
+
471
+ def make_cond_schedule(self, ):
472
+ self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)
473
+ ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()
474
+ self.cond_ids[:self.num_timesteps_cond] = ids
475
+
476
+ @rank_zero_only
477
+ @torch.no_grad()
478
+ def on_train_batch_start(self, batch, batch_idx, dataloader_idx):
479
+ # only for very first batch
480
+ 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:
481
+ assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously'
482
+ # set rescale weight to 1./std of encodings
483
+ print("### USING STD-RESCALING ###")
484
+ x = super().get_input(batch, self.first_stage_key)
485
+ x = x.to(self.device)
486
+ encoder_posterior = self.encode_first_stage(x)
487
+ z = self.get_first_stage_encoding(encoder_posterior).detach()
488
+ del self.scale_factor
489
+ self.register_buffer('scale_factor', 1. / z.flatten().std())
490
+ print(f"setting self.scale_factor to {self.scale_factor}")
491
+ print("### USING STD-RESCALING ###")
492
+
493
+ def register_schedule(self,
494
+ given_betas=None, beta_schedule="linear", timesteps=1000,
495
+ linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
496
+ super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)
497
+
498
+ self.shorten_cond_schedule = self.num_timesteps_cond > 1
499
+ if self.shorten_cond_schedule:
500
+ self.make_cond_schedule()
501
+
502
+ def instantiate_first_stage(self, config):
503
+ model = instantiate_from_config(config)
504
+ self.first_stage_model = model.eval()
505
+ self.first_stage_model.train = disabled_train
506
+ for param in self.first_stage_model.parameters():
507
+ param.requires_grad = False
508
+
509
+ def instantiate_cond_stage(self, config):
510
+ if not self.cond_stage_trainable:
511
+ if config == "__is_first_stage__":
512
+ print("Using first stage also as cond stage.")
513
+ self.cond_stage_model = self.first_stage_model
514
+ elif config == "__is_unconditional__":
515
+ print(f"Training {self.__class__.__name__} as an unconditional model.")
516
+ self.cond_stage_model = None
517
+ # self.be_unconditional = True
518
+ else:
519
+ model = instantiate_from_config(config)
520
+ self.cond_stage_model = model.eval()
521
+ self.cond_stage_model.train = disabled_train
522
+ for param in self.cond_stage_model.parameters():
523
+ param.requires_grad = False
524
+ else:
525
+ assert config != '__is_first_stage__'
526
+ assert config != '__is_unconditional__'
527
+ model = instantiate_from_config(config)
528
+ self.cond_stage_model = model
529
+
530
+ def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False):
531
+ denoise_row = []
532
+ for zd in tqdm(samples, desc=desc):
533
+ denoise_row.append(self.decode_first_stage(zd.to(self.device),
534
+ force_not_quantize=force_no_decoder_quantization))
535
+ n_imgs_per_row = len(denoise_row)
536
+ denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W
537
+ denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')
538
+ denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
539
+ denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
540
+ return denoise_grid
541
+
542
+ def get_first_stage_encoding(self, encoder_posterior):
543
+ if isinstance(encoder_posterior, DiagonalGaussianDistribution):
544
+ z = encoder_posterior.sample()
545
+ elif isinstance(encoder_posterior, torch.Tensor):
546
+ z = encoder_posterior
547
+ else:
548
+ raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented")
549
+ return self.scale_factor * z
550
+
551
+ def get_learned_conditioning(self, c):
552
+ if self.cond_stage_forward is None:
553
+ if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):
554
+ c = self.cond_stage_model.encode(c)
555
+ if isinstance(c, DiagonalGaussianDistribution):
556
+ c = c.mode()
557
+ else:
558
+ c = self.cond_stage_model(c)
559
+ else:
560
+ assert hasattr(self.cond_stage_model, self.cond_stage_forward)
561
+ c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)
562
+ return c
563
+
564
+ def meshgrid(self, h, w):
565
+ y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)
566
+ x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)
567
+
568
+ arr = torch.cat([y, x], dim=-1)
569
+ return arr
570
+
571
+ def delta_border(self, h, w):
572
+ """
573
+ :param h: height
574
+ :param w: width
575
+ :return: normalized distance to image border,
576
+ wtith min distance = 0 at border and max dist = 0.5 at image center
577
+ """
578
+ lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
579
+ arr = self.meshgrid(h, w) / lower_right_corner
580
+ dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]
581
+ dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]
582
+ edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0]
583
+ return edge_dist
584
+
585
+ def get_weighting(self, h, w, Ly, Lx, device):
586
+ weighting = self.delta_border(h, w)
587
+ weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"],
588
+ self.split_input_params["clip_max_weight"], )
589
+ weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)
590
+
591
+ if self.split_input_params["tie_braker"]:
592
+ L_weighting = self.delta_border(Ly, Lx)
593
+ L_weighting = torch.clip(L_weighting,
594
+ self.split_input_params["clip_min_tie_weight"],
595
+ self.split_input_params["clip_max_tie_weight"])
596
+
597
+ L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)
598
+ weighting = weighting * L_weighting
599
+ return weighting
600
+
601
+ def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code
602
+ """
603
+ :param x: img of size (bs, c, h, w)
604
+ :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])
605
+ """
606
+ bs, nc, h, w = x.shape
607
+
608
+ # number of crops in image
609
+ Ly = (h - kernel_size[0]) // stride[0] + 1
610
+ Lx = (w - kernel_size[1]) // stride[1] + 1
611
+
612
+ if uf == 1 and df == 1:
613
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
614
+ unfold = torch.nn.Unfold(**fold_params)
615
+
616
+ fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)
617
+
618
+ weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype)
619
+ normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap
620
+ weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))
621
+
622
+ elif uf > 1 and df == 1:
623
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
624
+ unfold = torch.nn.Unfold(**fold_params)
625
+
626
+ fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),
627
+ dilation=1, padding=0,
628
+ stride=(stride[0] * uf, stride[1] * uf))
629
+ fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2)
630
+
631
+ weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype)
632
+ normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap
633
+ weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx))
634
+
635
+ elif df > 1 and uf == 1:
636
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
637
+ unfold = torch.nn.Unfold(**fold_params)
638
+
639
+ fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df),
640
+ dilation=1, padding=0,
641
+ stride=(stride[0] // df, stride[1] // df))
642
+ fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2)
643
+
644
+ weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype)
645
+ normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap
646
+ weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx))
647
+
648
+ else:
649
+ raise NotImplementedError
650
+
651
+ return fold, unfold, normalization, weighting
652
+
653
+ @torch.no_grad()
654
+ def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False,
655
+ cond_key=None, return_original_cond=False, bs=None):
656
+ x = super().get_input(batch, k)
657
+ if bs is not None:
658
+ x = x[:bs]
659
+ x = x.to(self.device)
660
+ encoder_posterior = self.encode_first_stage(x)
661
+ z = self.get_first_stage_encoding(encoder_posterior).detach()
662
+
663
+ if self.model.conditioning_key is not None:
664
+ if cond_key is None:
665
+ cond_key = self.cond_stage_key
666
+ if cond_key != self.first_stage_key:
667
+ if cond_key in ['caption', 'coordinates_bbox']:
668
+ xc = batch[cond_key]
669
+ elif cond_key == 'class_label':
670
+ xc = batch
671
+ else:
672
+ xc = super().get_input(batch, cond_key).to(self.device)
673
+ else:
674
+ xc = x
675
+ if not self.cond_stage_trainable or force_c_encode:
676
+ if isinstance(xc, dict) or isinstance(xc, list):
677
+ # import pudb; pudb.set_trace()
678
+ c = self.get_learned_conditioning(xc)
679
+ else:
680
+ c = self.get_learned_conditioning(xc.to(self.device))
681
+ else:
682
+ c = xc
683
+ if bs is not None:
684
+ c = c[:bs]
685
+
686
+ if self.use_positional_encodings:
687
+ pos_x, pos_y = self.compute_latent_shifts(batch)
688
+ ckey = __conditioning_keys__[self.model.conditioning_key]
689
+ c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y}
690
+
691
+ else:
692
+ c = None
693
+ xc = None
694
+ if self.use_positional_encodings:
695
+ pos_x, pos_y = self.compute_latent_shifts(batch)
696
+ c = {'pos_x': pos_x, 'pos_y': pos_y}
697
+ out = [z, c]
698
+ if return_first_stage_outputs:
699
+ xrec = self.decode_first_stage(z)
700
+ out.extend([x, xrec])
701
+ if return_original_cond:
702
+ out.append(xc)
703
+ return out
704
+
705
+ @torch.no_grad()
706
+ def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
707
+ if predict_cids:
708
+ if z.dim() == 4:
709
+ z = torch.argmax(z.exp(), dim=1).long()
710
+ z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
711
+ z = rearrange(z, 'b h w c -> b c h w').contiguous()
712
+
713
+ z = 1. / self.scale_factor * z
714
+
715
+ if hasattr(self, "split_input_params"):
716
+ if self.split_input_params["patch_distributed_vq"]:
717
+ ks = self.split_input_params["ks"] # eg. (128, 128)
718
+ stride = self.split_input_params["stride"] # eg. (64, 64)
719
+ uf = self.split_input_params["vqf"]
720
+ bs, nc, h, w = z.shape
721
+ if ks[0] > h or ks[1] > w:
722
+ ks = (min(ks[0], h), min(ks[1], w))
723
+ print("reducing Kernel")
724
+
725
+ if stride[0] > h or stride[1] > w:
726
+ stride = (min(stride[0], h), min(stride[1], w))
727
+ print("reducing stride")
728
+
729
+ fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf)
730
+
731
+ z = unfold(z) # (bn, nc * prod(**ks), L)
732
+ # 1. Reshape to img shape
733
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
734
+
735
+ # 2. apply model loop over last dim
736
+ if isinstance(self.first_stage_model, VQModelInterface):
737
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
738
+ force_not_quantize=predict_cids or force_not_quantize)
739
+ for i in range(z.shape[-1])]
740
+ else:
741
+
742
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i])
743
+ for i in range(z.shape[-1])]
744
+
745
+ o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)
746
+ o = o * weighting
747
+ # Reverse 1. reshape to img shape
748
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
749
+ # stitch crops together
750
+ decoded = fold(o)
751
+ decoded = decoded / normalization # norm is shape (1, 1, h, w)
752
+ return decoded
753
+ else:
754
+ if isinstance(self.first_stage_model, VQModelInterface):
755
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
756
+ else:
757
+ return self.first_stage_model.decode(z)
758
+
759
+ else:
760
+ if isinstance(self.first_stage_model, VQModelInterface):
761
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
762
+ else:
763
+ return self.first_stage_model.decode(z)
764
+
765
+ # same as above but without decorator
766
+ def differentiable_decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
767
+ if predict_cids:
768
+ if z.dim() == 4:
769
+ z = torch.argmax(z.exp(), dim=1).long()
770
+ z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
771
+ z = rearrange(z, 'b h w c -> b c h w').contiguous()
772
+
773
+ z = 1. / self.scale_factor * z
774
+
775
+ if hasattr(self, "split_input_params"):
776
+ if self.split_input_params["patch_distributed_vq"]:
777
+ ks = self.split_input_params["ks"] # eg. (128, 128)
778
+ stride = self.split_input_params["stride"] # eg. (64, 64)
779
+ uf = self.split_input_params["vqf"]
780
+ bs, nc, h, w = z.shape
781
+ if ks[0] > h or ks[1] > w:
782
+ ks = (min(ks[0], h), min(ks[1], w))
783
+ print("reducing Kernel")
784
+
785
+ if stride[0] > h or stride[1] > w:
786
+ stride = (min(stride[0], h), min(stride[1], w))
787
+ print("reducing stride")
788
+
789
+ fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf)
790
+
791
+ z = unfold(z) # (bn, nc * prod(**ks), L)
792
+ # 1. Reshape to img shape
793
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
794
+
795
+ # 2. apply model loop over last dim
796
+ if isinstance(self.first_stage_model, VQModelInterface):
797
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
798
+ force_not_quantize=predict_cids or force_not_quantize)
799
+ for i in range(z.shape[-1])]
800
+ else:
801
+
802
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i])
803
+ for i in range(z.shape[-1])]
804
+
805
+ o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)
806
+ o = o * weighting
807
+ # Reverse 1. reshape to img shape
808
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
809
+ # stitch crops together
810
+ decoded = fold(o)
811
+ decoded = decoded / normalization # norm is shape (1, 1, h, w)
812
+ return decoded
813
+ else:
814
+ if isinstance(self.first_stage_model, VQModelInterface):
815
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
816
+ else:
817
+ return self.first_stage_model.decode(z)
818
+
819
+ else:
820
+ if isinstance(self.first_stage_model, VQModelInterface):
821
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
822
+ else:
823
+ return self.first_stage_model.decode(z)
824
+
825
+ @torch.no_grad()
826
+ def encode_first_stage(self, x):
827
+ if hasattr(self, "split_input_params"):
828
+ if self.split_input_params["patch_distributed_vq"]:
829
+ ks = self.split_input_params["ks"] # eg. (128, 128)
830
+ stride = self.split_input_params["stride"] # eg. (64, 64)
831
+ df = self.split_input_params["vqf"]
832
+ self.split_input_params['original_image_size'] = x.shape[-2:]
833
+ bs, nc, h, w = x.shape
834
+ if ks[0] > h or ks[1] > w:
835
+ ks = (min(ks[0], h), min(ks[1], w))
836
+ print("reducing Kernel")
837
+
838
+ if stride[0] > h or stride[1] > w:
839
+ stride = (min(stride[0], h), min(stride[1], w))
840
+ print("reducing stride")
841
+
842
+ fold, unfold, normalization, weighting = self.get_fold_unfold(x, ks, stride, df=df)
843
+ z = unfold(x) # (bn, nc * prod(**ks), L)
844
+ # Reshape to img shape
845
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
846
+
847
+ output_list = [self.first_stage_model.encode(z[:, :, :, :, i])
848
+ for i in range(z.shape[-1])]
849
+
850
+ o = torch.stack(output_list, axis=-1)
851
+ o = o * weighting
852
+
853
+ # Reverse reshape to img shape
854
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
855
+ # stitch crops together
856
+ decoded = fold(o)
857
+ decoded = decoded / normalization
858
+ return decoded
859
+
860
+ else:
861
+ return self.first_stage_model.encode(x)
862
+ else:
863
+ return self.first_stage_model.encode(x)
864
+
865
+ def shared_step(self, batch, **kwargs):
866
+ x, c = self.get_input(batch, self.first_stage_key)
867
+ loss = self(x, c)
868
+ return loss
869
+
870
+ def forward(self, x, c, *args, **kwargs):
871
+ t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
872
+ if self.model.conditioning_key is not None:
873
+ assert c is not None
874
+ if self.cond_stage_trainable:
875
+ c = self.get_learned_conditioning(c)
876
+ if self.shorten_cond_schedule: # TODO: drop this option
877
+ tc = self.cond_ids[t].to(self.device)
878
+ c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))
879
+ return self.p_losses(x, c, t, *args, **kwargs)
880
+
881
+ def _rescale_annotations(self, bboxes, crop_coordinates): # TODO: move to dataset
882
+ def rescale_bbox(bbox):
883
+ x0 = clamp((bbox[0] - crop_coordinates[0]) / crop_coordinates[2])
884
+ y0 = clamp((bbox[1] - crop_coordinates[1]) / crop_coordinates[3])
885
+ w = min(bbox[2] / crop_coordinates[2], 1 - x0)
886
+ h = min(bbox[3] / crop_coordinates[3], 1 - y0)
887
+ return x0, y0, w, h
888
+
889
+ return [rescale_bbox(b) for b in bboxes]
890
+
891
+ def apply_model(self, x_noisy, t, cond, return_ids=False):
892
+
893
+ if isinstance(cond, dict):
894
+ # hybrid case, cond is exptected to be a dict
895
+ pass
896
+ else:
897
+ if not isinstance(cond, list):
898
+ cond = [cond]
899
+ key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'
900
+ cond = {key: cond}
901
+
902
+ if hasattr(self, "split_input_params"):
903
+ assert len(cond) == 1 # todo can only deal with one conditioning atm
904
+ assert not return_ids
905
+ ks = self.split_input_params["ks"] # eg. (128, 128)
906
+ stride = self.split_input_params["stride"] # eg. (64, 64)
907
+
908
+ h, w = x_noisy.shape[-2:]
909
+
910
+ fold, unfold, normalization, weighting = self.get_fold_unfold(x_noisy, ks, stride)
911
+
912
+ z = unfold(x_noisy) # (bn, nc * prod(**ks), L)
913
+ # Reshape to img shape
914
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
915
+ z_list = [z[:, :, :, :, i] for i in range(z.shape[-1])]
916
+
917
+ if self.cond_stage_key in ["image", "LR_image", "segmentation",
918
+ 'bbox_img'] and self.model.conditioning_key: # todo check for completeness
919
+ c_key = next(iter(cond.keys())) # get key
920
+ c = next(iter(cond.values())) # get value
921
+ assert (len(c) == 1) # todo extend to list with more than one elem
922
+ c = c[0] # get element
923
+
924
+ c = unfold(c)
925
+ c = c.view((c.shape[0], -1, ks[0], ks[1], c.shape[-1])) # (bn, nc, ks[0], ks[1], L )
926
+
927
+ cond_list = [{c_key: [c[:, :, :, :, i]]} for i in range(c.shape[-1])]
928
+
929
+ elif self.cond_stage_key == 'coordinates_bbox':
930
+ assert 'original_image_size' in self.split_input_params, 'BoudingBoxRescaling is missing original_image_size'
931
+
932
+ # assuming padding of unfold is always 0 and its dilation is always 1
933
+ n_patches_per_row = int((w - ks[0]) / stride[0] + 1)
934
+ full_img_h, full_img_w = self.split_input_params['original_image_size']
935
+ # as we are operating on latents, we need the factor from the original image size to the
936
+ # spatial latent size to properly rescale the crops for regenerating the bbox annotations
937
+ num_downs = self.first_stage_model.encoder.num_resolutions - 1
938
+ rescale_latent = 2 ** (num_downs)
939
+
940
+ # get top left postions of patches as conforming for the bbbox tokenizer, therefore we
941
+ # need to rescale the tl patch coordinates to be in between (0,1)
942
+ tl_patch_coordinates = [(rescale_latent * stride[0] * (patch_nr % n_patches_per_row) / full_img_w,
943
+ rescale_latent * stride[1] * (patch_nr // n_patches_per_row) / full_img_h)
944
+ for patch_nr in range(z.shape[-1])]
945
+
946
+ # patch_limits are tl_coord, width and height coordinates as (x_tl, y_tl, h, w)
947
+ patch_limits = [(x_tl, y_tl,
948
+ rescale_latent * ks[0] / full_img_w,
949
+ rescale_latent * ks[1] / full_img_h) for x_tl, y_tl in tl_patch_coordinates]
950
+ # 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]
951
+
952
+ # tokenize crop coordinates for the bounding boxes of the respective patches
953
+ patch_limits_tknzd = [torch.LongTensor(self.bbox_tokenizer._crop_encoder(bbox))[None].to(self.device)
954
+ for bbox in patch_limits] # list of length l with tensors of shape (1, 2)
955
+ print(patch_limits_tknzd[0].shape)
956
+ # cut tknzd crop position from conditioning
957
+ assert isinstance(cond, dict), 'cond must be dict to be fed into model'
958
+ cut_cond = cond['c_crossattn'][0][..., :-2].to(self.device)
959
+ print(cut_cond.shape)
960
+
961
+ adapted_cond = torch.stack([torch.cat([cut_cond, p], dim=1) for p in patch_limits_tknzd])
962
+ adapted_cond = rearrange(adapted_cond, 'l b n -> (l b) n')
963
+ print(adapted_cond.shape)
964
+ adapted_cond = self.get_learned_conditioning(adapted_cond)
965
+ print(adapted_cond.shape)
966
+ adapted_cond = rearrange(adapted_cond, '(l b) n d -> l b n d', l=z.shape[-1])
967
+ print(adapted_cond.shape)
968
+
969
+ cond_list = [{'c_crossattn': [e]} for e in adapted_cond]
970
+
971
+ else:
972
+ cond_list = [cond for i in range(z.shape[-1])] # Todo make this more efficient
973
+
974
+ # apply model by loop over crops
975
+ output_list = [self.model(z_list[i], t, **cond_list[i]) for i in range(z.shape[-1])]
976
+ assert not isinstance(output_list[0],
977
+ tuple) # todo cant deal with multiple model outputs check this never happens
978
+
979
+ o = torch.stack(output_list, axis=-1)
980
+ o = o * weighting
981
+ # Reverse reshape to img shape
982
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
983
+ # stitch crops together
984
+ x_recon = fold(o) / normalization
985
+
986
+ else:
987
+ x_recon = self.model(x_noisy, t, **cond)
988
+
989
+ if isinstance(x_recon, tuple) and not return_ids:
990
+ return x_recon[0]
991
+ else:
992
+ return x_recon
993
+
994
+ def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
995
+ return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \
996
+ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
997
+
998
+ def _prior_bpd(self, x_start):
999
+ """
1000
+ Get the prior KL term for the variational lower-bound, measured in
1001
+ bits-per-dim.
1002
+ This term can't be optimized, as it only depends on the encoder.
1003
+ :param x_start: the [N x C x ...] tensor of inputs.
1004
+ :return: a batch of [N] KL values (in bits), one per batch element.
1005
+ """
1006
+ batch_size = x_start.shape[0]
1007
+ t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
1008
+ qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
1009
+ kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
1010
+ return mean_flat(kl_prior) / np.log(2.0)
1011
+
1012
+ def p_losses(self, x_start, cond, t, noise=None):
1013
+ noise = default(noise, lambda: torch.randn_like(x_start))
1014
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
1015
+ model_output = self.apply_model(x_noisy, t, cond)
1016
+
1017
+ loss_dict = {}
1018
+ prefix = 'train' if self.training else 'val'
1019
+
1020
+ if self.parameterization == "x0":
1021
+ target = x_start
1022
+ elif self.parameterization == "eps":
1023
+ target = noise
1024
+ else:
1025
+ raise NotImplementedError()
1026
+
1027
+ loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3])
1028
+ loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})
1029
+
1030
+ logvar_t = self.logvar[t].to(self.device)
1031
+ loss = loss_simple / torch.exp(logvar_t) + logvar_t
1032
+ # loss = loss_simple / torch.exp(self.logvar) + self.logvar
1033
+ if self.learn_logvar:
1034
+ loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})
1035
+ loss_dict.update({'logvar': self.logvar.data.mean()})
1036
+
1037
+ loss = self.l_simple_weight * loss.mean()
1038
+
1039
+ loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3))
1040
+ loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()
1041
+ loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})
1042
+ loss += (self.original_elbo_weight * loss_vlb)
1043
+ loss_dict.update({f'{prefix}/loss': loss})
1044
+
1045
+ return loss, loss_dict
1046
+
1047
+ def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False,
1048
+ return_x0=False, score_corrector=None, corrector_kwargs=None):
1049
+ t_in = t
1050
+ model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)
1051
+
1052
+ if score_corrector is not None:
1053
+ assert self.parameterization == "eps"
1054
+ model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)
1055
+
1056
+ if return_codebook_ids:
1057
+ model_out, logits = model_out
1058
+
1059
+ if self.parameterization == "eps":
1060
+ x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
1061
+ elif self.parameterization == "x0":
1062
+ x_recon = model_out
1063
+ else:
1064
+ raise NotImplementedError()
1065
+
1066
+ if clip_denoised:
1067
+ x_recon.clamp_(-1., 1.)
1068
+ if quantize_denoised:
1069
+ x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)
1070
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
1071
+ if return_codebook_ids:
1072
+ return model_mean, posterior_variance, posterior_log_variance, logits
1073
+ elif return_x0:
1074
+ return model_mean, posterior_variance, posterior_log_variance, x_recon
1075
+ else:
1076
+ return model_mean, posterior_variance, posterior_log_variance
1077
+
1078
+ @torch.no_grad()
1079
+ def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False,
1080
+ return_codebook_ids=False, quantize_denoised=False, return_x0=False,
1081
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):
1082
+ b, *_, device = *x.shape, x.device
1083
+ outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised,
1084
+ return_codebook_ids=return_codebook_ids,
1085
+ quantize_denoised=quantize_denoised,
1086
+ return_x0=return_x0,
1087
+ score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
1088
+ if return_codebook_ids:
1089
+ raise DeprecationWarning("Support dropped.")
1090
+ model_mean, _, model_log_variance, logits = outputs
1091
+ elif return_x0:
1092
+ model_mean, _, model_log_variance, x0 = outputs
1093
+ else:
1094
+ model_mean, _, model_log_variance = outputs
1095
+
1096
+ noise = noise_like(x.shape, device, repeat_noise) * temperature
1097
+ if noise_dropout > 0.:
1098
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
1099
+ # no noise when t == 0
1100
+ nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
1101
+
1102
+ if return_codebook_ids:
1103
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1)
1104
+ if return_x0:
1105
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0
1106
+ else:
1107
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
1108
+
1109
+ @torch.no_grad()
1110
+ def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False,
1111
+ img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0.,
1112
+ score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None,
1113
+ log_every_t=None):
1114
+ if not log_every_t:
1115
+ log_every_t = self.log_every_t
1116
+ timesteps = self.num_timesteps
1117
+ if batch_size is not None:
1118
+ b = batch_size if batch_size is not None else shape[0]
1119
+ shape = [batch_size] + list(shape)
1120
+ else:
1121
+ b = batch_size = shape[0]
1122
+ if x_T is None:
1123
+ img = torch.randn(shape, device=self.device)
1124
+ else:
1125
+ img = x_T
1126
+ intermediates = []
1127
+ if cond is not None:
1128
+ if isinstance(cond, dict):
1129
+ cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
1130
+ list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
1131
+ else:
1132
+ cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
1133
+
1134
+ if start_T is not None:
1135
+ timesteps = min(timesteps, start_T)
1136
+ iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation',
1137
+ total=timesteps) if verbose else reversed(
1138
+ range(0, timesteps))
1139
+ if type(temperature) == float:
1140
+ temperature = [temperature] * timesteps
1141
+
1142
+ for i in iterator:
1143
+ ts = torch.full((b,), i, device=self.device, dtype=torch.long)
1144
+ if self.shorten_cond_schedule:
1145
+ assert self.model.conditioning_key != 'hybrid'
1146
+ tc = self.cond_ids[ts].to(cond.device)
1147
+ cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
1148
+
1149
+ img, x0_partial = self.p_sample(img, cond, ts,
1150
+ clip_denoised=self.clip_denoised,
1151
+ quantize_denoised=quantize_denoised, return_x0=True,
1152
+ temperature=temperature[i], noise_dropout=noise_dropout,
1153
+ score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
1154
+ if mask is not None:
1155
+ assert x0 is not None
1156
+ img_orig = self.q_sample(x0, ts)
1157
+ img = img_orig * mask + (1. - mask) * img
1158
+
1159
+ if i % log_every_t == 0 or i == timesteps - 1:
1160
+ intermediates.append(x0_partial)
1161
+ if callback: callback(i)
1162
+ if img_callback: img_callback(img, i)
1163
+ return img, intermediates
1164
+
1165
+ @torch.no_grad()
1166
+ def p_sample_loop(self, cond, shape, return_intermediates=False,
1167
+ x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False,
1168
+ mask=None, x0=None, img_callback=None, start_T=None,
1169
+ log_every_t=None):
1170
+
1171
+ if not log_every_t:
1172
+ log_every_t = self.log_every_t
1173
+ device = self.betas.device
1174
+ b = shape[0]
1175
+ if x_T is None:
1176
+ img = torch.randn(shape, device=device)
1177
+ else:
1178
+ img = x_T
1179
+
1180
+ intermediates = [img]
1181
+ if timesteps is None:
1182
+ timesteps = self.num_timesteps
1183
+
1184
+ if start_T is not None:
1185
+ timesteps = min(timesteps, start_T)
1186
+ iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(
1187
+ range(0, timesteps))
1188
+
1189
+ if mask is not None:
1190
+ assert x0 is not None
1191
+ assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match
1192
+
1193
+ for i in iterator:
1194
+ ts = torch.full((b,), i, device=device, dtype=torch.long)
1195
+ if self.shorten_cond_schedule:
1196
+ assert self.model.conditioning_key != 'hybrid'
1197
+ tc = self.cond_ids[ts].to(cond.device)
1198
+ cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
1199
+
1200
+ img = self.p_sample(img, cond, ts,
1201
+ clip_denoised=self.clip_denoised,
1202
+ quantize_denoised=quantize_denoised)
1203
+ if mask is not None:
1204
+ img_orig = self.q_sample(x0, ts)
1205
+ img = img_orig * mask + (1. - mask) * img
1206
+
1207
+ if i % log_every_t == 0 or i == timesteps - 1:
1208
+ intermediates.append(img)
1209
+ if callback: callback(i)
1210
+ if img_callback: img_callback(img, i)
1211
+
1212
+ if return_intermediates:
1213
+ return img, intermediates
1214
+ return img
1215
+
1216
+ @torch.no_grad()
1217
+ def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None,
1218
+ verbose=True, timesteps=None, quantize_denoised=False,
1219
+ mask=None, x0=None, shape=None,**kwargs):
1220
+ if shape is None:
1221
+ shape = (batch_size, self.channels, self.image_size, self.image_size)
1222
+ if cond is not None:
1223
+ if isinstance(cond, dict):
1224
+ cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
1225
+ list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
1226
+ else:
1227
+ cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
1228
+ return self.p_sample_loop(cond,
1229
+ shape,
1230
+ return_intermediates=return_intermediates, x_T=x_T,
1231
+ verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised,
1232
+ mask=mask, x0=x0)
1233
+
1234
+ @torch.no_grad()
1235
+ def sample_log(self,cond,batch_size,ddim, ddim_steps,**kwargs):
1236
+
1237
+ if ddim:
1238
+ ddim_sampler = DDIMSampler(self)
1239
+ shape = (self.channels, self.image_size, self.image_size)
1240
+ samples, intermediates =ddim_sampler.sample(ddim_steps,batch_size,
1241
+ shape,cond,verbose=False,**kwargs)
1242
+
1243
+ else:
1244
+ samples, intermediates = self.sample(cond=cond, batch_size=batch_size,
1245
+ return_intermediates=True,**kwargs)
1246
+
1247
+ return samples, intermediates
1248
+
1249
+
1250
+ @torch.no_grad()
1251
+ def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
1252
+ quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
1253
+ plot_diffusion_rows=True, **kwargs):
1254
+
1255
+ use_ddim = ddim_steps is not None
1256
+
1257
+ log = dict()
1258
+ z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,
1259
+ return_first_stage_outputs=True,
1260
+ force_c_encode=True,
1261
+ return_original_cond=True,
1262
+ bs=N)
1263
+ N = min(x.shape[0], N)
1264
+ n_row = min(x.shape[0], n_row)
1265
+ log["inputs"] = x
1266
+ log["reconstruction"] = xrec
1267
+ if self.model.conditioning_key is not None:
1268
+ if hasattr(self.cond_stage_model, "decode"):
1269
+ xc = self.cond_stage_model.decode(c)
1270
+ log["conditioning"] = xc
1271
+ elif self.cond_stage_key in ["caption"]:
1272
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["caption"])
1273
+ log["conditioning"] = xc
1274
+ elif self.cond_stage_key == 'class_label':
1275
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"])
1276
+ log['conditioning'] = xc
1277
+ elif isimage(xc):
1278
+ log["conditioning"] = xc
1279
+ if ismap(xc):
1280
+ log["original_conditioning"] = self.to_rgb(xc)
1281
+
1282
+ if plot_diffusion_rows:
1283
+ # get diffusion row
1284
+ diffusion_row = list()
1285
+ z_start = z[:n_row]
1286
+ for t in range(self.num_timesteps):
1287
+ if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
1288
+ t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
1289
+ t = t.to(self.device).long()
1290
+ noise = torch.randn_like(z_start)
1291
+ z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
1292
+ diffusion_row.append(self.decode_first_stage(z_noisy))
1293
+
1294
+ diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
1295
+ diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
1296
+ diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
1297
+ diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
1298
+ log["diffusion_row"] = diffusion_grid
1299
+
1300
+ if sample:
1301
+ # get denoise row
1302
+ with self.ema_scope("Plotting"):
1303
+ samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim,
1304
+ ddim_steps=ddim_steps,eta=ddim_eta)
1305
+ # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
1306
+ x_samples = self.decode_first_stage(samples)
1307
+ log["samples"] = x_samples
1308
+ if plot_denoise_rows:
1309
+ denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
1310
+ log["denoise_row"] = denoise_grid
1311
+
1312
+ if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(
1313
+ self.first_stage_model, IdentityFirstStage):
1314
+ # also display when quantizing x0 while sampling
1315
+ with self.ema_scope("Plotting Quantized Denoised"):
1316
+ samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim,
1317
+ ddim_steps=ddim_steps,eta=ddim_eta,
1318
+ quantize_denoised=True)
1319
+ # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,
1320
+ # quantize_denoised=True)
1321
+ x_samples = self.decode_first_stage(samples.to(self.device))
1322
+ log["samples_x0_quantized"] = x_samples
1323
+
1324
+ if inpaint:
1325
+ # make a simple center square
1326
+ b, h, w = z.shape[0], z.shape[2], z.shape[3]
1327
+ mask = torch.ones(N, h, w).to(self.device)
1328
+ # zeros will be filled in
1329
+ mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.
1330
+ mask = mask[:, None, ...]
1331
+ with self.ema_scope("Plotting Inpaint"):
1332
+
1333
+ samples, _ = self.sample_log(cond=c,batch_size=N,ddim=use_ddim, eta=ddim_eta,
1334
+ ddim_steps=ddim_steps, x0=z[:N], mask=mask)
1335
+ x_samples = self.decode_first_stage(samples.to(self.device))
1336
+ log["samples_inpainting"] = x_samples
1337
+ log["mask"] = mask
1338
+
1339
+ # outpaint
1340
+ with self.ema_scope("Plotting Outpaint"):
1341
+ samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,eta=ddim_eta,
1342
+ ddim_steps=ddim_steps, x0=z[:N], mask=mask)
1343
+ x_samples = self.decode_first_stage(samples.to(self.device))
1344
+ log["samples_outpainting"] = x_samples
1345
+
1346
+ if plot_progressive_rows:
1347
+ with self.ema_scope("Plotting Progressives"):
1348
+ img, progressives = self.progressive_denoising(c,
1349
+ shape=(self.channels, self.image_size, self.image_size),
1350
+ batch_size=N)
1351
+ prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
1352
+ log["progressive_row"] = prog_row
1353
+
1354
+ if return_keys:
1355
+ if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
1356
+ return log
1357
+ else:
1358
+ return {key: log[key] for key in return_keys}
1359
+ return log
1360
+
1361
+ def configure_optimizers(self):
1362
+ lr = self.learning_rate
1363
+ params = list(self.model.parameters())
1364
+ if self.cond_stage_trainable:
1365
+ print(f"{self.__class__.__name__}: Also optimizing conditioner params!")
1366
+ params = params + list(self.cond_stage_model.parameters())
1367
+ if self.learn_logvar:
1368
+ print('Diffusion model optimizing logvar')
1369
+ params.append(self.logvar)
1370
+ opt = torch.optim.AdamW(params, lr=lr)
1371
+ if self.use_scheduler:
1372
+ assert 'target' in self.scheduler_config
1373
+ scheduler = instantiate_from_config(self.scheduler_config)
1374
+
1375
+ print("Setting up LambdaLR scheduler...")
1376
+ scheduler = [
1377
+ {
1378
+ 'scheduler': LambdaLR(opt, lr_lambda=scheduler.schedule),
1379
+ 'interval': 'step',
1380
+ 'frequency': 1
1381
+ }]
1382
+ return [opt], scheduler
1383
+ return opt
1384
+
1385
+ @torch.no_grad()
1386
+ def to_rgb(self, x):
1387
+ x = x.float()
1388
+ if not hasattr(self, "colorize"):
1389
+ self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)
1390
+ x = nn.functional.conv2d(x, weight=self.colorize)
1391
+ x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.
1392
+ return x
1393
+
1394
+
1395
+ class DiffusionWrapper(pl.LightningModule):
1396
+ def __init__(self, diff_model_config, conditioning_key):
1397
+ super().__init__()
1398
+ self.diffusion_model = instantiate_from_config(diff_model_config)
1399
+ self.conditioning_key = conditioning_key
1400
+ assert self.conditioning_key in [None, 'concat', 'crossattn', 'hybrid', 'adm']
1401
+
1402
+ def forward(self, x, t, c_concat: list = None, c_crossattn: list = None):
1403
+ if self.conditioning_key is None:
1404
+ out = self.diffusion_model(x, t)
1405
+ elif self.conditioning_key == 'concat':
1406
+ xc = torch.cat([x] + c_concat, dim=1)
1407
+ out = self.diffusion_model(xc, t)
1408
+ elif self.conditioning_key == 'crossattn':
1409
+ cc = torch.cat(c_crossattn, 1)
1410
+ out = self.diffusion_model(x, t, context=cc)
1411
+ elif self.conditioning_key == 'hybrid':
1412
+ xc = torch.cat([x] + c_concat, dim=1)
1413
+ cc = torch.cat(c_crossattn, 1)
1414
+ out = self.diffusion_model(xc, t, context=cc)
1415
+ elif self.conditioning_key == 'adm':
1416
+ cc = c_crossattn[0]
1417
+ out = self.diffusion_model(x, t, y=cc)
1418
+ else:
1419
+ raise NotImplementedError()
1420
+
1421
+ return out
1422
+
1423
+
1424
+ class Layout2ImgDiffusion(LatentDiffusion):
1425
+ # TODO: move all layout-specific hacks to this class
1426
+ def __init__(self, cond_stage_key, *args, **kwargs):
1427
+ assert cond_stage_key == 'coordinates_bbox', 'Layout2ImgDiffusion only for cond_stage_key="coordinates_bbox"'
1428
+ super().__init__(cond_stage_key=cond_stage_key, *args, **kwargs)
1429
+
1430
+ def log_images(self, batch, N=8, *args, **kwargs):
1431
+ logs = super().log_images(batch=batch, N=N, *args, **kwargs)
1432
+
1433
+ key = 'train' if self.training else 'validation'
1434
+ dset = self.trainer.datamodule.datasets[key]
1435
+ mapper = dset.conditional_builders[self.cond_stage_key]
1436
+
1437
+ bbox_imgs = []
1438
+ map_fn = lambda catno: dset.get_textual_label(dset.get_category_id(catno))
1439
+ for tknzd_bbox in batch[self.cond_stage_key][:N]:
1440
+ bboximg = mapper.plot(tknzd_bbox.detach().cpu(), map_fn, (256, 256))
1441
+ bbox_imgs.append(bboximg)
1442
+
1443
+ cond_img = torch.stack(bbox_imgs, dim=0)
1444
+ logs['bbox_image'] = cond_img
1445
+ return logs
stable_diffusion/ldm/models/diffusion/ddpm_edit.py ADDED
@@ -0,0 +1,1459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # File modified by authors of InstructPix2Pix from original (https://github.com/CompVis/stable-diffusion).
10
+ # See more details in LICENSE.
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ import numpy as np
15
+ import pytorch_lightning as pl
16
+ from torch.optim.lr_scheduler import LambdaLR
17
+ from einops import rearrange, repeat
18
+ from contextlib import contextmanager
19
+ from functools import partial
20
+ from tqdm import tqdm
21
+ from torchvision.utils import make_grid
22
+ from pytorch_lightning.utilities.distributed import rank_zero_only
23
+
24
+ from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config
25
+ from ldm.modules.ema import LitEma
26
+ from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution
27
+ from ldm.models.autoencoder import VQModelInterface, IdentityFirstStage, AutoencoderKL
28
+ from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like
29
+ from ldm.models.diffusion.ddim import DDIMSampler
30
+
31
+
32
+ __conditioning_keys__ = {'concat': 'c_concat',
33
+ 'crossattn': 'c_crossattn',
34
+ 'adm': 'y'}
35
+
36
+
37
+ def disabled_train(self, mode=True):
38
+ """Overwrite model.train with this function to make sure train/eval mode
39
+ does not change anymore."""
40
+ return self
41
+
42
+
43
+ def uniform_on_device(r1, r2, shape, device):
44
+ return (r1 - r2) * torch.rand(*shape, device=device) + r2
45
+
46
+
47
+ class DDPM(pl.LightningModule):
48
+ # classic DDPM with Gaussian diffusion, in image space
49
+ def __init__(self,
50
+ unet_config,
51
+ timesteps=1000,
52
+ beta_schedule="linear",
53
+ loss_type="l2",
54
+ ckpt_path=None,
55
+ ignore_keys=[],
56
+ load_only_unet=False,
57
+ monitor="val/loss",
58
+ use_ema=True,
59
+ first_stage_key="image",
60
+ image_size=256,
61
+ channels=3,
62
+ log_every_t=100,
63
+ clip_denoised=True,
64
+ linear_start=1e-4,
65
+ linear_end=2e-2,
66
+ cosine_s=8e-3,
67
+ given_betas=None,
68
+ original_elbo_weight=0.,
69
+ v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
70
+ l_simple_weight=1.,
71
+ conditioning_key=None,
72
+ parameterization="eps", # all assuming fixed variance schedules
73
+ scheduler_config=None,
74
+ use_positional_encodings=False,
75
+ learn_logvar=False,
76
+ logvar_init=0.,
77
+ load_ema=True,
78
+ ):
79
+ super().__init__()
80
+ assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"'
81
+ self.parameterization = parameterization
82
+ print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
83
+ self.cond_stage_model = None
84
+ self.clip_denoised = clip_denoised
85
+ self.log_every_t = log_every_t
86
+ self.first_stage_key = first_stage_key
87
+ self.image_size = image_size # try conv?
88
+ self.channels = channels
89
+ self.use_positional_encodings = use_positional_encodings
90
+ self.model = DiffusionWrapper(unet_config, conditioning_key)
91
+ count_params(self.model, verbose=True)
92
+ self.use_ema = use_ema
93
+
94
+ self.use_scheduler = scheduler_config is not None
95
+ if self.use_scheduler:
96
+ self.scheduler_config = scheduler_config
97
+
98
+ self.v_posterior = v_posterior
99
+ self.original_elbo_weight = original_elbo_weight
100
+ self.l_simple_weight = l_simple_weight
101
+
102
+ if monitor is not None:
103
+ self.monitor = monitor
104
+
105
+ if self.use_ema and load_ema:
106
+ self.model_ema = LitEma(self.model)
107
+ print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
108
+
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
+ # If initialing from EMA-only checkpoint, create EMA model after loading.
113
+ if self.use_ema and not load_ema:
114
+ self.model_ema = LitEma(self.model)
115
+ print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
116
+
117
+ self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
118
+ linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
119
+
120
+ self.loss_type = loss_type
121
+
122
+ self.learn_logvar = learn_logvar
123
+ self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
124
+ if self.learn_logvar:
125
+ self.logvar = nn.Parameter(self.logvar, requires_grad=True)
126
+
127
+
128
+ def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
129
+ linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
130
+ if exists(given_betas):
131
+ betas = given_betas
132
+ else:
133
+ betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
134
+ cosine_s=cosine_s)
135
+ alphas = 1. - betas
136
+ alphas_cumprod = np.cumprod(alphas, axis=0)
137
+ alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
138
+
139
+ timesteps, = betas.shape
140
+ self.num_timesteps = int(timesteps)
141
+ self.linear_start = linear_start
142
+ self.linear_end = linear_end
143
+ assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
144
+
145
+ to_torch = partial(torch.tensor, dtype=torch.float32)
146
+
147
+ self.register_buffer('betas', to_torch(betas))
148
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
149
+ self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
150
+
151
+ # calculations for diffusion q(x_t | x_{t-1}) and others
152
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
153
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
154
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
155
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
156
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
157
+
158
+ # calculations for posterior q(x_{t-1} | x_t, x_0)
159
+ posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / (
160
+ 1. - alphas_cumprod) + self.v_posterior * betas
161
+ # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
162
+ self.register_buffer('posterior_variance', to_torch(posterior_variance))
163
+ # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
164
+ self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
165
+ self.register_buffer('posterior_mean_coef1', to_torch(
166
+ betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
167
+ self.register_buffer('posterior_mean_coef2', to_torch(
168
+ (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
169
+
170
+ if self.parameterization == "eps":
171
+ lvlb_weights = self.betas ** 2 / (
172
+ 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))
173
+ elif self.parameterization == "x0":
174
+ lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod))
175
+ else:
176
+ raise NotImplementedError("mu not supported")
177
+ # TODO how to choose this term
178
+ lvlb_weights[0] = lvlb_weights[1]
179
+ self.register_buffer('lvlb_weights', lvlb_weights, persistent=False)
180
+ assert not torch.isnan(self.lvlb_weights).all()
181
+
182
+ @contextmanager
183
+ def ema_scope(self, context=None):
184
+ if self.use_ema:
185
+ self.model_ema.store(self.model.parameters())
186
+ self.model_ema.copy_to(self.model)
187
+ if context is not None:
188
+ print(f"{context}: Switched to EMA weights")
189
+ try:
190
+ yield None
191
+ finally:
192
+ if self.use_ema:
193
+ self.model_ema.restore(self.model.parameters())
194
+ if context is not None:
195
+ print(f"{context}: Restored training weights")
196
+
197
+ def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
198
+ sd = torch.load(path, map_location="cpu")
199
+ if "state_dict" in list(sd.keys()):
200
+ sd = sd["state_dict"]
201
+ keys = list(sd.keys())
202
+
203
+ # Our model adds additional channels to the first layer to condition on an input image.
204
+ # For the first layer, copy existing channel weights and initialize new channel weights to zero.
205
+ input_keys = [
206
+ "model.diffusion_model.input_blocks.0.0.weight",
207
+ "model_ema.diffusion_modelinput_blocks00weight",
208
+ ]
209
+
210
+ self_sd = self.state_dict()
211
+ for input_key in input_keys:
212
+ if input_key not in sd or input_key not in self_sd:
213
+ continue
214
+
215
+ input_weight = self_sd[input_key]
216
+
217
+ if input_weight.size() != sd[input_key].size():
218
+ print(f"Manual init: {input_key}")
219
+ input_weight.zero_()
220
+ input_weight[:, :4, :, :].copy_(sd[input_key])
221
+ ignore_keys.append(input_key)
222
+
223
+ for k in keys:
224
+ for ik in ignore_keys:
225
+ if k.startswith(ik):
226
+ print("Deleting key {} from state_dict.".format(k))
227
+ del sd[k]
228
+ missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
229
+ sd, strict=False)
230
+ print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
231
+ if len(missing) > 0:
232
+ print(f"Missing Keys: {missing}")
233
+ if len(unexpected) > 0:
234
+ print(f"Unexpected Keys: {unexpected}")
235
+
236
+ def q_mean_variance(self, x_start, t):
237
+ """
238
+ Get the distribution q(x_t | x_0).
239
+ :param x_start: the [N x C x ...] tensor of noiseless inputs.
240
+ :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
241
+ :return: A tuple (mean, variance, log_variance), all of x_start's shape.
242
+ """
243
+ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
244
+ variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
245
+ log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
246
+ return mean, variance, log_variance
247
+
248
+ def predict_start_from_noise(self, x_t, t, noise):
249
+ return (
250
+ extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
251
+ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
252
+ )
253
+
254
+ def q_posterior(self, x_start, x_t, t):
255
+ posterior_mean = (
256
+ extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start +
257
+ extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
258
+ )
259
+ posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape)
260
+ posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
261
+ return posterior_mean, posterior_variance, posterior_log_variance_clipped
262
+
263
+ def p_mean_variance(self, x, t, clip_denoised: bool):
264
+ model_out = self.model(x, t)
265
+ if self.parameterization == "eps":
266
+ x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
267
+ elif self.parameterization == "x0":
268
+ x_recon = model_out
269
+ if clip_denoised:
270
+ x_recon.clamp_(-1., 1.)
271
+
272
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
273
+ return model_mean, posterior_variance, posterior_log_variance
274
+
275
+ @torch.no_grad()
276
+ def p_sample(self, x, t, clip_denoised=True, repeat_noise=False):
277
+ b, *_, device = *x.shape, x.device
278
+ model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
279
+ noise = noise_like(x.shape, device, repeat_noise)
280
+ # no noise when t == 0
281
+ nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
282
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
283
+
284
+ @torch.no_grad()
285
+ def p_sample_loop(self, shape, return_intermediates=False):
286
+ device = self.betas.device
287
+ b = shape[0]
288
+ img = torch.randn(shape, device=device)
289
+ intermediates = [img]
290
+ for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps):
291
+ img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long),
292
+ clip_denoised=self.clip_denoised)
293
+ if i % self.log_every_t == 0 or i == self.num_timesteps - 1:
294
+ intermediates.append(img)
295
+ if return_intermediates:
296
+ return img, intermediates
297
+ return img
298
+
299
+ @torch.no_grad()
300
+ def sample(self, batch_size=16, return_intermediates=False):
301
+ image_size = self.image_size
302
+ channels = self.channels
303
+ return self.p_sample_loop((batch_size, channels, image_size, image_size),
304
+ return_intermediates=return_intermediates)
305
+
306
+ def q_sample(self, x_start, t, noise=None):
307
+ noise = default(noise, lambda: torch.randn_like(x_start))
308
+ return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
309
+ extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
310
+
311
+ def get_loss(self, pred, target, mean=True):
312
+ if self.loss_type == 'l1':
313
+ loss = (target - pred).abs()
314
+ if mean:
315
+ loss = loss.mean()
316
+ elif self.loss_type == 'l2':
317
+ if mean:
318
+ loss = torch.nn.functional.mse_loss(target, pred)
319
+ else:
320
+ loss = torch.nn.functional.mse_loss(target, pred, reduction='none')
321
+ else:
322
+ raise NotImplementedError("unknown loss type '{loss_type}'")
323
+
324
+ return loss
325
+
326
+ def p_losses(self, x_start, t, noise=None):
327
+ noise = default(noise, lambda: torch.randn_like(x_start))
328
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
329
+ model_out = self.model(x_noisy, t)
330
+
331
+ loss_dict = {}
332
+ if self.parameterization == "eps":
333
+ target = noise
334
+ elif self.parameterization == "x0":
335
+ target = x_start
336
+ else:
337
+ raise NotImplementedError(f"Paramterization {self.parameterization} not yet supported")
338
+
339
+ loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3])
340
+
341
+ log_prefix = 'train' if self.training else 'val'
342
+
343
+ loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()})
344
+ loss_simple = loss.mean() * self.l_simple_weight
345
+
346
+ loss_vlb = (self.lvlb_weights[t] * loss).mean()
347
+ loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb})
348
+
349
+ loss = loss_simple + self.original_elbo_weight * loss_vlb
350
+
351
+ loss_dict.update({f'{log_prefix}/loss': loss})
352
+
353
+ return loss, loss_dict
354
+
355
+ def forward(self, x, *args, **kwargs):
356
+ # b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size
357
+ # assert h == img_size and w == img_size, f'height and width of image must be {img_size}'
358
+ t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
359
+ return self.p_losses(x, t, *args, **kwargs)
360
+
361
+ def get_input(self, batch, k):
362
+ return batch[k]
363
+
364
+ def shared_step(self, batch):
365
+ x = self.get_input(batch, self.first_stage_key)
366
+ loss, loss_dict = self(x)
367
+ return loss, loss_dict
368
+
369
+ def training_step(self, batch, batch_idx):
370
+ loss, loss_dict = self.shared_step(batch)
371
+
372
+ self.log_dict(loss_dict, prog_bar=True,
373
+ logger=True, on_step=True, on_epoch=True)
374
+
375
+ self.log("global_step", self.global_step,
376
+ prog_bar=True, logger=True, on_step=True, on_epoch=False)
377
+
378
+ if self.use_scheduler:
379
+ lr = self.optimizers().param_groups[0]['lr']
380
+ self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False)
381
+
382
+ return loss
383
+
384
+ @torch.no_grad()
385
+ def validation_step(self, batch, batch_idx):
386
+ _, loss_dict_no_ema = self.shared_step(batch)
387
+ with self.ema_scope():
388
+ _, loss_dict_ema = self.shared_step(batch)
389
+ loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema}
390
+ self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
391
+ self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
392
+
393
+ def on_train_batch_end(self, *args, **kwargs):
394
+ if self.use_ema:
395
+ self.model_ema(self.model)
396
+
397
+ def _get_rows_from_list(self, samples):
398
+ n_imgs_per_row = len(samples)
399
+ denoise_grid = rearrange(samples, 'n b c h w -> b n c h w')
400
+ denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
401
+ denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
402
+ return denoise_grid
403
+
404
+ @torch.no_grad()
405
+ def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
406
+ log = dict()
407
+ x = self.get_input(batch, self.first_stage_key)
408
+ N = min(x.shape[0], N)
409
+ n_row = min(x.shape[0], n_row)
410
+ x = x.to(self.device)[:N]
411
+ log["inputs"] = x
412
+
413
+ # get diffusion row
414
+ diffusion_row = list()
415
+ x_start = x[:n_row]
416
+
417
+ for t in range(self.num_timesteps):
418
+ if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
419
+ t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
420
+ t = t.to(self.device).long()
421
+ noise = torch.randn_like(x_start)
422
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
423
+ diffusion_row.append(x_noisy)
424
+
425
+ log["diffusion_row"] = self._get_rows_from_list(diffusion_row)
426
+
427
+ if sample:
428
+ # get denoise row
429
+ with self.ema_scope("Plotting"):
430
+ samples, denoise_row = self.sample(batch_size=N, return_intermediates=True)
431
+
432
+ log["samples"] = samples
433
+ log["denoise_row"] = self._get_rows_from_list(denoise_row)
434
+
435
+ if return_keys:
436
+ if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
437
+ return log
438
+ else:
439
+ return {key: log[key] for key in return_keys}
440
+ return log
441
+
442
+ def configure_optimizers(self):
443
+ lr = self.learning_rate
444
+ params = list(self.model.parameters())
445
+ if self.learn_logvar:
446
+ params = params + [self.logvar]
447
+ opt = torch.optim.AdamW(params, lr=lr)
448
+ return opt
449
+
450
+
451
+ class LatentDiffusion(DDPM):
452
+ """main class"""
453
+ def __init__(self,
454
+ first_stage_config,
455
+ cond_stage_config,
456
+ num_timesteps_cond=None,
457
+ cond_stage_key="image",
458
+ cond_stage_trainable=False,
459
+ concat_mode=True,
460
+ cond_stage_forward=None,
461
+ conditioning_key=None,
462
+ scale_factor=1.0,
463
+ scale_by_std=False,
464
+ load_ema=True,
465
+ *args, **kwargs):
466
+ self.num_timesteps_cond = default(num_timesteps_cond, 1)
467
+ self.scale_by_std = scale_by_std
468
+ assert self.num_timesteps_cond <= kwargs['timesteps']
469
+ # for backwards compatibility after implementation of DiffusionWrapper
470
+ if conditioning_key is None:
471
+ conditioning_key = 'concat' if concat_mode else 'crossattn'
472
+ if cond_stage_config == '__is_unconditional__':
473
+ conditioning_key = None
474
+ ckpt_path = kwargs.pop("ckpt_path", None)
475
+ ignore_keys = kwargs.pop("ignore_keys", [])
476
+ super().__init__(conditioning_key=conditioning_key, *args, load_ema=load_ema, **kwargs)
477
+ self.concat_mode = concat_mode
478
+ self.cond_stage_trainable = cond_stage_trainable
479
+ self.cond_stage_key = cond_stage_key
480
+ try:
481
+ self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
482
+ except:
483
+ self.num_downs = 0
484
+ if not scale_by_std:
485
+ self.scale_factor = scale_factor
486
+ else:
487
+ self.register_buffer('scale_factor', torch.tensor(scale_factor))
488
+ self.instantiate_first_stage(first_stage_config)
489
+ self.instantiate_cond_stage(cond_stage_config)
490
+ self.cond_stage_forward = cond_stage_forward
491
+ self.clip_denoised = False
492
+ self.bbox_tokenizer = None
493
+
494
+ self.restarted_from_ckpt = False
495
+ if ckpt_path is not None:
496
+ self.init_from_ckpt(ckpt_path, ignore_keys)
497
+ self.restarted_from_ckpt = True
498
+
499
+ if self.use_ema and not load_ema:
500
+ self.model_ema = LitEma(self.model)
501
+ print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
502
+
503
+ def make_cond_schedule(self, ):
504
+ self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)
505
+ ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()
506
+ self.cond_ids[:self.num_timesteps_cond] = ids
507
+
508
+ @rank_zero_only
509
+ @torch.no_grad()
510
+ def on_train_batch_start(self, batch, batch_idx, dataloader_idx):
511
+ # only for very first batch
512
+ 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:
513
+ assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously'
514
+ # set rescale weight to 1./std of encodings
515
+ print("### USING STD-RESCALING ###")
516
+ x = super().get_input(batch, self.first_stage_key)
517
+ x = x.to(self.device)
518
+ encoder_posterior = self.encode_first_stage(x)
519
+ z = self.get_first_stage_encoding(encoder_posterior).detach()
520
+ del self.scale_factor
521
+ self.register_buffer('scale_factor', 1. / z.flatten().std())
522
+ print(f"setting self.scale_factor to {self.scale_factor}")
523
+ print("### USING STD-RESCALING ###")
524
+
525
+ def register_schedule(self,
526
+ given_betas=None, beta_schedule="linear", timesteps=1000,
527
+ linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
528
+ super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)
529
+
530
+ self.shorten_cond_schedule = self.num_timesteps_cond > 1
531
+ if self.shorten_cond_schedule:
532
+ self.make_cond_schedule()
533
+
534
+ def instantiate_first_stage(self, config):
535
+ model = instantiate_from_config(config)
536
+ self.first_stage_model = model.eval()
537
+ self.first_stage_model.train = disabled_train
538
+ for param in self.first_stage_model.parameters():
539
+ param.requires_grad = False
540
+
541
+ def instantiate_cond_stage(self, config):
542
+ if not self.cond_stage_trainable:
543
+ if config == "__is_first_stage__":
544
+ print("Using first stage also as cond stage.")
545
+ self.cond_stage_model = self.first_stage_model
546
+ elif config == "__is_unconditional__":
547
+ print(f"Training {self.__class__.__name__} as an unconditional model.")
548
+ self.cond_stage_model = None
549
+ # self.be_unconditional = True
550
+ else:
551
+ model = instantiate_from_config(config)
552
+ self.cond_stage_model = model.eval()
553
+ self.cond_stage_model.train = disabled_train
554
+ for param in self.cond_stage_model.parameters():
555
+ param.requires_grad = False
556
+ else:
557
+ assert config != '__is_first_stage__'
558
+ assert config != '__is_unconditional__'
559
+ model = instantiate_from_config(config)
560
+ self.cond_stage_model = model
561
+
562
+ def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False):
563
+ denoise_row = []
564
+ for zd in tqdm(samples, desc=desc):
565
+ denoise_row.append(self.decode_first_stage(zd.to(self.device),
566
+ force_not_quantize=force_no_decoder_quantization))
567
+ n_imgs_per_row = len(denoise_row)
568
+ denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W
569
+ denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')
570
+ denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
571
+ denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
572
+ return denoise_grid
573
+
574
+ def get_first_stage_encoding(self, encoder_posterior):
575
+ if isinstance(encoder_posterior, DiagonalGaussianDistribution):
576
+ z = encoder_posterior.sample()
577
+ elif isinstance(encoder_posterior, torch.Tensor):
578
+ z = encoder_posterior
579
+ else:
580
+ raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented")
581
+ return self.scale_factor * z
582
+
583
+ def get_learned_conditioning(self, c):
584
+ if self.cond_stage_forward is None:
585
+ if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):
586
+ c = self.cond_stage_model.encode(c)
587
+ if isinstance(c, DiagonalGaussianDistribution):
588
+ c = c.mode()
589
+ else:
590
+ c = self.cond_stage_model(c)
591
+ else:
592
+ assert hasattr(self.cond_stage_model, self.cond_stage_forward)
593
+ c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)
594
+ return c
595
+
596
+ def meshgrid(self, h, w):
597
+ y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)
598
+ x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)
599
+
600
+ arr = torch.cat([y, x], dim=-1)
601
+ return arr
602
+
603
+ def delta_border(self, h, w):
604
+ """
605
+ :param h: height
606
+ :param w: width
607
+ :return: normalized distance to image border,
608
+ wtith min distance = 0 at border and max dist = 0.5 at image center
609
+ """
610
+ lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
611
+ arr = self.meshgrid(h, w) / lower_right_corner
612
+ dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]
613
+ dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]
614
+ edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0]
615
+ return edge_dist
616
+
617
+ def get_weighting(self, h, w, Ly, Lx, device):
618
+ weighting = self.delta_border(h, w)
619
+ weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"],
620
+ self.split_input_params["clip_max_weight"], )
621
+ weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)
622
+
623
+ if self.split_input_params["tie_braker"]:
624
+ L_weighting = self.delta_border(Ly, Lx)
625
+ L_weighting = torch.clip(L_weighting,
626
+ self.split_input_params["clip_min_tie_weight"],
627
+ self.split_input_params["clip_max_tie_weight"])
628
+
629
+ L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)
630
+ weighting = weighting * L_weighting
631
+ return weighting
632
+
633
+ def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code
634
+ """
635
+ :param x: img of size (bs, c, h, w)
636
+ :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])
637
+ """
638
+ bs, nc, h, w = x.shape
639
+
640
+ # number of crops in image
641
+ Ly = (h - kernel_size[0]) // stride[0] + 1
642
+ Lx = (w - kernel_size[1]) // stride[1] + 1
643
+
644
+ if uf == 1 and df == 1:
645
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
646
+ unfold = torch.nn.Unfold(**fold_params)
647
+
648
+ fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)
649
+
650
+ weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype)
651
+ normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap
652
+ weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))
653
+
654
+ elif uf > 1 and df == 1:
655
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
656
+ unfold = torch.nn.Unfold(**fold_params)
657
+
658
+ fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),
659
+ dilation=1, padding=0,
660
+ stride=(stride[0] * uf, stride[1] * uf))
661
+ fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2)
662
+
663
+ weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype)
664
+ normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap
665
+ weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx))
666
+
667
+ elif df > 1 and uf == 1:
668
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
669
+ unfold = torch.nn.Unfold(**fold_params)
670
+
671
+ fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df),
672
+ dilation=1, padding=0,
673
+ stride=(stride[0] // df, stride[1] // df))
674
+ fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2)
675
+
676
+ weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype)
677
+ normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap
678
+ weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx))
679
+
680
+ else:
681
+ raise NotImplementedError
682
+
683
+ return fold, unfold, normalization, weighting
684
+
685
+ @torch.no_grad()
686
+ def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False,
687
+ cond_key=None, return_original_cond=False, bs=None, uncond=0.05):
688
+ x = super().get_input(batch, k)
689
+ if bs is not None:
690
+ x = x[:bs]
691
+ x = x.to(self.device)
692
+ encoder_posterior = self.encode_first_stage(x)
693
+ z = self.get_first_stage_encoding(encoder_posterior).detach()
694
+ cond_key = cond_key or self.cond_stage_key
695
+ xc = super().get_input(batch, cond_key)
696
+ if bs is not None:
697
+ xc["c_crossattn"] = xc["c_crossattn"][:bs]
698
+ xc["c_concat"] = xc["c_concat"][:bs]
699
+ cond = {}
700
+
701
+ # To support classifier-free guidance, randomly drop out only text conditioning 5%, only image conditioning 5%, and both 5%.
702
+ random = torch.rand(x.size(0), device=x.device)
703
+ prompt_mask = rearrange(random < 2 * uncond, "n -> n 1 1")
704
+ input_mask = 1 - rearrange((random >= uncond).float() * (random < 3 * uncond).float(), "n -> n 1 1 1")
705
+
706
+ null_prompt = self.get_learned_conditioning([""])
707
+ cond["c_crossattn"] = [torch.where(prompt_mask, null_prompt, self.get_learned_conditioning(xc["c_crossattn"]).detach())]
708
+ cond["c_concat"] = [input_mask * self.encode_first_stage((xc["c_concat"].to(self.device))).mode().detach()]
709
+
710
+ out = [z, cond]
711
+ if return_first_stage_outputs:
712
+ xrec = self.decode_first_stage(z)
713
+ out.extend([x, xrec])
714
+ if return_original_cond:
715
+ out.append(xc)
716
+ return out
717
+
718
+ @torch.no_grad()
719
+ def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
720
+ if predict_cids:
721
+ if z.dim() == 4:
722
+ z = torch.argmax(z.exp(), dim=1).long()
723
+ z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
724
+ z = rearrange(z, 'b h w c -> b c h w').contiguous()
725
+
726
+ z = 1. / self.scale_factor * z
727
+
728
+ if hasattr(self, "split_input_params"):
729
+ if self.split_input_params["patch_distributed_vq"]:
730
+ ks = self.split_input_params["ks"] # eg. (128, 128)
731
+ stride = self.split_input_params["stride"] # eg. (64, 64)
732
+ uf = self.split_input_params["vqf"]
733
+ bs, nc, h, w = z.shape
734
+ if ks[0] > h or ks[1] > w:
735
+ ks = (min(ks[0], h), min(ks[1], w))
736
+ print("reducing Kernel")
737
+
738
+ if stride[0] > h or stride[1] > w:
739
+ stride = (min(stride[0], h), min(stride[1], w))
740
+ print("reducing stride")
741
+
742
+ fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf)
743
+
744
+ z = unfold(z) # (bn, nc * prod(**ks), L)
745
+ # 1. Reshape to img shape
746
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
747
+
748
+ # 2. apply model loop over last dim
749
+ if isinstance(self.first_stage_model, VQModelInterface):
750
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
751
+ force_not_quantize=predict_cids or force_not_quantize)
752
+ for i in range(z.shape[-1])]
753
+ else:
754
+
755
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i])
756
+ for i in range(z.shape[-1])]
757
+
758
+ o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)
759
+ o = o * weighting
760
+ # Reverse 1. reshape to img shape
761
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
762
+ # stitch crops together
763
+ decoded = fold(o)
764
+ decoded = decoded / normalization # norm is shape (1, 1, h, w)
765
+ return decoded
766
+ else:
767
+ if isinstance(self.first_stage_model, VQModelInterface):
768
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
769
+ else:
770
+ return self.first_stage_model.decode(z)
771
+
772
+ else:
773
+ if isinstance(self.first_stage_model, VQModelInterface):
774
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
775
+ else:
776
+ return self.first_stage_model.decode(z)
777
+
778
+ # same as above but without decorator
779
+ def differentiable_decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
780
+ if predict_cids:
781
+ if z.dim() == 4:
782
+ z = torch.argmax(z.exp(), dim=1).long()
783
+ z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
784
+ z = rearrange(z, 'b h w c -> b c h w').contiguous()
785
+
786
+ z = 1. / self.scale_factor * z
787
+
788
+ if hasattr(self, "split_input_params"):
789
+ if self.split_input_params["patch_distributed_vq"]:
790
+ ks = self.split_input_params["ks"] # eg. (128, 128)
791
+ stride = self.split_input_params["stride"] # eg. (64, 64)
792
+ uf = self.split_input_params["vqf"]
793
+ bs, nc, h, w = z.shape
794
+ if ks[0] > h or ks[1] > w:
795
+ ks = (min(ks[0], h), min(ks[1], w))
796
+ print("reducing Kernel")
797
+
798
+ if stride[0] > h or stride[1] > w:
799
+ stride = (min(stride[0], h), min(stride[1], w))
800
+ print("reducing stride")
801
+
802
+ fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf)
803
+
804
+ z = unfold(z) # (bn, nc * prod(**ks), L)
805
+ # 1. Reshape to img shape
806
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
807
+
808
+ # 2. apply model loop over last dim
809
+ if isinstance(self.first_stage_model, VQModelInterface):
810
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
811
+ force_not_quantize=predict_cids or force_not_quantize)
812
+ for i in range(z.shape[-1])]
813
+ else:
814
+
815
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i])
816
+ for i in range(z.shape[-1])]
817
+
818
+ o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)
819
+ o = o * weighting
820
+ # Reverse 1. reshape to img shape
821
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
822
+ # stitch crops together
823
+ decoded = fold(o)
824
+ decoded = decoded / normalization # norm is shape (1, 1, h, w)
825
+ return decoded
826
+ else:
827
+ if isinstance(self.first_stage_model, VQModelInterface):
828
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
829
+ else:
830
+ return self.first_stage_model.decode(z)
831
+
832
+ else:
833
+ if isinstance(self.first_stage_model, VQModelInterface):
834
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
835
+ else:
836
+ return self.first_stage_model.decode(z)
837
+
838
+ @torch.no_grad()
839
+ def encode_first_stage(self, x):
840
+ if hasattr(self, "split_input_params"):
841
+ if self.split_input_params["patch_distributed_vq"]:
842
+ ks = self.split_input_params["ks"] # eg. (128, 128)
843
+ stride = self.split_input_params["stride"] # eg. (64, 64)
844
+ df = self.split_input_params["vqf"]
845
+ self.split_input_params['original_image_size'] = x.shape[-2:]
846
+ bs, nc, h, w = x.shape
847
+ if ks[0] > h or ks[1] > w:
848
+ ks = (min(ks[0], h), min(ks[1], w))
849
+ print("reducing Kernel")
850
+
851
+ if stride[0] > h or stride[1] > w:
852
+ stride = (min(stride[0], h), min(stride[1], w))
853
+ print("reducing stride")
854
+
855
+ fold, unfold, normalization, weighting = self.get_fold_unfold(x, ks, stride, df=df)
856
+ z = unfold(x) # (bn, nc * prod(**ks), L)
857
+ # Reshape to img shape
858
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
859
+
860
+ output_list = [self.first_stage_model.encode(z[:, :, :, :, i])
861
+ for i in range(z.shape[-1])]
862
+
863
+ o = torch.stack(output_list, axis=-1)
864
+ o = o * weighting
865
+
866
+ # Reverse reshape to img shape
867
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
868
+ # stitch crops together
869
+ decoded = fold(o)
870
+ decoded = decoded / normalization
871
+ return decoded
872
+
873
+ else:
874
+ return self.first_stage_model.encode(x)
875
+ else:
876
+ return self.first_stage_model.encode(x)
877
+
878
+ def shared_step(self, batch, **kwargs):
879
+ x, c = self.get_input(batch, self.first_stage_key)
880
+ loss = self(x, c)
881
+ return loss
882
+
883
+ def forward(self, x, c, *args, **kwargs):
884
+ t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
885
+ if self.model.conditioning_key is not None:
886
+ assert c is not None
887
+ if self.cond_stage_trainable:
888
+ c = self.get_learned_conditioning(c)
889
+ if self.shorten_cond_schedule: # TODO: drop this option
890
+ tc = self.cond_ids[t].to(self.device)
891
+ c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))
892
+ return self.p_losses(x, c, t, *args, **kwargs)
893
+
894
+ def _rescale_annotations(self, bboxes, crop_coordinates): # TODO: move to dataset
895
+ def rescale_bbox(bbox):
896
+ x0 = clamp((bbox[0] - crop_coordinates[0]) / crop_coordinates[2])
897
+ y0 = clamp((bbox[1] - crop_coordinates[1]) / crop_coordinates[3])
898
+ w = min(bbox[2] / crop_coordinates[2], 1 - x0)
899
+ h = min(bbox[3] / crop_coordinates[3], 1 - y0)
900
+ return x0, y0, w, h
901
+
902
+ return [rescale_bbox(b) for b in bboxes]
903
+
904
+ def apply_model(self, x_noisy, t, cond, return_ids=False):
905
+
906
+ if isinstance(cond, dict):
907
+ # hybrid case, cond is exptected to be a dict
908
+ pass
909
+ else:
910
+ if not isinstance(cond, list):
911
+ cond = [cond]
912
+ key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'
913
+ cond = {key: cond}
914
+
915
+ if hasattr(self, "split_input_params"):
916
+ assert len(cond) == 1 # todo can only deal with one conditioning atm
917
+ assert not return_ids
918
+ ks = self.split_input_params["ks"] # eg. (128, 128)
919
+ stride = self.split_input_params["stride"] # eg. (64, 64)
920
+
921
+ h, w = x_noisy.shape[-2:]
922
+
923
+ fold, unfold, normalization, weighting = self.get_fold_unfold(x_noisy, ks, stride)
924
+
925
+ z = unfold(x_noisy) # (bn, nc * prod(**ks), L)
926
+ # Reshape to img shape
927
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
928
+ z_list = [z[:, :, :, :, i] for i in range(z.shape[-1])]
929
+
930
+ if self.cond_stage_key in ["image", "LR_image", "segmentation",
931
+ 'bbox_img'] and self.model.conditioning_key: # todo check for completeness
932
+ c_key = next(iter(cond.keys())) # get key
933
+ c = next(iter(cond.values())) # get value
934
+ assert (len(c) == 1) # todo extend to list with more than one elem
935
+ c = c[0] # get element
936
+
937
+ c = unfold(c)
938
+ c = c.view((c.shape[0], -1, ks[0], ks[1], c.shape[-1])) # (bn, nc, ks[0], ks[1], L )
939
+
940
+ cond_list = [{c_key: [c[:, :, :, :, i]]} for i in range(c.shape[-1])]
941
+
942
+ elif self.cond_stage_key == 'coordinates_bbox':
943
+ assert 'original_image_size' in self.split_input_params, 'BoudingBoxRescaling is missing original_image_size'
944
+
945
+ # assuming padding of unfold is always 0 and its dilation is always 1
946
+ n_patches_per_row = int((w - ks[0]) / stride[0] + 1)
947
+ full_img_h, full_img_w = self.split_input_params['original_image_size']
948
+ # as we are operating on latents, we need the factor from the original image size to the
949
+ # spatial latent size to properly rescale the crops for regenerating the bbox annotations
950
+ num_downs = self.first_stage_model.encoder.num_resolutions - 1
951
+ rescale_latent = 2 ** (num_downs)
952
+
953
+ # get top left postions of patches as conforming for the bbbox tokenizer, therefore we
954
+ # need to rescale the tl patch coordinates to be in between (0,1)
955
+ tl_patch_coordinates = [(rescale_latent * stride[0] * (patch_nr % n_patches_per_row) / full_img_w,
956
+ rescale_latent * stride[1] * (patch_nr // n_patches_per_row) / full_img_h)
957
+ for patch_nr in range(z.shape[-1])]
958
+
959
+ # patch_limits are tl_coord, width and height coordinates as (x_tl, y_tl, h, w)
960
+ patch_limits = [(x_tl, y_tl,
961
+ rescale_latent * ks[0] / full_img_w,
962
+ rescale_latent * ks[1] / full_img_h) for x_tl, y_tl in tl_patch_coordinates]
963
+ # 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]
964
+
965
+ # tokenize crop coordinates for the bounding boxes of the respective patches
966
+ patch_limits_tknzd = [torch.LongTensor(self.bbox_tokenizer._crop_encoder(bbox))[None].to(self.device)
967
+ for bbox in patch_limits] # list of length l with tensors of shape (1, 2)
968
+ print(patch_limits_tknzd[0].shape)
969
+ # cut tknzd crop position from conditioning
970
+ assert isinstance(cond, dict), 'cond must be dict to be fed into model'
971
+ cut_cond = cond['c_crossattn'][0][..., :-2].to(self.device)
972
+ print(cut_cond.shape)
973
+
974
+ adapted_cond = torch.stack([torch.cat([cut_cond, p], dim=1) for p in patch_limits_tknzd])
975
+ adapted_cond = rearrange(adapted_cond, 'l b n -> (l b) n')
976
+ print(adapted_cond.shape)
977
+ adapted_cond = self.get_learned_conditioning(adapted_cond)
978
+ print(adapted_cond.shape)
979
+ adapted_cond = rearrange(adapted_cond, '(l b) n d -> l b n d', l=z.shape[-1])
980
+ print(adapted_cond.shape)
981
+
982
+ cond_list = [{'c_crossattn': [e]} for e in adapted_cond]
983
+
984
+ else:
985
+ cond_list = [cond for i in range(z.shape[-1])] # Todo make this more efficient
986
+
987
+ # apply model by loop over crops
988
+ output_list = [self.model(z_list[i], t, **cond_list[i]) for i in range(z.shape[-1])]
989
+ assert not isinstance(output_list[0],
990
+ tuple) # todo cant deal with multiple model outputs check this never happens
991
+
992
+ o = torch.stack(output_list, axis=-1)
993
+ o = o * weighting
994
+ # Reverse reshape to img shape
995
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
996
+ # stitch crops together
997
+ x_recon = fold(o) / normalization
998
+
999
+ else:
1000
+ x_recon = self.model(x_noisy, t, **cond)
1001
+
1002
+ if isinstance(x_recon, tuple) and not return_ids:
1003
+ return x_recon[0]
1004
+ else:
1005
+ return x_recon
1006
+
1007
+ def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
1008
+ return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \
1009
+ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
1010
+
1011
+ def _prior_bpd(self, x_start):
1012
+ """
1013
+ Get the prior KL term for the variational lower-bound, measured in
1014
+ bits-per-dim.
1015
+ This term can't be optimized, as it only depends on the encoder.
1016
+ :param x_start: the [N x C x ...] tensor of inputs.
1017
+ :return: a batch of [N] KL values (in bits), one per batch element.
1018
+ """
1019
+ batch_size = x_start.shape[0]
1020
+ t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
1021
+ qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
1022
+ kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
1023
+ return mean_flat(kl_prior) / np.log(2.0)
1024
+
1025
+ def p_losses(self, x_start, cond, t, noise=None):
1026
+ noise = default(noise, lambda: torch.randn_like(x_start))
1027
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
1028
+ model_output = self.apply_model(x_noisy, t, cond)
1029
+
1030
+ loss_dict = {}
1031
+ prefix = 'train' if self.training else 'val'
1032
+
1033
+ if self.parameterization == "x0":
1034
+ target = x_start
1035
+ elif self.parameterization == "eps":
1036
+ target = noise
1037
+ else:
1038
+ raise NotImplementedError()
1039
+
1040
+ loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3])
1041
+ loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})
1042
+ self.logvar = self.logvar.to(self.device)
1043
+ logvar_t = self.logvar[t].to(self.device)
1044
+ loss = loss_simple / torch.exp(logvar_t) + logvar_t
1045
+ # loss = loss_simple / torch.exp(self.logvar) + self.logvar
1046
+ if self.learn_logvar:
1047
+ loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})
1048
+ loss_dict.update({'logvar': self.logvar.data.mean()})
1049
+
1050
+ loss = self.l_simple_weight * loss.mean()
1051
+
1052
+ loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3))
1053
+ loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()
1054
+ loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})
1055
+ loss += (self.original_elbo_weight * loss_vlb)
1056
+ loss_dict.update({f'{prefix}/loss': loss})
1057
+
1058
+ return loss, loss_dict
1059
+
1060
+ def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False,
1061
+ return_x0=False, score_corrector=None, corrector_kwargs=None):
1062
+ t_in = t
1063
+ model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)
1064
+
1065
+ if score_corrector is not None:
1066
+ assert self.parameterization == "eps"
1067
+ model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)
1068
+
1069
+ if return_codebook_ids:
1070
+ model_out, logits = model_out
1071
+
1072
+ if self.parameterization == "eps":
1073
+ x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
1074
+ elif self.parameterization == "x0":
1075
+ x_recon = model_out
1076
+ else:
1077
+ raise NotImplementedError()
1078
+
1079
+ if clip_denoised:
1080
+ x_recon.clamp_(-1., 1.)
1081
+ if quantize_denoised:
1082
+ x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)
1083
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
1084
+ if return_codebook_ids:
1085
+ return model_mean, posterior_variance, posterior_log_variance, logits
1086
+ elif return_x0:
1087
+ return model_mean, posterior_variance, posterior_log_variance, x_recon
1088
+ else:
1089
+ return model_mean, posterior_variance, posterior_log_variance
1090
+
1091
+ @torch.no_grad()
1092
+ def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False,
1093
+ return_codebook_ids=False, quantize_denoised=False, return_x0=False,
1094
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):
1095
+ b, *_, device = *x.shape, x.device
1096
+ outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised,
1097
+ return_codebook_ids=return_codebook_ids,
1098
+ quantize_denoised=quantize_denoised,
1099
+ return_x0=return_x0,
1100
+ score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
1101
+ if return_codebook_ids:
1102
+ raise DeprecationWarning("Support dropped.")
1103
+ model_mean, _, model_log_variance, logits = outputs
1104
+ elif return_x0:
1105
+ model_mean, _, model_log_variance, x0 = outputs
1106
+ else:
1107
+ model_mean, _, model_log_variance = outputs
1108
+
1109
+ noise = noise_like(x.shape, device, repeat_noise) * temperature
1110
+ if noise_dropout > 0.:
1111
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
1112
+ # no noise when t == 0
1113
+ nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
1114
+
1115
+ if return_codebook_ids:
1116
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1)
1117
+ if return_x0:
1118
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0
1119
+ else:
1120
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
1121
+
1122
+ @torch.no_grad()
1123
+ def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False,
1124
+ img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0.,
1125
+ score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None,
1126
+ log_every_t=None):
1127
+ if not log_every_t:
1128
+ log_every_t = self.log_every_t
1129
+ timesteps = self.num_timesteps
1130
+ if batch_size is not None:
1131
+ b = batch_size if batch_size is not None else shape[0]
1132
+ shape = [batch_size] + list(shape)
1133
+ else:
1134
+ b = batch_size = shape[0]
1135
+ if x_T is None:
1136
+ img = torch.randn(shape, device=self.device)
1137
+ else:
1138
+ img = x_T
1139
+ intermediates = []
1140
+ if cond is not None:
1141
+ if isinstance(cond, dict):
1142
+ cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
1143
+ list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
1144
+ else:
1145
+ cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
1146
+
1147
+ if start_T is not None:
1148
+ timesteps = min(timesteps, start_T)
1149
+ iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation',
1150
+ total=timesteps) if verbose else reversed(
1151
+ range(0, timesteps))
1152
+ if type(temperature) == float:
1153
+ temperature = [temperature] * timesteps
1154
+
1155
+ for i in iterator:
1156
+ ts = torch.full((b,), i, device=self.device, dtype=torch.long)
1157
+ if self.shorten_cond_schedule:
1158
+ assert self.model.conditioning_key != 'hybrid'
1159
+ tc = self.cond_ids[ts].to(cond.device)
1160
+ cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
1161
+
1162
+ img, x0_partial = self.p_sample(img, cond, ts,
1163
+ clip_denoised=self.clip_denoised,
1164
+ quantize_denoised=quantize_denoised, return_x0=True,
1165
+ temperature=temperature[i], noise_dropout=noise_dropout,
1166
+ score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
1167
+ if mask is not None:
1168
+ assert x0 is not None
1169
+ img_orig = self.q_sample(x0, ts)
1170
+ img = img_orig * mask + (1. - mask) * img
1171
+
1172
+ if i % log_every_t == 0 or i == timesteps - 1:
1173
+ intermediates.append(x0_partial)
1174
+ if callback: callback(i)
1175
+ if img_callback: img_callback(img, i)
1176
+ return img, intermediates
1177
+
1178
+ @torch.no_grad()
1179
+ def p_sample_loop(self, cond, shape, return_intermediates=False,
1180
+ x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False,
1181
+ mask=None, x0=None, img_callback=None, start_T=None,
1182
+ log_every_t=None):
1183
+
1184
+ if not log_every_t:
1185
+ log_every_t = self.log_every_t
1186
+ device = self.betas.device
1187
+ b = shape[0]
1188
+ if x_T is None:
1189
+ img = torch.randn(shape, device=device)
1190
+ else:
1191
+ img = x_T
1192
+
1193
+ intermediates = [img]
1194
+ if timesteps is None:
1195
+ timesteps = self.num_timesteps
1196
+
1197
+ if start_T is not None:
1198
+ timesteps = min(timesteps, start_T)
1199
+ iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(
1200
+ range(0, timesteps))
1201
+
1202
+ if mask is not None:
1203
+ assert x0 is not None
1204
+ assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match
1205
+
1206
+ for i in iterator:
1207
+ ts = torch.full((b,), i, device=device, dtype=torch.long)
1208
+ if self.shorten_cond_schedule:
1209
+ assert self.model.conditioning_key != 'hybrid'
1210
+ tc = self.cond_ids[ts].to(cond.device)
1211
+ cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
1212
+
1213
+ img = self.p_sample(img, cond, ts,
1214
+ clip_denoised=self.clip_denoised,
1215
+ quantize_denoised=quantize_denoised)
1216
+ if mask is not None:
1217
+ img_orig = self.q_sample(x0, ts)
1218
+ img = img_orig * mask + (1. - mask) * img
1219
+
1220
+ if i % log_every_t == 0 or i == timesteps - 1:
1221
+ intermediates.append(img)
1222
+ if callback: callback(i)
1223
+ if img_callback: img_callback(img, i)
1224
+
1225
+ if return_intermediates:
1226
+ return img, intermediates
1227
+ return img
1228
+
1229
+ @torch.no_grad()
1230
+ def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None,
1231
+ verbose=True, timesteps=None, quantize_denoised=False,
1232
+ mask=None, x0=None, shape=None,**kwargs):
1233
+ if shape is None:
1234
+ shape = (batch_size, self.channels, self.image_size, self.image_size)
1235
+ if cond is not None:
1236
+ if isinstance(cond, dict):
1237
+ cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
1238
+ list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
1239
+ else:
1240
+ cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
1241
+ return self.p_sample_loop(cond,
1242
+ shape,
1243
+ return_intermediates=return_intermediates, x_T=x_T,
1244
+ verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised,
1245
+ mask=mask, x0=x0)
1246
+
1247
+ @torch.no_grad()
1248
+ def sample_log(self,cond,batch_size,ddim, ddim_steps,**kwargs):
1249
+
1250
+ if ddim:
1251
+ ddim_sampler = DDIMSampler(self)
1252
+ shape = (self.channels, self.image_size, self.image_size)
1253
+ samples, intermediates =ddim_sampler.sample(ddim_steps,batch_size,
1254
+ shape,cond,verbose=False,**kwargs)
1255
+
1256
+ else:
1257
+ samples, intermediates = self.sample(cond=cond, batch_size=batch_size,
1258
+ return_intermediates=True,**kwargs)
1259
+
1260
+ return samples, intermediates
1261
+
1262
+
1263
+ @torch.no_grad()
1264
+ def log_images(self, batch, N=4, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
1265
+ quantize_denoised=True, inpaint=False, plot_denoise_rows=False, plot_progressive_rows=False,
1266
+ plot_diffusion_rows=False, **kwargs):
1267
+
1268
+ use_ddim = False
1269
+
1270
+ log = dict()
1271
+ z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,
1272
+ return_first_stage_outputs=True,
1273
+ force_c_encode=True,
1274
+ return_original_cond=True,
1275
+ bs=N, uncond=0)
1276
+ N = min(x.shape[0], N)
1277
+ n_row = min(x.shape[0], n_row)
1278
+ log["inputs"] = x
1279
+ log["reals"] = xc["c_concat"]
1280
+ log["reconstruction"] = xrec
1281
+ if self.model.conditioning_key is not None:
1282
+ if hasattr(self.cond_stage_model, "decode"):
1283
+ xc = self.cond_stage_model.decode(c)
1284
+ log["conditioning"] = xc
1285
+ elif self.cond_stage_key in ["caption"]:
1286
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["caption"])
1287
+ log["conditioning"] = xc
1288
+ elif self.cond_stage_key == 'class_label':
1289
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"])
1290
+ log['conditioning'] = xc
1291
+ elif isimage(xc):
1292
+ log["conditioning"] = xc
1293
+ if ismap(xc):
1294
+ log["original_conditioning"] = self.to_rgb(xc)
1295
+
1296
+ if plot_diffusion_rows:
1297
+ # get diffusion row
1298
+ diffusion_row = list()
1299
+ z_start = z[:n_row]
1300
+ for t in range(self.num_timesteps):
1301
+ if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
1302
+ t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
1303
+ t = t.to(self.device).long()
1304
+ noise = torch.randn_like(z_start)
1305
+ z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
1306
+ diffusion_row.append(self.decode_first_stage(z_noisy))
1307
+
1308
+ diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
1309
+ diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
1310
+ diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
1311
+ diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
1312
+ log["diffusion_row"] = diffusion_grid
1313
+
1314
+ if sample:
1315
+ # get denoise row
1316
+ with self.ema_scope("Plotting"):
1317
+ samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim,
1318
+ ddim_steps=ddim_steps,eta=ddim_eta)
1319
+ # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
1320
+ x_samples = self.decode_first_stage(samples)
1321
+ log["samples"] = x_samples
1322
+ if plot_denoise_rows:
1323
+ denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
1324
+ log["denoise_row"] = denoise_grid
1325
+
1326
+ if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(
1327
+ self.first_stage_model, IdentityFirstStage):
1328
+ # also display when quantizing x0 while sampling
1329
+ with self.ema_scope("Plotting Quantized Denoised"):
1330
+ samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim,
1331
+ ddim_steps=ddim_steps,eta=ddim_eta,
1332
+ quantize_denoised=True)
1333
+ # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,
1334
+ # quantize_denoised=True)
1335
+ x_samples = self.decode_first_stage(samples.to(self.device))
1336
+ log["samples_x0_quantized"] = x_samples
1337
+
1338
+ if inpaint:
1339
+ # make a simple center square
1340
+ b, h, w = z.shape[0], z.shape[2], z.shape[3]
1341
+ mask = torch.ones(N, h, w).to(self.device)
1342
+ # zeros will be filled in
1343
+ mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.
1344
+ mask = mask[:, None, ...]
1345
+ with self.ema_scope("Plotting Inpaint"):
1346
+
1347
+ samples, _ = self.sample_log(cond=c,batch_size=N,ddim=use_ddim, eta=ddim_eta,
1348
+ ddim_steps=ddim_steps, x0=z[:N], mask=mask)
1349
+ x_samples = self.decode_first_stage(samples.to(self.device))
1350
+ log["samples_inpainting"] = x_samples
1351
+ log["mask"] = mask
1352
+
1353
+ # outpaint
1354
+ with self.ema_scope("Plotting Outpaint"):
1355
+ samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,eta=ddim_eta,
1356
+ ddim_steps=ddim_steps, x0=z[:N], mask=mask)
1357
+ x_samples = self.decode_first_stage(samples.to(self.device))
1358
+ log["samples_outpainting"] = x_samples
1359
+
1360
+ if plot_progressive_rows:
1361
+ with self.ema_scope("Plotting Progressives"):
1362
+ img, progressives = self.progressive_denoising(c,
1363
+ shape=(self.channels, self.image_size, self.image_size),
1364
+ batch_size=N)
1365
+ prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
1366
+ log["progressive_row"] = prog_row
1367
+
1368
+ if return_keys:
1369
+ if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
1370
+ return log
1371
+ else:
1372
+ return {key: log[key] for key in return_keys}
1373
+ return log
1374
+
1375
+ def configure_optimizers(self):
1376
+ lr = self.learning_rate
1377
+ params = list(self.model.parameters())
1378
+ if self.cond_stage_trainable:
1379
+ print(f"{self.__class__.__name__}: Also optimizing conditioner params!")
1380
+ params = params + list(self.cond_stage_model.parameters())
1381
+ if self.learn_logvar:
1382
+ print('Diffusion model optimizing logvar')
1383
+ params.append(self.logvar)
1384
+ opt = torch.optim.AdamW(params, lr=lr)
1385
+ if self.use_scheduler:
1386
+ assert 'target' in self.scheduler_config
1387
+ scheduler = instantiate_from_config(self.scheduler_config)
1388
+
1389
+ print("Setting up LambdaLR scheduler...")
1390
+ scheduler = [
1391
+ {
1392
+ 'scheduler': LambdaLR(opt, lr_lambda=scheduler.schedule),
1393
+ 'interval': 'step',
1394
+ 'frequency': 1
1395
+ }]
1396
+ return [opt], scheduler
1397
+ return opt
1398
+
1399
+ @torch.no_grad()
1400
+ def to_rgb(self, x):
1401
+ x = x.float()
1402
+ if not hasattr(self, "colorize"):
1403
+ self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)
1404
+ x = nn.functional.conv2d(x, weight=self.colorize)
1405
+ x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.
1406
+ return x
1407
+
1408
+
1409
+ class DiffusionWrapper(pl.LightningModule):
1410
+ def __init__(self, diff_model_config, conditioning_key):
1411
+ super().__init__()
1412
+ self.diffusion_model = instantiate_from_config(diff_model_config)
1413
+ self.conditioning_key = conditioning_key
1414
+ assert self.conditioning_key in [None, 'concat', 'crossattn', 'hybrid', 'adm']
1415
+
1416
+ def forward(self, x, t, c_concat: list = None, c_crossattn: list = None):
1417
+ if self.conditioning_key is None:
1418
+ out = self.diffusion_model(x, t)
1419
+ elif self.conditioning_key == 'concat':
1420
+ xc = torch.cat([x] + c_concat, dim=1)
1421
+ out = self.diffusion_model(xc, t)
1422
+ elif self.conditioning_key == 'crossattn':
1423
+ cc = torch.cat(c_crossattn, 1)
1424
+ out = self.diffusion_model(x, t, context=cc)
1425
+ elif self.conditioning_key == 'hybrid':
1426
+ xc = torch.cat([x] + c_concat, dim=1)
1427
+ cc = torch.cat(c_crossattn, 1)
1428
+ out = self.diffusion_model(xc, t, context=cc)
1429
+ elif self.conditioning_key == 'adm':
1430
+ cc = c_crossattn[0]
1431
+ out = self.diffusion_model(x, t, y=cc)
1432
+ else:
1433
+ raise NotImplementedError()
1434
+
1435
+ return out
1436
+
1437
+
1438
+ class Layout2ImgDiffusion(LatentDiffusion):
1439
+ # TODO: move all layout-specific hacks to this class
1440
+ def __init__(self, cond_stage_key, *args, **kwargs):
1441
+ assert cond_stage_key == 'coordinates_bbox', 'Layout2ImgDiffusion only for cond_stage_key="coordinates_bbox"'
1442
+ super().__init__(cond_stage_key=cond_stage_key, *args, **kwargs)
1443
+
1444
+ def log_images(self, batch, N=8, *args, **kwargs):
1445
+ logs = super().log_images(batch=batch, N=N, *args, **kwargs)
1446
+
1447
+ key = 'train' if self.training else 'validation'
1448
+ dset = self.trainer.datamodule.datasets[key]
1449
+ mapper = dset.conditional_builders[self.cond_stage_key]
1450
+
1451
+ bbox_imgs = []
1452
+ map_fn = lambda catno: dset.get_textual_label(dset.get_category_id(catno))
1453
+ for tknzd_bbox in batch[self.cond_stage_key][:N]:
1454
+ bboximg = mapper.plot(tknzd_bbox.detach().cpu(), map_fn, (256, 256))
1455
+ bbox_imgs.append(bboximg)
1456
+
1457
+ cond_img = torch.stack(bbox_imgs, dim=0)
1458
+ logs['bbox_image'] = cond_img
1459
+ return logs
stable_diffusion/ldm/models/diffusion/ddpm_edit_disc.py ADDED
@@ -0,0 +1,1669 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # File modified by authors of InstructPix2Pix from original (https://github.com/CompVis/stable-diffusion).
10
+ # See more details in LICENSE.
11
+
12
+ import os
13
+ import numpy as np
14
+ import torchvision
15
+ import pytorch_lightning as pl
16
+ import json
17
+ from PIL import Image
18
+ import pickle
19
+ import torch.distributed as dist
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+ import numpy as np
24
+ import pytorch_lightning as pl
25
+ from torch.optim.lr_scheduler import LambdaLR
26
+ from einops import rearrange, repeat
27
+ from contextlib import contextmanager
28
+ from functools import partial
29
+ from tqdm import tqdm
30
+ from torchvision.utils import make_grid
31
+ from pytorch_lightning.utilities.distributed import rank_zero_only
32
+
33
+ from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config
34
+ from ldm.modules.ema import LitEma
35
+ from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution
36
+ from ldm.models.autoencoder import VQModelInterface, IdentityFirstStage, AutoencoderKL
37
+ from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like
38
+ from ldm.models.diffusion.ddim import DDIMSampler
39
+
40
+
41
+ __conditioning_keys__ = {'concat': 'c_concat',
42
+ 'crossattn': 'c_crossattn',
43
+ 'adm': 'y'}
44
+
45
+ def get_world_size():
46
+ if not dist.is_available():
47
+ return 1
48
+ if not dist.is_initialized():
49
+ return 1
50
+ return dist.get_world_size()
51
+
52
+ def all_gather(data):
53
+ """
54
+ Run all_gather on arbitrary picklable data (not necessarily tensors)
55
+ Args:
56
+ data: any picklable object
57
+ Returns:
58
+ list[data]: list of data gathered from each rank
59
+ """
60
+ world_size = get_world_size()
61
+ if world_size == 1:
62
+ return [data]
63
+
64
+ # serialized to a Tensor
65
+ origin_size = None
66
+ if not isinstance(data, torch.Tensor):
67
+ buffer = pickle.dumps(data)
68
+ storage = torch.ByteStorage.from_buffer(buffer)
69
+ tensor = torch.ByteTensor(storage).to("cuda")
70
+ else:
71
+ origin_size = data.size()
72
+ tensor = data.reshape(-1)
73
+
74
+ tensor_type = tensor.dtype
75
+
76
+ # obtain Tensor size of each rank
77
+ local_size = torch.LongTensor([tensor.numel()]).to("cuda")
78
+ size_list = [torch.LongTensor([0]).to("cuda") for _ in range(world_size)]
79
+ dist.all_gather(size_list, local_size)
80
+ size_list = [int(size.item()) for size in size_list]
81
+ max_size = max(size_list)
82
+
83
+ # receiving Tensor from all ranks
84
+ # we pad the tensor because torch all_gather does not support
85
+ # gathering tensors of different shapes
86
+ tensor_list = []
87
+ for _ in size_list:
88
+ tensor_list.append(torch.FloatTensor(size=(max_size,)).cuda().to(tensor_type))
89
+ if local_size != max_size:
90
+ padding = torch.FloatTensor(size=(max_size - local_size,)).cuda().to(tensor_type)
91
+ tensor = torch.cat((tensor, padding), dim=0)
92
+ dist.all_gather(tensor_list, tensor)
93
+
94
+ data_list = []
95
+ for size, tensor in zip(size_list, tensor_list):
96
+ if origin_size is None:
97
+ buffer = tensor.cpu().numpy().tobytes()[:size]
98
+ data_list.append(pickle.loads(buffer))
99
+ else:
100
+ buffer = tensor[:size]
101
+ data_list.append(buffer)
102
+
103
+ if origin_size is not None:
104
+ new_shape = [-1] + list(origin_size[1:])
105
+ resized_list = []
106
+ for data in data_list:
107
+ # suppose the difference of tensor size exist in first dimension
108
+ data = data.reshape(new_shape)
109
+ resized_list.append(data)
110
+
111
+ return resized_list
112
+ else:
113
+ return data_list
114
+
115
+ def disabled_train(self, mode=True):
116
+ """Overwrite model.train with this function to make sure train/eval mode
117
+ does not change anymore."""
118
+ return self
119
+
120
+
121
+ def uniform_on_device(r1, r2, shape, device):
122
+ return (r1 - r2) * torch.rand(*shape, device=device) + r2
123
+
124
+
125
+ class DDPM(pl.LightningModule):
126
+ # classic DDPM with Gaussian diffusion, in image space
127
+ def __init__(self,
128
+ unet_config,
129
+ timesteps=1000,
130
+ beta_schedule="linear",
131
+ loss_type="l2",
132
+ ckpt_path=None,
133
+ ignore_keys=[],
134
+ load_only_unet=False,
135
+ monitor="val/loss",
136
+ use_ema=True,
137
+ first_stage_key="image",
138
+ image_size=256,
139
+ channels=3,
140
+ log_every_t=100,
141
+ clip_denoised=True,
142
+ linear_start=1e-4,
143
+ linear_end=2e-2,
144
+ cosine_s=8e-3,
145
+ given_betas=None,
146
+ original_elbo_weight=0.,
147
+ v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
148
+ l_simple_weight=1.,
149
+ conditioning_key=None,
150
+ parameterization="eps", # all assuming fixed variance schedules
151
+ scheduler_config=None,
152
+ use_positional_encodings=False,
153
+ learn_logvar=False,
154
+ logvar_init=0.,
155
+ load_ema=True,
156
+ ):
157
+ super().__init__()
158
+ assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"'
159
+ self.parameterization = parameterization
160
+ print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
161
+ self.cond_stage_model = None
162
+ self.clip_denoised = clip_denoised
163
+ self.log_every_t = log_every_t
164
+ self.first_stage_key = first_stage_key
165
+ self.image_size = image_size # try conv?
166
+ self.channels = channels
167
+ self.use_positional_encodings = use_positional_encodings
168
+ self.model = DiffusionWrapper(unet_config, conditioning_key)
169
+ count_params(self.model, verbose=True)
170
+ self.use_ema = use_ema
171
+
172
+ self.use_scheduler = scheduler_config is not None
173
+ if self.use_scheduler:
174
+ self.scheduler_config = scheduler_config
175
+
176
+ self.v_posterior = v_posterior
177
+ self.original_elbo_weight = original_elbo_weight
178
+ self.l_simple_weight = l_simple_weight
179
+
180
+ if monitor is not None:
181
+ self.monitor = monitor
182
+
183
+ if self.use_ema and load_ema:
184
+ self.model_ema = LitEma(self.model)
185
+ print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
186
+
187
+ if ckpt_path is not None:
188
+ self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet)
189
+
190
+ # If initialing from EMA-only checkpoint, create EMA model after loading.
191
+ if self.use_ema and not load_ema:
192
+ self.model_ema = LitEma(self.model)
193
+ print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
194
+
195
+ self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
196
+ linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
197
+
198
+ self.loss_type = loss_type
199
+
200
+ self.learn_logvar = learn_logvar
201
+ self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
202
+ if self.learn_logvar:
203
+ self.logvar = nn.Parameter(self.logvar, requires_grad=True)
204
+
205
+
206
+ def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
207
+ linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
208
+ if exists(given_betas):
209
+ betas = given_betas
210
+ else:
211
+ betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
212
+ cosine_s=cosine_s)
213
+ alphas = 1. - betas
214
+ alphas_cumprod = np.cumprod(alphas, axis=0)
215
+ alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
216
+
217
+ timesteps, = betas.shape
218
+ self.num_timesteps = int(timesteps)
219
+ self.linear_start = linear_start
220
+ self.linear_end = linear_end
221
+ assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
222
+
223
+ to_torch = partial(torch.tensor, dtype=torch.float32)
224
+
225
+ self.register_buffer('betas', to_torch(betas))
226
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
227
+ self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
228
+
229
+ # calculations for diffusion q(x_t | x_{t-1}) and others
230
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
231
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
232
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
233
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
234
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
235
+
236
+ # calculations for posterior q(x_{t-1} | x_t, x_0)
237
+ posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / (
238
+ 1. - alphas_cumprod) + self.v_posterior * betas
239
+ # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
240
+ self.register_buffer('posterior_variance', to_torch(posterior_variance))
241
+ # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
242
+ self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
243
+ self.register_buffer('posterior_mean_coef1', to_torch(
244
+ betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
245
+ self.register_buffer('posterior_mean_coef2', to_torch(
246
+ (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
247
+
248
+ if self.parameterization == "eps":
249
+ lvlb_weights = self.betas ** 2 / (
250
+ 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))
251
+ elif self.parameterization == "x0":
252
+ lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod))
253
+ else:
254
+ raise NotImplementedError("mu not supported")
255
+ # TODO how to choose this term
256
+ lvlb_weights[0] = lvlb_weights[1]
257
+ self.register_buffer('lvlb_weights', lvlb_weights, persistent=False)
258
+ assert not torch.isnan(self.lvlb_weights).all()
259
+
260
+ @contextmanager
261
+ def ema_scope(self, context=None):
262
+ if self.use_ema:
263
+ self.model_ema.store(self.model.parameters())
264
+ self.model_ema.copy_to(self.model)
265
+ if context is not None:
266
+ print(f"{context}: Switched to EMA weights")
267
+ try:
268
+ yield None
269
+ finally:
270
+ if self.use_ema:
271
+ self.model_ema.restore(self.model.parameters())
272
+ if context is not None:
273
+ print(f"{context}: Restored training weights")
274
+
275
+ def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
276
+ sd = torch.load(path, map_location="cpu")
277
+ if "state_dict" in list(sd.keys()):
278
+ sd = sd["state_dict"]
279
+ keys = list(sd.keys())
280
+
281
+ # Our model adds additional channels to the first layer to condition on an input image.
282
+ # For the first layer, copy existing channel weights and initialize new channel weights to zero.
283
+ input_keys = [
284
+ "model.diffusion_model.input_blocks.0.0.weight",
285
+ "model_ema.diffusion_modelinput_blocks00weight",
286
+ ]
287
+
288
+ self_sd = self.state_dict()
289
+ for input_key in input_keys:
290
+ if input_key not in sd or input_key not in self_sd:
291
+ continue
292
+
293
+ input_weight = self_sd[input_key]
294
+
295
+ if input_weight.size() != sd[input_key].size():
296
+ print(f"Manual init: {input_key}")
297
+ input_weight.zero_()
298
+ input_weight[:, :4, :, :].copy_(sd[input_key])
299
+ ignore_keys.append(input_key)
300
+
301
+ for k in keys:
302
+ for ik in ignore_keys:
303
+ if k.startswith(ik):
304
+ print("Deleting key {} from state_dict.".format(k))
305
+ del sd[k]
306
+ missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
307
+ sd, strict=False)
308
+ print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
309
+ if len(missing) > 0:
310
+ print(f"Missing Keys: {missing}")
311
+ if len(unexpected) > 0:
312
+ print(f"Unexpected Keys: {unexpected}")
313
+
314
+ def q_mean_variance(self, x_start, t):
315
+ """
316
+ Get the distribution q(x_t | x_0).
317
+ :param x_start: the [N x C x ...] tensor of noiseless inputs.
318
+ :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
319
+ :return: A tuple (mean, variance, log_variance), all of x_start's shape.
320
+ """
321
+ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
322
+ variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
323
+ log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
324
+ return mean, variance, log_variance
325
+
326
+ def predict_start_from_noise(self, x_t, t, noise):
327
+ return (
328
+ extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
329
+ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
330
+ )
331
+
332
+ def q_posterior(self, x_start, x_t, t):
333
+ posterior_mean = (
334
+ extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start +
335
+ extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
336
+ )
337
+ posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape)
338
+ posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
339
+ return posterior_mean, posterior_variance, posterior_log_variance_clipped
340
+
341
+ def p_mean_variance(self, x, t, clip_denoised: bool):
342
+ model_out = self.model(x, t)
343
+ if self.parameterization == "eps":
344
+ x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
345
+ elif self.parameterization == "x0":
346
+ x_recon = model_out
347
+ if clip_denoised:
348
+ x_recon.clamp_(-1., 1.)
349
+
350
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
351
+ return model_mean, posterior_variance, posterior_log_variance
352
+
353
+ @torch.no_grad()
354
+ def p_sample(self, x, t, clip_denoised=True, repeat_noise=False):
355
+ b, *_, device = *x.shape, x.device
356
+ model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
357
+ noise = noise_like(x.shape, device, repeat_noise)
358
+ # no noise when t == 0
359
+ nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
360
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
361
+
362
+ @torch.no_grad()
363
+ def p_sample_loop(self, shape, return_intermediates=False):
364
+ device = self.betas.device
365
+ b = shape[0]
366
+ img = torch.randn(shape, device=device)
367
+ intermediates = [img]
368
+ for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps):
369
+ img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long),
370
+ clip_denoised=self.clip_denoised)
371
+ if i % self.log_every_t == 0 or i == self.num_timesteps - 1:
372
+ intermediates.append(img)
373
+ if return_intermediates:
374
+ return img, intermediates
375
+ return img
376
+
377
+ @torch.no_grad()
378
+ def sample(self, batch_size=16, return_intermediates=False):
379
+ image_size = self.image_size
380
+ channels = self.channels
381
+ return self.p_sample_loop((batch_size, channels, image_size, image_size),
382
+ return_intermediates=return_intermediates)
383
+
384
+ def q_sample(self, x_start, t, noise=None):
385
+ noise = default(noise, lambda: torch.randn_like(x_start))
386
+ return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
387
+ extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
388
+
389
+ def get_loss(self, pred, target, mean=True):
390
+ if self.loss_type == 'l1':
391
+ loss = (target - pred).abs()
392
+ if mean:
393
+ loss = loss.mean()
394
+ elif self.loss_type == 'l2':
395
+ if mean:
396
+ loss = torch.nn.functional.mse_loss(target, pred)
397
+ else:
398
+ loss = torch.nn.functional.mse_loss(target, pred, reduction='none')
399
+ else:
400
+ raise NotImplementedError("unknown loss type '{loss_type}'")
401
+
402
+ return loss
403
+
404
+ def p_losses(self, x_start, t, noise=None):
405
+ noise = default(noise, lambda: torch.randn_like(x_start))
406
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
407
+ model_out = self.model(x_noisy, t)
408
+
409
+ loss_dict = {}
410
+ if self.parameterization == "eps":
411
+ target = noise
412
+ elif self.parameterization == "x0":
413
+ target = x_start
414
+ else:
415
+ raise NotImplementedError(f"Paramterization {self.parameterization} not yet supported")
416
+
417
+ loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3])
418
+
419
+ log_prefix = 'train' if self.training else 'val'
420
+
421
+ loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()})
422
+ loss_simple = loss.mean() * self.l_simple_weight
423
+
424
+ loss_vlb = (self.lvlb_weights[t] * loss).mean()
425
+ loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb})
426
+
427
+ loss = loss_simple + self.original_elbo_weight * loss_vlb
428
+
429
+ loss_dict.update({f'{log_prefix}/loss': loss})
430
+
431
+ return loss, loss_dict
432
+
433
+ def forward(self, x, *args, **kwargs):
434
+ print('\n\n I made it here: forward of DDPM \n\n')
435
+ # b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size
436
+ # assert h == img_size and w == img_size, f'height and width of image must be {img_size}'
437
+ t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
438
+ return self.p_losses(x, t, *args, **kwargs)
439
+
440
+ def get_input(self, batch, k):
441
+ return batch[k]
442
+
443
+ def shared_step(self, batch, discriminate=False):
444
+ if discriminate:
445
+ new_batch = {'edited': None, 'edit': {'c_concat': None, 'c_crossattn': None}}
446
+ for i in batch['edited'].shape[0]:
447
+ new_batch['edited'] = batch['edited'][i].unsqueeze(0).repeat((10, 1, 1, 1))
448
+ new_batch['edit']['c_concat'] = batch['edit']['c_concat'][i].unsqueeze(0).repeat((10, 1, 1, 1))
449
+ new_batch['edit']['c_crossattn'] = batch['edit']['c_crossattn'][i]
450
+ x = self.get_input(new_batch, self.first_stage_key)
451
+ loss, loss_dict = self(x)
452
+ else:
453
+ x = self.get_input(batch, self.first_stage_key)
454
+ loss, loss_dict = self(x)
455
+ return loss, loss_dict
456
+
457
+ def training_step(self, batch, batch_idx):
458
+ loss, loss_dict = self.shared_step(batch)
459
+
460
+ self.log_dict(loss_dict, prog_bar=True,
461
+ logger=True, on_step=True, on_epoch=True)
462
+
463
+ self.log("global_step", self.global_step,
464
+ prog_bar=True, logger=True, on_step=True, on_epoch=False)
465
+
466
+ if self.use_scheduler:
467
+ lr = self.optimizers().param_groups[0]['lr']
468
+ self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False)
469
+
470
+ return loss
471
+
472
+ # def log_local(self, save_dir, split, images, prompts,
473
+ # global_step, current_epoch, batch_idx):
474
+ # root = os.path.join(save_dir, "images", split)
475
+ # names = {"reals": "before", "inputs": "after", "reconstruction": "before-vq", "samples": "after-gen"}
476
+ # # print(root)
477
+ # for k in images:
478
+ # grid = torchvision.utils.make_grid(images[k], nrow=8)
479
+ # if self.rescale:
480
+ # grid = (grid + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w
481
+ # grid = grid.transpose(0, 1).transpose(1, 2).squeeze(-1)
482
+ # grid = grid.numpy()
483
+ # grid = (grid * 255).astype(np.uint8)
484
+ # filename = "gs-{:06}_e-{:06}_b-{:06}_{}.png".format(
485
+ # global_step,
486
+ # current_epoch,
487
+ # batch_idx,
488
+ # names[k])
489
+ # path = os.path.join(root, filename)
490
+ # os.makedirs(os.path.split(path)[0], exist_ok=True)
491
+ # # print(path)
492
+ # Image.fromarray(grid).save(path)
493
+
494
+ # filename = "gs-{:06}_e-{:06}_b-{:06}_prompt.json".format(
495
+ # global_step,
496
+ # current_epoch,
497
+ # batch_idx)
498
+ # path = os.path.join(root, filename)
499
+ # with open(path, "w") as f:
500
+ # for p in prompts:
501
+ # f.write(f"{json.dumps(p)}\n")
502
+
503
+ # def log_img(self, batch, batch_idx, split="val"):
504
+ # check_idx = batch_idx if self.log_on_batch_idx else self.global_step
505
+ # if (self.check_frequency(check_idx) and # batch_idx % self.batch_freq == 0
506
+ # hasattr(self, "log_images") and
507
+ # callable(self.log_images) and
508
+ # self.max_images > 0) or (split == "val" and batch_idx == 0):
509
+ # logger = type(self.logger)
510
+
511
+ # is_train = self.training
512
+ # if is_train:
513
+ # self.eval()
514
+
515
+ # with torch.no_grad():
516
+ # images = self.log_images(batch, split=split, **self.log_images_kwargs)
517
+
518
+ # prompts = batch["edit"]["c_crossattn"][:self.max_images]
519
+ # prompts = [p for ps in all_gather(prompts) for p in ps]
520
+
521
+ # for k in images:
522
+ # N = min(images[k].shape[0], self.max_images)
523
+ # images[k] = images[k][:N]
524
+ # images[k] = torch.cat(all_gather(images[k][:N]))
525
+ # if isinstance(images[k], torch.Tensor):
526
+ # images[k] = images[k].detach().cpu()
527
+ # if self.clamp:
528
+ # images[k] = torch.clamp(images[k], -1., 1.)
529
+
530
+ # self.log_local(self.logger.save_dir, split, images, prompts,
531
+ # self.global_step, self.current_epoch, batch_idx)
532
+
533
+ # logger_log_images = self.logger_log_images.get(logger, lambda *args, **kwargs: None)
534
+ # logger_log_images(self, images, self.global_step, split)
535
+
536
+ # if is_train:
537
+ # self.train()
538
+
539
+
540
+ @torch.no_grad()
541
+ def validation_step(self, batch, batch_idx, discriminate=False):
542
+ self.discriminate = discriminate
543
+ def calculate_accuracy(losses):
544
+ correct_count = 0
545
+ for loss in losses:
546
+ if loss[0] < min(loss[1:]):
547
+ correct_count += 1
548
+ return correct_count, len(losses) # Return counts for aggregation
549
+
550
+ # self.log_img(batch, batch_idx, split="val")
551
+ losses = self.shared_step(batch, discriminate=discriminate)
552
+ if discriminate:
553
+ correct_count, total_count = calculate_accuracy(losses)
554
+ return {'correct_count': correct_count, 'total_count': total_count}
555
+ else:
556
+ _, loss_dict_no_ema = self.shared_step(batch)
557
+ with self.ema_scope():
558
+ _, loss_dict_ema = self.shared_step(batch)
559
+ loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema}
560
+ self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
561
+ self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
562
+
563
+ def validation_epoch_end(self, outputs):
564
+ if self.discriminate:
565
+ correct_count = sum(x['correct_count'] for x in outputs)
566
+ total_count = sum(x['total_count'] for x in outputs)
567
+ overall_accuracy = (correct_count / total_count) * 100
568
+ print(f"Overall accuracy: {overall_accuracy:.2f}%")
569
+ import pdb; pdb.set_trace()
570
+ self.log('overall_accuracy', overall_accuracy, prog_bar=True, logger=True)
571
+
572
+ def on_train_batch_end(self, *args, **kwargs):
573
+ if self.use_ema:
574
+ self.model_ema(self.model)
575
+
576
+ def _get_rows_from_list(self, samples):
577
+ n_imgs_per_row = len(samples)
578
+ denoise_grid = rearrange(samples, 'n b c h w -> b n c h w')
579
+ denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
580
+ denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
581
+ return denoise_grid
582
+
583
+ @torch.no_grad()
584
+ def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
585
+ log = dict()
586
+ x = self.get_input(batch, self.first_stage_key)
587
+ N = min(x.shape[0], N)
588
+ n_row = min(x.shape[0], n_row)
589
+ x = x.to(self.device)[:N]
590
+ log["inputs"] = x
591
+
592
+ # get diffusion row
593
+ diffusion_row = list()
594
+ x_start = x[:n_row]
595
+
596
+ for t in range(self.num_timesteps):
597
+ if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
598
+ t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
599
+ t = t.to(self.device).long()
600
+ noise = torch.randn_like(x_start)
601
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
602
+ diffusion_row.append(x_noisy)
603
+
604
+ log["diffusion_row"] = self._get_rows_from_list(diffusion_row)
605
+
606
+ if sample:
607
+ # get denoise row
608
+ with self.ema_scope("Plotting"):
609
+ samples, denoise_row = self.sample(batch_size=N, return_intermediates=True)
610
+
611
+ log["samples"] = samples
612
+ log["denoise_row"] = self._get_rows_from_list(denoise_row)
613
+
614
+ if return_keys:
615
+ if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
616
+ return log
617
+ else:
618
+ return {key: log[key] for key in return_keys}
619
+ return log
620
+
621
+ def configure_optimizers(self):
622
+ lr = self.learning_rate
623
+ params = list(self.model.parameters())
624
+ if self.learn_logvar:
625
+ params = params + [self.logvar]
626
+ opt = torch.optim.AdamW(params, lr=lr)
627
+ return opt
628
+
629
+
630
+ class LatentDiffusion(DDPM):
631
+ """main class"""
632
+ def __init__(self,
633
+ first_stage_config,
634
+ cond_stage_config,
635
+ num_timesteps_cond=None,
636
+ cond_stage_key="image",
637
+ cond_stage_trainable=False,
638
+ concat_mode=True,
639
+ cond_stage_forward=None,
640
+ conditioning_key=None,
641
+ scale_factor=1.0,
642
+ scale_by_std=False,
643
+ load_ema=True,
644
+ *args, **kwargs):
645
+ self.num_timesteps_cond = default(num_timesteps_cond, 1)
646
+ self.scale_by_std = scale_by_std
647
+ assert self.num_timesteps_cond <= kwargs['timesteps']
648
+ # for backwards compatibility after implementation of DiffusionWrapper
649
+ if conditioning_key is None:
650
+ conditioning_key = 'concat' if concat_mode else 'crossattn'
651
+ if cond_stage_config == '__is_unconditional__':
652
+ conditioning_key = None
653
+ ckpt_path = kwargs.pop("ckpt_path", None)
654
+ ignore_keys = kwargs.pop("ignore_keys", [])
655
+ super().__init__(conditioning_key=conditioning_key, *args, load_ema=load_ema, **kwargs)
656
+ self.concat_mode = concat_mode
657
+ self.cond_stage_trainable = cond_stage_trainable
658
+ self.cond_stage_key = cond_stage_key
659
+ try:
660
+ self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
661
+ except:
662
+ self.num_downs = 0
663
+ if not scale_by_std:
664
+ self.scale_factor = scale_factor
665
+ else:
666
+ self.register_buffer('scale_factor', torch.tensor(scale_factor))
667
+ self.instantiate_first_stage(first_stage_config)
668
+ self.instantiate_cond_stage(cond_stage_config)
669
+ self.cond_stage_forward = cond_stage_forward
670
+ self.clip_denoised = False
671
+ self.bbox_tokenizer = None
672
+
673
+ self.restarted_from_ckpt = False
674
+ if ckpt_path is not None:
675
+ self.init_from_ckpt(ckpt_path, ignore_keys)
676
+ self.restarted_from_ckpt = True
677
+
678
+ if self.use_ema and not load_ema:
679
+ self.model_ema = LitEma(self.model)
680
+ print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
681
+
682
+ def make_cond_schedule(self, ):
683
+ self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)
684
+ ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()
685
+ self.cond_ids[:self.num_timesteps_cond] = ids
686
+
687
+ @rank_zero_only
688
+ @torch.no_grad()
689
+ def on_train_batch_start(self, batch, batch_idx, dataloader_idx):
690
+ # only for very first batch
691
+ 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:
692
+ assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously'
693
+ # set rescale weight to 1./std of encodings
694
+ print("### USING STD-RESCALING ###")
695
+ x = super().get_input(batch, self.first_stage_key)
696
+ x = x.to(self.device)
697
+ encoder_posterior = self.encode_first_stage(x)
698
+ z = self.get_first_stage_encoding(encoder_posterior).detach()
699
+ del self.scale_factor
700
+ self.register_buffer('scale_factor', 1. / z.flatten().std())
701
+ print(f"setting self.scale_factor to {self.scale_factor}")
702
+ print("### USING STD-RESCALING ###")
703
+
704
+ def register_schedule(self,
705
+ given_betas=None, beta_schedule="linear", timesteps=1000,
706
+ linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
707
+ super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)
708
+
709
+ self.shorten_cond_schedule = self.num_timesteps_cond > 1
710
+ if self.shorten_cond_schedule:
711
+ self.make_cond_schedule()
712
+
713
+ def instantiate_first_stage(self, config):
714
+ model = instantiate_from_config(config)
715
+ self.first_stage_model = model.eval()
716
+ self.first_stage_model.train = disabled_train
717
+ for param in self.first_stage_model.parameters():
718
+ param.requires_grad = False
719
+
720
+ def instantiate_cond_stage(self, config):
721
+ if not self.cond_stage_trainable:
722
+ if config == "__is_first_stage__":
723
+ print("Using first stage also as cond stage.")
724
+ self.cond_stage_model = self.first_stage_model
725
+ elif config == "__is_unconditional__":
726
+ print(f"Training {self.__class__.__name__} as an unconditional model.")
727
+ self.cond_stage_model = None
728
+ # self.be_unconditional = True
729
+ else:
730
+ model = instantiate_from_config(config)
731
+ self.cond_stage_model = model.eval()
732
+ self.cond_stage_model.train = disabled_train
733
+ for param in self.cond_stage_model.parameters():
734
+ param.requires_grad = False
735
+ else:
736
+ assert config != '__is_first_stage__'
737
+ assert config != '__is_unconditional__'
738
+ model = instantiate_from_config(config)
739
+ self.cond_stage_model = model
740
+
741
+ def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False):
742
+ denoise_row = []
743
+ for zd in tqdm(samples, desc=desc):
744
+ denoise_row.append(self.decode_first_stage(zd.to(self.device),
745
+ force_not_quantize=force_no_decoder_quantization))
746
+ n_imgs_per_row = len(denoise_row)
747
+ denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W
748
+ denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')
749
+ denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
750
+ denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
751
+ return denoise_grid
752
+
753
+ def get_first_stage_encoding(self, encoder_posterior):
754
+ if isinstance(encoder_posterior, DiagonalGaussianDistribution):
755
+ z = encoder_posterior.sample()
756
+ elif isinstance(encoder_posterior, torch.Tensor):
757
+ z = encoder_posterior
758
+ else:
759
+ raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented")
760
+ return self.scale_factor * z
761
+
762
+ def get_learned_conditioning(self, c):
763
+ if self.cond_stage_forward is None:
764
+ if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):
765
+ c = self.cond_stage_model.encode(c)
766
+ if isinstance(c, DiagonalGaussianDistribution):
767
+ c = c.mode()
768
+ else:
769
+ c = self.cond_stage_model(c)
770
+ else:
771
+ assert hasattr(self.cond_stage_model, self.cond_stage_forward)
772
+ c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)
773
+ return c
774
+
775
+ def meshgrid(self, h, w):
776
+ y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)
777
+ x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)
778
+
779
+ arr = torch.cat([y, x], dim=-1)
780
+ return arr
781
+
782
+ def delta_border(self, h, w):
783
+ """
784
+ :param h: height
785
+ :param w: width
786
+ :return: normalized distance to image border,
787
+ wtith min distance = 0 at border and max dist = 0.5 at image center
788
+ """
789
+ lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
790
+ arr = self.meshgrid(h, w) / lower_right_corner
791
+ dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]
792
+ dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]
793
+ edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0]
794
+ return edge_dist
795
+
796
+ def get_weighting(self, h, w, Ly, Lx, device):
797
+ weighting = self.delta_border(h, w)
798
+ weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"],
799
+ self.split_input_params["clip_max_weight"], )
800
+ weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)
801
+
802
+ if self.split_input_params["tie_braker"]:
803
+ L_weighting = self.delta_border(Ly, Lx)
804
+ L_weighting = torch.clip(L_weighting,
805
+ self.split_input_params["clip_min_tie_weight"],
806
+ self.split_input_params["clip_max_tie_weight"])
807
+
808
+ L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)
809
+ weighting = weighting * L_weighting
810
+ return weighting
811
+
812
+ def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code
813
+ """
814
+ :param x: img of size (bs, c, h, w)
815
+ :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])
816
+ """
817
+ bs, nc, h, w = x.shape
818
+
819
+ # number of crops in image
820
+ Ly = (h - kernel_size[0]) // stride[0] + 1
821
+ Lx = (w - kernel_size[1]) // stride[1] + 1
822
+
823
+ if uf == 1 and df == 1:
824
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
825
+ unfold = torch.nn.Unfold(**fold_params)
826
+
827
+ fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)
828
+
829
+ weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype)
830
+ normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap
831
+ weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))
832
+
833
+ elif uf > 1 and df == 1:
834
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
835
+ unfold = torch.nn.Unfold(**fold_params)
836
+
837
+ fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),
838
+ dilation=1, padding=0,
839
+ stride=(stride[0] * uf, stride[1] * uf))
840
+ fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2)
841
+
842
+ weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype)
843
+ normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap
844
+ weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx))
845
+
846
+ elif df > 1 and uf == 1:
847
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
848
+ unfold = torch.nn.Unfold(**fold_params)
849
+
850
+ fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df),
851
+ dilation=1, padding=0,
852
+ stride=(stride[0] // df, stride[1] // df))
853
+ fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2)
854
+
855
+ weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype)
856
+ normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap
857
+ weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx))
858
+
859
+ else:
860
+ raise NotImplementedError
861
+
862
+ return fold, unfold, normalization, weighting
863
+
864
+ @torch.no_grad()
865
+ def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False,
866
+ cond_key=None, return_original_cond=False, bs=None, uncond=0.05):
867
+ x = super().get_input(batch, k)
868
+ if bs is not None:
869
+ x = x[:bs]
870
+ x = x.to(self.device)
871
+ encoder_posterior = self.encode_first_stage(x)
872
+ z = self.get_first_stage_encoding(encoder_posterior).detach()
873
+ cond_key = cond_key or self.cond_stage_key
874
+ xc = super().get_input(batch, cond_key)
875
+ if bs is not None:
876
+ xc["c_crossattn"] = xc["c_crossattn"][:bs]
877
+ xc["c_concat"] = xc["c_concat"][:bs]
878
+ cond = {}
879
+
880
+ # To support classifier-free guidance, randomly drop out only text conditioning 5%, only image conditioning 5%, and both 5%.
881
+ random = torch.rand(x.size(0), device=x.device)
882
+ prompt_mask = rearrange(random < 2 * uncond, "n -> n 1 1")
883
+ input_mask = 1 - rearrange((random >= uncond).float() * (random < 3 * uncond).float(), "n -> n 1 1 1")
884
+
885
+ null_prompt = self.get_learned_conditioning([""])
886
+ cond["c_crossattn"] = [torch.where(prompt_mask, null_prompt, self.get_learned_conditioning(xc["c_crossattn"]).detach())]
887
+ cond["c_concat"] = [input_mask * self.encode_first_stage((xc["c_concat"].to(self.device))).mode().detach()]
888
+
889
+ out = [z, cond]
890
+ if return_first_stage_outputs:
891
+ xrec = self.decode_first_stage(z)
892
+ out.extend([x, xrec])
893
+ if return_original_cond:
894
+ out.append(xc)
895
+ return out
896
+
897
+ @torch.no_grad()
898
+ def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
899
+ if predict_cids:
900
+ if z.dim() == 4:
901
+ z = torch.argmax(z.exp(), dim=1).long()
902
+ z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
903
+ z = rearrange(z, 'b h w c -> b c h w').contiguous()
904
+
905
+ z = 1. / self.scale_factor * z
906
+
907
+ if hasattr(self, "split_input_params"):
908
+ if self.split_input_params["patch_distributed_vq"]:
909
+ ks = self.split_input_params["ks"] # eg. (128, 128)
910
+ stride = self.split_input_params["stride"] # eg. (64, 64)
911
+ uf = self.split_input_params["vqf"]
912
+ bs, nc, h, w = z.shape
913
+ if ks[0] > h or ks[1] > w:
914
+ ks = (min(ks[0], h), min(ks[1], w))
915
+ print("reducing Kernel")
916
+
917
+ if stride[0] > h or stride[1] > w:
918
+ stride = (min(stride[0], h), min(stride[1], w))
919
+ print("reducing stride")
920
+
921
+ fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf)
922
+
923
+ z = unfold(z) # (bn, nc * prod(**ks), L)
924
+ # 1. Reshape to img shape
925
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
926
+
927
+ # 2. apply model loop over last dim
928
+ if isinstance(self.first_stage_model, VQModelInterface):
929
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
930
+ force_not_quantize=predict_cids or force_not_quantize)
931
+ for i in range(z.shape[-1])]
932
+ else:
933
+
934
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i])
935
+ for i in range(z.shape[-1])]
936
+
937
+ o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)
938
+ o = o * weighting
939
+ # Reverse 1. reshape to img shape
940
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
941
+ # stitch crops together
942
+ decoded = fold(o)
943
+ decoded = decoded / normalization # norm is shape (1, 1, h, w)
944
+ return decoded
945
+ else:
946
+ if isinstance(self.first_stage_model, VQModelInterface):
947
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
948
+ else:
949
+ return self.first_stage_model.decode(z)
950
+
951
+ else:
952
+ if isinstance(self.first_stage_model, VQModelInterface):
953
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
954
+ else:
955
+ return self.first_stage_model.decode(z)
956
+
957
+ # same as above but without decorator
958
+ def differentiable_decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
959
+ if predict_cids:
960
+ if z.dim() == 4:
961
+ z = torch.argmax(z.exp(), dim=1).long()
962
+ z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
963
+ z = rearrange(z, 'b h w c -> b c h w').contiguous()
964
+
965
+ z = 1. / self.scale_factor * z
966
+
967
+ if hasattr(self, "split_input_params"):
968
+ if self.split_input_params["patch_distributed_vq"]:
969
+ ks = self.split_input_params["ks"] # eg. (128, 128)
970
+ stride = self.split_input_params["stride"] # eg. (64, 64)
971
+ uf = self.split_input_params["vqf"]
972
+ bs, nc, h, w = z.shape
973
+ if ks[0] > h or ks[1] > w:
974
+ ks = (min(ks[0], h), min(ks[1], w))
975
+ print("reducing Kernel")
976
+
977
+ if stride[0] > h or stride[1] > w:
978
+ stride = (min(stride[0], h), min(stride[1], w))
979
+ print("reducing stride")
980
+
981
+ fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf)
982
+
983
+ z = unfold(z) # (bn, nc * prod(**ks), L)
984
+ # 1. Reshape to img shape
985
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
986
+
987
+ # 2. apply model loop over last dim
988
+ if isinstance(self.first_stage_model, VQModelInterface):
989
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
990
+ force_not_quantize=predict_cids or force_not_quantize)
991
+ for i in range(z.shape[-1])]
992
+ else:
993
+
994
+ output_list = [self.first_stage_model.decode(z[:, :, :, :, i])
995
+ for i in range(z.shape[-1])]
996
+
997
+ o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)
998
+ o = o * weighting
999
+ # Reverse 1. reshape to img shape
1000
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
1001
+ # stitch crops together
1002
+ decoded = fold(o)
1003
+ decoded = decoded / normalization # norm is shape (1, 1, h, w)
1004
+ return decoded
1005
+ else:
1006
+ if isinstance(self.first_stage_model, VQModelInterface):
1007
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
1008
+ else:
1009
+ return self.first_stage_model.decode(z)
1010
+
1011
+ else:
1012
+ if isinstance(self.first_stage_model, VQModelInterface):
1013
+ return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
1014
+ else:
1015
+ return self.first_stage_model.decode(z)
1016
+
1017
+ @torch.no_grad()
1018
+ def encode_first_stage(self, x):
1019
+ if hasattr(self, "split_input_params"):
1020
+ if self.split_input_params["patch_distributed_vq"]:
1021
+ ks = self.split_input_params["ks"] # eg. (128, 128)
1022
+ stride = self.split_input_params["stride"] # eg. (64, 64)
1023
+ df = self.split_input_params["vqf"]
1024
+ self.split_input_params['original_image_size'] = x.shape[-2:]
1025
+ bs, nc, h, w = x.shape
1026
+ if ks[0] > h or ks[1] > w:
1027
+ ks = (min(ks[0], h), min(ks[1], w))
1028
+ print("reducing Kernel")
1029
+
1030
+ if stride[0] > h or stride[1] > w:
1031
+ stride = (min(stride[0], h), min(stride[1], w))
1032
+ print("reducing stride")
1033
+
1034
+ fold, unfold, normalization, weighting = self.get_fold_unfold(x, ks, stride, df=df)
1035
+ z = unfold(x) # (bn, nc * prod(**ks), L)
1036
+ # Reshape to img shape
1037
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
1038
+
1039
+ output_list = [self.first_stage_model.encode(z[:, :, :, :, i])
1040
+ for i in range(z.shape[-1])]
1041
+
1042
+ o = torch.stack(output_list, axis=-1)
1043
+ o = o * weighting
1044
+
1045
+ # Reverse reshape to img shape
1046
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
1047
+ # stitch crops together
1048
+ decoded = fold(o)
1049
+ decoded = decoded / normalization
1050
+ return decoded
1051
+
1052
+ else:
1053
+ return self.first_stage_model.encode(x)
1054
+ else:
1055
+ return self.first_stage_model.encode(x)
1056
+
1057
+ def shared_step(self, batch, discriminate=False, **kwargs):
1058
+ if discriminate:
1059
+ new_batch = {'edited': None, 'edit': {'c_concat': None, 'c_crossattn': None}}
1060
+ losses = []
1061
+ for i in range(batch['edited'].shape[0]):
1062
+ new_batch['edited'] = batch['edited'][i].unsqueeze(0).repeat((10, 1, 1, 1))
1063
+ new_batch['edit']['c_concat'] = batch['edit']['c_concat'][i].unsqueeze(0).repeat((10, 1, 1, 1))
1064
+ losses_ = []
1065
+ for k in range(len(batch['edit']['c_crossattn'])):
1066
+ new_batch['edit']['c_crossattn'] = batch['edit']['c_crossattn'][k][i]
1067
+ x, c = self.get_input(new_batch, self.first_stage_key, uncond=0.0)
1068
+ loss = self(x, c, discriminate=discriminate)
1069
+ loss = loss[1]['val/loss_simple']
1070
+ losses_.append(loss)
1071
+ losses.append(losses_)
1072
+ return losses
1073
+ else:
1074
+ x, c = self.get_input(batch, self.first_stage_key)
1075
+ loss = self(x, c)
1076
+ return loss
1077
+
1078
+ def forward(self, x, c, discriminate=False, *args, **kwargs):
1079
+ if discriminate:
1080
+ t = torch.linspace(10, self.num_timesteps-10, steps=x.shape[0], device=self.device).long()
1081
+ else:
1082
+ t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
1083
+ if self.model.conditioning_key is not None:
1084
+ assert c is not None
1085
+ if self.cond_stage_trainable:
1086
+ c = self.get_learned_conditioning(c)
1087
+ if self.shorten_cond_schedule: # TODO: drop this option
1088
+ tc = self.cond_ids[t].to(self.device)
1089
+ c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))
1090
+ return self.p_losses(x, c, t, discriminate=True, *args, **kwargs)
1091
+
1092
+ def _rescale_annotations(self, bboxes, crop_coordinates): # TODO: move to dataset
1093
+ def rescale_bbox(bbox):
1094
+ x0 = clamp((bbox[0] - crop_coordinates[0]) / crop_coordinates[2])
1095
+ y0 = clamp((bbox[1] - crop_coordinates[1]) / crop_coordinates[3])
1096
+ w = min(bbox[2] / crop_coordinates[2], 1 - x0)
1097
+ h = min(bbox[3] / crop_coordinates[3], 1 - y0)
1098
+ return x0, y0, w, h
1099
+
1100
+ return [rescale_bbox(b) for b in bboxes]
1101
+
1102
+ def apply_model(self, x_noisy, t, cond, return_ids=False):
1103
+
1104
+ if isinstance(cond, dict):
1105
+ # hybrid case, cond is exptected to be a dict
1106
+ pass
1107
+ else:
1108
+ if not isinstance(cond, list):
1109
+ cond = [cond]
1110
+ key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'
1111
+ cond = {key: cond}
1112
+
1113
+ if hasattr(self, "split_input_params"):
1114
+ assert len(cond) == 1 # todo can only deal with one conditioning atm
1115
+ assert not return_ids
1116
+ ks = self.split_input_params["ks"] # eg. (128, 128)
1117
+ stride = self.split_input_params["stride"] # eg. (64, 64)
1118
+
1119
+ h, w = x_noisy.shape[-2:]
1120
+
1121
+ fold, unfold, normalization, weighting = self.get_fold_unfold(x_noisy, ks, stride)
1122
+
1123
+ z = unfold(x_noisy) # (bn, nc * prod(**ks), L)
1124
+ # Reshape to img shape
1125
+ z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
1126
+ z_list = [z[:, :, :, :, i] for i in range(z.shape[-1])]
1127
+
1128
+ if self.cond_stage_key in ["image", "LR_image", "segmentation",
1129
+ 'bbox_img'] and self.model.conditioning_key: # todo check for completeness
1130
+ c_key = next(iter(cond.keys())) # get key
1131
+ c = next(iter(cond.values())) # get value
1132
+ assert (len(c) == 1) # todo extend to list with more than one elem
1133
+ c = c[0] # get element
1134
+
1135
+ c = unfold(c)
1136
+ c = c.view((c.shape[0], -1, ks[0], ks[1], c.shape[-1])) # (bn, nc, ks[0], ks[1], L )
1137
+
1138
+ cond_list = [{c_key: [c[:, :, :, :, i]]} for i in range(c.shape[-1])]
1139
+
1140
+ elif self.cond_stage_key == 'coordinates_bbox':
1141
+ assert 'original_image_size' in self.split_input_params, 'BoudingBoxRescaling is missing original_image_size'
1142
+
1143
+ # assuming padding of unfold is always 0 and its dilation is always 1
1144
+ n_patches_per_row = int((w - ks[0]) / stride[0] + 1)
1145
+ full_img_h, full_img_w = self.split_input_params['original_image_size']
1146
+ # as we are operating on latents, we need the factor from the original image size to the
1147
+ # spatial latent size to properly rescale the crops for regenerating the bbox annotations
1148
+ num_downs = self.first_stage_model.encoder.num_resolutions - 1
1149
+ rescale_latent = 2 ** (num_downs)
1150
+
1151
+ # get top left postions of patches as conforming for the bbbox tokenizer, therefore we
1152
+ # need to rescale the tl patch coordinates to be in between (0,1)
1153
+ tl_patch_coordinates = [(rescale_latent * stride[0] * (patch_nr % n_patches_per_row) / full_img_w,
1154
+ rescale_latent * stride[1] * (patch_nr // n_patches_per_row) / full_img_h)
1155
+ for patch_nr in range(z.shape[-1])]
1156
+
1157
+ # patch_limits are tl_coord, width and height coordinates as (x_tl, y_tl, h, w)
1158
+ patch_limits = [(x_tl, y_tl,
1159
+ rescale_latent * ks[0] / full_img_w,
1160
+ rescale_latent * ks[1] / full_img_h) for x_tl, y_tl in tl_patch_coordinates]
1161
+ # 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]
1162
+
1163
+ # tokenize crop coordinates for the bounding boxes of the respective patches
1164
+ patch_limits_tknzd = [torch.LongTensor(self.bbox_tokenizer._crop_encoder(bbox))[None].to(self.device)
1165
+ for bbox in patch_limits] # list of length l with tensors of shape (1, 2)
1166
+ print(patch_limits_tknzd[0].shape)
1167
+ # cut tknzd crop position from conditioning
1168
+ assert isinstance(cond, dict), 'cond must be dict to be fed into model'
1169
+ cut_cond = cond['c_crossattn'][0][..., :-2].to(self.device)
1170
+ print(cut_cond.shape)
1171
+
1172
+ adapted_cond = torch.stack([torch.cat([cut_cond, p], dim=1) for p in patch_limits_tknzd])
1173
+ adapted_cond = rearrange(adapted_cond, 'l b n -> (l b) n')
1174
+ print(adapted_cond.shape)
1175
+ adapted_cond = self.get_learned_conditioning(adapted_cond)
1176
+ print(adapted_cond.shape)
1177
+ adapted_cond = rearrange(adapted_cond, '(l b) n d -> l b n d', l=z.shape[-1])
1178
+ print(adapted_cond.shape)
1179
+
1180
+ cond_list = [{'c_crossattn': [e]} for e in adapted_cond]
1181
+
1182
+ else:
1183
+ cond_list = [cond for i in range(z.shape[-1])] # Todo make this more efficient
1184
+
1185
+ # apply model by loop over crops
1186
+ output_list = [self.model(z_list[i], t, **cond_list[i]) for i in range(z.shape[-1])]
1187
+ assert not isinstance(output_list[0],
1188
+ tuple) # todo cant deal with multiple model outputs check this never happens
1189
+
1190
+ o = torch.stack(output_list, axis=-1)
1191
+ o = o * weighting
1192
+ # Reverse reshape to img shape
1193
+ o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
1194
+ # stitch crops together
1195
+ x_recon = fold(o) / normalization
1196
+
1197
+ else:
1198
+ x_recon = self.model(x_noisy, t, **cond)
1199
+
1200
+ if isinstance(x_recon, tuple) and not return_ids:
1201
+ return x_recon[0]
1202
+ else:
1203
+ return x_recon
1204
+
1205
+ def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
1206
+ return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \
1207
+ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
1208
+
1209
+ def _prior_bpd(self, x_start):
1210
+ """
1211
+ Get the prior KL term for the variational lower-bound, measured in
1212
+ bits-per-dim.
1213
+ This term can't be optimized, as it only depends on the encoder.
1214
+ :param x_start: the [N x C x ...] tensor of inputs.
1215
+ :return: a batch of [N] KL values (in bits), one per batch element.
1216
+ """
1217
+ batch_size = x_start.shape[0]
1218
+ t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
1219
+ qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
1220
+ kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
1221
+ return mean_flat(kl_prior) / np.log(2.0)
1222
+
1223
+ def p_losses(self, x_start, cond, t, discriminate=False, noise=None):
1224
+ if discriminate:
1225
+ # set seed
1226
+ torch.manual_seed(0)
1227
+ noise = default(noise, lambda: torch.randn_like(x_start))
1228
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
1229
+
1230
+ #Override for debugging TODO: delete
1231
+ # import pickle
1232
+ # with open(os.path.expanduser("~/diffusion-itm/first_noise.pkl"), "rb") as f:
1233
+ # noise = pickle.load(f)
1234
+ # noise = noise.to(self.device).unsqueeze(0).repeat(x_start.shape[0], 1, 1, 1)
1235
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
1236
+
1237
+ model_output = self.apply_model(x_noisy, t, cond)
1238
+
1239
+ loss_dict = {}
1240
+ prefix = 'train' if self.training else 'val'
1241
+
1242
+ if self.parameterization == "x0":
1243
+ target = x_start
1244
+ elif self.parameterization == "eps":
1245
+ target = noise
1246
+ else:
1247
+ raise NotImplementedError()
1248
+
1249
+ loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3])
1250
+ # loss_dict.update({f'{prefix}/loss_simple_list': loss_simple})
1251
+ loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})
1252
+
1253
+ logvar_t = self.logvar.to(self.device)[t]
1254
+ loss = loss_simple / torch.exp(logvar_t) + logvar_t
1255
+ # loss = loss_simple / torch.exp(self.logvar) + self.logvar
1256
+ if self.learn_logvar:
1257
+ loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})
1258
+ loss_dict.update({'logvar': self.logvar.data.mean()})
1259
+
1260
+ loss = self.l_simple_weight * loss.mean()
1261
+
1262
+ loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3))
1263
+ loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()
1264
+ loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})
1265
+ loss += (self.original_elbo_weight * loss_vlb)
1266
+ loss_dict.update({f'{prefix}/loss': loss})
1267
+
1268
+ return loss, loss_dict
1269
+
1270
+ def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False,
1271
+ return_x0=False, score_corrector=None, corrector_kwargs=None):
1272
+ t_in = t
1273
+ model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)
1274
+
1275
+ if score_corrector is not None:
1276
+ assert self.parameterization == "eps"
1277
+ model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)
1278
+
1279
+ if return_codebook_ids:
1280
+ model_out, logits = model_out
1281
+
1282
+ if self.parameterization == "eps":
1283
+ x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
1284
+ elif self.parameterization == "x0":
1285
+ x_recon = model_out
1286
+ else:
1287
+ raise NotImplementedError()
1288
+
1289
+ if clip_denoised:
1290
+ x_recon.clamp_(-1., 1.)
1291
+ if quantize_denoised:
1292
+ x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)
1293
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
1294
+ if return_codebook_ids:
1295
+ return model_mean, posterior_variance, posterior_log_variance, logits
1296
+ elif return_x0:
1297
+ return model_mean, posterior_variance, posterior_log_variance, x_recon
1298
+ else:
1299
+ return model_mean, posterior_variance, posterior_log_variance
1300
+
1301
+ @torch.no_grad()
1302
+ def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False,
1303
+ return_codebook_ids=False, quantize_denoised=False, return_x0=False,
1304
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):
1305
+ b, *_, device = *x.shape, x.device
1306
+ outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised,
1307
+ return_codebook_ids=return_codebook_ids,
1308
+ quantize_denoised=quantize_denoised,
1309
+ return_x0=return_x0,
1310
+ score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
1311
+ if return_codebook_ids:
1312
+ raise DeprecationWarning("Support dropped.")
1313
+ model_mean, _, model_log_variance, logits = outputs
1314
+ elif return_x0:
1315
+ model_mean, _, model_log_variance, x0 = outputs
1316
+ else:
1317
+ model_mean, _, model_log_variance = outputs
1318
+
1319
+ noise = noise_like(x.shape, device, repeat_noise) * temperature
1320
+ if noise_dropout > 0.:
1321
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
1322
+ # no noise when t == 0
1323
+ nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
1324
+
1325
+ if return_codebook_ids:
1326
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1)
1327
+ if return_x0:
1328
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0
1329
+ else:
1330
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
1331
+
1332
+ @torch.no_grad()
1333
+ def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False,
1334
+ img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0.,
1335
+ score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None,
1336
+ log_every_t=None):
1337
+ if not log_every_t:
1338
+ log_every_t = self.log_every_t
1339
+ timesteps = self.num_timesteps
1340
+ if batch_size is not None:
1341
+ b = batch_size if batch_size is not None else shape[0]
1342
+ shape = [batch_size] + list(shape)
1343
+ else:
1344
+ b = batch_size = shape[0]
1345
+ if x_T is None:
1346
+ img = torch.randn(shape, device=self.device)
1347
+ else:
1348
+ img = x_T
1349
+ intermediates = []
1350
+ if cond is not None:
1351
+ if isinstance(cond, dict):
1352
+ cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
1353
+ list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
1354
+ else:
1355
+ cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
1356
+
1357
+ if start_T is not None:
1358
+ timesteps = min(timesteps, start_T)
1359
+ iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation',
1360
+ total=timesteps) if verbose else reversed(
1361
+ range(0, timesteps))
1362
+ if type(temperature) == float:
1363
+ temperature = [temperature] * timesteps
1364
+
1365
+ for i in iterator:
1366
+ ts = torch.full((b,), i, device=self.device, dtype=torch.long)
1367
+ if self.shorten_cond_schedule:
1368
+ assert self.model.conditioning_key != 'hybrid'
1369
+ tc = self.cond_ids[ts].to(cond.device)
1370
+ cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
1371
+
1372
+ img, x0_partial = self.p_sample(img, cond, ts,
1373
+ clip_denoised=self.clip_denoised,
1374
+ quantize_denoised=quantize_denoised, return_x0=True,
1375
+ temperature=temperature[i], noise_dropout=noise_dropout,
1376
+ score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
1377
+ if mask is not None:
1378
+ assert x0 is not None
1379
+ img_orig = self.q_sample(x0, ts)
1380
+ img = img_orig * mask + (1. - mask) * img
1381
+
1382
+ if i % log_every_t == 0 or i == timesteps - 1:
1383
+ intermediates.append(x0_partial)
1384
+ if callback: callback(i)
1385
+ if img_callback: img_callback(img, i)
1386
+ return img, intermediates
1387
+
1388
+ @torch.no_grad()
1389
+ def p_sample_loop(self, cond, shape, return_intermediates=False,
1390
+ x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False,
1391
+ mask=None, x0=None, img_callback=None, start_T=None,
1392
+ log_every_t=None):
1393
+
1394
+ if not log_every_t:
1395
+ log_every_t = self.log_every_t
1396
+ device = self.betas.device
1397
+ b = shape[0]
1398
+ if x_T is None:
1399
+ img = torch.randn(shape, device=device)
1400
+ else:
1401
+ img = x_T
1402
+
1403
+ intermediates = [img]
1404
+ if timesteps is None:
1405
+ timesteps = self.num_timesteps
1406
+
1407
+ if start_T is not None:
1408
+ timesteps = min(timesteps, start_T)
1409
+ iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(
1410
+ range(0, timesteps))
1411
+
1412
+ if mask is not None:
1413
+ assert x0 is not None
1414
+ assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match
1415
+
1416
+ for i in iterator:
1417
+ ts = torch.full((b,), i, device=device, dtype=torch.long)
1418
+ if self.shorten_cond_schedule:
1419
+ assert self.model.conditioning_key != 'hybrid'
1420
+ tc = self.cond_ids[ts].to(cond.device)
1421
+ cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
1422
+
1423
+ img = self.p_sample(img, cond, ts,
1424
+ clip_denoised=self.clip_denoised,
1425
+ quantize_denoised=quantize_denoised)
1426
+ if mask is not None:
1427
+ img_orig = self.q_sample(x0, ts)
1428
+ img = img_orig * mask + (1. - mask) * img
1429
+
1430
+ if i % log_every_t == 0 or i == timesteps - 1:
1431
+ intermediates.append(img)
1432
+ if callback: callback(i)
1433
+ if img_callback: img_callback(img, i)
1434
+
1435
+ if return_intermediates:
1436
+ return img, intermediates
1437
+ return img
1438
+
1439
+ @torch.no_grad()
1440
+ def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None,
1441
+ verbose=True, timesteps=None, quantize_denoised=False,
1442
+ mask=None, x0=None, shape=None,**kwargs):
1443
+ if shape is None:
1444
+ shape = (batch_size, self.channels, self.image_size, self.image_size)
1445
+ if cond is not None:
1446
+ if isinstance(cond, dict):
1447
+ cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
1448
+ list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
1449
+ else:
1450
+ cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
1451
+ return self.p_sample_loop(cond,
1452
+ shape,
1453
+ return_intermediates=return_intermediates, x_T=x_T,
1454
+ verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised,
1455
+ mask=mask, x0=x0)
1456
+
1457
+ @torch.no_grad()
1458
+ def sample_log(self,cond,batch_size,ddim, ddim_steps,**kwargs):
1459
+
1460
+ if ddim:
1461
+ ddim_sampler = DDIMSampler(self)
1462
+ shape = (self.channels, self.image_size, self.image_size)
1463
+ samples, intermediates =ddim_sampler.sample(ddim_steps,batch_size,
1464
+ shape,cond,verbose=False,**kwargs)
1465
+
1466
+ else:
1467
+ samples, intermediates = self.sample(cond=cond, batch_size=batch_size,
1468
+ return_intermediates=True,**kwargs)
1469
+
1470
+ return samples, intermediates
1471
+
1472
+
1473
+ @torch.no_grad()
1474
+ def log_images(self, batch, N=4, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
1475
+ quantize_denoised=True, inpaint=False, plot_denoise_rows=False, plot_progressive_rows=False,
1476
+ plot_diffusion_rows=False, **kwargs):
1477
+
1478
+ use_ddim = False
1479
+
1480
+ log = dict()
1481
+ z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,
1482
+ return_first_stage_outputs=True,
1483
+ force_c_encode=True,
1484
+ return_original_cond=True,
1485
+ bs=N, uncond=0)
1486
+ N = min(x.shape[0], N)
1487
+ n_row = min(x.shape[0], n_row)
1488
+ log["inputs"] = x
1489
+ log["reals"] = xc["c_concat"]
1490
+ log["reconstruction"] = xrec
1491
+ if self.model.conditioning_key is not None:
1492
+ if hasattr(self.cond_stage_model, "decode"):
1493
+ xc = self.cond_stage_model.decode(c)
1494
+ log["conditioning"] = xc
1495
+ elif self.cond_stage_key in ["caption"]:
1496
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["caption"])
1497
+ log["conditioning"] = xc
1498
+ elif self.cond_stage_key == 'class_label':
1499
+ xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"])
1500
+ log['conditioning'] = xc
1501
+ elif isimage(xc):
1502
+ log["conditioning"] = xc
1503
+ if ismap(xc):
1504
+ log["original_conditioning"] = self.to_rgb(xc)
1505
+
1506
+ if plot_diffusion_rows:
1507
+ # get diffusion row
1508
+ diffusion_row = list()
1509
+ z_start = z[:n_row]
1510
+ for t in range(self.num_timesteps):
1511
+ if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
1512
+ t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
1513
+ t = t.to(self.device).long()
1514
+ noise = torch.randn_like(z_start)
1515
+ z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
1516
+ diffusion_row.append(self.decode_first_stage(z_noisy))
1517
+
1518
+ diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
1519
+ diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
1520
+ diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
1521
+ diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
1522
+ log["diffusion_row"] = diffusion_grid
1523
+
1524
+ if sample:
1525
+ # get denoise row
1526
+ with self.ema_scope("Plotting"):
1527
+ samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim,
1528
+ ddim_steps=ddim_steps,eta=ddim_eta)
1529
+ # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
1530
+ x_samples = self.decode_first_stage(samples)
1531
+ log["samples"] = x_samples
1532
+ if plot_denoise_rows:
1533
+ denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
1534
+ log["denoise_row"] = denoise_grid
1535
+
1536
+ if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(
1537
+ self.first_stage_model, IdentityFirstStage):
1538
+ # also display when quantizing x0 while sampling
1539
+ with self.ema_scope("Plotting Quantized Denoised"):
1540
+ samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim,
1541
+ ddim_steps=ddim_steps,eta=ddim_eta,
1542
+ quantize_denoised=True)
1543
+ # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,
1544
+ # quantize_denoised=True)
1545
+ x_samples = self.decode_first_stage(samples.to(self.device))
1546
+ log["samples_x0_quantized"] = x_samples
1547
+
1548
+ if inpaint:
1549
+ # make a simple center square
1550
+ b, h, w = z.shape[0], z.shape[2], z.shape[3]
1551
+ mask = torch.ones(N, h, w).to(self.device)
1552
+ # zeros will be filled in
1553
+ mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.
1554
+ mask = mask[:, None, ...]
1555
+ with self.ema_scope("Plotting Inpaint"):
1556
+
1557
+ samples, _ = self.sample_log(cond=c,batch_size=N,ddim=use_ddim, eta=ddim_eta,
1558
+ ddim_steps=ddim_steps, x0=z[:N], mask=mask)
1559
+ x_samples = self.decode_first_stage(samples.to(self.device))
1560
+ log["samples_inpainting"] = x_samples
1561
+ log["mask"] = mask
1562
+
1563
+ # outpaint
1564
+ with self.ema_scope("Plotting Outpaint"):
1565
+ samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,eta=ddim_eta,
1566
+ ddim_steps=ddim_steps, x0=z[:N], mask=mask)
1567
+ x_samples = self.decode_first_stage(samples.to(self.device))
1568
+ log["samples_outpainting"] = x_samples
1569
+
1570
+ if plot_progressive_rows:
1571
+ with self.ema_scope("Plotting Progressives"):
1572
+ img, progressives = self.progressive_denoising(c,
1573
+ shape=(self.channels, self.image_size, self.image_size),
1574
+ batch_size=N)
1575
+ prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
1576
+ log["progressive_row"] = prog_row
1577
+
1578
+ if return_keys:
1579
+ if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
1580
+ return log
1581
+ else:
1582
+ return {key: log[key] for key in return_keys}
1583
+ return log
1584
+
1585
+ def configure_optimizers(self):
1586
+ lr = self.learning_rate
1587
+ params = list(self.model.parameters())
1588
+ if self.cond_stage_trainable:
1589
+ print(f"{self.__class__.__name__}: Also optimizing conditioner params!")
1590
+ params = params + list(self.cond_stage_model.parameters())
1591
+ if self.learn_logvar:
1592
+ print('Diffusion model optimizing logvar')
1593
+ params.append(self.logvar)
1594
+ opt = torch.optim.AdamW(params, lr=lr)
1595
+ if self.use_scheduler:
1596
+ assert 'target' in self.scheduler_config
1597
+ scheduler = instantiate_from_config(self.scheduler_config)
1598
+
1599
+ print("Setting up LambdaLR scheduler...")
1600
+ scheduler = [
1601
+ {
1602
+ 'scheduler': LambdaLR(opt, lr_lambda=scheduler.schedule),
1603
+ 'interval': 'step',
1604
+ 'frequency': 1
1605
+ }]
1606
+ return [opt], scheduler
1607
+ return opt
1608
+
1609
+ @torch.no_grad()
1610
+ def to_rgb(self, x):
1611
+ x = x.float()
1612
+ if not hasattr(self, "colorize"):
1613
+ self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)
1614
+ x = nn.functional.conv2d(x, weight=self.colorize)
1615
+ x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.
1616
+ return x
1617
+
1618
+
1619
+ class DiffusionWrapper(pl.LightningModule):
1620
+ def __init__(self, diff_model_config, conditioning_key):
1621
+ super().__init__()
1622
+ self.diffusion_model = instantiate_from_config(diff_model_config)
1623
+ self.conditioning_key = conditioning_key
1624
+ assert self.conditioning_key in [None, 'concat', 'crossattn', 'hybrid', 'adm']
1625
+
1626
+ def forward(self, x, t, c_concat: list = None, c_crossattn: list = None):
1627
+ if self.conditioning_key is None:
1628
+ out = self.diffusion_model(x, t)
1629
+ elif self.conditioning_key == 'concat':
1630
+ xc = torch.cat([x] + c_concat, dim=1)
1631
+ out = self.diffusion_model(xc, t)
1632
+ elif self.conditioning_key == 'crossattn':
1633
+ cc = torch.cat(c_crossattn, 1)
1634
+ out = self.diffusion_model(x, t, context=cc)
1635
+ elif self.conditioning_key == 'hybrid':
1636
+ xc = torch.cat([x] + c_concat, dim=1)
1637
+ cc = torch.cat(c_crossattn, 1)
1638
+ out = self.diffusion_model(xc, t, context=cc)
1639
+ elif self.conditioning_key == 'adm':
1640
+ cc = c_crossattn[0]
1641
+ out = self.diffusion_model(x, t, y=cc)
1642
+ else:
1643
+ raise NotImplementedError()
1644
+
1645
+ return out
1646
+
1647
+
1648
+ class Layout2ImgDiffusion(LatentDiffusion):
1649
+ # TODO: move all layout-specific hacks to this class
1650
+ def __init__(self, cond_stage_key, *args, **kwargs):
1651
+ assert cond_stage_key == 'coordinates_bbox', 'Layout2ImgDiffusion only for cond_stage_key="coordinates_bbox"'
1652
+ super().__init__(cond_stage_key=cond_stage_key, *args, **kwargs)
1653
+
1654
+ def log_images(self, batch, N=8, *args, **kwargs):
1655
+ logs = super().log_images(batch=batch, N=N, *args, **kwargs)
1656
+
1657
+ key = 'train' if self.training else 'validation'
1658
+ dset = self.trainer.datamodule.datasets[key]
1659
+ mapper = dset.conditional_builders[self.cond_stage_key]
1660
+
1661
+ bbox_imgs = []
1662
+ map_fn = lambda catno: dset.get_textual_label(dset.get_category_id(catno))
1663
+ for tknzd_bbox in batch[self.cond_stage_key][:N]:
1664
+ bboximg = mapper.plot(tknzd_bbox.detach().cpu(), map_fn, (256, 256))
1665
+ bbox_imgs.append(bboximg)
1666
+
1667
+ cond_img = torch.stack(bbox_imgs, dim=0)
1668
+ logs['bbox_image'] = cond_img
1669
+ return logs
stable_diffusion/ldm/models/diffusion/dpm_solver/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .sampler import DPMSolverSampler
stable_diffusion/ldm/models/diffusion/dpm_solver/dpm_solver.py ADDED
@@ -0,0 +1,1184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ import math
4
+
5
+
6
+ class NoiseScheduleVP:
7
+ def __init__(
8
+ self,
9
+ schedule='discrete',
10
+ betas=None,
11
+ alphas_cumprod=None,
12
+ continuous_beta_0=0.1,
13
+ continuous_beta_1=20.,
14
+ ):
15
+ """Create a wrapper class for the forward SDE (VP type).
16
+
17
+ ***
18
+ Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t.
19
+ We recommend to use schedule='discrete' for the discrete-time diffusion models, especially for high-resolution images.
20
+ ***
21
+
22
+ The forward SDE ensures that the condition distribution q_{t|0}(x_t | x_0) = N ( alpha_t * x_0, sigma_t^2 * I ).
23
+ We further define lambda_t = log(alpha_t) - log(sigma_t), which is the half-logSNR (described in the DPM-Solver paper).
24
+ Therefore, we implement the functions for computing alpha_t, sigma_t and lambda_t. For t in [0, T], we have:
25
+
26
+ log_alpha_t = self.marginal_log_mean_coeff(t)
27
+ sigma_t = self.marginal_std(t)
28
+ lambda_t = self.marginal_lambda(t)
29
+
30
+ Moreover, as lambda(t) is an invertible function, we also support its inverse function:
31
+
32
+ t = self.inverse_lambda(lambda_t)
33
+
34
+ ===============================================================
35
+
36
+ We support both discrete-time DPMs (trained on n = 0, 1, ..., N-1) and continuous-time DPMs (trained on t in [t_0, T]).
37
+
38
+ 1. For discrete-time DPMs:
39
+
40
+ For discrete-time DPMs trained on n = 0, 1, ..., N-1, we convert the discrete steps to continuous time steps by:
41
+ t_i = (i + 1) / N
42
+ e.g. for N = 1000, we have t_0 = 1e-3 and T = t_{N-1} = 1.
43
+ We solve the corresponding diffusion ODE from time T = 1 to time t_0 = 1e-3.
44
+
45
+ Args:
46
+ betas: A `torch.Tensor`. The beta array for the discrete-time DPM. (See the original DDPM paper for details)
47
+ alphas_cumprod: A `torch.Tensor`. The cumprod alphas for the discrete-time DPM. (See the original DDPM paper for details)
48
+
49
+ Note that we always have alphas_cumprod = cumprod(betas). Therefore, we only need to set one of `betas` and `alphas_cumprod`.
50
+
51
+ **Important**: Please pay special attention for the args for `alphas_cumprod`:
52
+ The `alphas_cumprod` is the \hat{alpha_n} arrays in the notations of DDPM. Specifically, DDPMs assume that
53
+ q_{t_n | 0}(x_{t_n} | x_0) = N ( \sqrt{\hat{alpha_n}} * x_0, (1 - \hat{alpha_n}) * I ).
54
+ Therefore, the notation \hat{alpha_n} is different from the notation alpha_t in DPM-Solver. In fact, we have
55
+ alpha_{t_n} = \sqrt{\hat{alpha_n}},
56
+ and
57
+ log(alpha_{t_n}) = 0.5 * log(\hat{alpha_n}).
58
+
59
+
60
+ 2. For continuous-time DPMs:
61
+
62
+ We support two types of VPSDEs: linear (DDPM) and cosine (improved-DDPM). The hyperparameters for the noise
63
+ schedule are the default settings in DDPM and improved-DDPM:
64
+
65
+ Args:
66
+ beta_min: A `float` number. The smallest beta for the linear schedule.
67
+ beta_max: A `float` number. The largest beta for the linear schedule.
68
+ cosine_s: A `float` number. The hyperparameter in the cosine schedule.
69
+ cosine_beta_max: A `float` number. The hyperparameter in the cosine schedule.
70
+ T: A `float` number. The ending time of the forward process.
71
+
72
+ ===============================================================
73
+
74
+ Args:
75
+ schedule: A `str`. The noise schedule of the forward SDE. 'discrete' for discrete-time DPMs,
76
+ 'linear' or 'cosine' for continuous-time DPMs.
77
+ Returns:
78
+ A wrapper object of the forward SDE (VP type).
79
+
80
+ ===============================================================
81
+
82
+ Example:
83
+
84
+ # For discrete-time DPMs, given betas (the beta array for n = 0, 1, ..., N - 1):
85
+ >>> ns = NoiseScheduleVP('discrete', betas=betas)
86
+
87
+ # For discrete-time DPMs, given alphas_cumprod (the \hat{alpha_n} array for n = 0, 1, ..., N - 1):
88
+ >>> ns = NoiseScheduleVP('discrete', alphas_cumprod=alphas_cumprod)
89
+
90
+ # For continuous-time DPMs (VPSDE), linear schedule:
91
+ >>> ns = NoiseScheduleVP('linear', continuous_beta_0=0.1, continuous_beta_1=20.)
92
+
93
+ """
94
+
95
+ if schedule not in ['discrete', 'linear', 'cosine']:
96
+ raise ValueError("Unsupported noise schedule {}. The schedule needs to be 'discrete' or 'linear' or 'cosine'".format(schedule))
97
+
98
+ self.schedule = schedule
99
+ if schedule == 'discrete':
100
+ if betas is not None:
101
+ log_alphas = 0.5 * torch.log(1 - betas).cumsum(dim=0)
102
+ else:
103
+ assert alphas_cumprod is not None
104
+ log_alphas = 0.5 * torch.log(alphas_cumprod)
105
+ self.total_N = len(log_alphas)
106
+ self.T = 1.
107
+ self.t_array = torch.linspace(0., 1., self.total_N + 1)[1:].reshape((1, -1))
108
+ self.log_alpha_array = log_alphas.reshape((1, -1,))
109
+ else:
110
+ self.total_N = 1000
111
+ self.beta_0 = continuous_beta_0
112
+ self.beta_1 = continuous_beta_1
113
+ self.cosine_s = 0.008
114
+ self.cosine_beta_max = 999.
115
+ self.cosine_t_max = math.atan(self.cosine_beta_max * (1. + self.cosine_s) / math.pi) * 2. * (1. + self.cosine_s) / math.pi - self.cosine_s
116
+ self.cosine_log_alpha_0 = math.log(math.cos(self.cosine_s / (1. + self.cosine_s) * math.pi / 2.))
117
+ self.schedule = schedule
118
+ if schedule == 'cosine':
119
+ # For the cosine schedule, T = 1 will have numerical issues. So we manually set the ending time T.
120
+ # Note that T = 0.9946 may be not the optimal setting. However, we find it works well.
121
+ self.T = 0.9946
122
+ else:
123
+ self.T = 1.
124
+
125
+ def marginal_log_mean_coeff(self, t):
126
+ """
127
+ Compute log(alpha_t) of a given continuous-time label t in [0, T].
128
+ """
129
+ if self.schedule == 'discrete':
130
+ return interpolate_fn(t.reshape((-1, 1)), self.t_array.to(t.device), self.log_alpha_array.to(t.device)).reshape((-1))
131
+ elif self.schedule == 'linear':
132
+ return -0.25 * t ** 2 * (self.beta_1 - self.beta_0) - 0.5 * t * self.beta_0
133
+ elif self.schedule == 'cosine':
134
+ log_alpha_fn = lambda s: torch.log(torch.cos((s + self.cosine_s) / (1. + self.cosine_s) * math.pi / 2.))
135
+ log_alpha_t = log_alpha_fn(t) - self.cosine_log_alpha_0
136
+ return log_alpha_t
137
+
138
+ def marginal_alpha(self, t):
139
+ """
140
+ Compute alpha_t of a given continuous-time label t in [0, T].
141
+ """
142
+ return torch.exp(self.marginal_log_mean_coeff(t))
143
+
144
+ def marginal_std(self, t):
145
+ """
146
+ Compute sigma_t of a given continuous-time label t in [0, T].
147
+ """
148
+ return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))
149
+
150
+ def marginal_lambda(self, t):
151
+ """
152
+ Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].
153
+ """
154
+ log_mean_coeff = self.marginal_log_mean_coeff(t)
155
+ log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff))
156
+ return log_mean_coeff - log_std
157
+
158
+ def inverse_lambda(self, lamb):
159
+ """
160
+ Compute the continuous-time label t in [0, T] of a given half-logSNR lambda_t.
161
+ """
162
+ if self.schedule == 'linear':
163
+ tmp = 2. * (self.beta_1 - self.beta_0) * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
164
+ Delta = self.beta_0**2 + tmp
165
+ return tmp / (torch.sqrt(Delta) + self.beta_0) / (self.beta_1 - self.beta_0)
166
+ elif self.schedule == 'discrete':
167
+ log_alpha = -0.5 * torch.logaddexp(torch.zeros((1,)).to(lamb.device), -2. * lamb)
168
+ t = interpolate_fn(log_alpha.reshape((-1, 1)), torch.flip(self.log_alpha_array.to(lamb.device), [1]), torch.flip(self.t_array.to(lamb.device), [1]))
169
+ return t.reshape((-1,))
170
+ else:
171
+ log_alpha = -0.5 * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
172
+ t_fn = lambda log_alpha_t: torch.arccos(torch.exp(log_alpha_t + self.cosine_log_alpha_0)) * 2. * (1. + self.cosine_s) / math.pi - self.cosine_s
173
+ t = t_fn(log_alpha)
174
+ return t
175
+
176
+
177
+ def model_wrapper(
178
+ model,
179
+ noise_schedule,
180
+ model_type="noise",
181
+ model_kwargs={},
182
+ guidance_type="uncond",
183
+ condition=None,
184
+ unconditional_condition=None,
185
+ guidance_scale=1.,
186
+ classifier_fn=None,
187
+ classifier_kwargs={},
188
+ ):
189
+ """Create a wrapper function for the noise prediction model.
190
+
191
+ DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to
192
+ firstly wrap the model function to a noise prediction model that accepts the continuous time as the input.
193
+
194
+ We support four types of the diffusion model by setting `model_type`:
195
+
196
+ 1. "noise": noise prediction model. (Trained by predicting noise).
197
+
198
+ 2. "x_start": data prediction model. (Trained by predicting the data x_0 at time 0).
199
+
200
+ 3. "v": velocity prediction model. (Trained by predicting the velocity).
201
+ The "v" prediction is derivation detailed in Appendix D of [1], and is used in Imagen-Video [2].
202
+
203
+ [1] Salimans, Tim, and Jonathan Ho. "Progressive distillation for fast sampling of diffusion models."
204
+ arXiv preprint arXiv:2202.00512 (2022).
205
+ [2] Ho, Jonathan, et al. "Imagen Video: High Definition Video Generation with Diffusion Models."
206
+ arXiv preprint arXiv:2210.02303 (2022).
207
+
208
+ 4. "score": marginal score function. (Trained by denoising score matching).
209
+ Note that the score function and the noise prediction model follows a simple relationship:
210
+ ```
211
+ noise(x_t, t) = -sigma_t * score(x_t, t)
212
+ ```
213
+
214
+ We support three types of guided sampling by DPMs by setting `guidance_type`:
215
+ 1. "uncond": unconditional sampling by DPMs.
216
+ The input `model` has the following format:
217
+ ``
218
+ model(x, t_input, **model_kwargs) -> noise | x_start | v | score
219
+ ``
220
+
221
+ 2. "classifier": classifier guidance sampling [3] by DPMs and another classifier.
222
+ The input `model` has the following format:
223
+ ``
224
+ model(x, t_input, **model_kwargs) -> noise | x_start | v | score
225
+ ``
226
+
227
+ The input `classifier_fn` has the following format:
228
+ ``
229
+ classifier_fn(x, t_input, cond, **classifier_kwargs) -> logits(x, t_input, cond)
230
+ ``
231
+
232
+ [3] P. Dhariwal and A. Q. Nichol, "Diffusion models beat GANs on image synthesis,"
233
+ in Advances in Neural Information Processing Systems, vol. 34, 2021, pp. 8780-8794.
234
+
235
+ 3. "classifier-free": classifier-free guidance sampling by conditional DPMs.
236
+ The input `model` has the following format:
237
+ ``
238
+ model(x, t_input, cond, **model_kwargs) -> noise | x_start | v | score
239
+ ``
240
+ And if cond == `unconditional_condition`, the model output is the unconditional DPM output.
241
+
242
+ [4] Ho, Jonathan, and Tim Salimans. "Classifier-free diffusion guidance."
243
+ arXiv preprint arXiv:2207.12598 (2022).
244
+
245
+
246
+ The `t_input` is the time label of the model, which may be discrete-time labels (i.e. 0 to 999)
247
+ or continuous-time labels (i.e. epsilon to T).
248
+
249
+ We wrap the model function to accept only `x` and `t_continuous` as inputs, and outputs the predicted noise:
250
+ ``
251
+ def model_fn(x, t_continuous) -> noise:
252
+ t_input = get_model_input_time(t_continuous)
253
+ return noise_pred(model, x, t_input, **model_kwargs)
254
+ ``
255
+ where `t_continuous` is the continuous time labels (i.e. epsilon to T). And we use `model_fn` for DPM-Solver.
256
+
257
+ ===============================================================
258
+
259
+ Args:
260
+ model: A diffusion model with the corresponding format described above.
261
+ noise_schedule: A noise schedule object, such as NoiseScheduleVP.
262
+ model_type: A `str`. The parameterization type of the diffusion model.
263
+ "noise" or "x_start" or "v" or "score".
264
+ model_kwargs: A `dict`. A dict for the other inputs of the model function.
265
+ guidance_type: A `str`. The type of the guidance for sampling.
266
+ "uncond" or "classifier" or "classifier-free".
267
+ condition: A pytorch tensor. The condition for the guided sampling.
268
+ Only used for "classifier" or "classifier-free" guidance type.
269
+ unconditional_condition: A pytorch tensor. The condition for the unconditional sampling.
270
+ Only used for "classifier-free" guidance type.
271
+ guidance_scale: A `float`. The scale for the guided sampling.
272
+ classifier_fn: A classifier function. Only used for the classifier guidance.
273
+ classifier_kwargs: A `dict`. A dict for the other inputs of the classifier function.
274
+ Returns:
275
+ A noise prediction model that accepts the noised data and the continuous time as the inputs.
276
+ """
277
+
278
+ def get_model_input_time(t_continuous):
279
+ """
280
+ Convert the continuous-time `t_continuous` (in [epsilon, T]) to the model input time.
281
+ For discrete-time DPMs, we convert `t_continuous` in [1 / N, 1] to `t_input` in [0, 1000 * (N - 1) / N].
282
+ For continuous-time DPMs, we just use `t_continuous`.
283
+ """
284
+ if noise_schedule.schedule == 'discrete':
285
+ return (t_continuous - 1. / noise_schedule.total_N) * 1000.
286
+ else:
287
+ return t_continuous
288
+
289
+ def noise_pred_fn(x, t_continuous, cond=None):
290
+ if t_continuous.reshape((-1,)).shape[0] == 1:
291
+ t_continuous = t_continuous.expand((x.shape[0]))
292
+ t_input = get_model_input_time(t_continuous)
293
+ if cond is None:
294
+ output = model(x, t_input, **model_kwargs)
295
+ else:
296
+ output = model(x, t_input, cond, **model_kwargs)
297
+ if model_type == "noise":
298
+ return output
299
+ elif model_type == "x_start":
300
+ alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
301
+ dims = x.dim()
302
+ return (x - expand_dims(alpha_t, dims) * output) / expand_dims(sigma_t, dims)
303
+ elif model_type == "v":
304
+ alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
305
+ dims = x.dim()
306
+ return expand_dims(alpha_t, dims) * output + expand_dims(sigma_t, dims) * x
307
+ elif model_type == "score":
308
+ sigma_t = noise_schedule.marginal_std(t_continuous)
309
+ dims = x.dim()
310
+ return -expand_dims(sigma_t, dims) * output
311
+
312
+ def cond_grad_fn(x, t_input):
313
+ """
314
+ Compute the gradient of the classifier, i.e. nabla_{x} log p_t(cond | x_t).
315
+ """
316
+ with torch.enable_grad():
317
+ x_in = x.detach().requires_grad_(True)
318
+ log_prob = classifier_fn(x_in, t_input, condition, **classifier_kwargs)
319
+ return torch.autograd.grad(log_prob.sum(), x_in)[0]
320
+
321
+ def model_fn(x, t_continuous):
322
+ """
323
+ The noise predicition model function that is used for DPM-Solver.
324
+ """
325
+ if t_continuous.reshape((-1,)).shape[0] == 1:
326
+ t_continuous = t_continuous.expand((x.shape[0]))
327
+ if guidance_type == "uncond":
328
+ return noise_pred_fn(x, t_continuous)
329
+ elif guidance_type == "classifier":
330
+ assert classifier_fn is not None
331
+ t_input = get_model_input_time(t_continuous)
332
+ cond_grad = cond_grad_fn(x, t_input)
333
+ sigma_t = noise_schedule.marginal_std(t_continuous)
334
+ noise = noise_pred_fn(x, t_continuous)
335
+ return noise - guidance_scale * expand_dims(sigma_t, dims=cond_grad.dim()) * cond_grad
336
+ elif guidance_type == "classifier-free":
337
+ if guidance_scale == 1. or unconditional_condition is None:
338
+ return noise_pred_fn(x, t_continuous, cond=condition)
339
+ else:
340
+ x_in = torch.cat([x] * 2)
341
+ t_in = torch.cat([t_continuous] * 2)
342
+ c_in = torch.cat([unconditional_condition, condition])
343
+ noise_uncond, noise = noise_pred_fn(x_in, t_in, cond=c_in).chunk(2)
344
+ return noise_uncond + guidance_scale * (noise - noise_uncond)
345
+
346
+ assert model_type in ["noise", "x_start", "v"]
347
+ assert guidance_type in ["uncond", "classifier", "classifier-free"]
348
+ return model_fn
349
+
350
+
351
+ class DPM_Solver:
352
+ def __init__(self, model_fn, noise_schedule, predict_x0=False, thresholding=False, max_val=1.):
353
+ """Construct a DPM-Solver.
354
+
355
+ We support both the noise prediction model ("predicting epsilon") and the data prediction model ("predicting x0").
356
+ If `predict_x0` is False, we use the solver for the noise prediction model (DPM-Solver).
357
+ If `predict_x0` is True, we use the solver for the data prediction model (DPM-Solver++).
358
+ In such case, we further support the "dynamic thresholding" in [1] when `thresholding` is True.
359
+ The "dynamic thresholding" can greatly improve the sample quality for pixel-space DPMs with large guidance scales.
360
+
361
+ Args:
362
+ model_fn: A noise prediction model function which accepts the continuous-time input (t in [epsilon, T]):
363
+ ``
364
+ def model_fn(x, t_continuous):
365
+ return noise
366
+ ``
367
+ noise_schedule: A noise schedule object, such as NoiseScheduleVP.
368
+ predict_x0: A `bool`. If true, use the data prediction model; else, use the noise prediction model.
369
+ thresholding: A `bool`. Valid when `predict_x0` is True. Whether to use the "dynamic thresholding" in [1].
370
+ max_val: A `float`. Valid when both `predict_x0` and `thresholding` are True. The max value for thresholding.
371
+
372
+ [1] Chitwan Saharia, William Chan, Saurabh Saxena, Lala Li, Jay Whang, Emily Denton, Seyed Kamyar Seyed Ghasemipour, Burcu Karagol Ayan, S Sara Mahdavi, Rapha Gontijo Lopes, et al. Photorealistic text-to-image diffusion models with deep language understanding. arXiv preprint arXiv:2205.11487, 2022b.
373
+ """
374
+ self.model = model_fn
375
+ self.noise_schedule = noise_schedule
376
+ self.predict_x0 = predict_x0
377
+ self.thresholding = thresholding
378
+ self.max_val = max_val
379
+
380
+ def noise_prediction_fn(self, x, t):
381
+ """
382
+ Return the noise prediction model.
383
+ """
384
+ return self.model(x, t)
385
+
386
+ def data_prediction_fn(self, x, t):
387
+ """
388
+ Return the data prediction model (with thresholding).
389
+ """
390
+ noise = self.noise_prediction_fn(x, t)
391
+ dims = x.dim()
392
+ alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t)
393
+ x0 = (x - expand_dims(sigma_t, dims) * noise) / expand_dims(alpha_t, dims)
394
+ if self.thresholding:
395
+ p = 0.995 # A hyperparameter in the paper of "Imagen" [1].
396
+ s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)
397
+ s = expand_dims(torch.maximum(s, self.max_val * torch.ones_like(s).to(s.device)), dims)
398
+ x0 = torch.clamp(x0, -s, s) / s
399
+ return x0
400
+
401
+ def model_fn(self, x, t):
402
+ """
403
+ Convert the model to the noise prediction model or the data prediction model.
404
+ """
405
+ if self.predict_x0:
406
+ return self.data_prediction_fn(x, t)
407
+ else:
408
+ return self.noise_prediction_fn(x, t)
409
+
410
+ def get_time_steps(self, skip_type, t_T, t_0, N, device):
411
+ """Compute the intermediate time steps for sampling.
412
+
413
+ Args:
414
+ skip_type: A `str`. The type for the spacing of the time steps. We support three types:
415
+ - 'logSNR': uniform logSNR for the time steps.
416
+ - 'time_uniform': uniform time for the time steps. (**Recommended for high-resolutional data**.)
417
+ - 'time_quadratic': quadratic time for the time steps. (Used in DDIM for low-resolutional data.)
418
+ t_T: A `float`. The starting time of the sampling (default is T).
419
+ t_0: A `float`. The ending time of the sampling (default is epsilon).
420
+ N: A `int`. The total number of the spacing of the time steps.
421
+ device: A torch device.
422
+ Returns:
423
+ A pytorch tensor of the time steps, with the shape (N + 1,).
424
+ """
425
+ if skip_type == 'logSNR':
426
+ lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device))
427
+ lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device))
428
+ logSNR_steps = torch.linspace(lambda_T.cpu().item(), lambda_0.cpu().item(), N + 1).to(device)
429
+ return self.noise_schedule.inverse_lambda(logSNR_steps)
430
+ elif skip_type == 'time_uniform':
431
+ return torch.linspace(t_T, t_0, N + 1).to(device)
432
+ elif skip_type == 'time_quadratic':
433
+ t_order = 2
434
+ t = torch.linspace(t_T**(1. / t_order), t_0**(1. / t_order), N + 1).pow(t_order).to(device)
435
+ return t
436
+ else:
437
+ raise ValueError("Unsupported skip_type {}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'".format(skip_type))
438
+
439
+ def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device):
440
+ """
441
+ Get the order of each step for sampling by the singlestep DPM-Solver.
442
+
443
+ We combine both DPM-Solver-1,2,3 to use all the function evaluations, which is named as "DPM-Solver-fast".
444
+ Given a fixed number of function evaluations by `steps`, the sampling procedure by DPM-Solver-fast is:
445
+ - If order == 1:
446
+ We take `steps` of DPM-Solver-1 (i.e. DDIM).
447
+ - If order == 2:
448
+ - Denote K = (steps // 2). We take K or (K + 1) intermediate time steps for sampling.
449
+ - If steps % 2 == 0, we use K steps of DPM-Solver-2.
450
+ - If steps % 2 == 1, we use K steps of DPM-Solver-2 and 1 step of DPM-Solver-1.
451
+ - If order == 3:
452
+ - Denote K = (steps // 3 + 1). We take K intermediate time steps for sampling.
453
+ - If steps % 3 == 0, we use (K - 2) steps of DPM-Solver-3, and 1 step of DPM-Solver-2 and 1 step of DPM-Solver-1.
454
+ - If steps % 3 == 1, we use (K - 1) steps of DPM-Solver-3 and 1 step of DPM-Solver-1.
455
+ - If steps % 3 == 2, we use (K - 1) steps of DPM-Solver-3 and 1 step of DPM-Solver-2.
456
+
457
+ ============================================
458
+ Args:
459
+ order: A `int`. The max order for the solver (2 or 3).
460
+ steps: A `int`. The total number of function evaluations (NFE).
461
+ skip_type: A `str`. The type for the spacing of the time steps. We support three types:
462
+ - 'logSNR': uniform logSNR for the time steps.
463
+ - 'time_uniform': uniform time for the time steps. (**Recommended for high-resolutional data**.)
464
+ - 'time_quadratic': quadratic time for the time steps. (Used in DDIM for low-resolutional data.)
465
+ t_T: A `float`. The starting time of the sampling (default is T).
466
+ t_0: A `float`. The ending time of the sampling (default is epsilon).
467
+ device: A torch device.
468
+ Returns:
469
+ orders: A list of the solver order of each step.
470
+ """
471
+ if order == 3:
472
+ K = steps // 3 + 1
473
+ if steps % 3 == 0:
474
+ orders = [3,] * (K - 2) + [2, 1]
475
+ elif steps % 3 == 1:
476
+ orders = [3,] * (K - 1) + [1]
477
+ else:
478
+ orders = [3,] * (K - 1) + [2]
479
+ elif order == 2:
480
+ if steps % 2 == 0:
481
+ K = steps // 2
482
+ orders = [2,] * K
483
+ else:
484
+ K = steps // 2 + 1
485
+ orders = [2,] * (K - 1) + [1]
486
+ elif order == 1:
487
+ K = 1
488
+ orders = [1,] * steps
489
+ else:
490
+ raise ValueError("'order' must be '1' or '2' or '3'.")
491
+ if skip_type == 'logSNR':
492
+ # To reproduce the results in DPM-Solver paper
493
+ timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, K, device)
494
+ else:
495
+ timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, steps, device)[torch.cumsum(torch.tensor([0,] + orders)).to(device)]
496
+ return timesteps_outer, orders
497
+
498
+ def denoise_to_zero_fn(self, x, s):
499
+ """
500
+ Denoise at the final step, which is equivalent to solve the ODE from lambda_s to infty by first-order discretization.
501
+ """
502
+ return self.data_prediction_fn(x, s)
503
+
504
+ def dpm_solver_first_update(self, x, s, t, model_s=None, return_intermediate=False):
505
+ """
506
+ DPM-Solver-1 (equivalent to DDIM) from time `s` to time `t`.
507
+
508
+ Args:
509
+ x: A pytorch tensor. The initial value at time `s`.
510
+ s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
511
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
512
+ model_s: A pytorch tensor. The model function evaluated at time `s`.
513
+ If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
514
+ return_intermediate: A `bool`. If true, also return the model value at time `s`.
515
+ Returns:
516
+ x_t: A pytorch tensor. The approximated solution at time `t`.
517
+ """
518
+ ns = self.noise_schedule
519
+ dims = x.dim()
520
+ lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
521
+ h = lambda_t - lambda_s
522
+ log_alpha_s, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(t)
523
+ sigma_s, sigma_t = ns.marginal_std(s), ns.marginal_std(t)
524
+ alpha_t = torch.exp(log_alpha_t)
525
+
526
+ if self.predict_x0:
527
+ phi_1 = torch.expm1(-h)
528
+ if model_s is None:
529
+ model_s = self.model_fn(x, s)
530
+ x_t = (
531
+ expand_dims(sigma_t / sigma_s, dims) * x
532
+ - expand_dims(alpha_t * phi_1, dims) * model_s
533
+ )
534
+ if return_intermediate:
535
+ return x_t, {'model_s': model_s}
536
+ else:
537
+ return x_t
538
+ else:
539
+ phi_1 = torch.expm1(h)
540
+ if model_s is None:
541
+ model_s = self.model_fn(x, s)
542
+ x_t = (
543
+ expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
544
+ - expand_dims(sigma_t * phi_1, dims) * model_s
545
+ )
546
+ if return_intermediate:
547
+ return x_t, {'model_s': model_s}
548
+ else:
549
+ return x_t
550
+
551
+ def singlestep_dpm_solver_second_update(self, x, s, t, r1=0.5, model_s=None, return_intermediate=False, solver_type='dpm_solver'):
552
+ """
553
+ Singlestep solver DPM-Solver-2 from time `s` to time `t`.
554
+
555
+ Args:
556
+ x: A pytorch tensor. The initial value at time `s`.
557
+ s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
558
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
559
+ r1: A `float`. The hyperparameter of the second-order solver.
560
+ model_s: A pytorch tensor. The model function evaluated at time `s`.
561
+ If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
562
+ return_intermediate: A `bool`. If true, also return the model value at time `s` and `s1` (the intermediate time).
563
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
564
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
565
+ Returns:
566
+ x_t: A pytorch tensor. The approximated solution at time `t`.
567
+ """
568
+ if solver_type not in ['dpm_solver', 'taylor']:
569
+ raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
570
+ if r1 is None:
571
+ r1 = 0.5
572
+ ns = self.noise_schedule
573
+ dims = x.dim()
574
+ lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
575
+ h = lambda_t - lambda_s
576
+ lambda_s1 = lambda_s + r1 * h
577
+ s1 = ns.inverse_lambda(lambda_s1)
578
+ log_alpha_s, log_alpha_s1, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(s1), ns.marginal_log_mean_coeff(t)
579
+ sigma_s, sigma_s1, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(t)
580
+ alpha_s1, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_t)
581
+
582
+ if self.predict_x0:
583
+ phi_11 = torch.expm1(-r1 * h)
584
+ phi_1 = torch.expm1(-h)
585
+
586
+ if model_s is None:
587
+ model_s = self.model_fn(x, s)
588
+ x_s1 = (
589
+ expand_dims(sigma_s1 / sigma_s, dims) * x
590
+ - expand_dims(alpha_s1 * phi_11, dims) * model_s
591
+ )
592
+ model_s1 = self.model_fn(x_s1, s1)
593
+ if solver_type == 'dpm_solver':
594
+ x_t = (
595
+ expand_dims(sigma_t / sigma_s, dims) * x
596
+ - expand_dims(alpha_t * phi_1, dims) * model_s
597
+ - (0.5 / r1) * expand_dims(alpha_t * phi_1, dims) * (model_s1 - model_s)
598
+ )
599
+ elif solver_type == 'taylor':
600
+ x_t = (
601
+ expand_dims(sigma_t / sigma_s, dims) * x
602
+ - expand_dims(alpha_t * phi_1, dims) * model_s
603
+ + (1. / r1) * expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * (model_s1 - model_s)
604
+ )
605
+ else:
606
+ phi_11 = torch.expm1(r1 * h)
607
+ phi_1 = torch.expm1(h)
608
+
609
+ if model_s is None:
610
+ model_s = self.model_fn(x, s)
611
+ x_s1 = (
612
+ expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x
613
+ - expand_dims(sigma_s1 * phi_11, dims) * model_s
614
+ )
615
+ model_s1 = self.model_fn(x_s1, s1)
616
+ if solver_type == 'dpm_solver':
617
+ x_t = (
618
+ expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
619
+ - expand_dims(sigma_t * phi_1, dims) * model_s
620
+ - (0.5 / r1) * expand_dims(sigma_t * phi_1, dims) * (model_s1 - model_s)
621
+ )
622
+ elif solver_type == 'taylor':
623
+ x_t = (
624
+ expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
625
+ - expand_dims(sigma_t * phi_1, dims) * model_s
626
+ - (1. / r1) * expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * (model_s1 - model_s)
627
+ )
628
+ if return_intermediate:
629
+ return x_t, {'model_s': model_s, 'model_s1': model_s1}
630
+ else:
631
+ return x_t
632
+
633
+ def singlestep_dpm_solver_third_update(self, x, s, t, r1=1./3., r2=2./3., model_s=None, model_s1=None, return_intermediate=False, solver_type='dpm_solver'):
634
+ """
635
+ Singlestep solver DPM-Solver-3 from time `s` to time `t`.
636
+
637
+ Args:
638
+ x: A pytorch tensor. The initial value at time `s`.
639
+ s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
640
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
641
+ r1: A `float`. The hyperparameter of the third-order solver.
642
+ r2: A `float`. The hyperparameter of the third-order solver.
643
+ model_s: A pytorch tensor. The model function evaluated at time `s`.
644
+ If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.
645
+ model_s1: A pytorch tensor. The model function evaluated at time `s1` (the intermediate time given by `r1`).
646
+ If `model_s1` is None, we evaluate the model at `s1`; otherwise we directly use it.
647
+ return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times).
648
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
649
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
650
+ Returns:
651
+ x_t: A pytorch tensor. The approximated solution at time `t`.
652
+ """
653
+ if solver_type not in ['dpm_solver', 'taylor']:
654
+ raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
655
+ if r1 is None:
656
+ r1 = 1. / 3.
657
+ if r2 is None:
658
+ r2 = 2. / 3.
659
+ ns = self.noise_schedule
660
+ dims = x.dim()
661
+ lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)
662
+ h = lambda_t - lambda_s
663
+ lambda_s1 = lambda_s + r1 * h
664
+ lambda_s2 = lambda_s + r2 * h
665
+ s1 = ns.inverse_lambda(lambda_s1)
666
+ s2 = ns.inverse_lambda(lambda_s2)
667
+ log_alpha_s, log_alpha_s1, log_alpha_s2, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(s1), ns.marginal_log_mean_coeff(s2), ns.marginal_log_mean_coeff(t)
668
+ sigma_s, sigma_s1, sigma_s2, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(s2), ns.marginal_std(t)
669
+ alpha_s1, alpha_s2, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_s2), torch.exp(log_alpha_t)
670
+
671
+ if self.predict_x0:
672
+ phi_11 = torch.expm1(-r1 * h)
673
+ phi_12 = torch.expm1(-r2 * h)
674
+ phi_1 = torch.expm1(-h)
675
+ phi_22 = torch.expm1(-r2 * h) / (r2 * h) + 1.
676
+ phi_2 = phi_1 / h + 1.
677
+ phi_3 = phi_2 / h - 0.5
678
+
679
+ if model_s is None:
680
+ model_s = self.model_fn(x, s)
681
+ if model_s1 is None:
682
+ x_s1 = (
683
+ expand_dims(sigma_s1 / sigma_s, dims) * x
684
+ - expand_dims(alpha_s1 * phi_11, dims) * model_s
685
+ )
686
+ model_s1 = self.model_fn(x_s1, s1)
687
+ x_s2 = (
688
+ expand_dims(sigma_s2 / sigma_s, dims) * x
689
+ - expand_dims(alpha_s2 * phi_12, dims) * model_s
690
+ + r2 / r1 * expand_dims(alpha_s2 * phi_22, dims) * (model_s1 - model_s)
691
+ )
692
+ model_s2 = self.model_fn(x_s2, s2)
693
+ if solver_type == 'dpm_solver':
694
+ x_t = (
695
+ expand_dims(sigma_t / sigma_s, dims) * x
696
+ - expand_dims(alpha_t * phi_1, dims) * model_s
697
+ + (1. / r2) * expand_dims(alpha_t * phi_2, dims) * (model_s2 - model_s)
698
+ )
699
+ elif solver_type == 'taylor':
700
+ D1_0 = (1. / r1) * (model_s1 - model_s)
701
+ D1_1 = (1. / r2) * (model_s2 - model_s)
702
+ D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1)
703
+ D2 = 2. * (D1_1 - D1_0) / (r2 - r1)
704
+ x_t = (
705
+ expand_dims(sigma_t / sigma_s, dims) * x
706
+ - expand_dims(alpha_t * phi_1, dims) * model_s
707
+ + expand_dims(alpha_t * phi_2, dims) * D1
708
+ - expand_dims(alpha_t * phi_3, dims) * D2
709
+ )
710
+ else:
711
+ phi_11 = torch.expm1(r1 * h)
712
+ phi_12 = torch.expm1(r2 * h)
713
+ phi_1 = torch.expm1(h)
714
+ phi_22 = torch.expm1(r2 * h) / (r2 * h) - 1.
715
+ phi_2 = phi_1 / h - 1.
716
+ phi_3 = phi_2 / h - 0.5
717
+
718
+ if model_s is None:
719
+ model_s = self.model_fn(x, s)
720
+ if model_s1 is None:
721
+ x_s1 = (
722
+ expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x
723
+ - expand_dims(sigma_s1 * phi_11, dims) * model_s
724
+ )
725
+ model_s1 = self.model_fn(x_s1, s1)
726
+ x_s2 = (
727
+ expand_dims(torch.exp(log_alpha_s2 - log_alpha_s), dims) * x
728
+ - expand_dims(sigma_s2 * phi_12, dims) * model_s
729
+ - r2 / r1 * expand_dims(sigma_s2 * phi_22, dims) * (model_s1 - model_s)
730
+ )
731
+ model_s2 = self.model_fn(x_s2, s2)
732
+ if solver_type == 'dpm_solver':
733
+ x_t = (
734
+ expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
735
+ - expand_dims(sigma_t * phi_1, dims) * model_s
736
+ - (1. / r2) * expand_dims(sigma_t * phi_2, dims) * (model_s2 - model_s)
737
+ )
738
+ elif solver_type == 'taylor':
739
+ D1_0 = (1. / r1) * (model_s1 - model_s)
740
+ D1_1 = (1. / r2) * (model_s2 - model_s)
741
+ D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1)
742
+ D2 = 2. * (D1_1 - D1_0) / (r2 - r1)
743
+ x_t = (
744
+ expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x
745
+ - expand_dims(sigma_t * phi_1, dims) * model_s
746
+ - expand_dims(sigma_t * phi_2, dims) * D1
747
+ - expand_dims(sigma_t * phi_3, dims) * D2
748
+ )
749
+
750
+ if return_intermediate:
751
+ return x_t, {'model_s': model_s, 'model_s1': model_s1, 'model_s2': model_s2}
752
+ else:
753
+ return x_t
754
+
755
+ def multistep_dpm_solver_second_update(self, x, model_prev_list, t_prev_list, t, solver_type="dpm_solver"):
756
+ """
757
+ Multistep solver DPM-Solver-2 from time `t_prev_list[-1]` to time `t`.
758
+
759
+ Args:
760
+ x: A pytorch tensor. The initial value at time `s`.
761
+ model_prev_list: A list of pytorch tensor. The previous computed model values.
762
+ t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)
763
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
764
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
765
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
766
+ Returns:
767
+ x_t: A pytorch tensor. The approximated solution at time `t`.
768
+ """
769
+ if solver_type not in ['dpm_solver', 'taylor']:
770
+ raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type))
771
+ ns = self.noise_schedule
772
+ dims = x.dim()
773
+ model_prev_1, model_prev_0 = model_prev_list
774
+ t_prev_1, t_prev_0 = t_prev_list
775
+ lambda_prev_1, lambda_prev_0, lambda_t = ns.marginal_lambda(t_prev_1), ns.marginal_lambda(t_prev_0), ns.marginal_lambda(t)
776
+ log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
777
+ sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
778
+ alpha_t = torch.exp(log_alpha_t)
779
+
780
+ h_0 = lambda_prev_0 - lambda_prev_1
781
+ h = lambda_t - lambda_prev_0
782
+ r0 = h_0 / h
783
+ D1_0 = expand_dims(1. / r0, dims) * (model_prev_0 - model_prev_1)
784
+ if self.predict_x0:
785
+ if solver_type == 'dpm_solver':
786
+ x_t = (
787
+ expand_dims(sigma_t / sigma_prev_0, dims) * x
788
+ - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0
789
+ - 0.5 * expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * D1_0
790
+ )
791
+ elif solver_type == 'taylor':
792
+ x_t = (
793
+ expand_dims(sigma_t / sigma_prev_0, dims) * x
794
+ - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0
795
+ + expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * D1_0
796
+ )
797
+ else:
798
+ if solver_type == 'dpm_solver':
799
+ x_t = (
800
+ expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
801
+ - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0
802
+ - 0.5 * expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * D1_0
803
+ )
804
+ elif solver_type == 'taylor':
805
+ x_t = (
806
+ expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
807
+ - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0
808
+ - expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * D1_0
809
+ )
810
+ return x_t
811
+
812
+ def multistep_dpm_solver_third_update(self, x, model_prev_list, t_prev_list, t, solver_type='dpm_solver'):
813
+ """
814
+ Multistep solver DPM-Solver-3 from time `t_prev_list[-1]` to time `t`.
815
+
816
+ Args:
817
+ x: A pytorch tensor. The initial value at time `s`.
818
+ model_prev_list: A list of pytorch tensor. The previous computed model values.
819
+ t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)
820
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
821
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
822
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
823
+ Returns:
824
+ x_t: A pytorch tensor. The approximated solution at time `t`.
825
+ """
826
+ ns = self.noise_schedule
827
+ dims = x.dim()
828
+ model_prev_2, model_prev_1, model_prev_0 = model_prev_list
829
+ t_prev_2, t_prev_1, t_prev_0 = t_prev_list
830
+ lambda_prev_2, lambda_prev_1, lambda_prev_0, lambda_t = ns.marginal_lambda(t_prev_2), ns.marginal_lambda(t_prev_1), ns.marginal_lambda(t_prev_0), ns.marginal_lambda(t)
831
+ log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
832
+ sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
833
+ alpha_t = torch.exp(log_alpha_t)
834
+
835
+ h_1 = lambda_prev_1 - lambda_prev_2
836
+ h_0 = lambda_prev_0 - lambda_prev_1
837
+ h = lambda_t - lambda_prev_0
838
+ r0, r1 = h_0 / h, h_1 / h
839
+ D1_0 = expand_dims(1. / r0, dims) * (model_prev_0 - model_prev_1)
840
+ D1_1 = expand_dims(1. / r1, dims) * (model_prev_1 - model_prev_2)
841
+ D1 = D1_0 + expand_dims(r0 / (r0 + r1), dims) * (D1_0 - D1_1)
842
+ D2 = expand_dims(1. / (r0 + r1), dims) * (D1_0 - D1_1)
843
+ if self.predict_x0:
844
+ x_t = (
845
+ expand_dims(sigma_t / sigma_prev_0, dims) * x
846
+ - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0
847
+ + expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * D1
848
+ - expand_dims(alpha_t * ((torch.exp(-h) - 1. + h) / h**2 - 0.5), dims) * D2
849
+ )
850
+ else:
851
+ x_t = (
852
+ expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
853
+ - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0
854
+ - expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * D1
855
+ - expand_dims(sigma_t * ((torch.exp(h) - 1. - h) / h**2 - 0.5), dims) * D2
856
+ )
857
+ return x_t
858
+
859
+ def singlestep_dpm_solver_update(self, x, s, t, order, return_intermediate=False, solver_type='dpm_solver', r1=None, r2=None):
860
+ """
861
+ Singlestep DPM-Solver with the order `order` from time `s` to time `t`.
862
+
863
+ Args:
864
+ x: A pytorch tensor. The initial value at time `s`.
865
+ s: A pytorch tensor. The starting time, with the shape (x.shape[0],).
866
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
867
+ order: A `int`. The order of DPM-Solver. We only support order == 1 or 2 or 3.
868
+ return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times).
869
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
870
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
871
+ r1: A `float`. The hyperparameter of the second-order or third-order solver.
872
+ r2: A `float`. The hyperparameter of the third-order solver.
873
+ Returns:
874
+ x_t: A pytorch tensor. The approximated solution at time `t`.
875
+ """
876
+ if order == 1:
877
+ return self.dpm_solver_first_update(x, s, t, return_intermediate=return_intermediate)
878
+ elif order == 2:
879
+ return self.singlestep_dpm_solver_second_update(x, s, t, return_intermediate=return_intermediate, solver_type=solver_type, r1=r1)
880
+ elif order == 3:
881
+ return self.singlestep_dpm_solver_third_update(x, s, t, return_intermediate=return_intermediate, solver_type=solver_type, r1=r1, r2=r2)
882
+ else:
883
+ raise ValueError("Solver order must be 1 or 2 or 3, got {}".format(order))
884
+
885
+ def multistep_dpm_solver_update(self, x, model_prev_list, t_prev_list, t, order, solver_type='dpm_solver'):
886
+ """
887
+ Multistep DPM-Solver with the order `order` from time `t_prev_list[-1]` to time `t`.
888
+
889
+ Args:
890
+ x: A pytorch tensor. The initial value at time `s`.
891
+ model_prev_list: A list of pytorch tensor. The previous computed model values.
892
+ t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)
893
+ t: A pytorch tensor. The ending time, with the shape (x.shape[0],).
894
+ order: A `int`. The order of DPM-Solver. We only support order == 1 or 2 or 3.
895
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
896
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
897
+ Returns:
898
+ x_t: A pytorch tensor. The approximated solution at time `t`.
899
+ """
900
+ if order == 1:
901
+ return self.dpm_solver_first_update(x, t_prev_list[-1], t, model_s=model_prev_list[-1])
902
+ elif order == 2:
903
+ return self.multistep_dpm_solver_second_update(x, model_prev_list, t_prev_list, t, solver_type=solver_type)
904
+ elif order == 3:
905
+ return self.multistep_dpm_solver_third_update(x, model_prev_list, t_prev_list, t, solver_type=solver_type)
906
+ else:
907
+ raise ValueError("Solver order must be 1 or 2 or 3, got {}".format(order))
908
+
909
+ def dpm_solver_adaptive(self, x, order, t_T, t_0, h_init=0.05, atol=0.0078, rtol=0.05, theta=0.9, t_err=1e-5, solver_type='dpm_solver'):
910
+ """
911
+ The adaptive step size solver based on singlestep DPM-Solver.
912
+
913
+ Args:
914
+ x: A pytorch tensor. The initial value at time `t_T`.
915
+ order: A `int`. The (higher) order of the solver. We only support order == 2 or 3.
916
+ t_T: A `float`. The starting time of the sampling (default is T).
917
+ t_0: A `float`. The ending time of the sampling (default is epsilon).
918
+ h_init: A `float`. The initial step size (for logSNR).
919
+ atol: A `float`. The absolute tolerance of the solver. For image data, the default setting is 0.0078, followed [1].
920
+ rtol: A `float`. The relative tolerance of the solver. The default setting is 0.05.
921
+ theta: A `float`. The safety hyperparameter for adapting the step size. The default setting is 0.9, followed [1].
922
+ t_err: A `float`. The tolerance for the time. We solve the diffusion ODE until the absolute error between the
923
+ current time and `t_0` is less than `t_err`. The default setting is 1e-5.
924
+ solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.
925
+ The type slightly impacts the performance. We recommend to use 'dpm_solver' type.
926
+ Returns:
927
+ x_0: A pytorch tensor. The approximated solution at time `t_0`.
928
+
929
+ [1] A. Jolicoeur-Martineau, K. Li, R. Piché-Taillefer, T. Kachman, and I. Mitliagkas, "Gotta go fast when generating data with score-based models," arXiv preprint arXiv:2105.14080, 2021.
930
+ """
931
+ ns = self.noise_schedule
932
+ s = t_T * torch.ones((x.shape[0],)).to(x)
933
+ lambda_s = ns.marginal_lambda(s)
934
+ lambda_0 = ns.marginal_lambda(t_0 * torch.ones_like(s).to(x))
935
+ h = h_init * torch.ones_like(s).to(x)
936
+ x_prev = x
937
+ nfe = 0
938
+ if order == 2:
939
+ r1 = 0.5
940
+ lower_update = lambda x, s, t: self.dpm_solver_first_update(x, s, t, return_intermediate=True)
941
+ higher_update = lambda x, s, t, **kwargs: self.singlestep_dpm_solver_second_update(x, s, t, r1=r1, solver_type=solver_type, **kwargs)
942
+ elif order == 3:
943
+ r1, r2 = 1. / 3., 2. / 3.
944
+ lower_update = lambda x, s, t: self.singlestep_dpm_solver_second_update(x, s, t, r1=r1, return_intermediate=True, solver_type=solver_type)
945
+ higher_update = lambda x, s, t, **kwargs: self.singlestep_dpm_solver_third_update(x, s, t, r1=r1, r2=r2, solver_type=solver_type, **kwargs)
946
+ else:
947
+ raise ValueError("For adaptive step size solver, order must be 2 or 3, got {}".format(order))
948
+ while torch.abs((s - t_0)).mean() > t_err:
949
+ t = ns.inverse_lambda(lambda_s + h)
950
+ x_lower, lower_noise_kwargs = lower_update(x, s, t)
951
+ x_higher = higher_update(x, s, t, **lower_noise_kwargs)
952
+ delta = torch.max(torch.ones_like(x).to(x) * atol, rtol * torch.max(torch.abs(x_lower), torch.abs(x_prev)))
953
+ norm_fn = lambda v: torch.sqrt(torch.square(v.reshape((v.shape[0], -1))).mean(dim=-1, keepdim=True))
954
+ E = norm_fn((x_higher - x_lower) / delta).max()
955
+ if torch.all(E <= 1.):
956
+ x = x_higher
957
+ s = t
958
+ x_prev = x_lower
959
+ lambda_s = ns.marginal_lambda(s)
960
+ h = torch.min(theta * h * torch.float_power(E, -1. / order).float(), lambda_0 - lambda_s)
961
+ nfe += order
962
+ print('adaptive solver nfe', nfe)
963
+ return x
964
+
965
+ def sample(self, x, steps=20, t_start=None, t_end=None, order=3, skip_type='time_uniform',
966
+ method='singlestep', lower_order_final=True, denoise_to_zero=False, solver_type='dpm_solver',
967
+ atol=0.0078, rtol=0.05,
968
+ ):
969
+ """
970
+ Compute the sample at time `t_end` by DPM-Solver, given the initial `x` at time `t_start`.
971
+
972
+ =====================================================
973
+
974
+ We support the following algorithms for both noise prediction model and data prediction model:
975
+ - 'singlestep':
976
+ Singlestep DPM-Solver (i.e. "DPM-Solver-fast" in the paper), which combines different orders of singlestep DPM-Solver.
977
+ We combine all the singlestep solvers with order <= `order` to use up all the function evaluations (steps).
978
+ The total number of function evaluations (NFE) == `steps`.
979
+ Given a fixed NFE == `steps`, the sampling procedure is:
980
+ - If `order` == 1:
981
+ - Denote K = steps. We use K steps of DPM-Solver-1 (i.e. DDIM).
982
+ - If `order` == 2:
983
+ - Denote K = (steps // 2) + (steps % 2). We take K intermediate time steps for sampling.
984
+ - If steps % 2 == 0, we use K steps of singlestep DPM-Solver-2.
985
+ - If steps % 2 == 1, we use (K - 1) steps of singlestep DPM-Solver-2 and 1 step of DPM-Solver-1.
986
+ - If `order` == 3:
987
+ - Denote K = (steps // 3 + 1). We take K intermediate time steps for sampling.
988
+ - If steps % 3 == 0, we use (K - 2) steps of singlestep DPM-Solver-3, and 1 step of singlestep DPM-Solver-2 and 1 step of DPM-Solver-1.
989
+ - If steps % 3 == 1, we use (K - 1) steps of singlestep DPM-Solver-3 and 1 step of DPM-Solver-1.
990
+ - If steps % 3 == 2, we use (K - 1) steps of singlestep DPM-Solver-3 and 1 step of singlestep DPM-Solver-2.
991
+ - 'multistep':
992
+ Multistep DPM-Solver with the order of `order`. The total number of function evaluations (NFE) == `steps`.
993
+ We initialize the first `order` values by lower order multistep solvers.
994
+ Given a fixed NFE == `steps`, the sampling procedure is:
995
+ Denote K = steps.
996
+ - If `order` == 1:
997
+ - We use K steps of DPM-Solver-1 (i.e. DDIM).
998
+ - If `order` == 2:
999
+ - We firstly use 1 step of DPM-Solver-1, then use (K - 1) step of multistep DPM-Solver-2.
1000
+ - If `order` == 3:
1001
+ - We firstly use 1 step of DPM-Solver-1, then 1 step of multistep DPM-Solver-2, then (K - 2) step of multistep DPM-Solver-3.
1002
+ - 'singlestep_fixed':
1003
+ Fixed order singlestep DPM-Solver (i.e. DPM-Solver-1 or singlestep DPM-Solver-2 or singlestep DPM-Solver-3).
1004
+ We use singlestep DPM-Solver-`order` for `order`=1 or 2 or 3, with total [`steps` // `order`] * `order` NFE.
1005
+ - 'adaptive':
1006
+ Adaptive step size DPM-Solver (i.e. "DPM-Solver-12" and "DPM-Solver-23" in the paper).
1007
+ We ignore `steps` and use adaptive step size DPM-Solver with a higher order of `order`.
1008
+ You can adjust the absolute tolerance `atol` and the relative tolerance `rtol` to balance the computatation costs
1009
+ (NFE) and the sample quality.
1010
+ - If `order` == 2, we use DPM-Solver-12 which combines DPM-Solver-1 and singlestep DPM-Solver-2.
1011
+ - If `order` == 3, we use DPM-Solver-23 which combines singlestep DPM-Solver-2 and singlestep DPM-Solver-3.
1012
+
1013
+ =====================================================
1014
+
1015
+ Some advices for choosing the algorithm:
1016
+ - For **unconditional sampling** or **guided sampling with small guidance scale** by DPMs:
1017
+ Use singlestep DPM-Solver ("DPM-Solver-fast" in the paper) with `order = 3`.
1018
+ e.g.
1019
+ >>> dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=False)
1020
+ >>> x_sample = dpm_solver.sample(x, steps=steps, t_start=t_start, t_end=t_end, order=3,
1021
+ skip_type='time_uniform', method='singlestep')
1022
+ - For **guided sampling with large guidance scale** by DPMs:
1023
+ Use multistep DPM-Solver with `predict_x0 = True` and `order = 2`.
1024
+ e.g.
1025
+ >>> dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=True)
1026
+ >>> x_sample = dpm_solver.sample(x, steps=steps, t_start=t_start, t_end=t_end, order=2,
1027
+ skip_type='time_uniform', method='multistep')
1028
+
1029
+ We support three types of `skip_type`:
1030
+ - 'logSNR': uniform logSNR for the time steps. **Recommended for low-resolutional images**
1031
+ - 'time_uniform': uniform time for the time steps. **Recommended for high-resolutional images**.
1032
+ - 'time_quadratic': quadratic time for the time steps.
1033
+
1034
+ =====================================================
1035
+ Args:
1036
+ x: A pytorch tensor. The initial value at time `t_start`
1037
+ e.g. if `t_start` == T, then `x` is a sample from the standard normal distribution.
1038
+ steps: A `int`. The total number of function evaluations (NFE).
1039
+ t_start: A `float`. The starting time of the sampling.
1040
+ If `T` is None, we use self.noise_schedule.T (default is 1.0).
1041
+ t_end: A `float`. The ending time of the sampling.
1042
+ If `t_end` is None, we use 1. / self.noise_schedule.total_N.
1043
+ e.g. if total_N == 1000, we have `t_end` == 1e-3.
1044
+ For discrete-time DPMs:
1045
+ - We recommend `t_end` == 1. / self.noise_schedule.total_N.
1046
+ For continuous-time DPMs:
1047
+ - We recommend `t_end` == 1e-3 when `steps` <= 15; and `t_end` == 1e-4 when `steps` > 15.
1048
+ order: A `int`. The order of DPM-Solver.
1049
+ skip_type: A `str`. The type for the spacing of the time steps. 'time_uniform' or 'logSNR' or 'time_quadratic'.
1050
+ method: A `str`. The method for sampling. 'singlestep' or 'multistep' or 'singlestep_fixed' or 'adaptive'.
1051
+ denoise_to_zero: A `bool`. Whether to denoise to time 0 at the final step.
1052
+ Default is `False`. If `denoise_to_zero` is `True`, the total NFE is (`steps` + 1).
1053
+
1054
+ This trick is firstly proposed by DDPM (https://arxiv.org/abs/2006.11239) and
1055
+ score_sde (https://arxiv.org/abs/2011.13456). Such trick can improve the FID
1056
+ for diffusion models sampling by diffusion SDEs for low-resolutional images
1057
+ (such as CIFAR-10). However, we observed that such trick does not matter for
1058
+ high-resolutional images. As it needs an additional NFE, we do not recommend
1059
+ it for high-resolutional images.
1060
+ lower_order_final: A `bool`. Whether to use lower order solvers at the final steps.
1061
+ Only valid for `method=multistep` and `steps < 15`. We empirically find that
1062
+ this trick is a key to stabilizing the sampling by DPM-Solver with very few steps
1063
+ (especially for steps <= 10). So we recommend to set it to be `True`.
1064
+ solver_type: A `str`. The taylor expansion type for the solver. `dpm_solver` or `taylor`. We recommend `dpm_solver`.
1065
+ atol: A `float`. The absolute tolerance of the adaptive step size solver. Valid when `method` == 'adaptive'.
1066
+ rtol: A `float`. The relative tolerance of the adaptive step size solver. Valid when `method` == 'adaptive'.
1067
+ Returns:
1068
+ x_end: A pytorch tensor. The approximated solution at time `t_end`.
1069
+
1070
+ """
1071
+ t_0 = 1. / self.noise_schedule.total_N if t_end is None else t_end
1072
+ t_T = self.noise_schedule.T if t_start is None else t_start
1073
+ device = x.device
1074
+ if method == 'adaptive':
1075
+ with torch.no_grad():
1076
+ x = self.dpm_solver_adaptive(x, order=order, t_T=t_T, t_0=t_0, atol=atol, rtol=rtol, solver_type=solver_type)
1077
+ elif method == 'multistep':
1078
+ assert steps >= order
1079
+ timesteps = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=steps, device=device)
1080
+ assert timesteps.shape[0] - 1 == steps
1081
+ with torch.no_grad():
1082
+ vec_t = timesteps[0].expand((x.shape[0]))
1083
+ model_prev_list = [self.model_fn(x, vec_t)]
1084
+ t_prev_list = [vec_t]
1085
+ # Init the first `order` values by lower order multistep DPM-Solver.
1086
+ for init_order in range(1, order):
1087
+ vec_t = timesteps[init_order].expand(x.shape[0])
1088
+ x = self.multistep_dpm_solver_update(x, model_prev_list, t_prev_list, vec_t, init_order, solver_type=solver_type)
1089
+ model_prev_list.append(self.model_fn(x, vec_t))
1090
+ t_prev_list.append(vec_t)
1091
+ # Compute the remaining values by `order`-th order multistep DPM-Solver.
1092
+ for step in range(order, steps + 1):
1093
+ vec_t = timesteps[step].expand(x.shape[0])
1094
+ if lower_order_final and steps < 15:
1095
+ step_order = min(order, steps + 1 - step)
1096
+ else:
1097
+ step_order = order
1098
+ x = self.multistep_dpm_solver_update(x, model_prev_list, t_prev_list, vec_t, step_order, solver_type=solver_type)
1099
+ for i in range(order - 1):
1100
+ t_prev_list[i] = t_prev_list[i + 1]
1101
+ model_prev_list[i] = model_prev_list[i + 1]
1102
+ t_prev_list[-1] = vec_t
1103
+ # We do not need to evaluate the final model value.
1104
+ if step < steps:
1105
+ model_prev_list[-1] = self.model_fn(x, vec_t)
1106
+ elif method in ['singlestep', 'singlestep_fixed']:
1107
+ if method == 'singlestep':
1108
+ timesteps_outer, orders = self.get_orders_and_timesteps_for_singlestep_solver(steps=steps, order=order, skip_type=skip_type, t_T=t_T, t_0=t_0, device=device)
1109
+ elif method == 'singlestep_fixed':
1110
+ K = steps // order
1111
+ orders = [order,] * K
1112
+ timesteps_outer = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=K, device=device)
1113
+ for i, order in enumerate(orders):
1114
+ t_T_inner, t_0_inner = timesteps_outer[i], timesteps_outer[i + 1]
1115
+ timesteps_inner = self.get_time_steps(skip_type=skip_type, t_T=t_T_inner.item(), t_0=t_0_inner.item(), N=order, device=device)
1116
+ lambda_inner = self.noise_schedule.marginal_lambda(timesteps_inner)
1117
+ vec_s, vec_t = t_T_inner.tile(x.shape[0]), t_0_inner.tile(x.shape[0])
1118
+ h = lambda_inner[-1] - lambda_inner[0]
1119
+ r1 = None if order <= 1 else (lambda_inner[1] - lambda_inner[0]) / h
1120
+ r2 = None if order <= 2 else (lambda_inner[2] - lambda_inner[0]) / h
1121
+ x = self.singlestep_dpm_solver_update(x, vec_s, vec_t, order, solver_type=solver_type, r1=r1, r2=r2)
1122
+ if denoise_to_zero:
1123
+ x = self.denoise_to_zero_fn(x, torch.ones((x.shape[0],)).to(device) * t_0)
1124
+ return x
1125
+
1126
+
1127
+
1128
+ #############################################################
1129
+ # other utility functions
1130
+ #############################################################
1131
+
1132
+ def interpolate_fn(x, xp, yp):
1133
+ """
1134
+ A piecewise linear function y = f(x), using xp and yp as keypoints.
1135
+ We implement f(x) in a differentiable way (i.e. applicable for autograd).
1136
+ The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the linear function.)
1137
+
1138
+ Args:
1139
+ x: PyTorch tensor with shape [N, C], where N is the batch size, C is the number of channels (we use C = 1 for DPM-Solver).
1140
+ xp: PyTorch tensor with shape [C, K], where K is the number of keypoints.
1141
+ yp: PyTorch tensor with shape [C, K].
1142
+ Returns:
1143
+ The function values f(x), with shape [N, C].
1144
+ """
1145
+ N, K = x.shape[0], xp.shape[1]
1146
+ all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2)
1147
+ sorted_all_x, x_indices = torch.sort(all_x, dim=2)
1148
+ x_idx = torch.argmin(x_indices, dim=2)
1149
+ cand_start_idx = x_idx - 1
1150
+ start_idx = torch.where(
1151
+ torch.eq(x_idx, 0),
1152
+ torch.tensor(1, device=x.device),
1153
+ torch.where(
1154
+ torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
1155
+ ),
1156
+ )
1157
+ end_idx = torch.where(torch.eq(start_idx, cand_start_idx), start_idx + 2, start_idx + 1)
1158
+ start_x = torch.gather(sorted_all_x, dim=2, index=start_idx.unsqueeze(2)).squeeze(2)
1159
+ end_x = torch.gather(sorted_all_x, dim=2, index=end_idx.unsqueeze(2)).squeeze(2)
1160
+ start_idx2 = torch.where(
1161
+ torch.eq(x_idx, 0),
1162
+ torch.tensor(0, device=x.device),
1163
+ torch.where(
1164
+ torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
1165
+ ),
1166
+ )
1167
+ y_positions_expanded = yp.unsqueeze(0).expand(N, -1, -1)
1168
+ start_y = torch.gather(y_positions_expanded, dim=2, index=start_idx2.unsqueeze(2)).squeeze(2)
1169
+ end_y = torch.gather(y_positions_expanded, dim=2, index=(start_idx2 + 1).unsqueeze(2)).squeeze(2)
1170
+ cand = start_y + (x - start_x) * (end_y - start_y) / (end_x - start_x)
1171
+ return cand
1172
+
1173
+
1174
+ def expand_dims(v, dims):
1175
+ """
1176
+ Expand the tensor `v` to the dim `dims`.
1177
+
1178
+ Args:
1179
+ `v`: a PyTorch tensor with shape [N].
1180
+ `dim`: a `int`.
1181
+ Returns:
1182
+ a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`.
1183
+ """
1184
+ return v[(...,) + (None,)*(dims - 1)]
stable_diffusion/ldm/models/diffusion/dpm_solver/sampler.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SAMPLING ONLY."""
2
+
3
+ import torch
4
+
5
+ from .dpm_solver import NoiseScheduleVP, model_wrapper, DPM_Solver
6
+
7
+
8
+ class DPMSolverSampler(object):
9
+ def __init__(self, model, **kwargs):
10
+ super().__init__()
11
+ self.model = model
12
+ to_torch = lambda x: x.clone().detach().to(torch.float32).to(model.device)
13
+ self.register_buffer('alphas_cumprod', to_torch(model.alphas_cumprod))
14
+
15
+ def register_buffer(self, name, attr):
16
+ if type(attr) == torch.Tensor:
17
+ if attr.device != torch.device("cuda"):
18
+ attr = attr.to(torch.device("cuda"))
19
+ setattr(self, name, attr)
20
+
21
+ @torch.no_grad()
22
+ def sample(self,
23
+ S,
24
+ batch_size,
25
+ shape,
26
+ conditioning=None,
27
+ callback=None,
28
+ normals_sequence=None,
29
+ img_callback=None,
30
+ quantize_x0=False,
31
+ eta=0.,
32
+ mask=None,
33
+ x0=None,
34
+ temperature=1.,
35
+ noise_dropout=0.,
36
+ score_corrector=None,
37
+ corrector_kwargs=None,
38
+ verbose=True,
39
+ x_T=None,
40
+ log_every_t=100,
41
+ unconditional_guidance_scale=1.,
42
+ unconditional_conditioning=None,
43
+ # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
44
+ **kwargs
45
+ ):
46
+ if conditioning is not None:
47
+ if isinstance(conditioning, dict):
48
+ cbs = conditioning[list(conditioning.keys())[0]].shape[0]
49
+ if cbs != batch_size:
50
+ print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
51
+ else:
52
+ if conditioning.shape[0] != batch_size:
53
+ print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
54
+
55
+ # sampling
56
+ C, H, W = shape
57
+ size = (batch_size, C, H, W)
58
+
59
+ # print(f'Data shape for DPM-Solver sampling is {size}, sampling steps {S}')
60
+
61
+ device = self.model.betas.device
62
+ if x_T is None:
63
+ img = torch.randn(size, device=device)
64
+ else:
65
+ img = x_T
66
+
67
+ ns = NoiseScheduleVP('discrete', alphas_cumprod=self.alphas_cumprod)
68
+
69
+ model_fn = model_wrapper(
70
+ lambda x, t, c: self.model.apply_model(x, t, c),
71
+ ns,
72
+ model_type="noise",
73
+ guidance_type="classifier-free",
74
+ condition=conditioning,
75
+ unconditional_condition=unconditional_conditioning,
76
+ guidance_scale=unconditional_guidance_scale,
77
+ )
78
+
79
+ dpm_solver = DPM_Solver(model_fn, ns, predict_x0=True, thresholding=False)
80
+ x = dpm_solver.sample(img, steps=S, skip_type="time_uniform", method="multistep", order=2, lower_order_final=True)
81
+
82
+ return x.to(device), None
stable_diffusion/ldm/models/diffusion/plms.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SAMPLING ONLY."""
2
+
3
+ import torch
4
+ import numpy as np
5
+ from tqdm import tqdm
6
+ from functools import partial
7
+
8
+ from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like
9
+
10
+
11
+ class PLMSSampler(object):
12
+ def __init__(self, model, schedule="linear", **kwargs):
13
+ super().__init__()
14
+ self.model = model
15
+ self.ddpm_num_timesteps = model.num_timesteps
16
+ self.schedule = schedule
17
+
18
+ def register_buffer(self, name, attr):
19
+ if type(attr) == torch.Tensor:
20
+ if attr.device != torch.device("cuda"):
21
+ attr = attr.to(torch.device("cuda"))
22
+ setattr(self, name, attr)
23
+
24
+ def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
25
+ if ddim_eta != 0:
26
+ raise ValueError('ddim_eta must be 0 for PLMS')
27
+ self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
28
+ num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
29
+ alphas_cumprod = self.model.alphas_cumprod
30
+ assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
31
+ to_torch = lambda x: x.clone().detach().to(torch.float32).to(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
+ unconditional_guidance_scale=1.,
78
+ unconditional_conditioning=None,
79
+ # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
80
+ **kwargs
81
+ ):
82
+ if conditioning is not None:
83
+ if isinstance(conditioning, dict):
84
+ cbs = conditioning[list(conditioning.keys())[0]].shape[0]
85
+ if cbs != batch_size:
86
+ print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
87
+ else:
88
+ if conditioning.shape[0] != batch_size:
89
+ print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
90
+
91
+ self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
92
+ # sampling
93
+ C, H, W = shape
94
+ size = (batch_size, C, H, W)
95
+ print(f'Data shape for PLMS sampling is {size}')
96
+
97
+ samples, intermediates = self.plms_sampling(conditioning, size,
98
+ callback=callback,
99
+ img_callback=img_callback,
100
+ quantize_denoised=quantize_x0,
101
+ mask=mask, x0=x0,
102
+ ddim_use_original_steps=False,
103
+ noise_dropout=noise_dropout,
104
+ temperature=temperature,
105
+ score_corrector=score_corrector,
106
+ corrector_kwargs=corrector_kwargs,
107
+ x_T=x_T,
108
+ log_every_t=log_every_t,
109
+ unconditional_guidance_scale=unconditional_guidance_scale,
110
+ unconditional_conditioning=unconditional_conditioning,
111
+ )
112
+ return samples, intermediates
113
+
114
+ @torch.no_grad()
115
+ def plms_sampling(self, cond, shape,
116
+ x_T=None, ddim_use_original_steps=False,
117
+ callback=None, timesteps=None, quantize_denoised=False,
118
+ mask=None, x0=None, img_callback=None, log_every_t=100,
119
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
120
+ unconditional_guidance_scale=1., unconditional_conditioning=None,):
121
+ device = self.model.betas.device
122
+ b = shape[0]
123
+ if x_T is None:
124
+ img = torch.randn(shape, device=device)
125
+ else:
126
+ img = x_T
127
+
128
+ if timesteps is None:
129
+ timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
130
+ elif timesteps is not None and not ddim_use_original_steps:
131
+ subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
132
+ timesteps = self.ddim_timesteps[:subset_end]
133
+
134
+ intermediates = {'x_inter': [img], 'pred_x0': [img]}
135
+ time_range = list(reversed(range(0,timesteps))) if ddim_use_original_steps else np.flip(timesteps)
136
+ total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
137
+ print(f"Running PLMS Sampling with {total_steps} timesteps")
138
+
139
+ iterator = tqdm(time_range, desc='PLMS Sampler', total=total_steps)
140
+ old_eps = []
141
+
142
+ for i, step in enumerate(iterator):
143
+ index = total_steps - i - 1
144
+ ts = torch.full((b,), step, device=device, dtype=torch.long)
145
+ ts_next = torch.full((b,), time_range[min(i + 1, len(time_range) - 1)], device=device, dtype=torch.long)
146
+
147
+ if mask is not None:
148
+ assert x0 is not None
149
+ img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
150
+ img = img_orig * mask + (1. - mask) * img
151
+
152
+ outs = self.p_sample_plms(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
153
+ quantize_denoised=quantize_denoised, temperature=temperature,
154
+ noise_dropout=noise_dropout, score_corrector=score_corrector,
155
+ corrector_kwargs=corrector_kwargs,
156
+ unconditional_guidance_scale=unconditional_guidance_scale,
157
+ unconditional_conditioning=unconditional_conditioning,
158
+ old_eps=old_eps, t_next=ts_next)
159
+ img, pred_x0, e_t = outs
160
+ old_eps.append(e_t)
161
+ if len(old_eps) >= 4:
162
+ old_eps.pop(0)
163
+ if callback: callback(i)
164
+ if img_callback: img_callback(pred_x0, i)
165
+
166
+ if index % log_every_t == 0 or index == total_steps - 1:
167
+ intermediates['x_inter'].append(img)
168
+ intermediates['pred_x0'].append(pred_x0)
169
+
170
+ return img, intermediates
171
+
172
+ @torch.no_grad()
173
+ def p_sample_plms(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
174
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
175
+ unconditional_guidance_scale=1., unconditional_conditioning=None, old_eps=None, t_next=None):
176
+ b, *_, device = *x.shape, x.device
177
+
178
+ def get_model_output(x, t):
179
+ if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
180
+ e_t = self.model.apply_model(x, t, c)
181
+ else:
182
+ x_in = torch.cat([x] * 2)
183
+ t_in = torch.cat([t] * 2)
184
+ c_in = torch.cat([unconditional_conditioning, c])
185
+ e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)
186
+ e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)
187
+
188
+ if score_corrector is not None:
189
+ assert self.model.parameterization == "eps"
190
+ e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
191
+
192
+ return e_t
193
+
194
+ alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
195
+ alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
196
+ sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
197
+ sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
198
+
199
+ def get_x_prev_and_pred_x0(e_t, index):
200
+ # select parameters corresponding to the currently considered timestep
201
+ a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
202
+ a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
203
+ sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
204
+ sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
205
+
206
+ # current prediction for x_0
207
+ pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
208
+ if quantize_denoised:
209
+ pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
210
+ # direction pointing to x_t
211
+ dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
212
+ noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
213
+ if noise_dropout > 0.:
214
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
215
+ x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
216
+ return x_prev, pred_x0
217
+
218
+ e_t = get_model_output(x, t)
219
+ if len(old_eps) == 0:
220
+ # Pseudo Improved Euler (2nd order)
221
+ x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t, index)
222
+ e_t_next = get_model_output(x_prev, t_next)
223
+ e_t_prime = (e_t + e_t_next) / 2
224
+ elif len(old_eps) == 1:
225
+ # 2nd order Pseudo Linear Multistep (Adams-Bashforth)
226
+ e_t_prime = (3 * e_t - old_eps[-1]) / 2
227
+ elif len(old_eps) == 2:
228
+ # 3nd order Pseudo Linear Multistep (Adams-Bashforth)
229
+ e_t_prime = (23 * e_t - 16 * old_eps[-1] + 5 * old_eps[-2]) / 12
230
+ elif len(old_eps) >= 3:
231
+ # 4nd order Pseudo Linear Multistep (Adams-Bashforth)
232
+ e_t_prime = (55 * e_t - 59 * old_eps[-1] + 37 * old_eps[-2] - 9 * old_eps[-3]) / 24
233
+
234
+ x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t_prime, index)
235
+
236
+ return x_prev, pred_x0, e_t
stable_diffusion/ldm/modules/attention.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File modified by authors of InstructPix2Pix from original (https://github.com/CompVis/stable-diffusion).
2
+ # See more details in LICENSE.
3
+
4
+ from inspect import isfunction
5
+ import math
6
+ import torch
7
+ import torch.nn.functional as F
8
+ from torch import nn, einsum
9
+ from einops import rearrange, repeat
10
+
11
+ from ldm.modules.diffusionmodules.util import checkpoint
12
+
13
+
14
+ def exists(val):
15
+ return val is not None
16
+
17
+
18
+ def uniq(arr):
19
+ return{el: True for el in arr}.keys()
20
+
21
+
22
+ def default(val, d):
23
+ if exists(val):
24
+ return val
25
+ return d() if isfunction(d) else d
26
+
27
+
28
+ def max_neg_value(t):
29
+ return -torch.finfo(t.dtype).max
30
+
31
+
32
+ def init_(tensor):
33
+ dim = tensor.shape[-1]
34
+ std = 1 / math.sqrt(dim)
35
+ tensor.uniform_(-std, std)
36
+ return tensor
37
+
38
+
39
+ # feedforward
40
+ class GEGLU(nn.Module):
41
+ def __init__(self, dim_in, dim_out):
42
+ super().__init__()
43
+ self.proj = nn.Linear(dim_in, dim_out * 2)
44
+
45
+ def forward(self, x):
46
+ x, gate = self.proj(x).chunk(2, dim=-1)
47
+ return x * F.gelu(gate)
48
+
49
+
50
+ class FeedForward(nn.Module):
51
+ def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
52
+ super().__init__()
53
+ inner_dim = int(dim * mult)
54
+ dim_out = default(dim_out, dim)
55
+ project_in = nn.Sequential(
56
+ nn.Linear(dim, inner_dim),
57
+ nn.GELU()
58
+ ) if not glu else GEGLU(dim, inner_dim)
59
+
60
+ self.net = nn.Sequential(
61
+ project_in,
62
+ nn.Dropout(dropout),
63
+ nn.Linear(inner_dim, dim_out)
64
+ )
65
+
66
+ def forward(self, x):
67
+ return self.net(x)
68
+
69
+
70
+ def zero_module(module):
71
+ """
72
+ Zero out the parameters of a module and return it.
73
+ """
74
+ for p in module.parameters():
75
+ p.detach().zero_()
76
+ return module
77
+
78
+
79
+ def Normalize(in_channels):
80
+ return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
81
+
82
+
83
+ class LinearAttention(nn.Module):
84
+ def __init__(self, dim, heads=4, dim_head=32):
85
+ super().__init__()
86
+ self.heads = heads
87
+ hidden_dim = dim_head * heads
88
+ self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias = False)
89
+ self.to_out = nn.Conv2d(hidden_dim, dim, 1)
90
+
91
+ def forward(self, x):
92
+ b, c, h, w = x.shape
93
+ qkv = self.to_qkv(x)
94
+ q, k, v = rearrange(qkv, 'b (qkv heads c) h w -> qkv b heads c (h w)', heads = self.heads, qkv=3)
95
+ k = k.softmax(dim=-1)
96
+ context = torch.einsum('bhdn,bhen->bhde', k, v)
97
+ out = torch.einsum('bhde,bhdn->bhen', context, q)
98
+ out = rearrange(out, 'b heads c (h w) -> b (heads c) h w', heads=self.heads, h=h, w=w)
99
+ return self.to_out(out)
100
+
101
+
102
+ class SpatialSelfAttention(nn.Module):
103
+ def __init__(self, in_channels):
104
+ super().__init__()
105
+ self.in_channels = in_channels
106
+
107
+ self.norm = Normalize(in_channels)
108
+ self.q = torch.nn.Conv2d(in_channels,
109
+ in_channels,
110
+ kernel_size=1,
111
+ stride=1,
112
+ padding=0)
113
+ self.k = torch.nn.Conv2d(in_channels,
114
+ in_channels,
115
+ kernel_size=1,
116
+ stride=1,
117
+ padding=0)
118
+ self.v = torch.nn.Conv2d(in_channels,
119
+ in_channels,
120
+ kernel_size=1,
121
+ stride=1,
122
+ padding=0)
123
+ self.proj_out = torch.nn.Conv2d(in_channels,
124
+ in_channels,
125
+ kernel_size=1,
126
+ stride=1,
127
+ padding=0)
128
+
129
+ def forward(self, x):
130
+ h_ = x
131
+ h_ = self.norm(h_)
132
+ q = self.q(h_)
133
+ k = self.k(h_)
134
+ v = self.v(h_)
135
+
136
+ # compute attention
137
+ b,c,h,w = q.shape
138
+ q = rearrange(q, 'b c h w -> b (h w) c')
139
+ k = rearrange(k, 'b c h w -> b c (h w)')
140
+ w_ = torch.einsum('bij,bjk->bik', q, k)
141
+
142
+ w_ = w_ * (int(c)**(-0.5))
143
+ w_ = torch.nn.functional.softmax(w_, dim=2)
144
+
145
+ # attend to values
146
+ v = rearrange(v, 'b c h w -> b c (h w)')
147
+ w_ = rearrange(w_, 'b i j -> b j i')
148
+ h_ = torch.einsum('bij,bjk->bik', v, w_)
149
+ h_ = rearrange(h_, 'b c (h w) -> b c h w', h=h)
150
+ h_ = self.proj_out(h_)
151
+
152
+ return x+h_
153
+
154
+
155
+ class CrossAttention(nn.Module):
156
+ def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.):
157
+ super().__init__()
158
+ inner_dim = dim_head * heads
159
+ context_dim = default(context_dim, query_dim)
160
+
161
+ self.scale = dim_head ** -0.5
162
+ self.heads = heads
163
+
164
+ self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
165
+ self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
166
+ self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
167
+
168
+ self.to_out = nn.Sequential(
169
+ nn.Linear(inner_dim, query_dim),
170
+ nn.Dropout(dropout)
171
+ )
172
+
173
+ self.prompt_to_prompt = False
174
+
175
+ def forward(self, x, context=None, mask=None):
176
+ is_self_attn = context is None
177
+
178
+ h = self.heads
179
+
180
+ q = self.to_q(x)
181
+ context = default(context, x)
182
+ k = self.to_k(context)
183
+ v = self.to_v(context)
184
+
185
+ q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
186
+
187
+ sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
188
+
189
+ if self.prompt_to_prompt and is_self_attn:
190
+ # Unlike the original Prompt-to-Prompt which uses cross-attention layers, we copy attention maps for self-attention layers.
191
+ # There must be 4 elements in the batch: {conditional, unconditional} x {prompt 1, prompt 2}
192
+ assert x.size(0) == 4
193
+ sims = sim.chunk(4)
194
+ sim = torch.cat((sims[0], sims[0], sims[2], sims[2]))
195
+
196
+ if exists(mask):
197
+ mask = rearrange(mask, 'b ... -> b (...)')
198
+ max_neg_value = -torch.finfo(sim.dtype).max
199
+ mask = repeat(mask, 'b j -> (b h) () j', h=h)
200
+ sim.masked_fill_(~mask, max_neg_value)
201
+
202
+ # attention, what we cannot get enough of
203
+ attn = sim.softmax(dim=-1)
204
+
205
+ out = einsum('b i j, b j d -> b i d', attn, v)
206
+ out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
207
+ return self.to_out(out)
208
+
209
+
210
+ class BasicTransformerBlock(nn.Module):
211
+ def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True):
212
+ super().__init__()
213
+ self.attn1 = CrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout) # is a self-attention
214
+ self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
215
+ self.attn2 = CrossAttention(query_dim=dim, context_dim=context_dim,
216
+ heads=n_heads, dim_head=d_head, dropout=dropout) # is self-attn if context is none
217
+ self.norm1 = nn.LayerNorm(dim)
218
+ self.norm2 = nn.LayerNorm(dim)
219
+ self.norm3 = nn.LayerNorm(dim)
220
+ self.checkpoint = checkpoint
221
+
222
+ def forward(self, x, context=None):
223
+ return checkpoint(self._forward, (x, context), self.parameters(), self.checkpoint)
224
+
225
+ def _forward(self, x, context=None):
226
+ x = self.attn1(self.norm1(x)) + x
227
+ x = self.attn2(self.norm2(x), context=context) + x
228
+ x = self.ff(self.norm3(x)) + x
229
+ return x
230
+
231
+
232
+ class SpatialTransformer(nn.Module):
233
+ """
234
+ Transformer block for image-like data.
235
+ First, project the input (aka embedding)
236
+ and reshape to b, t, d.
237
+ Then apply standard transformer action.
238
+ Finally, reshape to image
239
+ """
240
+ def __init__(self, in_channels, n_heads, d_head,
241
+ depth=1, dropout=0., context_dim=None):
242
+ super().__init__()
243
+ self.in_channels = in_channels
244
+ inner_dim = n_heads * d_head
245
+ self.norm = Normalize(in_channels)
246
+
247
+ self.proj_in = nn.Conv2d(in_channels,
248
+ inner_dim,
249
+ kernel_size=1,
250
+ stride=1,
251
+ padding=0)
252
+
253
+ self.transformer_blocks = nn.ModuleList(
254
+ [BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim)
255
+ for d in range(depth)]
256
+ )
257
+
258
+ self.proj_out = zero_module(nn.Conv2d(inner_dim,
259
+ in_channels,
260
+ kernel_size=1,
261
+ stride=1,
262
+ padding=0))
263
+
264
+ def forward(self, x, context=None):
265
+ # note: if no context is given, cross-attention defaults to self-attention
266
+ b, c, h, w = x.shape
267
+ x_in = x
268
+ x = self.norm(x)
269
+ x = self.proj_in(x)
270
+ x = rearrange(x, 'b c h w -> b (h w) c')
271
+ for block in self.transformer_blocks:
272
+ x = block(x, context=context)
273
+ x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w)
274
+ x = self.proj_out(x)
275
+ return x + x_in
stable_diffusion/ldm/modules/diffusionmodules/__init__.py ADDED
File without changes
stable_diffusion/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
+
stable_diffusion/ldm/modules/diffusionmodules/openaimodel.py ADDED
@@ -0,0 +1,961 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ legacy=True,
469
+ ):
470
+ super().__init__()
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
+ from omegaconf.listconfig import ListConfig
477
+ if type(context_dim) == ListConfig:
478
+ context_dim = list(context_dim)
479
+
480
+ if num_heads_upsample == -1:
481
+ num_heads_upsample = num_heads
482
+
483
+ if num_heads == -1:
484
+ assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
485
+
486
+ if num_head_channels == -1:
487
+ assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
488
+
489
+ self.image_size = image_size
490
+ self.in_channels = in_channels
491
+ self.model_channels = model_channels
492
+ self.out_channels = out_channels
493
+ self.num_res_blocks = num_res_blocks
494
+ self.attention_resolutions = attention_resolutions
495
+ self.dropout = dropout
496
+ self.channel_mult = channel_mult
497
+ self.conv_resample = conv_resample
498
+ self.num_classes = num_classes
499
+ self.use_checkpoint = use_checkpoint
500
+ self.dtype = th.float16 if use_fp16 else th.float32
501
+ self.num_heads = num_heads
502
+ self.num_head_channels = num_head_channels
503
+ self.num_heads_upsample = num_heads_upsample
504
+ self.predict_codebook_ids = n_embed is not None
505
+
506
+ time_embed_dim = model_channels * 4
507
+ self.time_embed = nn.Sequential(
508
+ linear(model_channels, time_embed_dim),
509
+ nn.SiLU(),
510
+ linear(time_embed_dim, time_embed_dim),
511
+ )
512
+
513
+ if self.num_classes is not None:
514
+ self.label_emb = nn.Embedding(num_classes, time_embed_dim)
515
+
516
+ self.input_blocks = nn.ModuleList(
517
+ [
518
+ TimestepEmbedSequential(
519
+ conv_nd(dims, in_channels, model_channels, 3, padding=1)
520
+ )
521
+ ]
522
+ )
523
+ self._feature_size = model_channels
524
+ input_block_chans = [model_channels]
525
+ ch = model_channels
526
+ ds = 1
527
+ for level, mult in enumerate(channel_mult):
528
+ for _ in range(num_res_blocks):
529
+ layers = [
530
+ ResBlock(
531
+ ch,
532
+ time_embed_dim,
533
+ dropout,
534
+ out_channels=mult * model_channels,
535
+ dims=dims,
536
+ use_checkpoint=use_checkpoint,
537
+ use_scale_shift_norm=use_scale_shift_norm,
538
+ )
539
+ ]
540
+ ch = mult * model_channels
541
+ if ds in attention_resolutions:
542
+ if num_head_channels == -1:
543
+ dim_head = ch // num_heads
544
+ else:
545
+ num_heads = ch // num_head_channels
546
+ dim_head = num_head_channels
547
+ if legacy:
548
+ #num_heads = 1
549
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
550
+ layers.append(
551
+ AttentionBlock(
552
+ ch,
553
+ use_checkpoint=use_checkpoint,
554
+ num_heads=num_heads,
555
+ num_head_channels=dim_head,
556
+ use_new_attention_order=use_new_attention_order,
557
+ ) if not use_spatial_transformer else SpatialTransformer(
558
+ ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
559
+ )
560
+ )
561
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
562
+ self._feature_size += ch
563
+ input_block_chans.append(ch)
564
+ if level != len(channel_mult) - 1:
565
+ out_ch = ch
566
+ self.input_blocks.append(
567
+ TimestepEmbedSequential(
568
+ ResBlock(
569
+ ch,
570
+ time_embed_dim,
571
+ dropout,
572
+ out_channels=out_ch,
573
+ dims=dims,
574
+ use_checkpoint=use_checkpoint,
575
+ use_scale_shift_norm=use_scale_shift_norm,
576
+ down=True,
577
+ )
578
+ if resblock_updown
579
+ else Downsample(
580
+ ch, conv_resample, dims=dims, out_channels=out_ch
581
+ )
582
+ )
583
+ )
584
+ ch = out_ch
585
+ input_block_chans.append(ch)
586
+ ds *= 2
587
+ self._feature_size += ch
588
+
589
+ if num_head_channels == -1:
590
+ dim_head = ch // num_heads
591
+ else:
592
+ num_heads = ch // num_head_channels
593
+ dim_head = num_head_channels
594
+ if legacy:
595
+ #num_heads = 1
596
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
597
+ self.middle_block = TimestepEmbedSequential(
598
+ ResBlock(
599
+ ch,
600
+ time_embed_dim,
601
+ dropout,
602
+ dims=dims,
603
+ use_checkpoint=use_checkpoint,
604
+ use_scale_shift_norm=use_scale_shift_norm,
605
+ ),
606
+ AttentionBlock(
607
+ ch,
608
+ use_checkpoint=use_checkpoint,
609
+ num_heads=num_heads,
610
+ num_head_channels=dim_head,
611
+ use_new_attention_order=use_new_attention_order,
612
+ ) if not use_spatial_transformer else SpatialTransformer(
613
+ ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
614
+ ),
615
+ ResBlock(
616
+ ch,
617
+ time_embed_dim,
618
+ dropout,
619
+ dims=dims,
620
+ use_checkpoint=use_checkpoint,
621
+ use_scale_shift_norm=use_scale_shift_norm,
622
+ ),
623
+ )
624
+ self._feature_size += ch
625
+
626
+ self.output_blocks = nn.ModuleList([])
627
+ for level, mult in list(enumerate(channel_mult))[::-1]:
628
+ for i in range(num_res_blocks + 1):
629
+ ich = input_block_chans.pop()
630
+ layers = [
631
+ ResBlock(
632
+ ch + ich,
633
+ time_embed_dim,
634
+ dropout,
635
+ out_channels=model_channels * mult,
636
+ dims=dims,
637
+ use_checkpoint=use_checkpoint,
638
+ use_scale_shift_norm=use_scale_shift_norm,
639
+ )
640
+ ]
641
+ ch = model_channels * mult
642
+ if ds in attention_resolutions:
643
+ if num_head_channels == -1:
644
+ dim_head = ch // num_heads
645
+ else:
646
+ num_heads = ch // num_head_channels
647
+ dim_head = num_head_channels
648
+ if legacy:
649
+ #num_heads = 1
650
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
651
+ layers.append(
652
+ AttentionBlock(
653
+ ch,
654
+ use_checkpoint=use_checkpoint,
655
+ num_heads=num_heads_upsample,
656
+ num_head_channels=dim_head,
657
+ use_new_attention_order=use_new_attention_order,
658
+ ) if not use_spatial_transformer else SpatialTransformer(
659
+ ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
660
+ )
661
+ )
662
+ if level and i == num_res_blocks:
663
+ out_ch = ch
664
+ layers.append(
665
+ ResBlock(
666
+ ch,
667
+ time_embed_dim,
668
+ dropout,
669
+ out_channels=out_ch,
670
+ dims=dims,
671
+ use_checkpoint=use_checkpoint,
672
+ use_scale_shift_norm=use_scale_shift_norm,
673
+ up=True,
674
+ )
675
+ if resblock_updown
676
+ else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
677
+ )
678
+ ds //= 2
679
+ self.output_blocks.append(TimestepEmbedSequential(*layers))
680
+ self._feature_size += ch
681
+
682
+ self.out = nn.Sequential(
683
+ normalization(ch),
684
+ nn.SiLU(),
685
+ zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)),
686
+ )
687
+ if self.predict_codebook_ids:
688
+ self.id_predictor = nn.Sequential(
689
+ normalization(ch),
690
+ conv_nd(dims, model_channels, n_embed, 1),
691
+ #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
692
+ )
693
+
694
+ def convert_to_fp16(self):
695
+ """
696
+ Convert the torso of the model to float16.
697
+ """
698
+ self.input_blocks.apply(convert_module_to_f16)
699
+ self.middle_block.apply(convert_module_to_f16)
700
+ self.output_blocks.apply(convert_module_to_f16)
701
+
702
+ def convert_to_fp32(self):
703
+ """
704
+ Convert the torso of the model to float32.
705
+ """
706
+ self.input_blocks.apply(convert_module_to_f32)
707
+ self.middle_block.apply(convert_module_to_f32)
708
+ self.output_blocks.apply(convert_module_to_f32)
709
+
710
+ def forward(self, x, timesteps=None, context=None, y=None,**kwargs):
711
+ """
712
+ Apply the model to an input batch.
713
+ :param x: an [N x C x ...] Tensor of inputs.
714
+ :param timesteps: a 1-D batch of timesteps.
715
+ :param context: conditioning plugged in via crossattn
716
+ :param y: an [N] Tensor of labels, if class-conditional.
717
+ :return: an [N x C x ...] Tensor of outputs.
718
+ """
719
+ assert (y is not None) == (
720
+ self.num_classes is not None
721
+ ), "must specify y if and only if the model is class-conditional"
722
+ hs = []
723
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
724
+ emb = self.time_embed(t_emb)
725
+
726
+ if self.num_classes is not None:
727
+ assert y.shape == (x.shape[0],)
728
+ emb = emb + self.label_emb(y)
729
+
730
+ h = x.type(self.dtype)
731
+ for module in self.input_blocks:
732
+ h = module(h, emb, context)
733
+ hs.append(h)
734
+ h = self.middle_block(h, emb, context)
735
+ for module in self.output_blocks:
736
+ h = th.cat([h, hs.pop()], dim=1)
737
+ h = module(h, emb, context)
738
+ h = h.type(x.dtype)
739
+ if self.predict_codebook_ids:
740
+ return self.id_predictor(h)
741
+ else:
742
+ return self.out(h)
743
+
744
+
745
+ class EncoderUNetModel(nn.Module):
746
+ """
747
+ The half UNet model with attention and timestep embedding.
748
+ For usage, see UNet.
749
+ """
750
+
751
+ def __init__(
752
+ self,
753
+ image_size,
754
+ in_channels,
755
+ model_channels,
756
+ out_channels,
757
+ num_res_blocks,
758
+ attention_resolutions,
759
+ dropout=0,
760
+ channel_mult=(1, 2, 4, 8),
761
+ conv_resample=True,
762
+ dims=2,
763
+ use_checkpoint=False,
764
+ use_fp16=False,
765
+ num_heads=1,
766
+ num_head_channels=-1,
767
+ num_heads_upsample=-1,
768
+ use_scale_shift_norm=False,
769
+ resblock_updown=False,
770
+ use_new_attention_order=False,
771
+ pool="adaptive",
772
+ *args,
773
+ **kwargs
774
+ ):
775
+ super().__init__()
776
+
777
+ if num_heads_upsample == -1:
778
+ num_heads_upsample = num_heads
779
+
780
+ self.in_channels = in_channels
781
+ self.model_channels = model_channels
782
+ self.out_channels = out_channels
783
+ self.num_res_blocks = num_res_blocks
784
+ self.attention_resolutions = attention_resolutions
785
+ self.dropout = dropout
786
+ self.channel_mult = channel_mult
787
+ self.conv_resample = conv_resample
788
+ self.use_checkpoint = use_checkpoint
789
+ self.dtype = th.float16 if use_fp16 else th.float32
790
+ self.num_heads = num_heads
791
+ self.num_head_channels = num_head_channels
792
+ self.num_heads_upsample = num_heads_upsample
793
+
794
+ time_embed_dim = model_channels * 4
795
+ self.time_embed = nn.Sequential(
796
+ linear(model_channels, time_embed_dim),
797
+ nn.SiLU(),
798
+ linear(time_embed_dim, time_embed_dim),
799
+ )
800
+
801
+ self.input_blocks = nn.ModuleList(
802
+ [
803
+ TimestepEmbedSequential(
804
+ conv_nd(dims, in_channels, model_channels, 3, padding=1)
805
+ )
806
+ ]
807
+ )
808
+ self._feature_size = model_channels
809
+ input_block_chans = [model_channels]
810
+ ch = model_channels
811
+ ds = 1
812
+ for level, mult in enumerate(channel_mult):
813
+ for _ in range(num_res_blocks):
814
+ layers = [
815
+ ResBlock(
816
+ ch,
817
+ time_embed_dim,
818
+ dropout,
819
+ out_channels=mult * model_channels,
820
+ dims=dims,
821
+ use_checkpoint=use_checkpoint,
822
+ use_scale_shift_norm=use_scale_shift_norm,
823
+ )
824
+ ]
825
+ ch = mult * model_channels
826
+ if ds in attention_resolutions:
827
+ layers.append(
828
+ AttentionBlock(
829
+ ch,
830
+ use_checkpoint=use_checkpoint,
831
+ num_heads=num_heads,
832
+ num_head_channels=num_head_channels,
833
+ use_new_attention_order=use_new_attention_order,
834
+ )
835
+ )
836
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
837
+ self._feature_size += ch
838
+ input_block_chans.append(ch)
839
+ if level != len(channel_mult) - 1:
840
+ out_ch = ch
841
+ self.input_blocks.append(
842
+ TimestepEmbedSequential(
843
+ ResBlock(
844
+ ch,
845
+ time_embed_dim,
846
+ dropout,
847
+ out_channels=out_ch,
848
+ dims=dims,
849
+ use_checkpoint=use_checkpoint,
850
+ use_scale_shift_norm=use_scale_shift_norm,
851
+ down=True,
852
+ )
853
+ if resblock_updown
854
+ else Downsample(
855
+ ch, conv_resample, dims=dims, out_channels=out_ch
856
+ )
857
+ )
858
+ )
859
+ ch = out_ch
860
+ input_block_chans.append(ch)
861
+ ds *= 2
862
+ self._feature_size += ch
863
+
864
+ self.middle_block = TimestepEmbedSequential(
865
+ ResBlock(
866
+ ch,
867
+ time_embed_dim,
868
+ dropout,
869
+ dims=dims,
870
+ use_checkpoint=use_checkpoint,
871
+ use_scale_shift_norm=use_scale_shift_norm,
872
+ ),
873
+ AttentionBlock(
874
+ ch,
875
+ use_checkpoint=use_checkpoint,
876
+ num_heads=num_heads,
877
+ num_head_channels=num_head_channels,
878
+ use_new_attention_order=use_new_attention_order,
879
+ ),
880
+ ResBlock(
881
+ ch,
882
+ time_embed_dim,
883
+ dropout,
884
+ dims=dims,
885
+ use_checkpoint=use_checkpoint,
886
+ use_scale_shift_norm=use_scale_shift_norm,
887
+ ),
888
+ )
889
+ self._feature_size += ch
890
+ self.pool = pool
891
+ if pool == "adaptive":
892
+ self.out = nn.Sequential(
893
+ normalization(ch),
894
+ nn.SiLU(),
895
+ nn.AdaptiveAvgPool2d((1, 1)),
896
+ zero_module(conv_nd(dims, ch, out_channels, 1)),
897
+ nn.Flatten(),
898
+ )
899
+ elif pool == "attention":
900
+ assert num_head_channels != -1
901
+ self.out = nn.Sequential(
902
+ normalization(ch),
903
+ nn.SiLU(),
904
+ AttentionPool2d(
905
+ (image_size // ds), ch, num_head_channels, out_channels
906
+ ),
907
+ )
908
+ elif pool == "spatial":
909
+ self.out = nn.Sequential(
910
+ nn.Linear(self._feature_size, 2048),
911
+ nn.ReLU(),
912
+ nn.Linear(2048, self.out_channels),
913
+ )
914
+ elif pool == "spatial_v2":
915
+ self.out = nn.Sequential(
916
+ nn.Linear(self._feature_size, 2048),
917
+ normalization(2048),
918
+ nn.SiLU(),
919
+ nn.Linear(2048, self.out_channels),
920
+ )
921
+ else:
922
+ raise NotImplementedError(f"Unexpected {pool} pooling")
923
+
924
+ def convert_to_fp16(self):
925
+ """
926
+ Convert the torso of the model to float16.
927
+ """
928
+ self.input_blocks.apply(convert_module_to_f16)
929
+ self.middle_block.apply(convert_module_to_f16)
930
+
931
+ def convert_to_fp32(self):
932
+ """
933
+ Convert the torso of the model to float32.
934
+ """
935
+ self.input_blocks.apply(convert_module_to_f32)
936
+ self.middle_block.apply(convert_module_to_f32)
937
+
938
+ def forward(self, x, timesteps):
939
+ """
940
+ Apply the model to an input batch.
941
+ :param x: an [N x C x ...] Tensor of inputs.
942
+ :param timesteps: a 1-D batch of timesteps.
943
+ :return: an [N x K] Tensor of outputs.
944
+ """
945
+ emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
946
+
947
+ results = []
948
+ h = x.type(self.dtype)
949
+ for module in self.input_blocks:
950
+ h = module(h, emb)
951
+ if self.pool.startswith("spatial"):
952
+ results.append(h.type(x.dtype).mean(dim=(2, 3)))
953
+ h = self.middle_block(h, emb)
954
+ if self.pool.startswith("spatial"):
955
+ results.append(h.type(x.dtype).mean(dim=(2, 3)))
956
+ h = th.cat(results, axis=-1)
957
+ return self.out(h)
958
+ else:
959
+ h = h.type(x.dtype)
960
+ return self.out(h)
961
+
stable_diffusion/ldm/modules/distributions/__init__.py ADDED
File without changes