Kayson commited on
Commit
7ae68fe
1 Parent(s): 8c7c06d
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. LICENSE +9 -0
  2. README.md +121 -12
  3. app.py +336 -0
  4. configs/instruct_diffusion.yaml +256 -0
  5. dataset/README.md +62 -0
  6. dataset/editing/edit_zip_dataset.py +494 -0
  7. dataset/low_level/lowlevel_clwd.py +106 -0
  8. dataset/low_level/lowlevel_gopro.py +106 -0
  9. dataset/low_level/lowlevel_reds.py +111 -0
  10. dataset/low_level/lowlevel_sidd.py +96 -0
  11. dataset/pose/pose.py +760 -0
  12. dataset/prompt/color_list_train_small.txt +17 -0
  13. dataset/prompt/prompt_deblur.txt +10 -0
  14. dataset/prompt/prompt_denoise.txt +10 -0
  15. dataset/prompt/prompt_dewatermark.txt +10 -0
  16. dataset/prompt/prompt_pose.txt +10 -0
  17. dataset/prompt/prompt_seg.txt +11 -0
  18. dataset/seg/coco_stuff.py +175 -0
  19. dataset/seg/grefcoco.py +329 -0
  20. dataset/seg/grefcoco_segmentation.py +149 -0
  21. dataset/seg/refcoco.py +354 -0
  22. dataset/seg/refcoco_segmentation.py +149 -0
  23. dataset/utils/zip_manager.py +144 -0
  24. edit_cli.py +136 -0
  25. environment.yaml +40 -0
  26. figure/animals.png +0 -0
  27. figure/mirrorcat.jpg +0 -0
  28. figure/people.jpg +0 -0
  29. figure/watermark.png +0 -0
  30. main.py +566 -0
  31. scripts/convert_ckpt.py +51 -0
  32. scripts/download_pretrained_sd.sh +7 -0
  33. scripts/inference_example.sh +12 -0
  34. scripts/run_multinode.sh +6 -0
  35. stable_diffusion/LICENSE +82 -0
  36. stable_diffusion/README.md +215 -0
  37. stable_diffusion/Stable_Diffusion_v1_Model_Card.md +144 -0
  38. stable_diffusion/assets/a-painting-of-a-fire.png +0 -0
  39. stable_diffusion/assets/a-photograph-of-a-fire.png +0 -0
  40. stable_diffusion/assets/a-shirt-with-a-fire-printed-on-it.png +0 -0
  41. stable_diffusion/assets/a-shirt-with-the-inscription-'fire'.png +0 -0
  42. stable_diffusion/assets/a-watercolor-painting-of-a-fire.png +0 -0
  43. stable_diffusion/assets/birdhouse.png +0 -0
  44. stable_diffusion/assets/fire.png +0 -0
  45. stable_diffusion/assets/inpainting.png +0 -0
  46. stable_diffusion/assets/modelfigure.png +0 -0
  47. stable_diffusion/assets/rdm-preview.jpg +0 -0
  48. stable_diffusion/assets/reconstruction1.png +0 -0
  49. stable_diffusion/assets/reconstruction2.png +0 -0
  50. stable_diffusion/assets/results.gif.REMOVED.git-id +1 -0
LICENSE ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2023 Authors of InstructDiffusion(https://arxiv.org/pdf/2309.03895.pdf)
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8
+
9
+ Portions of code and models (such as pretrained checkpoints, which are fine-tuned starting from released Stable Diffusion checkpoints) are derived from the Stable Diffusion codebase (https://github.com/CompVis/stable-diffusion) and Instruct-pix2pix codebase (https://github.com/timothybrooks/instruct-pix2pix). Further restrictions may apply. Please consult the Stable Diffusion license `stable_diffusion/LICENSE` and the Instruct-pix2pix license `instruct-pix2pix/LICENSE`. Modified code is denoted as such in comments at the start of each file.
README.md CHANGED
@@ -1,12 +1,121 @@
1
- ---
2
- title: InstructDiffusion
3
- emoji: 📚
4
- colorFrom: purple
5
- colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 3.44.4
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # InstructDiffusion: A Generalist Modeling Interface for Vision Tasks
2
+
3
+ <p align="center">
4
+ <a href="https://gengzigang.github.io/instructdiffusion.github.io/">Project Page</a> |
5
+ <a href="https://arxiv.org/pdf/2309.03895.pdf">Arxiv</a> |
6
+ <a href="https://f605b16c6b183b13ac.gradio.live">Web Demo</a> |
7
+ <a href="#QuickStart">QuickStart</a> |
8
+ <a href="#Training">Training</a> |
9
+ <a href="#Acknowledge">Acknowledge</a> |
10
+ <a href='#Citation'>Citation</a>
11
+ </p>
12
+
13
+ <div align="center">
14
+ <img src="figure/teaser.png" width="1000"/>
15
+ </div>
16
+
17
+ This is the pytorch implementation of InstructDiffusion, a unifying and generic framework for aligning computer vision tasks with human instructions. Our code is based on the [Instruct-pix2pix](https://github.com/timothybrooks/instruct-pix2pix) and [CompVis/stable_diffusion](https://github.com/CompVis/stable-diffusion).<br>
18
+
19
+ ## QuickStart
20
+ Follow the steps below to quickly edit your own images. The inference code in our repository requires **one GPU with > 9GB memory** to test images with a resolution of **512**.
21
+
22
+ 1. Clone this repo.
23
+ 2. Setup conda environment:
24
+ ```
25
+ conda env create -f environment.yaml
26
+ conda activate instructdiff
27
+ ```
28
+ 3. We provide a well-trained [checkpoint](https://mailustceducn-my.sharepoint.com/:u:/g/personal/aa397601_mail_ustc_edu_cn/EZmXduulFidIhJD73SGcbOoBNpm18CJmU4PgPTS21RM2Ow?e=KqQYpO) and a [checkpoint](https://mailustceducn-my.sharepoint.com/:u:/g/personal/aa397601_mail_ustc_edu_cn/EWlNmyeS9P1BkRg_IlXbPbwBeNMQXQTcIA0pCokyd61UWg?e=iKfRdk) that has undergone human-alignment. Feel free to download to the folder `checkpoints` and try both of them.
29
+
30
+ 4. You can edit your own images:
31
+ ```bash
32
+ python edit_cli.py --input example.jpg --edit "Transform it to van Gogh, starry night style."
33
+
34
+ # Optionally, you can customize the parameters by using the following syntax:
35
+ # --resolution 512 --steps 50 --config configs/instruct_diffusion.yaml --ckpt YOUR_CHECKPOINT --cfg-text 3.5 --cfg-image 1.25
36
+
37
+ # We also support loading image from the website and edit, e.g., you could run the command like this:
38
+ python edit_cli.py --input "https://wallup.net/wp-content/uploads/2016/01/207131-animals-nature-lion.jpg" \
39
+ --edit "Transform it to van Gogh, starry night style." \
40
+ --resolution 512 --steps 50 \
41
+ --config configs/instruct_diffusion.yaml \
42
+ --ckpt checkpoints/v1-5-pruned-emaonly-adaption-task-humanalign.ckpt \
43
+ --outdir logs/
44
+ ```
45
+ For other different tasks, we provide recommended parameter settings, which can be found in [`scripts/inference_example.sh`](./scripts/inference_example.sh).
46
+
47
+ 5. (Optional) You can launch your own interactive editing Gradio app:
48
+ ```bash
49
+ python edit_app.py
50
+
51
+ # You can also specify the path to the checkpoint
52
+ # The default checkpoint is checkpoints/v1-5-pruned-emaonly-adaption-task-humanalign.ckpt
53
+ python edit_app.py --ckpt checkpoints/v1-5-pruned-emaonly-adaption-task-humanalign.ckpt
54
+ ```
55
+
56
+ ## Training
57
+ The code is developed using python 3.8 on Ubuntu 18.04. The code is developed and tested using 48 NVIDIA V100 GPU cards, each with 32GB of memory. Other platforms are not fully tested.
58
+
59
+ ### Installation
60
+ 1. Clone this repo.
61
+ 2. Setup conda environment:
62
+ ```
63
+ conda env create -f environment.yaml
64
+ conda activate instructdiff
65
+ ```
66
+
67
+ ### Pre-trained Model Preparation
68
+ You can use the following command to download the official pre-trained stable diffusion model, or you can download the model trained by our pretraining adaptation process from [OneDrive](https://mailustceducn-my.sharepoint.com/:u:/g/personal/aa397601_mail_ustc_edu_cn/EXJSMIpFev5Nj0kuKI88U1IBZDSjegp3G8ukku0OxRRjFQ?e=QhnnB4) and put it into the following folder: stable_diffusion/models/ldm/stable-diffusion-v1/.
69
+ ```
70
+ bash scripts/download_pretrained_sd.sh
71
+ ```
72
+
73
+ ### Data Preparation
74
+ You can refer to the [dataset](https://github.com/cientgu/InstructDiffusion/tree/main/dataset) to prepare your data.
75
+
76
+ ### Training Command
77
+ For multi-GPU training on a single machine, you can use the following command:
78
+ ```
79
+ python -m torch.distributed.launch --nproc_per_node=8 main.py --name v0 --base configs/instruct_diffusion.yaml --train --logdir logs/instruct_diffusion
80
+ ```
81
+
82
+ For multi-GPU training on multiple machines, you can use the following command (assuming 6 machines as an example):
83
+ ```
84
+ bash run_multinode.sh instruct_diffusion v0 6
85
+ ```
86
+
87
+ ### Convert EMA-Model
88
+ You can get the final EMA checkpoint for inference using the command below:
89
+ ```
90
+ python convert_ckpt.py --ema-ckpt logs/instruct_diffusion/checkpoint/ckpt_epoch_200/state.pth --out-ckpt checkpoints/v1-5-pruned-emaonly-adaption-task.ckpt
91
+ ```
92
+
93
+ ## Acknowledge
94
+
95
+ Thanks to
96
+ - [Stable-diffusion](https://github.com/CompVis/stable-diffusion)
97
+ - [Instruct-pix2pix](https://github.com/timothybrooks/instruct-pix2pix)
98
+
99
+ ## Citation
100
+
101
+ ```
102
+ @article{Geng23instructdiff,
103
+ author = {Zigang Geng and
104
+ Binxin Yang and
105
+ Tiankai Hang and
106
+ Chen Li and
107
+ Shuyang Gu and
108
+ Ting Zhang and
109
+ Jianmin Bao and
110
+ Zheng Zhang and
111
+ Han Hu and
112
+ Dong Chen and
113
+ Baining Guo},
114
+ title = {InstructDiffusion: {A} Generalist Modeling Interface for Vision Tasks},
115
+ journal = {CoRR},
116
+ volume = {abs/2309.03895},
117
+ year = {2023},
118
+ url = {https://doi.org/10.48550/arXiv.2309.03895},
119
+ doi = {10.48550/arXiv.2309.03895},
120
+ }
121
+ ```
app.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InstructDiffusion
3
+ # Based on instruct-pix2pix (https://github.com/timothybrooks/instruct-pix2pix)
4
+ # Modified by Tiankai Hang (tkhang@seu.edu.cn)
5
+ # --------------------------------------------------------
6
+
7
+ import os
8
+ import sys
9
+ import re
10
+
11
+ import math
12
+ import numpy as np
13
+ import random
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ from omegaconf import OmegaConf
19
+ from torch import autocast
20
+ import einops
21
+ from einops import rearrange
22
+ import gradio as gr
23
+ import k_diffusion as K
24
+ import requests
25
+ from functools import partial
26
+ from copy import deepcopy
27
+
28
+ from PIL import Image, ImageOps
29
+ import click
30
+
31
+ sys.path.append("./stable_diffusion")
32
+
33
+ from stable_diffusion.ldm.util import instantiate_from_config
34
+
35
+
36
+ def load_model_from_config(config, ckpt, vae_ckpt=None, verbose=False):
37
+ model = instantiate_from_config(config.model)
38
+
39
+ print(f"Loading model from {ckpt}")
40
+ pl_sd = torch.load(ckpt, map_location="cpu")
41
+ if 'state_dict' in pl_sd:
42
+ pl_sd = pl_sd['state_dict']
43
+ m, u = model.load_state_dict(pl_sd, strict=False)
44
+
45
+ print(m, u)
46
+ return model
47
+
48
+
49
+ def read_content(file_path: str) -> str:
50
+ """read the content of target file
51
+ """
52
+ with open(file_path, 'r', encoding='utf-8') as f:
53
+ content = f.read()
54
+
55
+ return content
56
+
57
+
58
+ def get_header():
59
+ content = """
60
+ <div style="text-align: center; max-width: 650px; margin: 0 auto;">
61
+ <div style="
62
+ display: inline-flex;
63
+ gap: 0.8rem;
64
+ font-size: 1.75rem;
65
+ justify-content: center;
66
+ margin-bottom: 10px;
67
+ ">
68
+ <h1 style="font-weight: 900; align-items: center; margin-bottom: 7px; margin-top: 20px;">
69
+ InstructDiffusion 🎨
70
+ </h1>
71
+ </div>
72
+ <div>
73
+ <p style="align-items: center; margin-bottom: 7px;">
74
+ InstructDiffusion, upload a source image and write the instruction to conduct keypoint detection, referring segmentation, and image editing.
75
+ </p>
76
+ <p style="align-items: center; margin-bottom: 7px;">
77
+ Paper is available in <a style="text-decoration: underline;" href="https://gengzigang.github.io/instructdiffusion.github.io/">Arxiv</a>. If you like this demo, please help to ⭐ the <a style="text-decoration: underline;" href="https://github.com/cientgu/InstructDiffusion">Github Repo</a> 😊.
78
+ </p>
79
+ </div>
80
+ </div>
81
+ """
82
+ return content
83
+
84
+
85
+ class CFGDenoiser(nn.Module):
86
+ def __init__(self, model):
87
+ super().__init__()
88
+ self.inner_model = model
89
+
90
+ def forward(self, z, sigma, cond, uncond, text_cfg_scale, image_cfg_scale):
91
+ cfg_z = einops.repeat(z, "1 ... -> n ...", n=3)
92
+ cfg_sigma = einops.repeat(sigma, "1 ... -> n ...", n=3)
93
+ cfg_cond = {
94
+ "c_crossattn": [torch.cat([cond["c_crossattn"][0], uncond["c_crossattn"][0], cond["c_crossattn"][0]])],
95
+ "c_concat": [torch.cat([cond["c_concat"][0], cond["c_concat"][0], uncond["c_concat"][0]])],
96
+ }
97
+ out_cond, out_img_cond, out_txt_cond = self.inner_model(cfg_z, cfg_sigma, cond=cfg_cond).chunk(3)
98
+ return 0.5 * (out_img_cond + out_txt_cond) + text_cfg_scale * (out_cond - out_img_cond) + image_cfg_scale * (out_cond - out_txt_cond)
99
+
100
+
101
+ def predict(
102
+ model, model_wrap,
103
+ model_wrap_cfg,
104
+ null_token, resolution,
105
+ input_img, edit, seed, steps, cfg_text, cfg_image,
106
+ stochastic_steps=0, sampler="euler", additional={}):
107
+
108
+ # set seed
109
+ random.seed(seed)
110
+ np.random.seed(seed)
111
+ torch.manual_seed(seed)
112
+ torch.cuda.manual_seed(seed)
113
+
114
+ torch.cuda.empty_cache()
115
+
116
+ if isinstance(input_img, str):
117
+ if input_img.startswith("http"):
118
+ input_image = Image.open(requests.get(input_img, stream=True).raw).convert("RGB")
119
+ else:
120
+ input_image = Image.open(input_img).convert("RGB")
121
+ width, height = input_image.size
122
+
123
+ factor = resolution / max(width, height)
124
+
125
+ width = int((width * factor) // 64) * 64
126
+ height = int((height * factor) // 64) * 64
127
+ if hasattr(Image, "Resampling"):
128
+ input_image = ImageOps.fit(input_image, (width, height), method=Image.Resampling.LANCZOS)
129
+ else:
130
+ input_image = ImageOps.fit(input_image, (width, height), method=Image.LANCZOS)
131
+ input_image = 2 * torch.tensor(np.array(input_image)).float() / 255 - 1
132
+ input_image = rearrange(input_image, "h w c -> 1 c h w").cuda()
133
+
134
+ # if PIL Image
135
+ elif isinstance(input_img, Image.Image):
136
+ input_image = input_img
137
+ width, height = input_image.size
138
+ factor = resolution / max(width, height)
139
+ # factor = math.ceil(min(width, height) * factor / 64) * 64 / min(width, height)
140
+ width = int((width * factor) // 64) * 64
141
+ height = int((height * factor) // 64) * 64
142
+ if hasattr(Image, "Resampling"):
143
+ input_image = ImageOps.fit(input_image, (width, height), method=Image.Resampling.LANCZOS)
144
+ else:
145
+ input_image = ImageOps.fit(input_image, (width, height), method=Image.LANCZOS)
146
+ input_image = 2 * torch.tensor(np.array(input_image)).float() / 255 - 1
147
+ input_image = rearrange(input_image, "h w c -> 1 c h w").cuda()
148
+ elif isinstance(input_img, dict):
149
+ input_image = input_img["image"].convert("RGB")
150
+ width, height = input_image.size
151
+
152
+ factor = resolution / max(width, height)
153
+
154
+ width = int((width * factor) // 64) * 64
155
+ height = int((height * factor) // 64) * 64
156
+ if hasattr(Image, "Resampling"):
157
+ input_image = ImageOps.fit(input_image, (width, height), method=Image.Resampling.LANCZOS)
158
+ else:
159
+ input_image = ImageOps.fit(input_image, (width, height), method=Image.LANCZOS)
160
+ input_image = 2 * torch.tensor(np.array(input_image)).float() / 255 - 1
161
+ input_image = rearrange(input_image, "h w c -> 1 c h w").cuda()
162
+
163
+ assert input_image is not None
164
+ # print input image size
165
+ print(input_image.shape, factor, width, height)
166
+
167
+ with torch.no_grad(), autocast("cuda"):
168
+ cond = {}
169
+ cond["c_crossattn"] = [model.get_learned_conditioning([edit])]
170
+ cond["c_concat"] = [model.encode_first_stage(input_image).mode()]
171
+
172
+ uncond = {}
173
+ if "txt_embed" in additional:
174
+ uncond["c_crossattn"] = [additional["txt_embed"].cuda().unsqueeze(0)]
175
+ else:
176
+ uncond["c_crossattn"] = [null_token]
177
+ if "img_embed" in additional:
178
+ # uncond["c_concat"] = [additional["img_embed"].cuda()]
179
+ # resize to cond["c_concat"][0]
180
+ uncond["c_concat"] = [additional["img_embed"].cuda()]
181
+ uncond["c_concat"][0] = F.interpolate(uncond["c_concat"][0], size=cond["c_concat"][0].shape[-2:], mode="bilinear", align_corners=False)
182
+ else:
183
+ uncond["c_concat"] = [torch.zeros_like(cond["c_concat"][0])]
184
+
185
+ sigmas = model_wrap.get_sigmas(steps)
186
+
187
+ extra_args = {
188
+ "cond": cond,
189
+ "uncond": uncond,
190
+ "text_cfg_scale": cfg_text,
191
+ "image_cfg_scale": cfg_image,
192
+ }
193
+
194
+ if stochastic_steps <= 0:
195
+ z = torch.randn_like(cond["c_concat"][0]) * sigmas[0]
196
+ if sampler == "euler":
197
+ z = K.sampling.sample_euler_ancestral(model_wrap_cfg, z, sigmas, extra_args=extra_args)
198
+ elif sampler == "heun":
199
+ z = K.sampling.sample_heun(model_wrap_cfg, z, sigmas, extra_args=extra_args)
200
+ else:
201
+ z = torch.randn_like(cond["c_concat"][0]) * sigmas[stochastic_steps] + cond["c_concat"][0]
202
+ z = K.sampling.sample_euler_ancestral(model_wrap_cfg, z, sigmas[stochastic_steps:], extra_args=extra_args)
203
+
204
+ x = model.decode_first_stage(z)
205
+ x = torch.clamp((x + 1.0) / 2.0, min=0.0, max=1.0)
206
+ x = 255.0 * rearrange(x, "1 c h w -> h w c")
207
+ edited_image = Image.fromarray(x.type(torch.uint8).cpu().numpy())
208
+
209
+ # input_image to PIL
210
+ input_image = torch.clamp((input_image + 1.0) / 2.0, min=0.0, max=1.0)
211
+ input_image = 255.0 * rearrange(input_image, "1 c h w -> h w c")
212
+ input_image = Image.fromarray(input_image.type(torch.uint8).cpu().numpy())
213
+
214
+ return edited_image # , gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
215
+
216
+
217
+ @click.command()
218
+ @click.option("--ckpt", type=str, default="checkpoints/v1-5-pruned-emaonly-adaption-task-humanalign.ckpt")
219
+ def main(ckpt="checkpoints/v1-5-pruned-emaonly-adaption-task-humanalign.ckpt"):
220
+ css = '''
221
+ .container {max-width: 1150px;margin: auto;padding-top: 1.5rem}
222
+ #image_upload{min-height:400px}
223
+ #image_upload [data-testid="image"], #image_upload [data-testid="image"] > div{min-height: 400px}
224
+ #mask_radio .gr-form{background:transparent; border: none}
225
+ #word_mask{margin-top: .75em !important}
226
+ #word_mask textarea:disabled{opacity: 0.3}
227
+ .footer {margin-bottom: 45px;margin-top: 35px;text-align: center;border-bottom: 1px solid #e5e5e5}
228
+ .footer>p {font-size: .8rem; display: inline-block; padding: 0 10px;transform: translateY(10px);background: white}
229
+ .dark .footer {border-color: #303030}
230
+ .dark .footer>p {background: #0b0f19}
231
+ .acknowledgments h4{margin: 1.25em 0 .25em 0;font-weight: bold;font-size: 115%}
232
+ #image_upload .touch-none{display: flex}
233
+ @keyframes spin {
234
+ from {
235
+ transform: rotate(0deg);
236
+ }
237
+ to {
238
+ transform: rotate(360deg);
239
+ }
240
+ }
241
+ #share-btn-container {
242
+ display: flex; padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; width: 13rem;
243
+ }
244
+ #share-btn {
245
+ all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.25rem !important; padding-bottom: 0.25rem !important;
246
+ }
247
+ #share-btn * {
248
+ all: unset;
249
+ }
250
+ #share-btn-container div:nth-child(-n+2){
251
+ width: auto !important;
252
+ min-height: 0px !important;
253
+ }
254
+ #share-btn-container .wrap {
255
+ display: none !important;
256
+ }
257
+ '''
258
+
259
+ config = OmegaConf.load("configs/instruct_diffusion.yaml")
260
+
261
+ # ckpt = "checkpoints/v1-5-pruned-emaonly-adaption-task-humanalign.ckpt"
262
+
263
+ if not os.path.exists(ckpt):
264
+ raise ValueError(f"Checkpoint {ckpt} does not exist")
265
+
266
+ vae_ckpt = None
267
+ model = load_model_from_config(config, ckpt, vae_ckpt)
268
+ model.eval().cuda()
269
+
270
+ model_wrap = K.external.CompVisDenoiser(model)
271
+ model_wrap_cfg = CFGDenoiser(model_wrap)
272
+ null_token = model.get_learned_conditioning([""])
273
+
274
+ image_blocks = gr.Blocks(css=css)
275
+ with image_blocks as demo:
276
+ gr.HTML(get_header())
277
+ with gr.Group():
278
+ with gr.Box():
279
+ with gr.Row():
280
+
281
+ with gr.Column():
282
+ image = gr.Image(source='upload', tool=None, elem_id="image_upload", type="pil", label="Source Image")
283
+ instruction = gr.Textbox(lines=3, placeholder="Enter text to edit", label="Text")
284
+
285
+ cfg_text = gr.Slider(label="Guidance scale (TXT)", value=7.0, maximum=15,interactive=True)
286
+ cfg_image = gr.Slider(label="Guidance scale (IMG)", value=1.25, maximum=15,interactive=True)
287
+
288
+ steps = gr.Slider(label="Steps", value=50, minimum=2, maximum=75, step=1,interactive=True)
289
+ resolution = gr.Slider(label="Resolution (long side)", value=512, minimum=256, maximum=768, step=64, interactive=True)
290
+
291
+ seed = gr.Slider(0, 10000, label='Seed', value=0, step=1)
292
+
293
+ with gr.Row(elem_id="prompt-container", mobile_collapse=False, equal_height=True):
294
+ btn = gr.Button(
295
+ "Edit!",
296
+ margin=False,
297
+ rounded=(False, True, True, False),
298
+ full_width=True,
299
+ )
300
+
301
+ # output
302
+ with gr.Column():
303
+ image_out = gr.Image(label="Output", elem_id="output-img", height=400, show_download_button=True)
304
+
305
+ partial_predict = partial(
306
+ predict,
307
+ model, model_wrap,
308
+ model_wrap_cfg,
309
+ null_token, # RESOLUTION
310
+ )
311
+
312
+ btn.click(
313
+ fn=partial_predict,
314
+ inputs=[
315
+ resolution, image, instruction, seed, steps, cfg_text, cfg_image
316
+ ],
317
+ outputs=[image_out])
318
+
319
+ gr.HTML(
320
+ """
321
+ <div class="footer">
322
+ <p>
323
+ InstructDiffusion Demo
324
+ </p>
325
+ </div>
326
+ <div class="acknowledgments">
327
+ <p><h4>LICENSE</h4>
328
+ The model is licensed with a <a href="https://huggingface.co/spaces/CompVis/stable-diffusion-license" style="text-decoration: underline;" target="_blank">CreativeML Open RAIL-M</a> license. The authors claim no rights on the outputs you generate, you are free to use them and are accountable for their use which must not go against the provisions set in this license. The license forbids you from sharing any content that violates any laws, produce any harm to a person, disseminate any personal information that would be meant for harm, spread misinformation and target vulnerable groups. For the full list of restrictions please <a href="https://huggingface.co/spaces/CompVis/stable-diffusion-license" target="_blank" style="text-decoration: underline;" target="_blank">read the license</a></p>
329
+ """
330
+ )
331
+
332
+ image_blocks.launch(share=True, max_threads=1).queue()
333
+
334
+
335
+ if __name__ == "__main__":
336
+ main()
configs/instruct_diffusion.yaml ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File modified by authors of InstructDiffusion from original (https://github.com/CompVis/stable-diffusion).
2
+ # See more details in LICENSE.
3
+
4
+ model:
5
+ base_learning_rate: 1.0e-04
6
+ weight_decay: 0.01
7
+ target: ldm.models.diffusion.ddpm_edit.LatentDiffusion
8
+ params:
9
+ fp16: True
10
+ deepspeed: 'deepspeed_1'
11
+ ckpt_path: stable_diffusion/models/ldm/stable-diffusion-v1/v1-5-pruned-emaonly-adaption.ckpt
12
+ linear_start: 0.00085
13
+ linear_end: 0.0120
14
+ num_timesteps_cond: 1
15
+ log_every_t: 200
16
+ timesteps: 1000
17
+ first_stage_key: edited
18
+ cond_stage_key: edit
19
+ image_size: 32
20
+ channels: 4
21
+ cond_stage_trainable: false # Note: different from the one we trained before
22
+ conditioning_key: hybrid
23
+ monitor: val/loss_simple_ema
24
+ scale_factor: 0.18215
25
+
26
+ scheduler_config: # 10000 warmup steps
27
+ target: ldm.lr_scheduler.LambdaLinearScheduler
28
+ params:
29
+ warm_up_steps: [ 0 ]
30
+ cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
31
+ f_start: [ 1.e-6 ]
32
+ f_max: [ 1. ]
33
+ f_min: [ 1. ]
34
+
35
+ unet_config:
36
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
37
+ params:
38
+ image_size: 32 # unused
39
+ in_channels: 8
40
+ out_channels: 4
41
+ model_channels: 320
42
+ attention_resolutions: [ 4, 2, 1 ]
43
+ num_res_blocks: 2
44
+ channel_mult: [ 1, 2, 4, 4 ]
45
+ num_heads: 8
46
+ use_spatial_transformer: True
47
+ transformer_depth: 1
48
+ context_dim: 768
49
+ use_checkpoint: True
50
+ legacy: False
51
+ force_type_convert: True
52
+
53
+ first_stage_config:
54
+ target: ldm.models.autoencoder.AutoencoderKL
55
+ params:
56
+ embed_dim: 4
57
+ monitor: val/rec_loss
58
+ ddconfig:
59
+ double_z: true
60
+ z_channels: 4
61
+ resolution: 256
62
+ in_channels: 3
63
+ out_ch: 3
64
+ ch: 128
65
+ ch_mult:
66
+ - 1
67
+ - 2
68
+ - 4
69
+ - 4
70
+ num_res_blocks: 2
71
+ attn_resolutions: []
72
+ dropout: 0.0
73
+ lossconfig:
74
+ target: torch.nn.Identity
75
+
76
+ cond_stage_config:
77
+ target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
78
+
79
+ data:
80
+ target: main.DataModuleFromConfig
81
+ params:
82
+ batch_size: 64
83
+ num_workers: 4
84
+ train:
85
+
86
+ - ds1:
87
+ target: dataset.pose.pose.MPIIDataset
88
+ params:
89
+ root: data/mpii/
90
+ image_set: train
91
+ is_train: True
92
+ max_prompt_num: 5
93
+ min_prompt_num: 1
94
+ radius: 10
95
+ - ds2:
96
+ target: dataset.pose.pose.COCODataset
97
+ params:
98
+ root: data/coco/
99
+ image_set: train2017
100
+ is_train: True
101
+ max_prompt_num: 5
102
+ min_prompt_num: 1
103
+ radius: 10
104
+ - ds3:
105
+ target: dataset.pose.pose.CrowdPoseDataset
106
+ params:
107
+ root: data/crowdpose/
108
+ image_set: train
109
+ is_train: True
110
+ max_prompt_num: 5
111
+ min_prompt_num: 1
112
+ radius: 10
113
+ - ds4:
114
+ target: dataset.pose.pose.AICDataset
115
+ params:
116
+ root: data/aic/
117
+ image_set: train
118
+ is_train: True
119
+ max_prompt_num: 5
120
+ min_prompt_num: 1
121
+ radius: 10
122
+ sample_weight: 0.1
123
+
124
+ - ds5:
125
+ target: dataset.seg.coco_stuff.COCOStuffDataset
126
+ params:
127
+ path: data/coco-stuff
128
+ split: train2017
129
+ crop_res: 256
130
+ flip_prob: 0.5
131
+ transparency: 0.5
132
+ empty_percentage: 0.2
133
+ - ds6:
134
+ target: dataset.seg.grefcoco_segmentation.GrefCOCODataset
135
+ params:
136
+ path: data/coco_2014
137
+ split: train
138
+ min_resize_res: 256
139
+ max_resize_res: 256
140
+ crop_res: 256
141
+ flip_prob: 0.0
142
+ transparency: 0.5
143
+ - ds7:
144
+ target: dataset.seg.refcoco_segmentation.RefCOCODataset
145
+ params:
146
+ path: data/coco_2014
147
+ split: train
148
+ crop_res: 256
149
+ flip_prob: 0.0
150
+ transparency: 0.5
151
+
152
+ - ds8:
153
+ target: dataset.low_level.lowlevel_gopro.GoPro
154
+ params:
155
+ path: data/GoPro
156
+ split: train
157
+ size: 256
158
+ flip_prob: 0.5
159
+ interpolation: pil_lanczos
160
+ sample_weight: 2.0
161
+ - ds9:
162
+ target: dataset.low_level.lowlevel_reds.REDS
163
+ params:
164
+ path: data/REDS
165
+ split: train
166
+ size: 256
167
+ flip_prob: 0.5
168
+ interpolation: pil_lanczos
169
+ sample_weight: 0.2
170
+ - ds10:
171
+ target: dataset.low_level.lowlevel_sidd.SIDD
172
+ params:
173
+ path: data/SIDD
174
+ split: train
175
+ size: 256
176
+ flip_prob: 0.5
177
+ interpolation: pil_lanczos
178
+ sample_weight: 20
179
+ - ds11:
180
+ target: dataset.low_level.lowlevel_clwd.CLWD
181
+ params:
182
+ path: data/CLWD
183
+ split: train
184
+ size: 256
185
+ flip_prob: 0.5
186
+ interpolation: pil_lanczos
187
+ sample_weight: 0.2
188
+
189
+ - ds12:
190
+ target: dataset.editing.edit_zip_dataset.FilteredIP2PDataset
191
+ params:
192
+ path: data/clip-filtered-dataset
193
+ split: train
194
+ min_resize_res: 256
195
+ max_resize_res: 256
196
+ crop_res: 256
197
+ flip_prob: 0.5
198
+ sample_weight: 0.2
199
+ - ds13:
200
+ target: dataset.editing.edit_zip_dataset.GIERDataset
201
+ params:
202
+ path: data/GIER_editing_data/
203
+ split: train
204
+ min_resize_res: 256
205
+ max_resize_res: 256
206
+ crop_res: 256
207
+ flip_prob: 0.0
208
+ zip_start_index: 0
209
+ zip_end_index: 100
210
+ sample_weight: 2.0
211
+ - ds14:
212
+ target: dataset.editing.edit_zip_dataset.GQAInpaintDataset
213
+ params:
214
+ path: data/gqa-inpaint
215
+ min_resize_res: 256
216
+ max_resize_res: 256
217
+ crop_res: 256
218
+ flip_prob: 0.0
219
+ - ds15:
220
+ target: dataset.editing.edit_zip_dataset.MagicBrushDataset
221
+ params:
222
+ path: data/MagicBrush/
223
+ split: train
224
+ min_resize_res: 256
225
+ max_resize_res: 256
226
+ crop_res: 256
227
+ flip_prob: 0.5
228
+ zip_start_index: 0
229
+ zip_end_index: 100
230
+ - ds16:
231
+ target: dataset.editing.edit_zip_dataset.IEIWDataset
232
+ params:
233
+ path: data/ieiw/
234
+ split: train
235
+ min_resize_res: 256
236
+ max_resize_res: 256
237
+ crop_res: 256
238
+ flip_prob: 0.5
239
+
240
+ validation:
241
+ target: dataset.pose.pose.COCODataset
242
+ params:
243
+ root: data/coco/
244
+ image_set: val2017
245
+ is_train: False
246
+ max_prompt_num: 5
247
+ min_prompt_num: 1
248
+ radius: 10
249
+
250
+ trainer:
251
+ initial_scale: 13
252
+ max_epochs: 200
253
+ save_freq: 5
254
+ accumulate_grad_batches: 1
255
+ clip_grad: 0.0
256
+ optimizer: adamw
dataset/README.md ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You can download these datasets: [COCO](http://cocodataset.org/#download), [CrowdPose](https://github.com/Jeff-sjtu/CrowdPose#dataset), [MPII](http://human-pose.mpi-inf.mpg.de/), [AIC](https://arxiv.org/abs/1711.06475), [COCO-Stuff](https://github.com/nightrome/cocostuff), [RefCOCO](https://github.com/lichengunc/refer), [GrefCOCO](https://github.com/henghuiding/gRefCOCO), [GoPro](https://seungjunnah.github.io/Datasets/gopro), [REDS](https://seungjunnah.github.io/Datasets/reds.html), [SIDD](https://www.eecs.yorku.ca/~kamel/sidd/), [CLWD](https://arxiv.org/abs/2012.07616), [IP2PDataset](https://github.com/timothybrooks/instruct-pix2pix), [GIER](https://sites.google.com/view/gierdataset), [GQAInpaint](https://github.com/abyildirim/inst-inpaint), [MagicBrush](https://osu-nlp-group.github.io/MagicBrush/). The resulting data directory should look like this:
2
+
3
+ InstructDiffusion
4
+ |-- data
5
+ `-- |-- coco
6
+ | |-- annotations
7
+ | `-- images
8
+ |-- mpii
9
+ | |-- annot
10
+ | `-- images
11
+ |-- crowdpose
12
+ | |-- json
13
+ | `-- images
14
+ |-- aic
15
+ | |-- annotations
16
+ | `-- ai_challenger_keypoint_train_20170902
17
+ |
18
+ |-- coco-stuff
19
+ | |-- annotations
20
+ | |-- labels.txt
21
+ | `-- images
22
+ |-- coco_2014
23
+ | |-- grefcoco
24
+ | | |-- grefs(unc).json
25
+ | | `-- instances.json
26
+ | |-- refcoco
27
+ | | |-- instances.json
28
+ | | |-- refs(google).p
29
+ | | `-- refs(unc).p
30
+ | `-- images
31
+ |
32
+ |-- GoPro
33
+ | |-- train
34
+ | `-- test
35
+ |-- REDS
36
+ | |-- train
37
+ | `-- val
38
+ |-- SIDD
39
+ | |-- train
40
+ | `-- val
41
+ |-- CLWD
42
+ | |-- train
43
+ | |-- test
44
+ | `-- watermark_logo
45
+ |
46
+ |-- clip-filtered-dataset
47
+ | |-- shard-00.zip
48
+ | |-- shard-01.zip
49
+ | `-- ...
50
+ |-- GIER_editing_data
51
+ | |-- images
52
+ | `-- GIER.json
53
+ |-- gqa-inpaint
54
+ | |-- images
55
+ | |-- images_inpainted
56
+ | |-- masks
57
+ | |-- train_scenes.json
58
+ | `-- meta_info.json
59
+ `-- MagicBrush
60
+ |-- data
61
+ |-- processed-train
62
+ `-- magic_train.json
dataset/editing/edit_zip_dataset.py ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InstructDiffusion
3
+ # Based on instruct-pix2pix (https://github.com/timothybrooks/instruct-pix2pix)
4
+ # Modified by Tiankai Hang (tkhang@seu.edu.cn)
5
+ # --------------------------------------------------------
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import json
11
+ import math
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ import numpy as np
16
+ import torch
17
+ import torchvision
18
+ from einops import rearrange
19
+ import PIL
20
+ from PIL import Image
21
+ from torch.utils.data import Dataset
22
+ from tqdm.auto import tqdm
23
+
24
+ import random
25
+
26
+ from dataset.utils.zip_manager import MultipleZipManager
27
+
28
+
29
+ if hasattr(Image, "Resampling"):
30
+ # deprecated in pillow >= 10.0.0
31
+ RESAMPLING_METHOD = Image.Resampling.LANCZOS
32
+ else:
33
+ RESAMPLING_METHOD = Image.LANCZOS
34
+
35
+
36
+ class FilteredIP2PDataset(Dataset):
37
+ def __init__(
38
+ self,
39
+ path: str,
40
+ split: str = "train",
41
+ splits: tuple[float, float, float] = (0.9, 0.05, 0.05),
42
+ min_resize_res: int = 256,
43
+ max_resize_res: int = 256,
44
+ crop_res: int = 256,
45
+ flip_prob: float = 0.0,
46
+ zip_start_index: int = 0,
47
+ zip_end_index: int = 30,
48
+ instruct: bool = False,
49
+ max_num_images = None,
50
+ sample_weight: float = 1.0,
51
+ reverse_version: bool = False,
52
+ **kwargs
53
+ ):
54
+ assert split in ("train", "val", "test")
55
+ assert sum(splits) == 1
56
+ self.path = path
57
+ self.min_resize_res = min_resize_res
58
+ self.max_resize_res = max_resize_res
59
+ self.crop_res = crop_res
60
+ self.flip_prob = flip_prob
61
+ self.instruct = instruct
62
+
63
+ zip_list = []
64
+ for i in range(zip_start_index, zip_end_index):
65
+ name = "shard-"+str(i).zfill(2)+'.zip'
66
+ zip_list.append(os.path.join(self.path, name))
67
+
68
+ self.image_dataset = MultipleZipManager(zip_list, 'image', sync=True) # sync=True is faster
69
+
70
+ with open(Path(self.path, "seeds.json")) as f:
71
+ self.seeds = json.load(f)
72
+
73
+ split_0, split_1 = {
74
+ "train": (0.0, splits[0]),
75
+ "val": (splits[0], splits[0] + splits[1]),
76
+ "test": (splits[0] + splits[1], 1.0),
77
+ }[split]
78
+
79
+ idx_0 = math.floor(split_0 * len(self.seeds))
80
+ idx_1 = math.floor(split_1 * len(self.seeds))
81
+ self.seeds = self.seeds[idx_0:idx_1]
82
+
83
+ if max_num_images is not None and max_num_images > 0:
84
+ self.seeds = self.seeds[:min(max_num_images, len(self.seeds))]
85
+
86
+ # flatten seeds
87
+ self.seeds = [(name, seed) for name, seeds in self.seeds for seed in seeds]
88
+ self.sample_weight = sample_weight
89
+
90
+ while True:
91
+ try:
92
+ with open('filtered_ids_ip2p.json') as json_file:
93
+ filtered_ids = json.load(json_file)
94
+ break
95
+ except:
96
+ # download json file from url
97
+ if reverse_version:
98
+ os.system('wget https://github.com/TiankaiHang/storage/releases/download/readout/filtered_ids_ip2p.json')
99
+ else:
100
+ os.system("wget https://github.com/TiankaiHang/storage/releases/download/readout/filtered-ip2p-thres5.5-0.5.json -O filtered_ids_ip2p.json")
101
+
102
+ print("seeds:", len(self.seeds))
103
+ # self.seeds = [seed for seed in self.seeds if seed[1] in filtered_ids]
104
+ # faster
105
+ # self.seeds = list(filter(lambda seed: seed[1] in filtered_ids, self.seeds))
106
+ # to numpy and faster in parallel
107
+ # import pdb; pdb.set_trace()
108
+ _seeds = [f"{a}/{b}" for a, b in self.seeds]
109
+ self.seeds = np.array(self.seeds)
110
+ _seeds = np.array(_seeds)
111
+ self.seeds = self.seeds[np.isin(_seeds, filtered_ids)]
112
+ self.seeds = self.seeds.tolist()
113
+
114
+ self.return_add_kwargs = kwargs.get("return_add_kwargs", False)
115
+
116
+ def __len__(self) -> int:
117
+ return int(len(self.seeds) * self.sample_weight)
118
+
119
+ def __getitem__(self, i: int) -> dict[str, Any]:
120
+ # name, seeds = self.seeds[i]
121
+ if self.sample_weight >= 1:
122
+ i = i % len(self.seeds)
123
+ else:
124
+ remainder = math.ceil(i / self.sample_weight - int(i / self.sample_weight))
125
+ i = int(i / self.sample_weight) + random.randint(0, int(1 / self.sample_weight) - 1 + remainder)
126
+
127
+ name, seed = self.seeds[i]
128
+ propt_name = name + "/prompt.json"
129
+ if not self.image_dataset.managers[self.image_dataset.mapping[propt_name]]._init:
130
+ self.image_dataset.managers[self.image_dataset.mapping[propt_name]].initialize(close=False)
131
+ # propt_name = name + "/prompt.json"
132
+ byteflow = self.image_dataset.managers[self.image_dataset.mapping[propt_name]].zip_fd.read(propt_name)
133
+ texts = json.loads(byteflow.decode('utf-8'))
134
+ prompt = texts["edit"]
135
+ if self.instruct:
136
+ prompt = "Image Editing: " + prompt
137
+
138
+ text_input = texts["input"]
139
+ text_output = texts["output"]
140
+
141
+ # image_0 = Image.open(propt_dir.joinpath(f"{seed}_0.jpg"))
142
+ # image_1 = Image.open(propt_dir.joinpath(f"{seed}_1.jpg"))
143
+ image_0 = self.image_dataset.get(name+f"/{seed}_0.jpg")
144
+ image_1 = self.image_dataset.get(name+f"/{seed}_1.jpg")
145
+
146
+ reize_res = torch.randint(self.min_resize_res, self.max_resize_res + 1, ()).item()
147
+ image_0 = image_0.resize((reize_res, reize_res), RESAMPLING_METHOD)
148
+ image_1 = image_1.resize((reize_res, reize_res), RESAMPLING_METHOD)
149
+
150
+ image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
151
+ image_1 = rearrange(2 * torch.tensor(np.array(image_1)).float() / 255 - 1, "h w c -> c h w")
152
+
153
+ crop = torchvision.transforms.RandomCrop(self.crop_res)
154
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
155
+ image_0, image_1 = flip(crop(torch.cat((image_0, image_1)))).chunk(2)
156
+
157
+ if self.return_add_kwargs:
158
+ add_kwargs = dict(
159
+ name=name,
160
+ seed=seed,
161
+ text_input=text_input,
162
+ text_output=text_output,
163
+ )
164
+ else:
165
+ add_kwargs = {}
166
+
167
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt), **add_kwargs)
168
+
169
+
170
+ class GIERDataset(Dataset):
171
+ def __init__(
172
+ self,
173
+ path: str,
174
+ split: str = "train",
175
+ splits: tuple[float, float, float] = (0.9, 0.05, 0.05),
176
+ min_resize_res: int = 256,
177
+ max_resize_res: int = 256,
178
+ crop_res: int = 256,
179
+ flip_prob: float = 0.0,
180
+ zip_start_index: int = 0,
181
+ zip_end_index: int = 30,
182
+ sample_weight: float = 1.0,
183
+ instruct: bool = False,
184
+ ):
185
+ assert split in ("train", "val", "test")
186
+ assert sum(splits) == 1
187
+ self.path = path
188
+ self.min_resize_res = min_resize_res
189
+ self.max_resize_res = max_resize_res
190
+ self.crop_res = crop_res
191
+ self.flip_prob = flip_prob
192
+ self.instruct = instruct
193
+
194
+ # self.meta = torch.load(Path(self.path, "GIER.json"), map_location="cpu")
195
+ # load json file
196
+ with open(Path(self.path, "GIER_new.json")) as json_file:
197
+ self.meta = json.load(json_file)
198
+
199
+ print(f"||||||||||||||||||||||||||||| \n Loaded {len(self.meta)} images from json file")
200
+
201
+ input_does_not_exist = []
202
+ output_does_not_exist = []
203
+ # filter out out images that do not exist
204
+ if not os.path.exists(os.path.join(self.path, "filtered_meta_new.pt")):
205
+ filtered_meta = []
206
+ for i in tqdm(range(len(self.meta))):
207
+ input_path = os.path.join(self.path, "warped", self.meta[i]["input"])
208
+ output_path = os.path.join(self.path, "warped", self.meta[i]["output"])
209
+
210
+ if not os.path.exists(input_path):
211
+ input_path = os.path.join(self.path, "images", self.meta[i]["input"])
212
+ if not os.path.exists(input_path):
213
+ input_does_not_exist.append(input_path)
214
+
215
+ if not os.path.exists(output_path):
216
+ output_path = os.path.join(self.path, "images", self.meta[i]["output"])
217
+ if not os.path.exists(output_path):
218
+ output_does_not_exist.append(output_path)
219
+
220
+ if os.path.exists(input_path) and os.path.exists(output_path):
221
+ filtered_meta.append(
222
+ dict(
223
+ input=input_path,
224
+ output=output_path,
225
+ prompts=self.meta[i]["prompts"],
226
+ )
227
+ )
228
+ else:
229
+ print(f"\n {input_path} or {output_path} does not exist")
230
+ torch.save(filtered_meta, os.path.join(self.path, "filtered_meta_new.pt"))
231
+ else:
232
+ filtered_meta = torch.load(os.path.join(self.path, "filtered_meta_new.pt"), map_location="cpu")
233
+
234
+ self.meta = filtered_meta
235
+ print(f"||||||||||||||||||||||||||||| \n Filtered {len(self.meta)} images")
236
+ for i in range(len(self.meta)):
237
+ self.meta[i]['input'] = self.meta[i]['input'].replace('/mnt/external/datasets/GIER_editing_data/', self.path)
238
+ self.meta[i]['output'] = self.meta[i]['output'].replace('/mnt/external/datasets/GIER_editing_data/', self.path)
239
+
240
+ # write input_does_not_exist and output_does_not_exist to file
241
+ with open(Path(self.path, f"input_does_not_exist.txt"), "w") as f:
242
+ for item in input_does_not_exist:
243
+ f.write("%s\n" % item)
244
+ with open(Path(self.path, f"output_does_not_exist.txt"), "w") as f:
245
+ for item in output_does_not_exist:
246
+ f.write("%s\n" % item)
247
+
248
+ split_0, split_1 = {
249
+ "train": (0.0, splits[0]),
250
+ "val": (splits[0], splits[0] + splits[1]),
251
+ "test": (splits[0] + splits[1], 1.0),
252
+ }[split]
253
+
254
+ idx_0 = math.floor(split_0 * len(self.meta))
255
+ idx_1 = math.floor(split_1 * len(self.meta))
256
+
257
+ self.meta = self.meta[idx_0:idx_1]
258
+ self.sample_weight = sample_weight
259
+ print('original GIER', len(self.meta))
260
+
261
+ def __len__(self) -> int:
262
+ return int(len(self.meta) * self.sample_weight)
263
+
264
+ def __getitem__(self, i: int) -> dict[str, Any]:
265
+ if self.sample_weight >= 1:
266
+ i = i % len(self.meta)
267
+ else:
268
+ i = int(i / self.sample_weight) + random.randint(0, int(1 / self.sample_weight) - 1)
269
+
270
+ # prompt = self.meta[i]["prompts"]
271
+ prompt = random.choice(self.meta[i]["prompts"])
272
+ try:
273
+ image_0 = Image.open(self.meta[i]["input"]).convert("RGB")
274
+ image_1 = Image.open(self.meta[i]["output"]).convert("RGB")
275
+ except PIL.UnidentifiedImageError:
276
+ print(f"\n {self.meta[i]['input']} or {self.meta[i]['output']} is not a valid image")
277
+ i = random.randint(0, len(self.meta) - 1)
278
+ return self.__getitem__(i)
279
+
280
+ reize_res = torch.randint(self.min_resize_res, self.max_resize_res + 1, ()).item()
281
+ image_0 = image_0.resize((reize_res, reize_res), RESAMPLING_METHOD)
282
+ image_1 = image_1.resize((reize_res, reize_res), RESAMPLING_METHOD)
283
+
284
+ image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
285
+ image_1 = rearrange(2 * torch.tensor(np.array(image_1)).float() / 255 - 1, "h w c -> c h w")
286
+
287
+ crop = torchvision.transforms.RandomCrop(self.crop_res)
288
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
289
+ image_0, image_1 = flip(crop(torch.cat((image_0, image_1)))).chunk(2)
290
+
291
+ if self.instruct:
292
+ prompt = "Image Editing: " + prompt
293
+
294
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
295
+
296
+
297
+ class GQAInpaintDataset(Dataset):
298
+ r"""
299
+ shoud download and unzip the data first
300
+
301
+ ```
302
+ mkdir -p ../datasets
303
+ cd ../datasets
304
+
305
+ # if file exists, then skip
306
+ if [ ! -f "gqa-inpaint.zip" ]; then
307
+ sudo azcopy copy "https://bingdatawu2.blob.core.windows.net/genrecog/private/t-thang/gqa-inpaint.zip${TOKEN}" .
308
+ unzip gqa-inpaint.zip -d gqa-inpaint > /dev/null
309
+ fi
310
+
311
+ if [ ! -f "images.zip" ]; then
312
+ sudo azcopy copy "https://bingdatawu2.blob.core.windows.net/genrecog/private/t-thang/images.zip${TOKEN}" .
313
+ unzip images.zip > /dev/null
314
+ fi
315
+ ```
316
+
317
+ """
318
+ def __init__(self, **kwargs):
319
+ # load from json ../datasets/gqa-inpaint/meta_info.json
320
+ self.path = kwargs.get("path", "../datasets/gqa-inpaint")
321
+ self.instruct = kwargs.get("instruct", False)
322
+ with open(self.path + "/meta_info.json", "r") as f:
323
+ self.meta_info = json.load(f)
324
+
325
+ self.min_resize_res = kwargs.get("min_resize_res", 256)
326
+ self.max_resize_res = kwargs.get("max_resize_res", 256)
327
+ self.crop_res = kwargs.get("crop_res", 256)
328
+
329
+ self.flip_prob = kwargs.get("flip_prob", 0.5)
330
+
331
+ def __len__(self):
332
+ return len(self.meta_info)
333
+
334
+ def __getitem__(self, i):
335
+ item = self.meta_info[i]
336
+ src_img = Image.open(item["source_image_path"].replace("../datasets", self.path)).convert("RGB")
337
+ tgt_img = Image.open(item["target_image_path"].replace("../datasets/gqa-inpaint", self.path)).convert("RGB")
338
+
339
+ image_0 = src_img
340
+ image_1 = tgt_img
341
+
342
+ reize_res = torch.randint(self.min_resize_res, self.max_resize_res + 1, ()).item()
343
+ image_0 = image_0.resize((reize_res, reize_res), RESAMPLING_METHOD)
344
+ image_1 = image_1.resize((reize_res, reize_res), RESAMPLING_METHOD)
345
+ instruction = item["instruction"]
346
+ if self.instruct:
347
+ instruction = "Image Editing: " + instruction
348
+ # return image_0, image_1, instruction
349
+
350
+ image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
351
+ image_1 = rearrange(2 * torch.tensor(np.array(image_1)).float() / 255 - 1, "h w c -> c h w")
352
+
353
+ crop = torchvision.transforms.RandomCrop(self.crop_res)
354
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
355
+ image_0, image_1 = flip(crop(torch.cat((image_0, image_1)))).chunk(2)
356
+
357
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=instruction))
358
+
359
+
360
+ class MagicBrushDataset(Dataset):
361
+ def __init__(
362
+ self,
363
+ path: str,
364
+ split: str = "train",
365
+ splits: tuple[float, float, float] = (0.9, 0.05, 0.05),
366
+ min_resize_res: int = 256,
367
+ max_resize_res: int = 256,
368
+ crop_res: int = 256,
369
+ flip_prob: float = 0.0,
370
+ zip_start_index: int = 0,
371
+ zip_end_index: int = 30,
372
+ len_dataset: int = -1,
373
+ instruct: bool = False,
374
+ sample_weight: float = 1.0,
375
+ ):
376
+ assert split in ("train", "val", "test")
377
+ assert sum(splits) == 1
378
+ self.path = path
379
+ self.min_resize_res = min_resize_res
380
+ self.max_resize_res = max_resize_res
381
+ self.crop_res = crop_res
382
+ self.flip_prob = flip_prob
383
+ self.instruct = instruct
384
+ self.sample_weight = sample_weight
385
+
386
+ self.meta_path = os.path.join(self.path, "magic_train.json")
387
+ with open(self.meta_path, "r") as f:
388
+ self.meta = json.load(f)
389
+
390
+ def __len__(self) -> int:
391
+ return int(len(self.meta) * self.sample_weight)
392
+
393
+ def __getitem__(self, i: int) -> dict[str, Any]:
394
+ if self.sample_weight >= 1:
395
+ i = i % len(self.meta)
396
+ else:
397
+ i = int(i / self.sample_weight) + random.randint(0, int(1 / self.sample_weight) - 1)
398
+
399
+ item = self.meta[i]
400
+ try:
401
+ image_0 = Image.open(os.path.join(self.path, item["input"])).convert("RGB")
402
+ image_1 = Image.open(os.path.join(self.path, item["edited"])).convert("RGB")
403
+ except (PIL.UnidentifiedImageError, FileNotFoundError):
404
+ print(f"\n {self.path}/{item['input']} or {self.path}/{item['edited']} is not a valid image")
405
+ i = random.randint(0, len(self.meta) - 1)
406
+ return self.__getitem__(i)
407
+ prompt = item["instruction"]
408
+
409
+ reize_res = torch.randint(self.min_resize_res, self.max_resize_res + 1, ()).item()
410
+ image_0 = image_0.resize((reize_res, reize_res), RESAMPLING_METHOD)
411
+ image_1 = image_1.resize((reize_res, reize_res), RESAMPLING_METHOD)
412
+
413
+ if self.instruct:
414
+ prompt = "Image Editing: " + prompt
415
+ # return image_0, image_1, prompt
416
+
417
+ image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
418
+ image_1 = rearrange(2 * torch.tensor(np.array(image_1)).float() / 255 - 1, "h w c -> c h w")
419
+
420
+ crop = torchvision.transforms.RandomCrop(self.crop_res)
421
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
422
+ image_0, image_1 = flip(crop(torch.cat((image_0, image_1)))).chunk(2)
423
+
424
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
425
+
426
+
427
+ class IEIWDataset(Dataset):
428
+ def __init__(
429
+ self,
430
+ path: str,
431
+ split: str = "train",
432
+ splits: tuple[float, float, float] = (0.9, 0.05, 0.05),
433
+ min_resize_res: int = 256,
434
+ max_resize_res: int = 256,
435
+ crop_res: int = 256,
436
+ flip_prob: float = 0.0,
437
+ zip_start_index: int = 0,
438
+ zip_end_index: int = 30,
439
+ sample_weight: float = 1.0,
440
+ instruct: bool = False,
441
+ ):
442
+ assert split in ("train", "val", "test")
443
+ assert sum(splits) == 1
444
+ self.path = path
445
+ self.min_resize_res = min_resize_res
446
+ self.max_resize_res = max_resize_res
447
+ self.crop_res = crop_res
448
+ self.flip_prob = flip_prob
449
+ self.instruct = instruct
450
+
451
+ self.meta_path = os.path.join(self.path, "meta_infov1.json")
452
+ with open(self.meta_path, "r") as f:
453
+ self.meta = json.load(f)
454
+ self.sample_weight = sample_weight
455
+ print('original synthetic', len(self.meta))
456
+
457
+ def __len__(self) -> int:
458
+ return int(len(self.meta) * self.sample_weight)
459
+
460
+ def __getitem__(self, i: int) -> dict[str, Any]:
461
+ if self.sample_weight >= 1:
462
+ i = i % len(self.meta)
463
+ else:
464
+ i = int(i / self.sample_weight) + random.randint(0, int(1 / self.sample_weight) - 1)
465
+
466
+ item = self.meta[i]
467
+ item['input'] = item['input'].replace('/mnt/external/tmp/2023/06/11/', self.path)
468
+ item['edited'] = item['edited'].replace('/mnt/external/tmp/2023/06/11/', self.path)
469
+ try:
470
+ image_0 = Image.open(item["input"]).convert("RGB")
471
+ image_1 = Image.open(item["edited"]).convert("RGB")
472
+ except (PIL.UnidentifiedImageError, FileNotFoundError):
473
+ print(f"\n {item['input']} or {item['edited']} is not a valid image")
474
+ i = random.randint(0, len(self.meta) - 1)
475
+ return self.__getitem__(i)
476
+ prompt = item["instruction"]
477
+
478
+ reize_res = torch.randint(self.min_resize_res, self.max_resize_res + 1, ()).item()
479
+ image_0 = image_0.resize((reize_res, reize_res), RESAMPLING_METHOD)
480
+ image_1 = image_1.resize((reize_res, reize_res), RESAMPLING_METHOD)
481
+ if self.instruct:
482
+ prompt = "Image Editing: " + prompt
483
+ # return image_0, image_1, prompt
484
+
485
+ image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
486
+ image_1 = rearrange(2 * torch.tensor(np.array(image_1)).float() / 255 - 1, "h w c -> c h w")
487
+
488
+ crop = torchvision.transforms.RandomCrop(self.crop_res)
489
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
490
+ image_0, image_1 = flip(crop(torch.cat((image_0, image_1)))).chunk(2)
491
+
492
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
493
+
494
+
dataset/low_level/lowlevel_clwd.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InstructDiffusion
3
+ # Based on instruct-pix2pix (https://github.com/timothybrooks/instruct-pix2pix)
4
+ # Modified by Chen Li (edward82@stu.xjtu.edu.cn)
5
+ # --------------------------------------------------------
6
+
7
+ import os
8
+ import numpy as np
9
+ from torch.utils.data import Dataset
10
+ import torch
11
+ from PIL import Image
12
+ import torchvision.transforms.functional as TF
13
+ from pdb import set_trace as stx
14
+ import random
15
+ import cv2
16
+ from PIL import Image
17
+ import torchvision
18
+
19
+
20
+ def is_image_file(filename):
21
+ return any(filename.endswith(extension) for extension in ['jpeg', 'JPEG', 'jpg', 'png', 'JPG', 'PNG', 'gif'])
22
+
23
+
24
+ class CLWD(Dataset):
25
+ def __init__(self, path, split="train", size=256, interpolation="pil_lanczos",
26
+ flip_prob=0.5, sample_weight=1.0, instruct=False):
27
+ super(CLWD, self).__init__()
28
+
29
+ inp_files = sorted(os.listdir(os.path.join(path, split, 'Watermarked_image')))
30
+ tar_files = sorted(os.listdir(os.path.join(path, split, 'Watermark_free_image')))
31
+
32
+ self.inp_filenames = [os.path.join(path, split, 'Watermarked_image', x) for x in inp_files if is_image_file(x)]
33
+ self.tar_filenames = [os.path.join(path, split, 'Watermark_free_image', x) for x in tar_files if is_image_file(x)]
34
+
35
+ self.size = size
36
+ self.flip_prob = flip_prob
37
+ self.sample_weight = sample_weight
38
+ self.instruct = instruct
39
+ self.sizex = len(self.tar_filenames) # get the size of target
40
+
41
+ self.interpolation = {
42
+ "cv_nearest": cv2.INTER_NEAREST,
43
+ "cv_bilinear": cv2.INTER_LINEAR,
44
+ "cv_bicubic": cv2.INTER_CUBIC,
45
+ "cv_area": cv2.INTER_AREA,
46
+ "cv_lanczos": cv2.INTER_LANCZOS4,
47
+ "pil_nearest": Image.NEAREST,
48
+ "pil_bilinear": Image.BILINEAR,
49
+ "pil_bicubic": Image.BICUBIC,
50
+ "pil_box": Image.BOX,
51
+ "pil_hamming": Image.HAMMING,
52
+ "pil_lanczos": Image.LANCZOS,
53
+ }[interpolation]
54
+
55
+ prompt_path='dataset/prompt/prompt_dewatermark.txt'
56
+ self.prompt_list=[]
57
+ with open(prompt_path) as f:
58
+ line=f.readline()
59
+ while line:
60
+ line=line.strip('\n')
61
+ self.prompt_list.append(line)
62
+ line=f.readline()
63
+
64
+ print(f"CLWD has {len(self)} samples!!")
65
+
66
+ def __len__(self):
67
+ return int(self.sizex * self.sample_weight)
68
+
69
+ def __getitem__(self, index):
70
+ if self.sample_weight >= 1:
71
+ index_ = index % self.sizex
72
+ else:
73
+ index_ = int(index / self.sample_weight) + random.randint(0, int(1 / self.sample_weight) - 1)
74
+
75
+ inp_path = self.inp_filenames[index_]
76
+ tar_path = self.tar_filenames[index_]
77
+
78
+ inp_img = Image.open(inp_path)
79
+ tar_img = Image.open(tar_path)
80
+
81
+ width, height = inp_img.size
82
+ tar_width, tar_height = tar_img.size
83
+ assert tar_width == width and tar_height == height, "Input and target image mismatch"
84
+ aspect_ratio = float(width) / float(height)
85
+ if width < height:
86
+ new_width = self.size
87
+ new_height = int(self.size / aspect_ratio)
88
+ else:
89
+ new_height = self.size
90
+ new_width = int(self.size * aspect_ratio)
91
+ inp_img = inp_img.resize((new_width, new_height), self.interpolation)
92
+ tar_img = tar_img.resize((new_width, new_height), self.interpolation)
93
+
94
+ inp_img = np.array(inp_img).astype(np.float32).transpose(2, 0, 1)
95
+ inp_img_tensor = torch.tensor((inp_img / 127.5 - 1.0).astype(np.float32))
96
+ tar_img = np.array(tar_img).astype(np.float32).transpose(2, 0, 1)
97
+ tar_img_tensor = torch.tensor((tar_img / 127.5 - 1.0).astype(np.float32))
98
+ crop = torchvision.transforms.RandomCrop(self.size)
99
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
100
+ image_0, image_1 = flip(crop(torch.cat((inp_img_tensor, tar_img_tensor)))).chunk(2)
101
+
102
+ prompt = random.choice(self.prompt_list)
103
+ if self.instruct:
104
+ prompt = "Watermark Removal: " + prompt
105
+
106
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
dataset/low_level/lowlevel_gopro.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InstructDiffusion
3
+ # Based on instruct-pix2pix (https://github.com/timothybrooks/instruct-pix2pix)
4
+ # Modified by Chen Li (edward82@stu.xjtu.edu.cn)
5
+ # --------------------------------------------------------
6
+
7
+ import os
8
+ import numpy as np
9
+ from torch.utils.data import Dataset
10
+ import torch
11
+ from PIL import Image
12
+ import torchvision.transforms.functional as TF
13
+ from pdb import set_trace as stx
14
+ import random
15
+ import cv2
16
+ from PIL import Image
17
+ import torchvision
18
+
19
+
20
+ def is_image_file(filename):
21
+ return any(filename.endswith(extension) for extension in ['jpeg', 'JPEG', 'jpg', 'png', 'JPG', 'PNG', 'gif'])
22
+
23
+
24
+ class GoPro(Dataset):
25
+ def __init__(self, path, split="train", size=256, interpolation="pil_lanczos",
26
+ flip_prob=0.5, sample_weight=1.0, instruct=False):
27
+ super(GoPro, self).__init__()
28
+
29
+ inp_files = sorted(os.listdir(os.path.join(path, split, 'input')))
30
+ tar_files = sorted(os.listdir(os.path.join(path, split, 'target')))
31
+
32
+ self.inp_filenames = [os.path.join(path, split, 'input', x) for x in inp_files if is_image_file(x)]
33
+ self.tar_filenames = [os.path.join(path, split, 'target', x) for x in tar_files if is_image_file(x)]
34
+
35
+ self.size = size
36
+ self.flip_prob = flip_prob
37
+ self.sample_weight = sample_weight
38
+ self.instruct = instruct
39
+ self.sizex = len(self.tar_filenames) # get the size of target
40
+
41
+ self.interpolation = {
42
+ "cv_nearest": cv2.INTER_NEAREST,
43
+ "cv_bilinear": cv2.INTER_LINEAR,
44
+ "cv_bicubic": cv2.INTER_CUBIC,
45
+ "cv_area": cv2.INTER_AREA,
46
+ "cv_lanczos": cv2.INTER_LANCZOS4,
47
+ "pil_nearest": Image.NEAREST,
48
+ "pil_bilinear": Image.BILINEAR,
49
+ "pil_bicubic": Image.BICUBIC,
50
+ "pil_box": Image.BOX,
51
+ "pil_hamming": Image.HAMMING,
52
+ "pil_lanczos": Image.LANCZOS,
53
+ }[interpolation]
54
+
55
+ prompt_path='dataset/prompt/prompt_deblur.txt'
56
+ self.prompt_list=[]
57
+ with open(prompt_path) as f:
58
+ line=f.readline()
59
+ while line:
60
+ line=line.strip('\n')
61
+ self.prompt_list.append(line)
62
+ line=f.readline()
63
+
64
+ print(f"GoPro has {len(self)} samples!!")
65
+
66
+ def __len__(self):
67
+ return int(self.sizex * self.sample_weight)
68
+
69
+ def __getitem__(self, index):
70
+ if self.sample_weight >= 1:
71
+ index_ = index % self.sizex
72
+ else:
73
+ index_ = int(index / self.sample_weight) + random.randint(0, int(1 / self.sample_weight) - 1)
74
+
75
+ inp_path = self.inp_filenames[index_]
76
+ tar_path = self.tar_filenames[index_]
77
+
78
+ inp_img = Image.open(inp_path)
79
+ tar_img = Image.open(tar_path)
80
+
81
+ width, height = inp_img.size
82
+ tar_width, tar_height = tar_img.size
83
+ assert tar_width == width and tar_height == height, "Input and target image mismatch"
84
+ aspect_ratio = float(width) / float(height)
85
+ if width < height:
86
+ new_width = self.size
87
+ new_height = int(self.size / aspect_ratio)
88
+ else:
89
+ new_height = self.size
90
+ new_width = int(self.size * aspect_ratio)
91
+ inp_img = inp_img.resize((new_width, new_height), self.interpolation)
92
+ tar_img = tar_img.resize((new_width, new_height), self.interpolation)
93
+
94
+ inp_img = np.array(inp_img).astype(np.float32).transpose(2, 0, 1)
95
+ inp_img_tensor = torch.tensor((inp_img / 127.5 - 1.0).astype(np.float32))
96
+ tar_img = np.array(tar_img).astype(np.float32).transpose(2, 0, 1)
97
+ tar_img_tensor = torch.tensor((tar_img / 127.5 - 1.0).astype(np.float32))
98
+ crop = torchvision.transforms.RandomCrop(self.size)
99
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
100
+ image_0, image_1 = flip(crop(torch.cat((inp_img_tensor, tar_img_tensor)))).chunk(2)
101
+
102
+ prompt = random.choice(self.prompt_list)
103
+ if self.instruct:
104
+ prompt = "Image Deblurring: " + prompt
105
+
106
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
dataset/low_level/lowlevel_reds.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InstructDiffusion
3
+ # Based on instruct-pix2pix (https://github.com/timothybrooks/instruct-pix2pix)
4
+ # Modified by Chen Li (edward82@stu.xjtu.edu.cn)
5
+ # --------------------------------------------------------
6
+
7
+ import os
8
+ import numpy as np
9
+ from torch.utils.data import Dataset
10
+ import torch
11
+ from PIL import Image
12
+ import torchvision.transforms.functional as TF
13
+ from pdb import set_trace as stx
14
+ import random
15
+ import cv2
16
+ from PIL import Image
17
+ import torchvision
18
+
19
+
20
+ def is_image_file(filename):
21
+ return any(filename.endswith(extension) for extension in ['jpeg', 'JPEG', 'jpg', 'png', 'JPG', 'PNG', 'gif'])
22
+
23
+
24
+ class REDS(Dataset):
25
+ def __init__(self, path, split="train", size=256, interpolation="pil_lanczos",
26
+ flip_prob=0.5, sample_weight=1.0, instruct=False):
27
+ super(REDS, self).__init__()
28
+
29
+ inp_files = sorted(os.listdir(os.path.join(path, split, 'blur')))
30
+ tar_files = sorted(os.listdir(os.path.join(path, split, 'sharp')))
31
+
32
+ if split == "train":
33
+ self.inp_filenames = [os.path.join(path, split, 'blur', d, x) for d in inp_files for x in sorted(os.listdir(os.path.join(path, split, 'blur', d))) if is_image_file(x)]
34
+ self.tar_filenames = [os.path.join(path, split, 'sharp', d, x) for d in tar_files for x in sorted(os.listdir(os.path.join(path, split, 'sharp', d))) if is_image_file(x)]
35
+ else:
36
+ self.inp_filenames = [os.path.join(path, split, 'blur', x) for x in inp_files if is_image_file(x)]
37
+ self.tar_filenames = [os.path.join(path, split, 'sharp', x) for x in tar_files if is_image_file(x)]
38
+
39
+ self.size = size
40
+ self.flip_prob = flip_prob
41
+ self.sample_weight = sample_weight
42
+ self.instruct = instruct
43
+ assert len(self.inp_filenames) == len(self.tar_filenames)
44
+ self.sizex = len(self.tar_filenames) # get the size of target
45
+
46
+ self.interpolation = {
47
+ "cv_nearest": cv2.INTER_NEAREST,
48
+ "cv_bilinear": cv2.INTER_LINEAR,
49
+ "cv_bicubic": cv2.INTER_CUBIC,
50
+ "cv_area": cv2.INTER_AREA,
51
+ "cv_lanczos": cv2.INTER_LANCZOS4,
52
+ "pil_nearest": Image.NEAREST,
53
+ "pil_bilinear": Image.BILINEAR,
54
+ "pil_bicubic": Image.BICUBIC,
55
+ "pil_box": Image.BOX,
56
+ "pil_hamming": Image.HAMMING,
57
+ "pil_lanczos": Image.LANCZOS,
58
+ }[interpolation]
59
+
60
+ prompt_path='dataset/prompt/prompt_deblur.txt'
61
+ self.prompt_list=[]
62
+ with open(prompt_path) as f:
63
+ line=f.readline()
64
+ while line:
65
+ line=line.strip('\n')
66
+ self.prompt_list.append(line)
67
+ line=f.readline()
68
+
69
+ print(f"REDS has {len(self)} samples!!")
70
+
71
+ def __len__(self):
72
+ return int(self.sizex * self.sample_weight)
73
+
74
+ def __getitem__(self, index):
75
+ if self.sample_weight >= 1:
76
+ index_ = index % self.sizex
77
+ else:
78
+ index_ = int(index / self.sample_weight) + random.randint(0, int(1 / self.sample_weight) - 1)
79
+
80
+ inp_path = self.inp_filenames[index_]
81
+ tar_path = self.tar_filenames[index_]
82
+
83
+ inp_img = Image.open(inp_path)
84
+ tar_img = Image.open(tar_path)
85
+
86
+ width, height = inp_img.size
87
+ tar_width, tar_height = tar_img.size
88
+ assert tar_width == width and tar_height == height, "Input and target image mismatch"
89
+ aspect_ratio = float(width) / float(height)
90
+ if width < height:
91
+ new_width = self.size
92
+ new_height = int(self.size / aspect_ratio)
93
+ else:
94
+ new_height = self.size
95
+ new_width = int(self.size * aspect_ratio)
96
+ inp_img = inp_img.resize((new_width, new_height), self.interpolation)
97
+ tar_img = tar_img.resize((new_width, new_height), self.interpolation)
98
+
99
+ inp_img = np.array(inp_img).astype(np.float32).transpose(2, 0, 1)
100
+ inp_img_tensor = torch.tensor((inp_img / 127.5 - 1.0).astype(np.float32))
101
+ tar_img = np.array(tar_img).astype(np.float32).transpose(2, 0, 1)
102
+ tar_img_tensor = torch.tensor((tar_img / 127.5 - 1.0).astype(np.float32))
103
+ crop = torchvision.transforms.RandomCrop(self.size)
104
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
105
+ image_0, image_1 = flip(crop(torch.cat((inp_img_tensor, tar_img_tensor)))).chunk(2)
106
+
107
+ prompt = random.choice(self.prompt_list)
108
+ if self.instruct:
109
+ prompt = "Image Deblurring: " + prompt
110
+
111
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
dataset/low_level/lowlevel_sidd.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InstructDiffusion
3
+ # Based on instruct-pix2pix (https://github.com/timothybrooks/instruct-pix2pix)
4
+ # Modified by Chen Li (edward82@stu.xjtu.edu.cn)
5
+ # --------------------------------------------------------
6
+
7
+ import os
8
+ import numpy as np
9
+ from torch.utils.data import Dataset
10
+ import torch
11
+ from PIL import Image
12
+ import torchvision.transforms.functional as TF
13
+ from pdb import set_trace as stx
14
+ import random
15
+ import cv2
16
+ from PIL import Image
17
+ import torchvision
18
+
19
+
20
+ def is_image_file(filename):
21
+ return any(filename.endswith(extension) for extension in ['jpeg', 'JPEG', 'jpg', 'png', 'JPG', 'PNG', 'gif'])
22
+
23
+
24
+ class SIDD(Dataset):
25
+ def __init__(self, path, split="train", size=256, interpolation="pil_lanczos",
26
+ flip_prob=0.5, sample_weight=1.0, instruct=False):
27
+ super(SIDD, self).__init__()
28
+
29
+ inp_files = sorted(os.listdir(os.path.join(path, split, 'input')))
30
+ tar_files = sorted(os.listdir(os.path.join(path, split, 'gt')))
31
+
32
+ self.inp_filenames = [os.path.join(path, split, 'input', x) for x in inp_files if is_image_file(x)]
33
+ self.tar_filenames = [os.path.join(path, split, 'gt', x) for x in tar_files if is_image_file(x)]
34
+
35
+ self.size = size
36
+ self.flip_prob = flip_prob
37
+ self.sample_weight = sample_weight
38
+ self.instruct = instruct
39
+ self.sizex = len(self.tar_filenames) # get the size of target
40
+
41
+ self.interpolation = {
42
+ "cv_nearest": cv2.INTER_NEAREST,
43
+ "cv_bilinear": cv2.INTER_LINEAR,
44
+ "cv_bicubic": cv2.INTER_CUBIC,
45
+ "cv_area": cv2.INTER_AREA,
46
+ "cv_lanczos": cv2.INTER_LANCZOS4,
47
+ "pil_nearest": Image.NEAREST,
48
+ "pil_bilinear": Image.BILINEAR,
49
+ "pil_bicubic": Image.BICUBIC,
50
+ "pil_box": Image.BOX,
51
+ "pil_hamming": Image.HAMMING,
52
+ "pil_lanczos": Image.LANCZOS,
53
+ }[interpolation]
54
+
55
+ prompt_path='dataset/prompt/prompt_denoise.txt'
56
+ self.prompt_list=[]
57
+ with open(prompt_path) as f:
58
+ line=f.readline()
59
+ while line:
60
+ line=line.strip('\n')
61
+ self.prompt_list.append(line)
62
+ line=f.readline()
63
+ print(f"SIDD has {len(self)} samples!!")
64
+
65
+ def __len__(self):
66
+ return int(self.sizex * self.sample_weight)
67
+
68
+ def __getitem__(self, index):
69
+ if self.sample_weight >= 1:
70
+ index_ = index % self.sizex
71
+ else:
72
+ index_ = int(index / self.sample_weight) + random.randint(0, int(1 / self.sample_weight) - 1)
73
+
74
+ inp_path = self.inp_filenames[index_]
75
+ tar_path = self.tar_filenames[index_]
76
+
77
+ inp_img = Image.open(inp_path)
78
+ tar_img = Image.open(tar_path)
79
+
80
+ width, height = inp_img.size
81
+ tar_width, tar_height = tar_img.size
82
+ assert tar_width == width and tar_height == height, "Input and target image mismatch"
83
+
84
+ inp_img = np.array(inp_img).astype(np.float32).transpose(2, 0, 1)
85
+ inp_img_tensor = torch.tensor((inp_img / 127.5 - 1.0).astype(np.float32))
86
+ tar_img = np.array(tar_img).astype(np.float32).transpose(2, 0, 1)
87
+ tar_img_tensor = torch.tensor((tar_img / 127.5 - 1.0).astype(np.float32))
88
+ crop = torchvision.transforms.RandomCrop(self.size)
89
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
90
+ image_0, image_1 = flip(crop(torch.cat((inp_img_tensor, tar_img_tensor)))).chunk(2)
91
+
92
+ prompt = random.choice(self.prompt_list)
93
+ if self.instruct:
94
+ prompt = "Image Denoising: " + prompt
95
+
96
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
dataset/pose/pose.py ADDED
@@ -0,0 +1,760 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft
3
+ # Licensed under the MIT License.
4
+ # Written by Bin Xiao (Bin.Xiao@microsoft.com)
5
+ # Modified by Zigang Geng (zigang@mail.ustc.edu.cn)
6
+ # ------------------------------------------------------------------------------
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ import os
12
+ import json
13
+ import copy
14
+ import math
15
+ import random
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import cv2
20
+ import numpy as np
21
+ import torch
22
+ import torchvision
23
+ from einops import rearrange
24
+ from PIL import Image
25
+ from torch.utils.data import Dataset
26
+ import torchvision.transforms as transforms
27
+ from pycocotools.coco import COCO
28
+
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ colors = {
34
+ 'red': (255, 0, 0),
35
+ 'green': (0, 255, 0),
36
+ 'blue': (0, 0, 255),
37
+ 'yellow': (255, 255, 0),
38
+ 'cyan': (0, 255, 255),
39
+ 'magenta': (255, 0, 255),
40
+ 'gray': (128, 128, 128),
41
+ 'white': (255, 255, 255),
42
+ 'black': (0, 0, 0)}
43
+
44
+
45
+ def readTXT(txt_path):
46
+ with open(txt_path, 'r') as f:
47
+ listInTXT = [line.strip() for line in f]
48
+
49
+ return listInTXT
50
+
51
+
52
+ class PoseDataset(Dataset):
53
+ def __init__(self, root, image_set, is_train, max_prompt_num=5, min_prompt_num=1,
54
+ radius=10, size=256, transparency=0.0, sample_weight=1.0, transform=None):
55
+
56
+ self.sample_weight = sample_weight
57
+ self.max_prompt_num = max_prompt_num
58
+ self.min_prompt_num = min_prompt_num
59
+ self.radius = radius
60
+ self.transparency = transparency
61
+ self.num_joints = 0
62
+ self.pixel_std = 200
63
+ self.flip_pairs = []
64
+ self.parent_ids = []
65
+
66
+ self.keypoints_type = {}
67
+
68
+ self.is_train = is_train
69
+ self.image_set = image_set
70
+ self.root = root
71
+
72
+ self.scale_factor = 0.35
73
+ self.rotation_factor = 45
74
+ self.flip = True
75
+ self.num_joints_half_body = 8
76
+ self.prob_half_body = 0.3
77
+
78
+ self.image_size = np.array((size, size))
79
+ self.heatmap_size = np.array((size, size))
80
+
81
+ self.transform = transform
82
+ self.db = []
83
+
84
+ pose_diverse_prompt_path = 'dataset/prompt/prompt_pose.txt'
85
+ self.pose_diverse_prompt_list = []
86
+ with open(pose_diverse_prompt_path) as f:
87
+ line = f.readline()
88
+ while line:
89
+ line = line.strip('\n')
90
+ self.pose_diverse_prompt_list.append(line)
91
+ line = f.readline()
92
+
93
+ def _get_db(self):
94
+ raise NotImplementedError
95
+
96
+ def evaluate(self, preds, output_dir, *args, **kwargs):
97
+ raise NotImplementedError
98
+
99
+ def half_body_transform(self, joints, joints_vis):
100
+ upper_joints = []
101
+ lower_joints = []
102
+ for joint_id in range(self.num_joints):
103
+ if joints_vis[joint_id][0] > 0:
104
+ if joint_id in self.upper_body_ids:
105
+ upper_joints.append(joints[joint_id])
106
+ else:
107
+ lower_joints.append(joints[joint_id])
108
+
109
+ if np.random.randn() < 0.5 and len(upper_joints) > 2:
110
+ selected_joints = upper_joints
111
+ else:
112
+ selected_joints = lower_joints \
113
+ if len(lower_joints) > 2 else upper_joints
114
+
115
+ if len(selected_joints) < 2:
116
+ return None, None
117
+
118
+ selected_joints = np.array(selected_joints, dtype=np.float32)
119
+ center = selected_joints.mean(axis=0)[:2]
120
+
121
+ left_top = np.amin(selected_joints, axis=0)
122
+ right_bottom = np.amax(selected_joints, axis=0)
123
+
124
+ w = right_bottom[0] - left_top[0]
125
+ h = right_bottom[1] - left_top[1]
126
+
127
+ if w > self.aspect_ratio * h:
128
+ h = w * 1.0 / self.aspect_ratio
129
+ elif w < self.aspect_ratio * h:
130
+ w = h * self.aspect_ratio
131
+
132
+ scale = np.array(
133
+ [
134
+ w * 1.0 / self.pixel_std,
135
+ h * 1.0 / self.pixel_std
136
+ ],
137
+ dtype=np.float32
138
+ )
139
+
140
+ scale = scale * 1.5
141
+
142
+ return center, scale
143
+
144
+ def __len__(self,):
145
+ return int(len(self.db) * self.sample_weight)
146
+
147
+ def __getitem__(self, idx):
148
+ if self.sample_weight >= 1:
149
+ idx = idx % len(self.db)
150
+ else:
151
+ idx = int(idx / self.sample_weight) + random.randint(0, int(1 / self.sample_weight) - 1)
152
+
153
+ db_rec = copy.deepcopy(self.db[idx])
154
+
155
+ image_file = db_rec['image']
156
+ filename = db_rec['filename'] if 'filename' in db_rec else ''
157
+ imgnum = db_rec['imgnum'] if 'imgnum' in db_rec else ''
158
+
159
+ data_numpy = cv2.imread(
160
+ image_file, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION
161
+ )
162
+ data_numpy = cv2.cvtColor(data_numpy, cv2.COLOR_BGR2RGB)
163
+
164
+ if data_numpy is None:
165
+ logger.error('=> fail to read {}'.format(image_file))
166
+ raise ValueError('Fail to read {}'.format(image_file))
167
+
168
+ joints = db_rec['joints_3d']
169
+ joints_vis = db_rec['joints_3d_vis']
170
+
171
+ c = db_rec['center']
172
+ s = db_rec['scale']
173
+ score = db_rec['score'] if 'score' in db_rec else 1
174
+ r = 0
175
+
176
+ if self.is_train:
177
+ if (np.sum(joints_vis[:, 0]) > self.num_joints_half_body
178
+ and np.random.rand() < self.prob_half_body):
179
+ c_half_body, s_half_body = self.half_body_transform(
180
+ joints, joints_vis
181
+ )
182
+
183
+ if c_half_body is not None and s_half_body is not None:
184
+ c, s = c_half_body, s_half_body
185
+
186
+ sf = self.scale_factor
187
+ rf = self.rotation_factor
188
+ s = s * np.clip(np.random.randn()*sf + 1, 1 - sf, 1 + sf)
189
+ r = np.clip(np.random.randn()*rf, -rf*2, rf*2) \
190
+ if random.random() <= 0.6 else 0
191
+
192
+ if self.flip and random.random() <= 0.5:
193
+ data_numpy = data_numpy[:, ::-1, :]
194
+ joints, joints_vis = fliplr_joints(
195
+ joints, joints_vis, data_numpy.shape[1], self.flip_pairs)
196
+ c[0] = data_numpy.shape[1] - c[0] - 1
197
+
198
+ trans = get_affine_transform(c, s, r, self.image_size)
199
+ input = cv2.warpAffine(
200
+ data_numpy,
201
+ trans,
202
+ (int(self.image_size[0]), int(self.image_size[1])),
203
+ flags=cv2.INTER_LINEAR)
204
+
205
+ if self.transform:
206
+ input = self.transform(input)
207
+
208
+ for i in range(self.num_joints):
209
+ if joints_vis[i, 0] > 0.0:
210
+ joints[i, 0:2] = affine_transform(joints[i, 0:2], trans)
211
+
212
+ target, prompt = self.generate_target(input, joints, joints_vis)
213
+
214
+ # return Image.fromarray(input), Image.fromarray(target), prompt
215
+
216
+ image_0 = rearrange(2 * torch.tensor(np.array(input)).float() / 255 - 1, "h w c -> c h w")
217
+ image_1 = rearrange(2 * torch.tensor(np.array(target)).float() / 255 - 1, "h w c -> c h w")
218
+
219
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
220
+
221
+ def generate_target(self, input, joints, joints_vis):
222
+ '''
223
+ :param input: [height, width, 3]
224
+ :param joints: [num_joints, 3]
225
+ :param joints_vis: [num_joints, 3]
226
+ :return: target
227
+ '''
228
+ radius = self.radius
229
+ target = copy.deepcopy(input)
230
+
231
+ joint_num = random.randint(self.min_prompt_num, self.max_prompt_num)
232
+ joint_ids = np.random.choice([i for i in range(self.num_joints)], joint_num, replace=False)
233
+ random_color_names = random.sample(list(colors.keys()), len(joint_ids))
234
+ random_marker_names = ['circle' for i in range(len(joint_ids))]
235
+
236
+ prompt = ""
237
+
238
+ for color_idx, joint_id in enumerate(joint_ids):
239
+ feat_stride = self.image_size / self.heatmap_size
240
+ mu_x = int(joints[joint_id][0] / feat_stride[0] + 0.5)
241
+ mu_y = int(joints[joint_id][1] / feat_stride[1] + 0.5)
242
+ # Check that any part of the gaussian is in-bounds
243
+ ul = [int(mu_x - radius), int(mu_y - radius)]
244
+ br = [int(mu_x + radius + 1), int(mu_y + radius + 1)]
245
+ if ul[0] >= self.heatmap_size[0] or ul[1] >= self.heatmap_size[1] \
246
+ or br[0] < 0 or br[1] < 0:
247
+ # If not, just return the image as is
248
+ joints_vis[joint_id][0] = 0
249
+ continue
250
+
251
+ marker_size = 2 * radius + 1
252
+ g = np.zeros((marker_size, marker_size))
253
+ x, y = np.indices((marker_size, marker_size))
254
+ interval = int((marker_size - marker_size / math.sqrt(2)) // 2)
255
+ mask = (x - radius) ** 2 + (y - radius) ** 2 <= radius ** 2 + 1
256
+ g[mask] = 1
257
+
258
+ # Usable gaussian range
259
+ g_x = max(0, -ul[0]), min(br[0], self.heatmap_size[0]) - ul[0]
260
+ g_y = max(0, -ul[1]), min(br[1], self.heatmap_size[1]) - ul[1]
261
+ # Image range
262
+ img_x = max(0, ul[0]), min(br[0], self.heatmap_size[0])
263
+ img_y = max(0, ul[1]), min(br[1], self.heatmap_size[1])
264
+
265
+ v = joints_vis[joint_id][0]
266
+ random_color_name = random_color_names[color_idx]
267
+ random_color = colors[random_color_name]
268
+
269
+ prompt += random.choice(self.pose_diverse_prompt_list).format(
270
+ color=random_color_name,
271
+ joint=self.keypoints_type[joint_id])
272
+
273
+ if v > 0.5:
274
+ target[img_y[0]:img_y[1], img_x[0]:img_x[1]][g[g_y[0]:g_y[1], g_x[0]:g_x[1]]>0] \
275
+ = self.transparency*target[img_y[0]:img_y[1], img_x[0]:img_x[1]][g[g_y[0]:g_y[1], g_x[0]:g_x[1]]>0] \
276
+ + (1-self.transparency)*np.array(random_color)
277
+
278
+ return target, prompt
279
+
280
+
281
+ class COCODataset(PoseDataset):
282
+ def __init__(self, root, image_set, is_train, max_prompt_num=5, min_prompt_num=1,
283
+ radius=10, size=256, transparency=0.0, sample_weight=1.0, transform=None):
284
+
285
+ super().__init__(root, image_set, is_train, max_prompt_num, min_prompt_num,
286
+ radius, size, transparency, sample_weight, transform)
287
+
288
+ self.keypoints_type = {
289
+ 0: "nose",
290
+ 1: "left eye",
291
+ 2: "right eye",
292
+ 3: "left ear",
293
+ 4: "right ear",
294
+ 5: "left shoulder",
295
+ 6: "right shoulder",
296
+ 7: "left elbow",
297
+ 8: "right elbow",
298
+ 9: "left wrist",
299
+ 10: "right wrist",
300
+ 11: "left hip",
301
+ 12: "right hip",
302
+ 13: "left knee",
303
+ 14: "right knee",
304
+ 15: "left ankle",
305
+ 16: "right ankle"
306
+ }
307
+
308
+ self.image_width = size
309
+ self.image_height = size
310
+ self.aspect_ratio = self.image_width * 1.0 / self.image_height
311
+ self.pixel_std = 200
312
+
313
+ self.coco = COCO(self._get_ann_file_keypoint())
314
+
315
+ # deal with class names
316
+ cats = [cat['name']
317
+ for cat in self.coco.loadCats(self.coco.getCatIds())]
318
+ self.classes = ['__background__'] + cats
319
+ logger.info('=> classes: {}'.format(self.classes))
320
+ self.num_classes = len(self.classes)
321
+ self._class_to_ind = dict(zip(self.classes, range(self.num_classes)))
322
+ self._class_to_coco_ind = dict(zip(cats, self.coco.getCatIds()))
323
+ self._coco_ind_to_class_ind = dict(
324
+ [
325
+ (self._class_to_coco_ind[cls], self._class_to_ind[cls])
326
+ for cls in self.classes[1:]
327
+ ]
328
+ )
329
+
330
+ # load image file names
331
+ self.image_set_index = self._load_image_set_index()
332
+ self.num_images = len(self.image_set_index)
333
+ logger.info('=> num_images: {}'.format(self.num_images))
334
+
335
+ self.num_joints = 17
336
+ self.flip_pairs = [[1, 2], [3, 4], [5, 6], [7, 8],
337
+ [9, 10], [11, 12], [13, 14], [15, 16]]
338
+ self.parent_ids = None
339
+ self.upper_body_ids = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
340
+ self.lower_body_ids = (11, 12, 13, 14, 15, 16)
341
+
342
+ if 'coco' in self.root:
343
+ self.db = self._get_db()
344
+
345
+ logger.info('=> load {} samples'.format(len(self.db)))
346
+
347
+ def _get_ann_file_keypoint(self):
348
+ """ self.root / annotations / person_keypoints_train2017.json """
349
+ if 'coco' in self.root:
350
+ prefix = 'person_keypoints' \
351
+ if 'test' not in self.image_set else 'image_info'
352
+ return os.path.join(
353
+ self.root,
354
+ 'annotations',
355
+ prefix + '_' + self.image_set + '.json'
356
+ )
357
+ elif 'crowdpose' in self.root:
358
+ prefix = 'crowdpose'
359
+ return os.path.join(
360
+ self.root,
361
+ 'json',
362
+ prefix + '_' + self.image_set + '.json'
363
+ )
364
+ elif 'aic' in self.root:
365
+ prefix = 'aic'
366
+ return os.path.join(
367
+ self.root,
368
+ 'annotations',
369
+ prefix + '_' + self.image_set + '.json'
370
+ )
371
+ else:
372
+ raise ValueError('Please write the path for this new dataset.')
373
+
374
+ def _load_image_set_index(self):
375
+ """ image id: int """
376
+ image_ids = self.coco.getImgIds()
377
+ return image_ids
378
+
379
+ def _get_db(self):
380
+ gt_db = self._load_coco_keypoint_annotations()
381
+ return gt_db
382
+
383
+ def _load_coco_keypoint_annotations(self):
384
+ """ ground truth bbox and keypoints """
385
+ gt_db = []
386
+ for index in self.image_set_index:
387
+ gt_db.extend(self._load_coco_keypoint_annotation_kernal(index))
388
+ return gt_db
389
+
390
+ def _load_coco_keypoint_annotation_kernal(self, index):
391
+ """
392
+ coco ann: [u'segmentation', u'area', u'iscrowd', u'image_id', u'bbox', u'category_id', u'id']
393
+ iscrowd:
394
+ crowd instances are handled by marking their overlaps with all categories to -1
395
+ and later excluded in training
396
+ bbox:
397
+ [x1, y1, w, h]
398
+ :param index: coco image id
399
+ :return: db entry
400
+ """
401
+ im_ann = self.coco.loadImgs(index)[0]
402
+ width = im_ann['width']
403
+ height = im_ann['height']
404
+
405
+ annIds = self.coco.getAnnIds(imgIds=index, iscrowd=False)
406
+ objs = self.coco.loadAnns(annIds)
407
+
408
+ # sanitize bboxes
409
+ valid_objs = []
410
+ for obj in objs:
411
+ x, y, w, h = obj['bbox']
412
+ x1 = np.max((0, x))
413
+ y1 = np.max((0, y))
414
+ x2 = np.min((width - 1, x1 + np.max((0, w - 1))))
415
+ y2 = np.min((height - 1, y1 + np.max((0, h - 1))))
416
+ if 'crowdpose' in self.root:
417
+ obj['area'] = 1
418
+ if obj['area'] > 0 and x2 >= x1 and y2 >= y1:
419
+ obj['clean_bbox'] = [x1, y1, x2-x1, y2-y1]
420
+ valid_objs.append(obj)
421
+ objs = valid_objs
422
+
423
+ rec = []
424
+ for obj in objs:
425
+ cls = self._coco_ind_to_class_ind[obj['category_id']]
426
+ if cls != 1:
427
+ continue
428
+
429
+ # ignore objs without keypoints annotation
430
+ if max(obj['keypoints']) == 0:
431
+ continue
432
+
433
+ joints_3d = np.zeros((self.num_joints, 3), dtype=np.float32)
434
+ joints_3d_vis = np.zeros((self.num_joints, 3), dtype=np.float32)
435
+ for ipt in range(self.num_joints):
436
+ joints_3d[ipt, 0] = obj['keypoints'][ipt * 3 + 0]
437
+ joints_3d[ipt, 1] = obj['keypoints'][ipt * 3 + 1]
438
+ joints_3d[ipt, 2] = 0
439
+ t_vis = obj['keypoints'][ipt * 3 + 2]
440
+ if t_vis > 1:
441
+ t_vis = 1
442
+ joints_3d_vis[ipt, 0] = t_vis
443
+ joints_3d_vis[ipt, 1] = t_vis
444
+ joints_3d_vis[ipt, 2] = 0
445
+
446
+ center, scale = self._box2cs(obj['clean_bbox'][:4])
447
+ rec.append({
448
+ 'image': self.image_path_from_index(index, im_ann),
449
+ 'center': center,
450
+ 'scale': scale,
451
+ 'joints_3d': joints_3d,
452
+ 'joints_3d_vis': joints_3d_vis,
453
+ 'filename': '',
454
+ 'imgnum': 0,
455
+ })
456
+
457
+ return rec
458
+
459
+ def _box2cs(self, box):
460
+ x, y, w, h = box[:4]
461
+ return self._xywh2cs(x, y, w, h)
462
+
463
+ def _xywh2cs(self, x, y, w, h):
464
+ center = np.zeros((2), dtype=np.float32)
465
+ center[0] = x + w * 0.5
466
+ center[1] = y + h * 0.5
467
+
468
+ if w > self.aspect_ratio * h:
469
+ h = w * 1.0 / self.aspect_ratio
470
+ elif w < self.aspect_ratio * h:
471
+ w = h * self.aspect_ratio
472
+ scale = np.array(
473
+ [w * 1.0 / self.pixel_std, h * 1.0 / self.pixel_std],
474
+ dtype=np.float32)
475
+ if center[0] != -1:
476
+ scale = scale * 1.25
477
+
478
+ return center, scale
479
+
480
+ def image_path_from_index(self, index, im_ann):
481
+ """ example: images / train2017 / 000000119993.jpg """
482
+ if 'coco' in self.root:
483
+ file_name = '%012d.jpg' % index
484
+ if '2014' in self.image_set:
485
+ file_name = 'COCO_%s_' % self.image_set + file_name
486
+
487
+ prefix = 'test2017' if 'test' in self.image_set else self.image_set
488
+
489
+ data_name = prefix
490
+
491
+ image_path = os.path.join(
492
+ self.root, 'images', data_name, file_name)
493
+
494
+ return image_path
495
+ elif 'crowdpose' in self.root:
496
+ file_name = f'{index}.jpg'
497
+
498
+ image_path = os.path.join(
499
+ self.root, 'images', file_name)
500
+
501
+ return image_path
502
+ elif 'aic' in self.root:
503
+ file_name = im_ann["file_name"]
504
+
505
+ image_path = os.path.join(
506
+ self.root, 'ai_challenger_keypoint_train_20170902', 'keypoint_train_images_20170902', file_name)
507
+
508
+ return image_path
509
+
510
+
511
+ def flip_back(output_flipped, matched_parts):
512
+ '''
513
+ ouput_flipped: numpy.ndarray(batch_size, num_joints, height, width)
514
+ '''
515
+ assert output_flipped.ndim == 4,\
516
+ 'output_flipped should be [batch_size, num_joints, height, width]'
517
+
518
+ output_flipped = output_flipped[:, :, :, ::-1]
519
+
520
+ for pair in matched_parts:
521
+ tmp = output_flipped[:, pair[0], :, :].copy()
522
+ output_flipped[:, pair[0], :, :] = output_flipped[:, pair[1], :, :]
523
+ output_flipped[:, pair[1], :, :] = tmp
524
+
525
+ return output_flipped
526
+
527
+
528
+ def fliplr_joints(joints, joints_vis, width, matched_parts):
529
+ """
530
+ flip coords
531
+ """
532
+ # Flip horizontal
533
+ joints[:, 0] = width - joints[:, 0] - 1
534
+
535
+ # Change left-right parts
536
+ for pair in matched_parts:
537
+ joints[pair[0], :], joints[pair[1], :] = \
538
+ joints[pair[1], :], joints[pair[0], :].copy()
539
+ joints_vis[pair[0], :], joints_vis[pair[1], :] = \
540
+ joints_vis[pair[1], :], joints_vis[pair[0], :].copy()
541
+
542
+ return joints*joints_vis, joints_vis
543
+
544
+
545
+ def get_affine_transform(
546
+ center, scale, rot, output_size,
547
+ shift=np.array([0, 0], dtype=np.float32), inv=0
548
+ ):
549
+ if not isinstance(scale, np.ndarray) and not isinstance(scale, list):
550
+ print(scale)
551
+ scale = np.array([scale, scale])
552
+
553
+ scale_tmp = scale * 200.0
554
+ src_w = scale_tmp[0]
555
+ dst_w = output_size[0]
556
+ dst_h = output_size[1]
557
+
558
+ rot_rad = np.pi * rot / 180
559
+ src_dir = get_dir([0, src_w * -0.5], rot_rad)
560
+ dst_dir = np.array([0, dst_w * -0.5], np.float32)
561
+
562
+ src = np.zeros((3, 2), dtype=np.float32)
563
+ dst = np.zeros((3, 2), dtype=np.float32)
564
+ src[0, :] = center + scale_tmp * shift
565
+ src[1, :] = center + src_dir + scale_tmp * shift
566
+ dst[0, :] = [dst_w * 0.5, dst_h * 0.5]
567
+ dst[1, :] = np.array([dst_w * 0.5, dst_h * 0.5]) + dst_dir
568
+
569
+ src[2:, :] = get_3rd_point(src[0, :], src[1, :])
570
+ dst[2:, :] = get_3rd_point(dst[0, :], dst[1, :])
571
+
572
+ if inv:
573
+ trans = cv2.getAffineTransform(np.float32(dst), np.float32(src))
574
+ else:
575
+ trans = cv2.getAffineTransform(np.float32(src), np.float32(dst))
576
+
577
+ return trans
578
+
579
+
580
+ def affine_transform(pt, t):
581
+ new_pt = np.array([pt[0], pt[1], 1.]).T
582
+ new_pt = np.dot(t, new_pt)
583
+ return new_pt[:2]
584
+
585
+
586
+ def get_3rd_point(a, b):
587
+ direct = a - b
588
+ return b + np.array([-direct[1], direct[0]], dtype=np.float32)
589
+
590
+
591
+ def get_dir(src_point, rot_rad):
592
+ sn, cs = np.sin(rot_rad), np.cos(rot_rad)
593
+
594
+ src_result = [0, 0]
595
+ src_result[0] = src_point[0] * cs - src_point[1] * sn
596
+ src_result[1] = src_point[0] * sn + src_point[1] * cs
597
+
598
+ return src_result
599
+
600
+
601
+ class CrowdPoseDataset(COCODataset):
602
+ def __init__(self, root, image_set, is_train, max_prompt_num=5, min_prompt_num=1,
603
+ radius=10, size=256, transparency=0.0, sample_weight=1.0, transform=None):
604
+
605
+ super().__init__(root, image_set, is_train, max_prompt_num, min_prompt_num,
606
+ radius, size, transparency, sample_weight, transform)
607
+
608
+ self.keypoints_type = {
609
+ 0: 'left_shoulder',
610
+ 1: 'right_shoulder',
611
+ 2: 'left_elbow',
612
+ 3: 'right_elbow',
613
+ 4: 'left_wrist',
614
+ 5: 'right_wrist',
615
+ 6: 'left_hip',
616
+ 7: 'right_hip',
617
+ 8: 'left_knee',
618
+ 9: 'right_knee',
619
+ 10: 'left_ankle',
620
+ 11: 'right_ankle',
621
+ 12: 'top_head',
622
+ 13: 'neck'
623
+ }
624
+
625
+ self.num_joints = 14
626
+ self.prob_half_body = -1
627
+ self.flip_pairs = [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]
628
+ self.parent_ids = None
629
+ self.upper_body_ids = (0, 1, 2, 3, 4, 5, 12, 13)
630
+ self.lower_body_ids = (6, 7, 8, 9, 10, 11)
631
+
632
+ self.db = self._get_db()
633
+
634
+ logger.info('=> load {} samples'.format(len(self.db)))
635
+
636
+
637
+ class AICDataset(COCODataset):
638
+ def __init__(self, root, image_set, is_train, max_prompt_num=5, min_prompt_num=1,
639
+ radius=10, size=256, transparency=0.0, sample_weight=1.0, transform=None):
640
+ super().__init__(root, image_set, is_train, max_prompt_num, min_prompt_num,
641
+ radius, size, transparency, sample_weight, transform)
642
+
643
+ self.keypoints_type = {
644
+ 0: "right_shoulder",
645
+ 1: "right_elbow",
646
+ 2: "right_wrist",
647
+ 3: "left_shoulder",
648
+ 4: "left_elbow",
649
+ 5: "left_wrist",
650
+ 6: "right_hip",
651
+ 7: "right_knee",
652
+ 8: "right_ankle",
653
+ 9: "left_hip",
654
+ 10: "left_knee",
655
+ 11: "left_ankle",
656
+ 12: "head_top",
657
+ 13: "neck"
658
+ }
659
+
660
+ self.num_joints = 14
661
+ self.prob_half_body = -1
662
+ self.flip_pairs = [[0, 3], [1, 4], [2, 5], [6, 9], [7, 10], [8, 11]]
663
+ self.parent_ids = None
664
+ self.upper_body_ids = (0, 1, 2, 3, 4, 5, 12, 13)
665
+ self.lower_body_ids = (6, 7, 8, 9, 10, 11)
666
+
667
+ self.db = self._get_db()
668
+
669
+ logger.info('=> load {} samples'.format(len(self.db)))
670
+
671
+
672
+ class MPIIDataset(PoseDataset):
673
+ def __init__(self, root, image_set, is_train, max_prompt_num=5, min_prompt_num=1,
674
+ radius=10, size=256, transparency=0.0, sample_weight=1.0, transform=None):
675
+ super().__init__(root, image_set, is_train, max_prompt_num, min_prompt_num,
676
+ radius, size, transparency, sample_weight, transform)
677
+
678
+ self.keypoints_type = {
679
+ 0: 'right_ankle',
680
+ 1: 'right_knee',
681
+ 2: 'right_hip',
682
+ 3: 'left_hip',
683
+ 4: 'left_knee',
684
+ 5: 'left_ankle',
685
+ 6: 'pelvis',
686
+ 7: 'thorax',
687
+ 8: 'upper_neck',
688
+ 9: 'head_top',
689
+ 10: 'right_wrist',
690
+ 11: 'right_elbow',
691
+ 12: 'right_shoulder',
692
+ 13: 'left_shoulder',
693
+ 14: 'left_elbow',
694
+ 15: 'left_wrist'
695
+ }
696
+
697
+ self.data_format = 'jpg'
698
+ self.num_joints = 16
699
+ self.prob_half_body = -1
700
+ self.flip_pairs = [[0, 5], [1, 4], [2, 3], [10, 15], [11, 14], [12, 13]]
701
+ self.parent_ids = None
702
+ self.upper_body_ids = (7, 8, 9, 10, 11, 12, 13, 14, 15)
703
+ self.lower_body_ids = (0, 1, 2, 3, 4, 5, 6)
704
+
705
+ self.db = self._get_db()
706
+
707
+ logger.info('=> load {} samples'.format(len(self.db)))
708
+
709
+ def _get_db(self):
710
+ # create train/val split
711
+ file_name = os.path.join(
712
+ self.root, 'annot', self.image_set+'.json'
713
+ )
714
+ with open(file_name) as anno_file:
715
+ anno = json.load(anno_file)
716
+
717
+ gt_db = []
718
+ for a in anno:
719
+ image_name = a['image']
720
+
721
+ c = np.array(a['center'], dtype=np.float32)
722
+ s = np.array([a['scale'], a['scale']], dtype=np.float32)
723
+
724
+ # Adjust center/scale slightly to avoid cropping limbs
725
+ if c[0] != -1:
726
+ c[1] = c[1] + 15 * s[1]
727
+ s = s * 1.25
728
+
729
+ # MPII uses matlab format, index is based 1,
730
+ # we should first convert to 0-based index
731
+ c = c - 1
732
+
733
+ joints_3d = np.zeros((self.num_joints, 3), dtype=np.float32)
734
+ joints_3d_vis = np.zeros((self.num_joints, 3), dtype=np.float32)
735
+ if self.image_set != 'test':
736
+ joints = np.array(a['joints'])
737
+ joints[:, 0:2] = joints[:, 0:2] - 1
738
+ joints_vis = np.array(a['joints_vis'])
739
+ assert len(joints) == self.num_joints, \
740
+ 'joint num diff: {} vs {}'.format(len(joints),
741
+ self.num_joints)
742
+
743
+ joints_3d[:, 0:2] = joints[:, 0:2]
744
+ joints_3d_vis[:, 0] = joints_vis[:]
745
+ joints_3d_vis[:, 1] = joints_vis[:]
746
+
747
+ image_dir = 'images.zip@' if self.data_format == 'zip' else 'images'
748
+ gt_db.append(
749
+ {
750
+ 'image': os.path.join(self.root, image_dir, image_name),
751
+ 'center': c,
752
+ 'scale': s,
753
+ 'joints_3d': joints_3d,
754
+ 'joints_3d_vis': joints_3d_vis,
755
+ 'filename': '',
756
+ 'imgnum': 0,
757
+ }
758
+ )
759
+
760
+ return gt_db
dataset/prompt/color_list_train_small.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Red 纯红 #FF0000 255,0,0
2
+
3
+ Purple 紫色 #800080 128,0,128
4
+
5
+ Blue 纯蓝 #0000FF 0,0,255
6
+
7
+ Green 纯绿 #008000 0,128,0
8
+
9
+ Yellow 纯黄 #FFFF00 255,255,0
10
+
11
+ White 纯白 #FFFFFF 255,255,255
12
+
13
+ Black 纯黑 #000000 0,0,0
14
+
15
+ Gray 灰色 #808080 128,128,128
16
+
17
+
dataset/prompt/prompt_deblur.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ Sharpen this blurry image
2
+ Increase the sharpness of this unclear photo
3
+ Correct the lack of focus in this misty picture
4
+ Heighten the definition of this smeared image
5
+ Clear up this fuzzy picture
6
+ Refine this indistinct photograph
7
+ Improve the focus of this hazy image
8
+ Amend the softness of this out-of-focus photograph
9
+ Polish the murkiness of this low-definition photo
10
+ Rectify the vagueness of this blurred image
dataset/prompt/prompt_denoise.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ Remove noise from this image
2
+ Eliminate the noise in this picture
3
+ Purify this photo by removing noise
4
+ Clear up the image by filtering out noise
5
+ Eradicate the noise from this photograph
6
+ Minimize the noise present in this picture
7
+ Cancel out the noise within this image
8
+ Clean this photo by discarding the noise
9
+ Suppress the noise in this visual representation
10
+ Rectify the noise interference in this image
dataset/prompt/prompt_dewatermark.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ Remove watermark from this picture
2
+ Erase the watermark from this photograph.
3
+ Extract the watermark from this image.
4
+ Take out the watermark overlay from this photo.
5
+ Wipe off the watermark imprint on this image.
6
+ Detach the watermark from this visual representation.
7
+ Get rid of the watermarking on this picture.
8
+ Withdraw the watermark applied to this photograph.
9
+ Clean up this image by deleting the watermark.
10
+ Unmark this photo by removing the watermark.
dataset/prompt/prompt_pose.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ Circle the {joint} of the people with the color {color},
2
+ Use the {color} color to draw circles around the {joint} of the people,
3
+ Make {color} circles around the {joint} of the people,
4
+ Put {color} circles on the {joint} of the people,
5
+ Draw {color} circles over the {joint} of the people,
6
+ Surround the {joint} of the people with {color} circles,
7
+ Use the color {color} to make circles on the {joint} of the people,
8
+ Mark the {joint} of the people with {color} circles,
9
+ Create {color} circles around the {joint} of the people,
10
+ Use the color {color} to encircle the {joint} of the people,
dataset/prompt/prompt_seg.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Mark the pixels of {object} in {color} and leave the rest unchanged.
2
+ Color the {object}'s pixels in {color}, keeping the remaining pixels unaltered.
3
+ Apply {color} to the pixels of {object} while maintaining the current state of other pixels.
4
+ Assign {color} to the pixels belonging to {object}, preserving the rest as they are.
5
+ For {object}, set its pixels to {color} and let the others remain the same.
6
+ Modify the pixels of {object} to {color} without affecting any other pixels.
7
+ Set the {object} pixels to {color} and keep the other pixels in their original state.
8
+ Update the pixels of {object} to {color}, but leave the other pixels untouched.
9
+ Fill in the pixels of {object} with {color}, retaining the existing colors of the remaining pixels.
10
+ Change the {object} pixels to {color}, while keeping the other pixels constant.
11
+ Paint the pixels of {object} in {color} and maintain the current appearance of the other pixels.
dataset/seg/coco_stuff.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InstructDiffusion
3
+ # Based on instruct-pix2pix (https://github.com/timothybrooks/instruct-pix2pix)
4
+ # Modified by Binxin Yang (tennyson@mail.ustc.edu.cn)
5
+ # --------------------------------------------------------
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import math
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import numpy as np
15
+ import torch
16
+ import torchvision
17
+ from einops import rearrange
18
+ from PIL import Image
19
+ from torch.utils.data import Dataset
20
+ import cv2
21
+ import os
22
+ import random
23
+ import copy
24
+ from glob import glob
25
+
26
+
27
+ class COCOStuffDataset(Dataset):
28
+ def __init__(
29
+ self,
30
+ path: str,
31
+ path_edit: str = "None",
32
+ split: str = "train",
33
+ splits: tuple[float, float, float] = (0.9, 0.05, 0.05),
34
+ crop_res: int = 256,
35
+ flip_prob: float = 0.0,
36
+ transparency: float = 0,
37
+ batch_size: int = 10,
38
+ empty_percentage: float = 0,
39
+ ):
40
+ assert split in ("train2017", "val2017")
41
+ assert sum(splits) == 1
42
+ self.split = split
43
+ self.path = path
44
+ self.path_edit = path_edit
45
+ self.batch_size = batch_size
46
+ self.crop_res = crop_res
47
+ self.flip_prob = flip_prob
48
+ self.empty_percentage = empty_percentage
49
+ self.transparency = transparency
50
+ if self.split in ["train2017", "val2017"]:
51
+ file_list = sorted(glob(os.path.join(self.path, "images", self.split, "*.jpg")))
52
+ assert len(file_list) > 0, "{} has no image".format(
53
+ os.path.join(self.path, "images", self.split)
54
+ )
55
+ file_list = [f.split("/")[-1].replace(".jpg", "") for f in file_list]
56
+ self.files = file_list
57
+
58
+ else:
59
+ raise ValueError("Invalid split name: {}".format(self.split))
60
+
61
+ seg_diverse_prompt_path = 'dataset/prompt/prompt_seg.txt'
62
+ self.seg_diverse_prompt_list=[]
63
+ with open(seg_diverse_prompt_path) as f:
64
+ line=f.readline()
65
+ while line:
66
+ line=line.strip('\n')
67
+ self.seg_diverse_prompt_list.append(line)
68
+ line=f.readline()
69
+
70
+ color_list_file_path='dataset/prompt/color_list_train_small.txt'
71
+ self.color_list=[]
72
+ with open(color_list_file_path) as f:
73
+ line = f.readline()
74
+ while line:
75
+ line_split = line.strip('\n').split(" ")
76
+ if len(line_split)>1:
77
+ temp = []
78
+ for i in range(4):
79
+ temp.append(line_split[i])
80
+ self.color_list.append(temp)
81
+ line = f.readline()
82
+
83
+ coco_label_list_path = self.path + '/labels.txt'
84
+ self.label_dict={}
85
+ with open(coco_label_list_path) as f:
86
+ line = f.readline()
87
+ while line:
88
+ line_split = line.strip('\n').split(": ")
89
+ self.label_dict[int(line_split[0])]=line_split[1]
90
+ line = f.readline()
91
+
92
+ def __len__(self) -> int:
93
+ length=len(self.files)
94
+ return length
95
+
96
+ def _augmentation_new(self, image, label):
97
+
98
+ # Cropping
99
+ h, w = label.shape
100
+ if h > w:
101
+ start_h = random.randint(0, h - w)
102
+ end_h = start_h + w
103
+ image = image[start_h:end_h]
104
+ label = label[start_h:end_h]
105
+ elif h < w:
106
+ start_w = random.randint(0, w - h)
107
+ end_w = start_w + h
108
+ image = image[:, start_w:end_w]
109
+ label = label[:, start_w:end_w]
110
+ else:
111
+ pass
112
+ image = Image.fromarray(image).resize((self.crop_res, self.crop_res), resample=Image.Resampling.LANCZOS)
113
+ image = np.asarray(image, dtype=np.uint8)
114
+ label = Image.fromarray(label).resize((self.crop_res, self.crop_res), resample=Image.Resampling.NEAREST)
115
+ label = np.asarray(label, dtype=np.int64)
116
+ return image, label
117
+
118
+ def __getitem__(self, i):
119
+
120
+ image_id = self.files[i]
121
+ img_path = os.path.join(self.path, "images", self.split, image_id + ".jpg")
122
+ mask_path = os.path.join(self.path, "annotations", self.split, image_id + ".png")
123
+
124
+ label = Image.open(mask_path).convert("L")
125
+ image = Image.open(img_path).convert("RGB")
126
+ label = np.asarray(label)
127
+ image = np.asarray(image)
128
+ image, label = self._augmentation_new(image,label)
129
+
130
+ label_list = np.unique(label)
131
+ label_list = list(label_list)
132
+ label_list_rest = [i for i in range(182)]
133
+ for item in label_list_rest:
134
+ if item in label_list:
135
+ label_list_rest.remove(item)
136
+ if 255 in label_list:
137
+ label_list.remove(255)
138
+ if len(label_list)!=0:
139
+ label_idx = random.choice(label_list)
140
+ if random.uniform(0, 1) < self.empty_percentage:
141
+ label_idx = random.choice(label_list_rest)
142
+
143
+ class_name = self.label_dict[label_idx+1]
144
+
145
+ prompt = random.choice(self.seg_diverse_prompt_list)
146
+ color = random.choice(self.color_list)
147
+ color_name = color[0]
148
+ prompt = prompt.format(color=color_name.lower(), object=class_name.lower())
149
+ R, G, B = color[3].split(",")
150
+ R = int(R)
151
+ G = int(G)
152
+ B = int(B)
153
+ else:
154
+ label_idx = 200
155
+ prompt = "leave the picture as it is."
156
+ mask = (label==label_idx)
157
+ image_0 = Image.fromarray(image)
158
+ image_1 = copy.deepcopy(image)
159
+
160
+ if len(label_list)!=0:
161
+ image_1[:,:,0][mask]=self.transparency*image_1[:,:,0][mask]+(1-self.transparency)*R
162
+ image_1[:,:,1][mask]=self.transparency*image_1[:,:,1][mask]+(1-self.transparency)*G
163
+ image_1[:,:,2][mask]=self.transparency*image_1[:,:,2][mask]+(1-self.transparency)*B
164
+
165
+ image_1 = Image.fromarray(image_1)
166
+ # return image_0, image_1, prompt
167
+
168
+ image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
169
+ image_1 = rearrange(2 * torch.tensor(np.array(image_1)).float() / 255 - 1, "h w c -> c h w")
170
+
171
+ mask = torch.tensor(mask).float()
172
+ crop = torchvision.transforms.RandomCrop(self.crop_res)
173
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
174
+ image_0, image_1 = flip(crop(torch.cat((image_0, image_1)))).chunk(2)
175
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
dataset/seg/grefcoco.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ grefer v0.1
3
+ This interface provides access to gRefCOCO.
4
+
5
+ The following API functions are defined:
6
+ G_REFER - REFER api class
7
+ getRefIds - get ref ids that satisfy given filter conditions.
8
+ getAnnIds - get ann ids that satisfy given filter conditions.
9
+ getImgIds - get image ids that satisfy given filter conditions.
10
+ getCatIds - get category ids that satisfy given filter conditions.
11
+ loadRefs - load refs with the specified ref ids.
12
+ loadAnns - load anns with the specified ann ids.
13
+ loadImgs - load images with the specified image ids.
14
+ loadCats - load category names with the specified category ids.
15
+ getRefBox - get ref's bounding box [x, y, w, h] given the ref_id
16
+ showRef - show image, segmentation or box of the referred object with the ref
17
+ getMaskByRef - get mask and area of the referred object given ref or ref ids
18
+ getMask - get mask and area of the referred object given ref
19
+ showMask - show mask of the referred object given ref
20
+ """
21
+
22
+ import os.path as osp
23
+ import json
24
+ import pickle
25
+ import time
26
+ import itertools
27
+ import skimage.io as io
28
+ import matplotlib.pyplot as plt
29
+ from matplotlib.collections import PatchCollection
30
+ from matplotlib.patches import Polygon, Rectangle
31
+ import numpy as np
32
+ from pycocotools import mask
33
+
34
+ class G_REFER:
35
+
36
+ def __init__(self, data_root, dataset='grefcoco', splitBy='unc'):
37
+ # provide data_root folder which contains grefcoco
38
+ print('loading dataset %s into memory...' % dataset)
39
+ self.ROOT_DIR = osp.abspath(osp.dirname(__file__))
40
+ self.DATA_DIR = osp.join(data_root, dataset)
41
+ if dataset in ['grefcoco']:
42
+ self.IMAGE_DIR = osp.join(data_root, 'images/train2014')
43
+ else:
44
+ raise KeyError('No refer dataset is called [%s]' % dataset)
45
+
46
+ tic = time.time()
47
+
48
+ # load refs from data/dataset/refs(dataset).json
49
+ self.data = {}
50
+ self.data['dataset'] = dataset
51
+
52
+ ref_file = osp.join(self.DATA_DIR, f'grefs({splitBy}).p')
53
+ if osp.exists(ref_file):
54
+ self.data['refs'] = pickle.load(open(ref_file, 'rb'),fix_imports=True)
55
+ else:
56
+ ref_file = osp.join(self.DATA_DIR, f'grefs({splitBy}).json')
57
+ if osp.exists(ref_file):
58
+ self.data['refs'] = json.load(open(ref_file, 'rb'))
59
+ else:
60
+ raise FileNotFoundError('JSON file not found')
61
+
62
+ # load annotations from data/dataset/instances.json
63
+ instances_file = osp.join(self.DATA_DIR, 'instances.json')
64
+ instances = json.load(open(instances_file, 'r'))
65
+ self.data['images'] = instances['images']
66
+ self.data['annotations'] = instances['annotations']
67
+ self.data['categories'] = instances['categories']
68
+
69
+ # create index
70
+ self.createIndex()
71
+ print('DONE (t=%.2fs)' % (time.time()-tic))
72
+
73
+ @staticmethod
74
+ def _toList(x):
75
+ return x if isinstance(x, list) else [x]
76
+
77
+ @staticmethod
78
+ def match_any(a, b):
79
+ a = a if isinstance(a, list) else [a]
80
+ b = b if isinstance(b, list) else [b]
81
+ return set(a) & set(b)
82
+
83
+ def createIndex(self):
84
+ # create sets of mapping
85
+ # 1) Refs: {ref_id: ref}
86
+ # 2) Anns: {ann_id: ann}
87
+ # 3) Imgs: {image_id: image}
88
+ # 4) Cats: {category_id: category_name}
89
+ # 5) Sents: {sent_id: sent}
90
+ # 6) imgToRefs: {image_id: refs}
91
+ # 7) imgToAnns: {image_id: anns}
92
+ # 8) refToAnn: {ref_id: ann}
93
+ # 9) annToRef: {ann_id: ref}
94
+ # 10) catToRefs: {category_id: refs}
95
+ # 11) sentToRef: {sent_id: ref}
96
+ # 12) sentToTokens: {sent_id: tokens}
97
+ print('creating index...')
98
+ # fetch info from instances
99
+ Anns, Imgs, Cats, imgToAnns = {}, {}, {}, {}
100
+ Anns[-1] = None
101
+ for ann in self.data['annotations']:
102
+ Anns[ann['id']] = ann
103
+ imgToAnns[ann['image_id']] = imgToAnns.get(ann['image_id'], []) + [ann]
104
+ for img in self.data['images']:
105
+ Imgs[img['id']] = img
106
+ for cat in self.data['categories']:
107
+ Cats[cat['id']] = cat['name']
108
+
109
+ # fetch info from refs
110
+ Refs, imgToRefs, refToAnn, annToRef, catToRefs = {}, {}, {}, {}, {}
111
+ Sents, sentToRef, sentToTokens = {}, {}, {}
112
+ availableSplits = []
113
+ for ref in self.data['refs']:
114
+ # ids
115
+ ref_id = ref['ref_id']
116
+ ann_id = ref['ann_id']
117
+ category_id = ref['category_id']
118
+ image_id = ref['image_id']
119
+
120
+ if ref['split'] not in availableSplits:
121
+ availableSplits.append(ref['split'])
122
+
123
+ # add mapping related to ref
124
+ if ref_id in Refs:
125
+ print('Duplicate ref id')
126
+ Refs[ref_id] = ref
127
+ imgToRefs[image_id] = imgToRefs.get(image_id, []) + [ref]
128
+
129
+ category_id = self._toList(category_id)
130
+ added_cats = []
131
+ for cat in category_id:
132
+ if cat not in added_cats:
133
+ added_cats.append(cat)
134
+ catToRefs[cat] = catToRefs.get(cat, []) + [ref]
135
+
136
+ ann_id = self._toList(ann_id)
137
+ refToAnn[ref_id] = [Anns[ann] for ann in ann_id]
138
+ for ann_id_n in ann_id:
139
+ annToRef[ann_id_n] = annToRef.get(ann_id_n, []) + [ref]
140
+
141
+ # add mapping of sent
142
+ for sent in ref['sentences']:
143
+ Sents[sent['sent_id']] = sent
144
+ sentToRef[sent['sent_id']] = ref
145
+ sentToTokens[sent['sent_id']] = sent['tokens']
146
+
147
+ # create class members
148
+ self.Refs = Refs
149
+ self.Anns = Anns
150
+ self.Imgs = Imgs
151
+ self.Cats = Cats
152
+ self.Sents = Sents
153
+ self.imgToRefs = imgToRefs
154
+ self.imgToAnns = imgToAnns
155
+ self.refToAnn = refToAnn
156
+ self.annToRef = annToRef
157
+ self.catToRefs = catToRefs
158
+ self.sentToRef = sentToRef
159
+ self.sentToTokens = sentToTokens
160
+ self.availableSplits = availableSplits
161
+ print('index created.')
162
+
163
+ def getRefIds(self, image_ids=[], cat_ids=[], split=[]):
164
+ image_ids = self._toList(image_ids)
165
+ cat_ids = self._toList(cat_ids)
166
+ split = self._toList(split)
167
+
168
+ for s in split:
169
+ if s not in self.availableSplits:
170
+ raise ValueError(f'Invalid split name: {s}')
171
+
172
+ refs = self.data['refs']
173
+
174
+ if len(image_ids) > 0:
175
+ lists = [self.imgToRefs[image_id] for image_id in image_ids]
176
+ refs = list(itertools.chain.from_iterable(lists))
177
+ if len(cat_ids) > 0:
178
+ refs = [ref for ref in refs if self.match_any(ref['category_id'], cat_ids)]
179
+ if len(split) > 0:
180
+ refs = [ref for ref in refs if ref['split'] in split]
181
+
182
+ ref_ids = [ref['ref_id'] for ref in refs]
183
+ return ref_ids
184
+
185
+ def getAnnIds(self, image_ids=[], ref_ids=[]):
186
+ image_ids = self._toList(image_ids)
187
+ ref_ids = self._toList(ref_ids)
188
+
189
+ if any([len(image_ids), len(ref_ids)]):
190
+ if len(image_ids) > 0:
191
+ lists = [self.imgToAnns[image_id] for image_id in image_ids if image_id in self.imgToAnns]
192
+ anns = list(itertools.chain.from_iterable(lists))
193
+ else:
194
+ anns = self.data['annotations']
195
+ ann_ids = [ann['id'] for ann in anns]
196
+ if len(ref_ids) > 0:
197
+ lists = [self.Refs[ref_id]['ann_id'] for ref_id in ref_ids]
198
+ anns_by_ref_id = list(itertools.chain.from_iterable(lists))
199
+ ann_ids = list(set(ann_ids).intersection(set(anns_by_ref_id)))
200
+ else:
201
+ ann_ids = [ann['id'] for ann in self.data['annotations']]
202
+
203
+ return ann_ids
204
+
205
+ def getImgIds(self, ref_ids=[]):
206
+ ref_ids = self._toList(ref_ids)
207
+
208
+ if len(ref_ids) > 0:
209
+ image_ids = list(set([self.Refs[ref_id]['image_id'] for ref_id in ref_ids]))
210
+ else:
211
+ image_ids = self.Imgs.keys()
212
+ return image_ids
213
+
214
+ def getCatIds(self):
215
+ return self.Cats.keys()
216
+
217
+ def loadRefs(self, ref_ids=[]):
218
+ return [self.Refs[ref_id] for ref_id in self._toList(ref_ids)]
219
+
220
+ def loadAnns(self, ann_ids=[]):
221
+ if isinstance(ann_ids, str):
222
+ ann_ids = int(ann_ids)
223
+ return [self.Anns[ann_id] for ann_id in self._toList(ann_ids)]
224
+
225
+ def loadImgs(self, image_ids=[]):
226
+ return [self.Imgs[image_id] for image_id in self._toList(image_ids)]
227
+
228
+ def loadCats(self, cat_ids=[]):
229
+ return [self.Cats[cat_id] for cat_id in self._toList(cat_ids)]
230
+
231
+ def getRefBox(self, ref_id):
232
+ anns = self.refToAnn[ref_id]
233
+ return [ann['bbox'] for ann in anns] # [x, y, w, h]
234
+
235
+ def showRef(self, ref, seg_box='seg'):
236
+ ax = plt.gca()
237
+ # show image
238
+ image = self.Imgs[ref['image_id']]
239
+ I = io.imread(osp.join(self.IMAGE_DIR, image['file_name']))
240
+ ax.imshow(I)
241
+ # show refer expression
242
+ for sid, sent in enumerate(ref['sentences']):
243
+ print('%s. %s' % (sid+1, sent['sent']))
244
+ # show segmentations
245
+ if seg_box == 'seg':
246
+ ann_id = ref['ann_id']
247
+ ann = self.Anns[ann_id]
248
+ polygons = []
249
+ color = []
250
+ c = 'none'
251
+ if type(ann['segmentation'][0]) == list:
252
+ # polygon used for refcoco*
253
+ for seg in ann['segmentation']:
254
+ poly = np.array(seg).reshape((len(seg)/2, 2))
255
+ polygons.append(Polygon(poly, True, alpha=0.4))
256
+ color.append(c)
257
+ p = PatchCollection(polygons, facecolors=color, edgecolors=(1,1,0,0), linewidths=3, alpha=1)
258
+ ax.add_collection(p) # thick yellow polygon
259
+ p = PatchCollection(polygons, facecolors=color, edgecolors=(1,0,0,0), linewidths=1, alpha=1)
260
+ ax.add_collection(p) # thin red polygon
261
+ else:
262
+ # mask used for refclef
263
+ rle = ann['segmentation']
264
+ m = mask.decode(rle)
265
+ img = np.ones( (m.shape[0], m.shape[1], 3) )
266
+ color_mask = np.array([2.0,166.0,101.0])/255
267
+ for i in range(3):
268
+ img[:,:,i] = color_mask[i]
269
+ ax.imshow(np.dstack( (img, m*0.5) ))
270
+ # show bounding-box
271
+ elif seg_box == 'box':
272
+ ann_id = ref['ann_id']
273
+ ann = self.Anns[ann_id]
274
+ bbox = self.getRefBox(ref['ref_id'])
275
+ box_plot = Rectangle((bbox[0], bbox[1]), bbox[2], bbox[3], fill=False, edgecolor='green', linewidth=3)
276
+ ax.add_patch(box_plot)
277
+
278
+ def getMask(self, ann):
279
+ if not ann:
280
+ return None
281
+ if ann['iscrowd']:
282
+ raise ValueError('Crowd object')
283
+ image = self.Imgs[ann['image_id']]
284
+ if type(ann['segmentation'][0]) == list: # polygon
285
+ rle = mask.frPyObjects(ann['segmentation'], image['height'], image['width'])
286
+ else:
287
+ rle = ann['segmentation']
288
+
289
+ m = mask.decode(rle)
290
+ m = np.sum(m, axis=2) # sometimes there are multiple binary map (corresponding to multiple segs)
291
+ m = m.astype(np.uint8) # convert to np.uint8
292
+ # compute area
293
+ area = sum(mask.area(rle)) # should be close to ann['area']
294
+ return {'mask': m, 'area': area}
295
+
296
+ def getMaskByRef(self, ref=None, ref_id=None, merge=False):
297
+ if not ref and not ref_id:
298
+ raise ValueError
299
+ if ref:
300
+ ann_ids = ref['ann_id']
301
+ ref_id = ref['ref_id']
302
+ else:
303
+ ann_ids = self.getAnnIds(ref_ids=ref_id)
304
+
305
+ if ann_ids == [-1]:
306
+ img = self.Imgs[self.Refs[ref_id]['image_id']]
307
+ return {
308
+ 'mask': np.zeros([img['height'], img['width']], dtype=np.uint8),
309
+ 'empty': True
310
+ }
311
+
312
+ anns = self.loadAnns(ann_ids)
313
+ mask_list = [self.getMask(ann) for ann in anns if not ann['iscrowd']]
314
+
315
+ if merge:
316
+ merged_masks = sum([mask['mask'] for mask in mask_list])
317
+ merged_masks[np.where(merged_masks>1)] = 1
318
+ return {
319
+ 'mask': merged_masks,
320
+ 'empty': False
321
+ }
322
+ else:
323
+ return mask_list
324
+
325
+ def showMask(self, ref):
326
+ M = self.getMask(ref)
327
+ msk = M['mask']
328
+ ax = plt.gca()
329
+ ax.imshow(msk)
dataset/seg/grefcoco_segmentation.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InstructDiffusion
3
+ # Based on instruct-pix2pix (https://github.com/timothybrooks/instruct-pix2pix)
4
+ # Modified by Binxin Yang (tennyson@mail.ustc.edu.cn)
5
+ # --------------------------------------------------------
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import random
11
+ import copy
12
+ import json
13
+ import math
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ import numpy as np
18
+ import torch
19
+ import torchvision
20
+ from einops import rearrange
21
+ from PIL import Image
22
+ from torch.utils.data import Dataset
23
+
24
+ from dataset.seg.grefcoco import G_REFER
25
+
26
+
27
+ class GrefCOCODataset(Dataset):
28
+ def __init__(
29
+ self,
30
+ path: str,
31
+ split: str = "train",
32
+ min_resize_res: int = 256,
33
+ max_resize_res: int = 256,
34
+ crop_res: int = 256,
35
+ flip_prob: float = 0.0,
36
+ transparency: float = 0.0,
37
+ test: bool = False,
38
+ ):
39
+ assert split in ("train", "val", "test")
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.G_ref_dataset=G_REFER(data_root=path)
46
+ self.IMAGE_DIR = os.path.join(path, 'images/train2014')
47
+ self.list_ref=self.G_ref_dataset.getRefIds(split=split)
48
+ self.transparency = transparency
49
+ self.test = test
50
+
51
+ seg_diverse_prompt_path = 'dataset/prompt/prompt_seg.txt'
52
+ self.seg_diverse_prompt_list=[]
53
+ with open(seg_diverse_prompt_path) as f:
54
+ line=f.readline()
55
+ while line:
56
+ line=line.strip('\n')
57
+ self.seg_diverse_prompt_list.append(line)
58
+ line=f.readline()
59
+
60
+ color_list_file_path='dataset/prompt/color_list_train_small.txt'
61
+ self.color_list=[]
62
+ with open(color_list_file_path) as f:
63
+ line = f.readline()
64
+ while line:
65
+ line_split = line.strip('\n').split(" ")
66
+ if len(line_split)>1:
67
+ temp = []
68
+ for i in range(4):
69
+ temp.append(line_split[i])
70
+ self.color_list.append(temp)
71
+ line = f.readline()
72
+
73
+ def __len__(self) -> int:
74
+ return len(self.list_ref)
75
+
76
+ def _augmentation_new(self, image, label):
77
+
78
+ # Cropping
79
+ h, w = label.shape
80
+ if h > w:
81
+ start_h = random.randint(0, h - w)
82
+ end_h = start_h + w
83
+ image = image[start_h:end_h]
84
+ label = label[start_h:end_h]
85
+ elif h < w:
86
+ start_w = random.randint(0, w - h)
87
+ end_w = start_w + h
88
+ image = image[:, start_w:end_w]
89
+ label = label[:, start_w:end_w]
90
+ else:
91
+ pass
92
+ image = Image.fromarray(image).resize((self.min_resize_res, self.min_resize_res), resample=Image.Resampling.LANCZOS)
93
+ image = np.asarray(image, dtype=np.uint8)
94
+ label = Image.fromarray(label).resize((self.min_resize_res, self.min_resize_res), resample=Image.Resampling.NEAREST)
95
+ label = np.asarray(label, dtype=np.int64)
96
+ return image, label
97
+
98
+ def __getitem__(self, i: int) -> dict[str, Any]:
99
+
100
+ ref_ids = self.list_ref[i]
101
+ ref = self.G_ref_dataset.loadRefs(ref_ids)[0]
102
+ sentences = random.choice(ref['sentences'])['sent']
103
+
104
+ prompt = random.choice(self.seg_diverse_prompt_list)
105
+
106
+ color = random.choice(self.color_list)
107
+ color_name = color[0]
108
+ prompt = prompt.format(color=color_name.lower(), object=sentences.lower())
109
+
110
+ R, G, B = color[3].split(",")
111
+ R = int(R)
112
+ G = int(G)
113
+ B = int(B)
114
+
115
+ image_name = self.G_ref_dataset.loadImgs(ref['image_id'])[0]['file_name']
116
+ image_path = os.path.join(self.IMAGE_DIR,image_name)
117
+ mask = self.G_ref_dataset.getMaskByRef(ref=ref,merge=True)['mask']
118
+
119
+ image = Image.open(image_path).convert("RGB")
120
+ image = np.asarray(image)
121
+
122
+ image, mask = self._augmentation_new(image,mask)
123
+
124
+ mask = (mask == 1)
125
+
126
+ image_0 = Image.fromarray(image)
127
+ image_1 = copy.deepcopy(image)
128
+ image_1[:,:,0][mask]=self.transparency*image_1[:,:,0][mask]+(1-self.transparency)*R
129
+ image_1[:,:,1][mask]=self.transparency*image_1[:,:,1][mask]+(1-self.transparency)*G
130
+ image_1[:,:,2][mask]=self.transparency*image_1[:,:,2][mask]+(1-self.transparency)*B
131
+ image_1 = Image.fromarray(image_1)
132
+
133
+ reize_res = torch.randint(self.min_resize_res, self.max_resize_res + 1, ()).item()
134
+ image_0 = image_0.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
135
+ image_1 = image_1.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
136
+
137
+
138
+ image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
139
+ image_1 = rearrange(2 * torch.tensor(np.array(image_1)).float() / 255 - 1, "h w c -> c h w")
140
+
141
+ crop = torchvision.transforms.RandomCrop(self.crop_res)
142
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
143
+ image_0, image_1 = flip(crop(torch.cat((image_0, image_1)))).chunk(2)
144
+
145
+ mask = torch.tensor(mask).float()
146
+ crop = torchvision.transforms.RandomCrop(self.crop_res)
147
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
148
+ image_0, image_1 = flip(crop(torch.cat((image_0, image_1)))).chunk(2)
149
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
dataset/seg/refcoco.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __author__ = 'licheng'
2
+
3
+ """
4
+ This interface provides access to four datasets:
5
+ 1) refclef
6
+ 2) refcoco
7
+ 3) refcoco+
8
+ 4) refcocog
9
+ split by unc and google
10
+
11
+ The following API functions are defined:
12
+ REFER - REFER api class
13
+ getRefIds - get ref ids that satisfy given filter conditions.
14
+ getAnnIds - get ann ids that satisfy given filter conditions.
15
+ getImgIds - get image ids that satisfy given filter conditions.
16
+ getCatIds - get category ids that satisfy given filter conditions.
17
+ loadRefs - load refs with the specified ref ids.
18
+ loadAnns - load anns with the specified ann ids.
19
+ loadImgs - load images with the specified image ids.
20
+ loadCats - load category names with the specified category ids.
21
+ getRefBox - get ref's bounding box [x, y, w, h] given the ref_id
22
+ showRef - show image, segmentation or box of the referred object with the ref
23
+ getMask - get mask and area of the referred object given ref
24
+ showMask - show mask of the referred object given ref
25
+ """
26
+
27
+ import sys
28
+ sys.path.append("./dataset")
29
+ import os.path as osp
30
+ import json
31
+ import pickle
32
+ import time
33
+ import itertools
34
+ import skimage.io as io
35
+ import matplotlib.pyplot as plt
36
+ from matplotlib.collections import PatchCollection
37
+ from matplotlib.patches import Polygon, Rectangle
38
+ from pprint import pprint
39
+ import numpy as np
40
+ from pycocotools import mask
41
+ # import cv2
42
+ # from skimage.measure import label, regionprops
43
+
44
+ class REFER:
45
+
46
+ def __init__(self, data_root, dataset='refcoco', splitBy='unc'):
47
+ # provide data_root folder which contains refclef, refcoco, refcoco+ and refcocog
48
+ # also provide dataset name and splitBy information
49
+ # e.g., dataset = 'refcoco', splitBy = 'unc'
50
+ print('loading dataset %s into memory...' % dataset)
51
+ self.ROOT_DIR = osp.abspath(osp.dirname(__file__))
52
+ self.DATA_DIR = osp.join(data_root, dataset)
53
+ if dataset in ['refcoco', 'refcoco+', 'refcocog']:
54
+ self.IMAGE_DIR = osp.join(data_root, 'images/mscoco/images/train2014')
55
+ elif dataset == 'refclef':
56
+ self.IMAGE_DIR = osp.join(data_root, 'images/saiapr_tc-12')
57
+ else:
58
+ print('No refer dataset is called [%s]' % dataset)
59
+ sys.exit()
60
+
61
+ # load refs from data/dataset/refs(dataset).json
62
+ tic = time.time()
63
+ ref_file = osp.join(self.DATA_DIR, 'refs('+splitBy+').p')
64
+ self.data = {}
65
+ self.data['dataset'] = dataset
66
+ self.data['refs'] = pickle.load(open(ref_file, 'rb'),fix_imports=True)
67
+
68
+ # load annotations from data/dataset/instances.json
69
+ instances_file = osp.join(self.DATA_DIR, 'instances.json')
70
+ instances = json.load(open(instances_file, 'r'))
71
+ self.data['images'] = instances['images']
72
+ self.data['annotations'] = instances['annotations']
73
+ self.data['categories'] = instances['categories']
74
+
75
+ # create index
76
+ self.createIndex()
77
+ print('DONE (t=%.2fs)' % (time.time()-tic))
78
+
79
+ def createIndex(self):
80
+ # create sets of mapping
81
+ # 1) Refs: {ref_id: ref}
82
+ # 2) Anns: {ann_id: ann}
83
+ # 3) Imgs: {image_id: image}
84
+ # 4) Cats: {category_id: category_name}
85
+ # 5) Sents: {sent_id: sent}
86
+ # 6) imgToRefs: {image_id: refs}
87
+ # 7) imgToAnns: {image_id: anns}
88
+ # 8) refToAnn: {ref_id: ann}
89
+ # 9) annToRef: {ann_id: ref}
90
+ # 10) catToRefs: {category_id: refs}
91
+ # 11) sentToRef: {sent_id: ref}
92
+ # 12) sentToTokens: {sent_id: tokens}
93
+ print('creating index...')
94
+ # fetch info from instances
95
+ Anns, Imgs, Cats, imgToAnns = {}, {}, {}, {}
96
+ for ann in self.data['annotations']:
97
+ Anns[ann['id']] = ann
98
+ imgToAnns[ann['image_id']] = imgToAnns.get(ann['image_id'], []) + [ann]
99
+ for img in self.data['images']:
100
+ Imgs[img['id']] = img
101
+ for cat in self.data['categories']:
102
+ Cats[cat['id']] = cat['name']
103
+
104
+ # fetch info from refs
105
+ Refs, imgToRefs, refToAnn, annToRef, catToRefs = {}, {}, {}, {}, {}
106
+ Sents, sentToRef, sentToTokens = {}, {}, {}
107
+ for ref in self.data['refs']:
108
+ # ids
109
+ ref_id = ref['ref_id']
110
+ ann_id = ref['ann_id']
111
+ category_id = ref['category_id']
112
+ image_id = ref['image_id']
113
+
114
+ # add mapping related to ref
115
+ Refs[ref_id] = ref
116
+ imgToRefs[image_id] = imgToRefs.get(image_id, []) + [ref]
117
+ catToRefs[category_id] = catToRefs.get(category_id, []) + [ref]
118
+ refToAnn[ref_id] = Anns[ann_id]
119
+ annToRef[ann_id] = ref
120
+
121
+ # add mapping of sent
122
+ for sent in ref['sentences']:
123
+ Sents[sent['sent_id']] = sent
124
+ sentToRef[sent['sent_id']] = ref
125
+ sentToTokens[sent['sent_id']] = sent['tokens']
126
+
127
+ # create class members
128
+ self.Refs = Refs
129
+ self.Anns = Anns
130
+ self.Imgs = Imgs
131
+ self.Cats = Cats
132
+ self.Sents = Sents
133
+ self.imgToRefs = imgToRefs
134
+ self.imgToAnns = imgToAnns
135
+ self.refToAnn = refToAnn
136
+ self.annToRef = annToRef
137
+ self.catToRefs = catToRefs
138
+ self.sentToRef = sentToRef
139
+ self.sentToTokens = sentToTokens
140
+ print('index created.')
141
+
142
+ def getRefIds(self, image_ids=[], cat_ids=[], ref_ids=[], split=''):
143
+ image_ids = image_ids if type(image_ids) == list else [image_ids]
144
+ cat_ids = cat_ids if type(cat_ids) == list else [cat_ids]
145
+ ref_ids = ref_ids if type(ref_ids) == list else [ref_ids]
146
+
147
+ if len(image_ids)==len(cat_ids)==len(ref_ids)==len(split)==0:
148
+ refs = self.data['refs']
149
+ else:
150
+ if not len(image_ids) == 0:
151
+ refs = [self.imgToRefs[image_id] for image_id in image_ids]
152
+ else:
153
+ refs = self.data['refs']
154
+ if not len(cat_ids) == 0:
155
+ refs = [ref for ref in refs if ref['category_id'] in cat_ids]
156
+ if not len(ref_ids) == 0:
157
+ refs = [ref for ref in refs if ref['ref_id'] in ref_ids]
158
+ if not len(split) == 0:
159
+ if split in ['testA', 'testB', 'testC']:
160
+ refs = [ref for ref in refs if split[-1] in ref['split']] # we also consider testAB, testBC, ...
161
+ elif split in ['testAB', 'testBC', 'testAC']:
162
+ refs = [ref for ref in refs if ref['split'] == split] # rarely used I guess...
163
+ elif split == 'test':
164
+ refs = [ref for ref in refs if 'test' in ref['split']]
165
+ elif split == 'train' or split == 'val':
166
+ refs = [ref for ref in refs if ref['split'] == split]
167
+ else:
168
+ print('No such split [%s]' % split)
169
+ sys.exit()
170
+ ref_ids = [ref['ref_id'] for ref in refs]
171
+ return ref_ids
172
+
173
+ def getAnnIds(self, image_ids=[], cat_ids=[], ref_ids=[]):
174
+ image_ids = image_ids if type(image_ids) == list else [image_ids]
175
+ cat_ids = cat_ids if type(cat_ids) == list else [cat_ids]
176
+ ref_ids = ref_ids if type(ref_ids) == list else [ref_ids]
177
+
178
+ if len(image_ids) == len(cat_ids) == len(ref_ids) == 0:
179
+ ann_ids = [ann['id'] for ann in self.data['annotations']]
180
+ else:
181
+ if not len(image_ids) == 0:
182
+ lists = [self.imgToAnns[image_id] for image_id in image_ids if image_id in self.imgToAnns] # list of [anns]
183
+ anns = list(itertools.chain.from_iterable(lists))
184
+ else:
185
+ anns = self.data['annotations']
186
+ if not len(cat_ids) == 0:
187
+ anns = [ann for ann in anns if ann['category_id'] in cat_ids]
188
+ ann_ids = [ann['id'] for ann in anns]
189
+ if not len(ref_ids) == 0:
190
+ ids = set(ann_ids).intersection(set([self.Refs[ref_id]['ann_id'] for ref_id in ref_ids]))
191
+ return ann_ids
192
+
193
+ def getImgIds(self, ref_ids=[]):
194
+ ref_ids = ref_ids if type(ref_ids) == list else [ref_ids]
195
+
196
+ if not len(ref_ids) == 0:
197
+ image_ids = list(set([self.Refs[ref_id]['image_id'] for ref_id in ref_ids]))
198
+ else:
199
+ image_ids = self.Imgs.keys()
200
+ return image_ids
201
+
202
+ def getCatIds(self):
203
+ return self.Cats.keys()
204
+
205
+ def loadRefs(self, ref_ids=[]):
206
+ if type(ref_ids) == list:
207
+ return [self.Refs[ref_id] for ref_id in ref_ids]
208
+ elif type(ref_ids) == int:
209
+ return [self.Refs[ref_ids]]
210
+
211
+ def loadAnns(self, ann_ids=[]):
212
+ if type(ann_ids) == list:
213
+ return [self.Anns[ann_id] for ann_id in ann_ids]
214
+ elif type(ann_ids) == int or type(ann_ids) == unicode:
215
+ return [self.Anns[ann_ids]]
216
+
217
+ def loadImgs(self, image_ids=[]):
218
+ if type(image_ids) == list:
219
+ return [self.Imgs[image_id] for image_id in image_ids]
220
+ elif type(image_ids) == int:
221
+ return [self.Imgs[image_ids]]
222
+
223
+ def loadCats(self, cat_ids=[]):
224
+ if type(cat_ids) == list:
225
+ return [self.Cats[cat_id] for cat_id in cat_ids]
226
+ elif type(cat_ids) == int:
227
+ return [self.Cats[cat_ids]]
228
+
229
+ def getRefBox(self, ref_id):
230
+ ref = self.Refs[ref_id]
231
+ ann = self.refToAnn[ref_id]
232
+ return ann['bbox'] # [x, y, w, h]
233
+
234
+ def showRef(self, ref, seg_box='seg'):
235
+ ax = plt.gca()
236
+ # show image
237
+ image = self.Imgs[ref['image_id']]
238
+ I = io.imread(osp.join(self.IMAGE_DIR, image['file_name']))
239
+ ax.imshow(I)
240
+ # show refer expression
241
+ for sid, sent in enumerate(ref['sentences']):
242
+ print('%s. %s' % (sid+1, sent['sent']))
243
+ # show segmentations
244
+ if seg_box == 'seg':
245
+ ann_id = ref['ann_id']
246
+ ann = self.Anns[ann_id]
247
+ polygons = []
248
+ color = []
249
+ c = 'none'
250
+ if type(ann['segmentation'][0]) == list:
251
+ # polygon used for refcoco*
252
+ for seg in ann['segmentation']:
253
+ poly = np.array(seg).reshape((len(seg)/2, 2))
254
+ polygons.append(Polygon(poly, True, alpha=0.4))
255
+ color.append(c)
256
+ p = PatchCollection(polygons, facecolors=color, edgecolors=(1,1,0,0), linewidths=3, alpha=1)
257
+ ax.add_collection(p) # thick yellow polygon
258
+ p = PatchCollection(polygons, facecolors=color, edgecolors=(1,0,0,0), linewidths=1, alpha=1)
259
+ ax.add_collection(p) # thin red polygon
260
+ else:
261
+ # mask used for refclef
262
+ rle = ann['segmentation']
263
+ m = mask.decode(rle)
264
+ img = np.ones( (m.shape[0], m.shape[1], 3) )
265
+ color_mask = np.array([2.0,166.0,101.0])/255
266
+ for i in range(3):
267
+ img[:,:,i] = color_mask[i]
268
+ ax.imshow(np.dstack( (img, m*0.5) ))
269
+ # show bounding-box
270
+ elif seg_box == 'box':
271
+ ann_id = ref['ann_id']
272
+ ann = self.Anns[ann_id]
273
+ bbox = self.getRefBox(ref['ref_id'])
274
+ box_plot = Rectangle((bbox[0], bbox[1]), bbox[2], bbox[3], fill=False, edgecolor='green', linewidth=3)
275
+ ax.add_patch(box_plot)
276
+
277
+ def getMask(self, ref):
278
+ # return mask, area and mask-center
279
+ ann = self.refToAnn[ref['ref_id']]
280
+ image = self.Imgs[ref['image_id']]
281
+ if type(ann['segmentation'][0]) == list: # polygon
282
+ rle = mask.frPyObjects(ann['segmentation'], image['height'], image['width'])
283
+ else:
284
+ rle = ann['segmentation']
285
+ m = mask.decode(rle)
286
+ m = np.sum(m, axis=2) # sometimes there are multiple binary map (corresponding to multiple segs)
287
+ m = m.astype(np.uint8) # convert to np.uint8
288
+ # compute area
289
+ area = sum(mask.area(rle)) # should be close to ann['area']
290
+ return {'mask': m, 'area': area}
291
+ # # position
292
+ # position_x = np.mean(np.where(m==1)[1]) # [1] means columns (matlab style) -> x (c style)
293
+ # position_y = np.mean(np.where(m==1)[0]) # [0] means rows (matlab style) -> y (c style)
294
+ # # mass position (if there were multiple regions, we use the largest one.)
295
+ # label_m = label(m, connectivity=m.ndim)
296
+ # regions = regionprops(label_m)
297
+ # if len(regions) > 0:
298
+ # largest_id = np.argmax(np.array([props.filled_area for props in regions]))
299
+ # largest_props = regions[largest_id]
300
+ # mass_y, mass_x = largest_props.centroid
301
+ # else:
302
+ # mass_x, mass_y = position_x, position_y
303
+ # # if centroid is not in mask, we find the closest point to it from mask
304
+ # if m[mass_y, mass_x] != 1:
305
+ # print 'Finding closes mask point ...'
306
+ # kernel = np.ones((10, 10),np.uint8)
307
+ # me = cv2.erode(m, kernel, iterations = 1)
308
+ # points = zip(np.where(me == 1)[0].tolist(), np.where(me == 1)[1].tolist()) # row, col style
309
+ # points = np.array(points)
310
+ # dist = np.sum((points - (mass_y, mass_x))**2, axis=1)
311
+ # id = np.argsort(dist)[0]
312
+ # mass_y, mass_x = points[id]
313
+ # # return
314
+ # return {'mask': m, 'area': area, 'position_x': position_x, 'position_y': position_y, 'mass_x': mass_x, 'mass_y': mass_y}
315
+ # # show image and mask
316
+ # I = io.imread(osp.join(self.IMAGE_DIR, image['file_name']))
317
+ # plt.figure()
318
+ # plt.imshow(I)
319
+ # ax = plt.gca()
320
+ # img = np.ones( (m.shape[0], m.shape[1], 3) )
321
+ # color_mask = np.array([2.0,166.0,101.0])/255
322
+ # for i in range(3):
323
+ # img[:,:,i] = color_mask[i]
324
+ # ax.imshow(np.dstack( (img, m*0.5) ))
325
+ # plt.show()
326
+
327
+ def showMask(self, ref):
328
+ M = self.getMask(ref)
329
+ msk = M['mask']
330
+ ax = plt.gca()
331
+ ax.imshow(msk)
332
+
333
+
334
+ if __name__ == '__main__':
335
+ refer = REFER(dataset='refcocog', splitBy='google')
336
+ ref_ids = refer.getRefIds()
337
+ print(len(ref_ids))
338
+
339
+ print(len(refer.Imgs))
340
+ print(len(refer.imgToRefs))
341
+
342
+ ref_ids = refer.getRefIds(split='train')
343
+ print('There are %s training referred objects.' % len(ref_ids))
344
+
345
+ for ref_id in ref_ids:
346
+ ref = refer.loadRefs(ref_id)[0]
347
+ if len(ref['sentences']) < 2:
348
+ continue
349
+
350
+ pprint(ref)
351
+ print('The label is %s.' % refer.Cats[ref['category_id']])
352
+ plt.figure()
353
+ refer.showRef(ref, seg_box='box')
354
+ plt.show()
dataset/seg/refcoco_segmentation.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InstructDiffusion
3
+ # Based on instruct-pix2pix (https://github.com/timothybrooks/instruct-pix2pix)
4
+ # Modified by Binxin Yang (tennyson@mail.ustc.edu.cn)
5
+ # --------------------------------------------------------
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import random
11
+ import copy
12
+ import json
13
+ import math
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ import numpy as np
18
+ import torch
19
+ import torchvision
20
+ from einops import rearrange
21
+ from PIL import Image
22
+ from torch.utils.data import Dataset
23
+
24
+ from dataset.seg.refcoco import REFER
25
+
26
+
27
+ class RefCOCODataset(Dataset):
28
+ def __init__(
29
+ self,
30
+ path: str,
31
+ split: str = "train",
32
+ min_resize_res: int = 256,
33
+ max_resize_res: int = 256,
34
+ crop_res: int = 256,
35
+ flip_prob: float = 0.0,
36
+ transparency: float = 0.0,
37
+ test: bool = False,
38
+ ):
39
+ assert split in ("train", "val", "test")
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.G_ref_dataset=REFER(data_root=path)
46
+ self.IMAGE_DIR = os.path.join(path, 'images/train2014')
47
+ self.list_ref=self.G_ref_dataset.getRefIds(split=split)
48
+ self.transparency = transparency
49
+ self.test = test
50
+
51
+ seg_diverse_prompt_path = 'dataset/prompt/prompt_seg.txt'
52
+ self.seg_diverse_prompt_list=[]
53
+ with open(seg_diverse_prompt_path) as f:
54
+ line=f.readline()
55
+ while line:
56
+ line=line.strip('\n')
57
+ self.seg_diverse_prompt_list.append(line)
58
+ line=f.readline()
59
+
60
+ color_list_file_path='dataset/prompt/color_list_train_small.txt'
61
+ self.color_list=[]
62
+ with open(color_list_file_path) as f:
63
+ line = f.readline()
64
+ while line:
65
+ line_split = line.strip('\n').split(" ")
66
+ if len(line_split)>1:
67
+ temp = []
68
+ for i in range(4):
69
+ temp.append(line_split[i])
70
+ self.color_list.append(temp)
71
+ line = f.readline()
72
+
73
+ def __len__(self) -> int:
74
+ return len(self.list_ref)
75
+
76
+ def _augmentation_new(self, image, label):
77
+
78
+ # Cropping
79
+ h, w = label.shape
80
+ if h > w:
81
+ start_h = random.randint(0, h - w)
82
+ end_h = start_h + w
83
+ image = image[start_h:end_h]
84
+ label = label[start_h:end_h]
85
+ elif h < w:
86
+ start_w = random.randint(0, w - h)
87
+ end_w = start_w + h
88
+ image = image[:, start_w:end_w]
89
+ label = label[:, start_w:end_w]
90
+ else:
91
+ pass
92
+ image = Image.fromarray(image).resize((self.min_resize_res, self.min_resize_res), resample=Image.Resampling.LANCZOS)
93
+ image = np.asarray(image, dtype=np.uint8)
94
+ label = Image.fromarray(label).resize((self.min_resize_res, self.min_resize_res), resample=Image.Resampling.NEAREST)
95
+ label = np.asarray(label, dtype=np.int64)
96
+ return image, label
97
+
98
+ def __getitem__(self, i: int) -> dict[str, Any]:
99
+
100
+ ref_ids = self.list_ref[i]
101
+ ref = self.G_ref_dataset.loadRefs(ref_ids)[0]
102
+ sentences = random.choice(ref['sentences'])['sent']
103
+
104
+ prompt = random.choice(self.seg_diverse_prompt_list)
105
+
106
+ color = random.choice(self.color_list)
107
+ color_name = color[0]
108
+ prompt = prompt.format(color=color_name.lower(), object=sentences.lower())
109
+
110
+ R, G, B = color[3].split(",")
111
+ R = int(R)
112
+ G = int(G)
113
+ B = int(B)
114
+
115
+ image_name = self.G_ref_dataset.loadImgs(ref['image_id'])[0]['file_name']
116
+ image_path = os.path.join(self.IMAGE_DIR,image_name)
117
+ mask = self.G_ref_dataset.getMask(ref=ref)['mask']
118
+
119
+ image = Image.open(image_path).convert("RGB")
120
+ image = np.asarray(image)
121
+
122
+ image, mask = self._augmentation_new(image,mask)
123
+
124
+ mask = (mask == 1)
125
+
126
+ image_0 = Image.fromarray(image)
127
+ image_1 = copy.deepcopy(image)
128
+ image_1[:,:,0][mask]=self.transparency*image_1[:,:,0][mask]+(1-self.transparency)*R
129
+ image_1[:,:,1][mask]=self.transparency*image_1[:,:,1][mask]+(1-self.transparency)*G
130
+ image_1[:,:,2][mask]=self.transparency*image_1[:,:,2][mask]+(1-self.transparency)*B
131
+ image_1 = Image.fromarray(image_1)
132
+
133
+ reize_res = torch.randint(self.min_resize_res, self.max_resize_res + 1, ()).item()
134
+ image_0 = image_0.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
135
+ image_1 = image_1.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
136
+
137
+
138
+ image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
139
+ image_1 = rearrange(2 * torch.tensor(np.array(image_1)).float() / 255 - 1, "h w c -> c h w")
140
+
141
+ crop = torchvision.transforms.RandomCrop(self.crop_res)
142
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
143
+ image_0, image_1 = flip(crop(torch.cat((image_0, image_1)))).chunk(2)
144
+
145
+ mask = torch.tensor(mask).float()
146
+ crop = torchvision.transforms.RandomCrop(self.crop_res)
147
+ flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
148
+ image_0, image_1 = flip(crop(torch.cat((image_0, image_1)))).chunk(2)
149
+ return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
dataset/utils/zip_manager.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import zipfile
2
+ import os.path as osp
3
+ # import lmdb
4
+ import logging
5
+ from PIL import Image
6
+ import pickle
7
+ import io
8
+ import glob
9
+ import os
10
+ from pathlib import Path
11
+ import time
12
+ from threading import Thread
13
+ from PIL import ImageFile
14
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
15
+
16
+ home = str(Path.home())
17
+ abs_blob_path=os.path.realpath("/mnt/blob/")
18
+ CACHE_FOLDER=os.path.join(home,"caching")
19
+ USE_CACHE=True
20
+
21
+ def norm(path):
22
+ assert "*" not in path
23
+ return os.path.realpath(os.path.abspath(path))
24
+
25
+ def in_blob(file):
26
+ if abs_blob_path in file:
27
+ return True
28
+ else:
29
+ return False
30
+
31
+ def map_name(file):
32
+ path=norm(file)
33
+ path=path.lstrip(abs_blob_path+"/")
34
+ path=path.replace("/","_")
35
+ assert len(path)<250
36
+ return path
37
+
38
+
39
+ def preload(db,sync=False):
40
+ if sync:
41
+ db.initialize()
42
+ else:
43
+ p = Thread(target=db.initialize)
44
+ p.start()
45
+
46
+ def get_keys_from_lmdb(db):
47
+ with db.begin(write=False) as txn:
48
+ return list(txn.cursor().iternext(values=False))
49
+
50
+ def decode_img(byteflow):
51
+ try:
52
+ img=Image.open(io.BytesIO(byteflow)).convert("RGB")
53
+ img.load()
54
+ except:
55
+ img = Image.open("white.jpeg").convert("RGB")
56
+ img.load()
57
+ return img
58
+
59
+ def decode_text(byteflow):
60
+ return pickle.loads(byteflow)
61
+
62
+ decode_funcs={
63
+ "image": decode_img,
64
+ "text": decode_text
65
+ }
66
+
67
+
68
+ class ZipManager:
69
+ def __init__(self, zip_path,data_type,prefix=None) -> None:
70
+ self.decode_func=decode_funcs[data_type]
71
+ self.zip_path=zip_path
72
+ self._init=False
73
+ preload(self)
74
+
75
+ def deinitialze(self):
76
+ self.zip_fd.close()
77
+ del self.zip_fd
78
+ self._init = False
79
+
80
+ def initialize(self,close=True):
81
+ self.zip_fd = zipfile.ZipFile(self.zip_path, mode="r")
82
+ if not hasattr(self,"_keys"):
83
+ self._keys = self.zip_fd.namelist()
84
+ self._init = True
85
+ if close:
86
+ self.deinitialze()
87
+
88
+ @property
89
+ def keys(self):
90
+ while not hasattr(self,"_keys"):
91
+ time.sleep(0.1)
92
+ return self._keys
93
+
94
+ def get(self, name):
95
+ if not self._init:
96
+ self.initialize(close=False)
97
+ byteflow = self.zip_fd.read(name)
98
+ return self.decode_func(byteflow)
99
+
100
+
101
+ class MultipleZipManager:
102
+ def __init__(self, files: list, data_type, sync=True):
103
+ self.files = files
104
+ self._is_init = False
105
+ self.data_type=data_type
106
+ if sync:
107
+ print("sync",files)
108
+ self.initialize()
109
+ else:
110
+ print("async",files)
111
+ preload(self)
112
+ print("initialize over")
113
+
114
+
115
+ def initialize(self):
116
+ self.mapping={}
117
+ self.managers={}
118
+ for file in self.files:
119
+ manager = ZipManager(file, self.data_type)
120
+ self.managers[file]=manager
121
+
122
+ for file,manager in self.managers.items():
123
+ print(file)
124
+ # print("loading")
125
+ logging.info(f"{file} loading")
126
+ keys=manager.keys
127
+ for key in keys:
128
+ self.mapping[key]=file
129
+ logging.info(f"{file} loaded, size = {len(keys)}")
130
+ print("loaded")
131
+
132
+ self._keys=list(self.mapping.keys())
133
+ self._is_init=True
134
+
135
+ @property
136
+ def keys(self):
137
+ while not self._is_init:
138
+ time.sleep(0.1)
139
+ return self._keys
140
+
141
+ def get(self, name):
142
+ data = self.managers[self.mapping[name]].get(name)
143
+ return data
144
+
edit_cli.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InstructDiffusion
3
+ # Based on instruct-pix2pix (https://github.com/timothybrooks/instruct-pix2pix)
4
+ # Modified by Zigang Geng (zigang@mail.ustc.edu.cn)
5
+ # --------------------------------------------------------
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import math
11
+ import random
12
+ import sys
13
+ from argparse import ArgumentParser
14
+
15
+ import einops
16
+ import k_diffusion as K
17
+ import numpy as np
18
+ import torch
19
+ import torch.nn as nn
20
+ from einops import rearrange
21
+ from omegaconf import OmegaConf
22
+ from PIL import Image, ImageOps
23
+ from torch import autocast
24
+
25
+ import requests
26
+
27
+ sys.path.append("./stable_diffusion")
28
+
29
+ from stable_diffusion.ldm.util import instantiate_from_config
30
+
31
+
32
+ class CFGDenoiser(nn.Module):
33
+ def __init__(self, model):
34
+ super().__init__()
35
+ self.inner_model = model
36
+
37
+ def forward(self, z, sigma, cond, uncond, text_cfg_scale, image_cfg_scale):
38
+ cfg_z = einops.repeat(z, "b ... -> (repeat b) ...", repeat=3)
39
+ cfg_sigma = einops.repeat(sigma, "b ... -> (repeat b) ...", repeat=3)
40
+ cfg_cond = {
41
+ "c_crossattn": [torch.cat([cond["c_crossattn"][0], uncond["c_crossattn"][0], cond["c_crossattn"][0]])],
42
+ "c_concat": [torch.cat([cond["c_concat"][0], cond["c_concat"][0], uncond["c_concat"][0]])],
43
+ }
44
+ out_cond, out_img_cond, out_txt_cond \
45
+ = self.inner_model(cfg_z, cfg_sigma, cond=cfg_cond).chunk(3)
46
+ return 0.5 * (out_img_cond + out_txt_cond) + \
47
+ text_cfg_scale * (out_cond - out_img_cond) + \
48
+ image_cfg_scale * (out_cond - out_txt_cond)
49
+
50
+
51
+ def load_model_from_config(config, ckpt, vae_ckpt=None, verbose=False):
52
+ model = instantiate_from_config(config.model)
53
+
54
+ print(f"Loading model from {ckpt}")
55
+ pl_sd = torch.load(ckpt, map_location="cpu")
56
+ if 'state_dict' in pl_sd:
57
+ pl_sd = pl_sd['state_dict']
58
+ m, u = model.load_state_dict(pl_sd, strict=False)
59
+
60
+ print(m, u)
61
+ return model
62
+
63
+
64
+ def main():
65
+ parser = ArgumentParser()
66
+ parser.add_argument("--resolution", default=512, type=int)
67
+ parser.add_argument("--steps", default=100, type=int)
68
+ parser.add_argument("--config", default="configs/instruct_diffusion.yaml", type=str)
69
+ parser.add_argument("--ckpt", default="checkpoints/v1-5-pruned-emaonly-adaption-task.ckpt", type=str)
70
+ parser.add_argument("--vae-ckpt", default=None, type=str)
71
+ parser.add_argument("--input", required=True, type=str)
72
+ parser.add_argument("--outdir", default="logs", type=str)
73
+ parser.add_argument("--edit", required=True, type=str)
74
+ parser.add_argument("--cfg-text", default=5.0, type=float)
75
+ parser.add_argument("--cfg-image", default=1.25, type=float)
76
+ parser.add_argument("--seed", type=int)
77
+ args = parser.parse_args()
78
+
79
+ config = OmegaConf.load(args.config)
80
+ model = load_model_from_config(config, args.ckpt, args.vae_ckpt)
81
+ model.eval().cuda()
82
+
83
+ model_wrap = K.external.CompVisDenoiser(model)
84
+ model_wrap_cfg = CFGDenoiser(model_wrap)
85
+ null_token = model.get_learned_conditioning([""])
86
+
87
+ seed = random.randint(0, 100000) if args.seed is None else args.seed
88
+
89
+ if args.input.startswith("http"):
90
+ input_image = Image.open(requests.get(args.input, stream=True).raw).convert("RGB")
91
+ else:
92
+ input_image = Image.open(args.input).convert("RGB")
93
+ width, height = input_image.size
94
+ factor = args.resolution / max(width, height)
95
+ factor = math.ceil(min(width, height) * factor / 64) * 64 / min(width, height)
96
+ width_resize = int((width * factor) // 64) * 64
97
+ height_resize = int((height * factor) // 64) * 64
98
+ input_image = ImageOps.fit(input_image, (width_resize, height_resize), method=Image.Resampling.LANCZOS)
99
+
100
+ output_dir = args.outdir
101
+ os.makedirs(output_dir, exist_ok=True)
102
+ with torch.no_grad(), autocast("cuda"):
103
+ cond = {}
104
+ cond["c_crossattn"] = [model.get_learned_conditioning([args.edit])]
105
+ input_image = 2 * torch.tensor(np.array(input_image)).float() / 255 - 1
106
+ input_image = rearrange(input_image, "h w c -> 1 c h w").to(next(model.parameters()).device)
107
+ cond["c_concat"] = [model.encode_first_stage(input_image).mode()]
108
+
109
+ uncond = {}
110
+ uncond["c_crossattn"] = [null_token]
111
+ uncond["c_concat"] = [torch.zeros_like(cond["c_concat"][0])]
112
+
113
+ sigmas = model_wrap.get_sigmas(args.steps)
114
+
115
+ extra_args = {
116
+ "cond": cond,
117
+ "uncond": uncond,
118
+ "text_cfg_scale": args.cfg_text,
119
+ "image_cfg_scale": args.cfg_image,
120
+ }
121
+
122
+ torch.manual_seed(seed)
123
+ z = torch.randn_like(cond["c_concat"][0]) * sigmas[0]
124
+ z = K.sampling.sample_euler_ancestral(model_wrap_cfg, z, sigmas, extra_args=extra_args)
125
+ x = model.decode_first_stage(z)
126
+ x = torch.clamp((x + 1.0) / 2.0, min=0.0, max=1.0)
127
+ x = 255.0 * rearrange(x, "1 c h w -> h w c")
128
+ print(x.shape)
129
+ edited_image = Image.fromarray(x.type(torch.uint8).cpu().numpy())
130
+
131
+ edited_image = ImageOps.fit(edited_image, (width, height), method=Image.Resampling.LANCZOS)
132
+ edited_image.save(output_dir+'/output_'+args.input.split('/')[-1].split('.')[0]+'_seed'+str(seed)+'.jpg')
133
+
134
+
135
+ if __name__ == "__main__":
136
+ main()
environment.yaml ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File modified by authors of InstructDiffusion from original (https://github.com/CompVis/stable-diffusion).
2
+ # See more details in LICENSE.
3
+
4
+ name: instructdiff
5
+ channels:
6
+ - pytorch
7
+ - defaults
8
+ dependencies:
9
+ - python=3.8.5
10
+ - pip=20.3
11
+ - cudatoolkit=11.3
12
+ - pytorch=1.11.0
13
+ - torchvision=0.12.0
14
+ - numpy=1.19.2
15
+ - pip:
16
+ - albumentations==0.4.3
17
+ - datasets==2.8.0
18
+ - diffusers
19
+ - opencv-python==4.1.2.30
20
+ - pudb==2019.2
21
+ - invisible-watermark
22
+ - imageio==2.9.0
23
+ - imageio-ffmpeg==0.4.2
24
+ - pytorch-lightning==1.4.2
25
+ - omegaconf==2.1.1
26
+ - test-tube>=0.7.5
27
+ - streamlit>=0.73.1
28
+ - einops==0.3.0
29
+ - torch-fidelity==0.3.0
30
+ - transformers==4.19.2
31
+ - torchmetrics==0.6.0
32
+ - kornia==0.6
33
+ - -e git+https://github.com/CompVis/taming-transformers.git@master#egg=taming-transformers
34
+ - -e git+https://github.com/openai/CLIP.git@main#egg=clip
35
+ - openai
36
+ - gradio
37
+ - seaborn
38
+ - git+https://github.com/crowsonkb/k-diffusion.git
39
+ - deepspeed
40
+ - timm
figure/animals.png ADDED
figure/mirrorcat.jpg ADDED
figure/people.jpg ADDED
figure/watermark.png ADDED
main.py ADDED
@@ -0,0 +1,566 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InstructDiffusion
3
+ # Based on instruct-pix2pix (https://github.com/timothybrooks/instruct-pix2pix)
4
+ # Removed Pytorch-lightning and supported deepspeed by Zigang Geng (zigang@mail.ustc.edu.cn)
5
+ # --------------------------------------------------------
6
+
7
+ import argparse, os, sys, datetime, glob
8
+ import numpy as np
9
+ import time
10
+ import json
11
+ import pickle
12
+ import wandb
13
+ import deepspeed
14
+
15
+ from packaging import version
16
+ from omegaconf import OmegaConf
17
+ from functools import partial
18
+ from PIL import Image
19
+
20
+ from timm.utils import AverageMeter
21
+
22
+ import torch
23
+ import torchvision
24
+ import torch.cuda.amp as amp
25
+ import torch.distributed as dist
26
+ import torch.backends.cudnn as cudnn
27
+ from torch.utils.data import DataLoader, Dataset, ConcatDataset
28
+ sys.path.append("./stable_diffusion")
29
+
30
+ from ldm.data.base import Txt2ImgIterableBaseDataset
31
+ from ldm.util import instantiate_from_config
32
+ from ldm.modules.ema import LitEma
33
+ from utils.logger import create_logger
34
+ from utils.utils import load_checkpoint, save_checkpoint, get_grad_norm, auto_resume_helper
35
+ from utils.deepspeed import create_ds_config
36
+
37
+
38
+ def wandb_log(*args, **kwargs):
39
+ if dist.get_rank() == 0:
40
+ wandb.log(*args, **kwargs)
41
+
42
+
43
+ def get_parser(**parser_kwargs):
44
+ def str2bool(v):
45
+ if isinstance(v, bool):
46
+ return v
47
+ if v.lower() in ("yes", "true", "t", "y", "1"):
48
+ return True
49
+ elif v.lower() in ("no", "false", "f", "n", "0"):
50
+ return False
51
+ else:
52
+ raise argparse.ArgumentTypeError("Boolean value expected.")
53
+
54
+ parser = argparse.ArgumentParser(**parser_kwargs)
55
+ parser.add_argument(
56
+ "-n",
57
+ "--name",
58
+ type=str,
59
+ const=True,
60
+ default="",
61
+ nargs="?",
62
+ help="postfix for logdir",
63
+ )
64
+ parser.add_argument(
65
+ "-r",
66
+ "--resume",
67
+ type=str,
68
+ const=True,
69
+ default="",
70
+ nargs="?",
71
+ help="resume from logdir or checkpoint in logdir",
72
+ )
73
+ parser.add_argument(
74
+ "-b",
75
+ "--base",
76
+ nargs="*",
77
+ metavar="base_config.yaml",
78
+ help="paths to base configs. Loaded from left-to-right. "
79
+ "Parameters can be overwritten or added with command-line options of the form `--key value`.",
80
+ default=list(),
81
+ )
82
+ parser.add_argument(
83
+ "-t",
84
+ "--train",
85
+ type=str2bool,
86
+ const=True,
87
+ default=False,
88
+ nargs="?",
89
+ help="train",
90
+ )
91
+ parser.add_argument(
92
+ "--no-test",
93
+ type=str2bool,
94
+ const=True,
95
+ default=False,
96
+ nargs="?",
97
+ help="disable test",
98
+ )
99
+ parser.add_argument(
100
+ "-p",
101
+ "--project",
102
+ help="name of new or path to existing project"
103
+ )
104
+ parser.add_argument(
105
+ "-d",
106
+ "--debug",
107
+ type=str2bool,
108
+ nargs="?",
109
+ const=True,
110
+ default=False,
111
+ help="enable post-mortem debugging",
112
+ )
113
+ parser.add_argument(
114
+ "-s",
115
+ "--seed",
116
+ type=int,
117
+ default=23,
118
+ help="seed for seed_everything",
119
+ )
120
+ parser.add_argument(
121
+ "-f",
122
+ "--postfix",
123
+ type=str,
124
+ default="",
125
+ help="post-postfix for default name",
126
+ )
127
+ parser.add_argument(
128
+ "-l",
129
+ "--logdir",
130
+ type=str,
131
+ default="logs",
132
+ help="directory for logging dat shit",
133
+ )
134
+ parser.add_argument(
135
+ "--scale_lr",
136
+ action="store_true",
137
+ default=False,
138
+ help="scale base-lr by ngpu * batch_size * n_accumulate",
139
+ )
140
+ parser.add_argument(
141
+ "--amd",
142
+ action="store_true",
143
+ default=False,
144
+ help="amd",
145
+ )
146
+ parser.add_argument(
147
+ "--local_rank",
148
+ type=int,
149
+ # required=False,
150
+ default=int(os.environ.get('LOCAL_RANK', 0)),
151
+ help="local rank for DistributedDataParallel",
152
+ )
153
+ return parser
154
+
155
+
156
+ class WrappedDataset(Dataset):
157
+ """Wraps an arbitrary object with __len__ and __getitem__ into a pytorch dataset"""
158
+
159
+ def __init__(self, dataset):
160
+ self.data = dataset
161
+
162
+ def __len__(self):
163
+ return len(self.data)
164
+
165
+ def __getitem__(self, idx):
166
+ return self.data[idx]
167
+
168
+
169
+ class DataModuleFromConfig():
170
+ def __init__(self, batch_size, train=None, validation=None, test=None, predict=None,
171
+ wrap=False, num_workers=None, shuffle_test_loader=False, use_worker_init_fn=False,
172
+ shuffle_val_dataloader=False):
173
+ super().__init__()
174
+ self.batch_size = batch_size
175
+ self.dataset_configs = dict()
176
+ self.num_workers = num_workers if num_workers is not None else batch_size * 2
177
+ self.use_worker_init_fn = use_worker_init_fn
178
+ if train is not None:
179
+ if "target" in train:
180
+ self.dataset_configs["train"] = train
181
+ self.train_dataloader = self._train_dataloader
182
+ else:
183
+ for ds in train:
184
+ ds_name = str([key for key in ds.keys()][0])
185
+ self.dataset_configs[ds_name] = ds
186
+ self.train_dataloader = self._train_concat_dataloader
187
+
188
+ if validation is not None:
189
+ self.dataset_configs["validation"] = validation
190
+ self.val_dataloader = partial(self._val_dataloader, shuffle=shuffle_val_dataloader)
191
+ if test is not None:
192
+ self.dataset_configs["test"] = test
193
+ self.test_dataloader = partial(self._test_dataloader, shuffle=shuffle_test_loader)
194
+ if predict is not None:
195
+ self.dataset_configs["predict"] = predict
196
+ self.predict_dataloader = self._predict_dataloader
197
+ self.wrap = wrap
198
+
199
+ def prepare_data(self):
200
+ for data_cfg in self.dataset_configs.values():
201
+ instantiate_from_config(data_cfg)
202
+
203
+ def setup(self, stage=None):
204
+ self.datasets = dict(
205
+ (k, instantiate_from_config(self.dataset_configs[k]))
206
+ for k in self.dataset_configs)
207
+ if self.wrap:
208
+ for k in self.datasets:
209
+ self.datasets[k] = WrappedDataset(self.datasets[k])
210
+
211
+ def _train_concat_dataloader(self):
212
+ is_iterable_dataset = isinstance(self.datasets['ds1'], Txt2ImgIterableBaseDataset)
213
+
214
+ if is_iterable_dataset or self.use_worker_init_fn:
215
+ init_fn = worker_init_fn
216
+ else:
217
+ init_fn = None
218
+
219
+ concat_dataset = []
220
+ for ds in self.datasets.keys():
221
+ concat_dataset.append(self.datasets[ds])
222
+
223
+ concat_dataset = ConcatDataset(concat_dataset)
224
+ sampler_train = torch.utils.data.DistributedSampler(
225
+ concat_dataset, num_replicas=dist.get_world_size(), rank=dist.get_rank(), shuffle=True
226
+ )
227
+ return DataLoader(concat_dataset, batch_size=self.batch_size, sampler=sampler_train,
228
+ num_workers=self.num_workers, worker_init_fn=init_fn, persistent_workers=True)
229
+
230
+ def _train_dataloader(self):
231
+ is_iterable_dataset = isinstance(self.datasets['train'], Txt2ImgIterableBaseDataset)
232
+ if is_iterable_dataset or self.use_worker_init_fn:
233
+ init_fn = worker_init_fn
234
+ else:
235
+ init_fn = None
236
+
237
+ sampler_train = torch.utils.data.DistributedSampler(
238
+ self.datasets["train"], num_replicas=dist.get_world_size(), rank=dist.get_rank(), shuffle=True
239
+ )
240
+ return DataLoader(self.datasets["train"], batch_size=self.batch_size, sampler=sampler_train,
241
+ num_workers=self.num_workers, worker_init_fn=init_fn, persistent_workers=True)
242
+
243
+ def _val_dataloader(self, shuffle=False):
244
+ if isinstance(self.datasets['validation'], Txt2ImgIterableBaseDataset) or self.use_worker_init_fn:
245
+ init_fn = worker_init_fn
246
+ else:
247
+ init_fn = None
248
+ return DataLoader(self.datasets["validation"],
249
+ batch_size=self.batch_size,
250
+ num_workers=self.num_workers,
251
+ worker_init_fn=init_fn,
252
+ shuffle=shuffle, persistent_workers=True)
253
+
254
+ def _test_dataloader(self, shuffle=False):
255
+ is_iterable_dataset = isinstance(self.datasets['train'], Txt2ImgIterableBaseDataset)
256
+ if is_iterable_dataset or self.use_worker_init_fn:
257
+ init_fn = worker_init_fn
258
+ else:
259
+ init_fn = None
260
+
261
+ # do not shuffle dataloader for iterable dataset
262
+ shuffle = shuffle and (not is_iterable_dataset)
263
+
264
+ return DataLoader(self.datasets["test"], batch_size=self.batch_size,
265
+ num_workers=self.num_workers, worker_init_fn=init_fn, shuffle=shuffle, persistent_workers=True)
266
+
267
+ def _predict_dataloader(self, shuffle=False):
268
+ if isinstance(self.datasets['predict'], Txt2ImgIterableBaseDataset) or self.use_worker_init_fn:
269
+ init_fn = worker_init_fn
270
+ else:
271
+ init_fn = None
272
+ return DataLoader(self.datasets["predict"], batch_size=self.batch_size,
273
+ num_workers=self.num_workers, worker_init_fn=init_fn, persistent_workers=True)
274
+
275
+
276
+ def train_one_epoch(config, model, model_ema, data_loader, val_data_loader, optimizer, epoch, lr_scheduler, scaler):
277
+ model.train()
278
+ optimizer.zero_grad()
279
+
280
+ num_steps = len(data_loader)
281
+ accumul_steps = config.trainer.accumulate_grad_batches
282
+ batch_time = AverageMeter()
283
+ loss_meter = AverageMeter()
284
+ val_loss_meter = AverageMeter()
285
+ norm_meter = AverageMeter()
286
+ loss_scale_meter = AverageMeter()
287
+ loss_scale_meter_min = AverageMeter()
288
+
289
+ start = time.time()
290
+ end = time.time()
291
+ for idx, batch in enumerate(data_loader):
292
+ batch_size = batch['edited'].shape[0]
293
+
294
+ if config.model.params.deepspeed != '':
295
+ loss, _ = model(batch, idx, accumul_steps)
296
+ model.backward(loss)
297
+
298
+ model.step()
299
+ loss_scale = optimizer.cur_scale
300
+ grad_norm = model.get_global_grad_norm()
301
+
302
+ with torch.no_grad():
303
+ if idx % config.trainer.accumulate_grad_batches == 0:
304
+ model_ema(model)
305
+
306
+ loss_number = loss.item()
307
+ else:
308
+ with amp.autocast(enabled=config.model.params.fp16):
309
+ loss, _ = model(batch, idx, accumul_steps)
310
+
311
+ if config.trainer.accumulate_grad_batches > 1:
312
+ loss = loss / config.trainer.accumulate_grad_batches
313
+ scaler.scale(loss).backward()
314
+ # loss.backward()
315
+ if config.trainer.clip_grad > 0.0:
316
+ scaler.unscale_(optimizer)
317
+ grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), config.trainer.clip_grad)
318
+ else:
319
+ grad_norm = get_grad_norm(model.parameters())
320
+ if (idx + 1) % config.trainer.accumulate_grad_batches == 0:
321
+ scaler.step(optimizer)
322
+ optimizer.zero_grad()
323
+ scaler.update()
324
+ # scaler.unscale_grads()
325
+ # optimizer.step()
326
+ # optimizer.zero_grad()
327
+ # lr_scheduler.step_update(epoch * num_steps + idx)
328
+ else:
329
+ optimizer.zero_grad()
330
+ scaler.scale(loss).backward()
331
+ if config.trainer.clip_grad > 0.0:
332
+ scaler.unscale_(optimizer)
333
+ grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), config.trainer.clip_grad)
334
+ else:
335
+ grad_norm = get_grad_norm(model.parameters())
336
+ scaler.step(optimizer)
337
+ scaler.update()
338
+ # lr_scheduler.step_update(epoch * num_steps + idx)
339
+
340
+ loss_scale = scaler.get_scale()
341
+ loss_number = loss.item() * config.trainer.accumulate_grad_batches
342
+
343
+ torch.cuda.synchronize()
344
+
345
+ loss_meter.update(loss_number, batch_size)
346
+ if grad_norm is not None:
347
+ norm_meter.update(grad_norm)
348
+ else:
349
+ norm_meter.update(0.0)
350
+
351
+ loss_scale_meter.update(loss_scale)
352
+ # loss_scale_meter.update(0.0)
353
+ batch_time.update(time.time() - end)
354
+ end = time.time()
355
+
356
+ if idx % 100 == 0:
357
+ lr = optimizer.param_groups[0]['lr']
358
+ memory_used = torch.cuda.max_memory_allocated() / (1024.0 * 1024.0)
359
+ etas = batch_time.avg * (num_steps - idx)
360
+ logger.info(
361
+ f'Train: [{epoch}][{idx}/{num_steps}]\t'
362
+ f'eta {datetime.timedelta(seconds=int(etas))} lr {lr:.6f}\t'
363
+ f'time {batch_time.val:.4f} ({batch_time.avg:.4f})\t'
364
+ f'loss {loss_meter.val:.4f} ({loss_meter.avg:.4f})\t'
365
+ f'grad_norm {norm_meter.val:.4f} ({norm_meter.avg:.4f})\t'
366
+ f'loss_scale {loss_scale_meter.val:.4f} ({loss_scale_meter.avg:.4f})\t'
367
+ f'mem {memory_used:.0f}MB')
368
+
369
+ if (epoch * num_steps + idx) % 100 == 0:
370
+ log_message = dict(
371
+ lr=optimizer.param_groups[0]['lr'],
372
+ time=batch_time.val,
373
+ epoch=epoch,
374
+ iter=idx,
375
+ loss=loss_meter.val,
376
+ grad_norm=norm_meter.val,
377
+ loss_scale=loss_scale_meter.val,
378
+ memory=torch.cuda.max_memory_allocated() / (1024.0 * 1024.0),
379
+ global_iter=epoch * num_steps + idx)
380
+
381
+ # log_message.update({'ref_img': wandb.Image(unnormalize(img[:8].cpu().float())), 'mask': wandb.Image(mask[:8].cpu().float().unsqueeze(1))})
382
+ # if x_rec is not None:
383
+ # log_message.update({'rec_img': wandb.Image(unnormalize(x_rec[:8].cpu().float()))})
384
+ wandb_log(
385
+ data=log_message,
386
+ step=epoch * num_steps + idx,
387
+ )
388
+
389
+ if idx == num_steps - 1:
390
+ with torch.no_grad():
391
+ model_ema.store(model.parameters())
392
+ model_ema.copy_to(model)
393
+ for val_idx, batch in enumerate(val_data_loader):
394
+ batch_size = batch['edited'].shape[0]
395
+
396
+ loss, _ = model(batch, -1, 1)
397
+
398
+ loss_number = loss.item()
399
+ val_loss_meter.update(loss_number, batch_size)
400
+ if val_idx % 10 == 0:
401
+ logger.info(
402
+ f'Val: [{val_idx}/{len(val_data_loader)}]\t'
403
+ f'loss {val_loss_meter.val:.4f} ({val_loss_meter.avg:.4f})\t')
404
+ if val_idx == 50:
405
+ break
406
+ model_ema.restore(model.parameters())
407
+
408
+ epoch_time = time.time() - start
409
+ logger.info(f"EPOCH {epoch} training takes {datetime.timedelta(seconds=int(epoch_time))}")
410
+
411
+
412
+ if __name__ == "__main__":
413
+
414
+ now = datetime.datetime.now().strftime("%Y-%m-%dT%H-%M-%S")
415
+
416
+ # add cwd for convenience and to make classes in this file available when
417
+ # running as `python main.py`
418
+ # (in particular `main.DataModuleFromConfig`)
419
+ sys.path.append(os.getcwd())
420
+
421
+ parser = get_parser()
422
+ opt, unknown = parser.parse_known_args()
423
+
424
+ assert opt.name
425
+ cfg_fname = os.path.split(opt.base[0])[-1]
426
+ cfg_name = os.path.splitext(cfg_fname)[0]
427
+ nowname = f"{cfg_name}_{opt.name}"
428
+ logdir = os.path.join(opt.logdir, nowname)
429
+
430
+ if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:
431
+ rank = int(os.environ["RANK"])
432
+ world_size = int(os.environ['WORLD_SIZE'])
433
+ print(f"RANK and WORLD_SIZE in environ: {rank}/{world_size}")
434
+ else:
435
+ rank = -1
436
+ world_size = -1
437
+ if opt.amd:
438
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(opt.local_rank)
439
+ torch.distributed.init_process_group(backend='gloo', init_method='env://', world_size=world_size, rank=rank)
440
+ else:
441
+ torch.cuda.set_device(opt.local_rank)
442
+ torch.distributed.init_process_group(backend='nccl', init_method='env://', world_size=world_size, rank=rank)
443
+ torch.distributed.barrier()
444
+
445
+ seed = opt.seed + dist.get_rank()
446
+ torch.manual_seed(seed)
447
+ np.random.seed(seed)
448
+ cudnn.benchmark = True
449
+
450
+ ckptdir = os.path.join(logdir, "checkpoints")
451
+ cfgdir = os.path.join(logdir, "configs")
452
+
453
+ os.makedirs(logdir, exist_ok=True)
454
+ os.makedirs(ckptdir, exist_ok=True)
455
+ os.makedirs(cfgdir, exist_ok=True)
456
+
457
+ # init and save configs
458
+ # config: the configs in the config file
459
+ configs = [OmegaConf.load(cfg) for cfg in opt.base]
460
+ cli = OmegaConf.from_dotlist(unknown)
461
+ config = OmegaConf.merge(*configs, cli)
462
+
463
+ if config.model.params.deepspeed != '':
464
+ create_ds_config(opt, config, cfgdir)
465
+
466
+ if dist.get_rank() == 0:
467
+ run = wandb.init(
468
+ id=nowname,
469
+ name=nowname,
470
+ project='readoutpose',
471
+ config=OmegaConf.to_container(config, resolve=True),
472
+ )
473
+
474
+ logger = create_logger(output_dir=logdir, dist_rank=dist.get_rank(), name=f"{nowname}")
475
+
476
+ resume_file = auto_resume_helper(config, ckptdir)
477
+ if resume_file:
478
+ resume = True
479
+ logger.info(f'resume checkpoint in {resume_file}')
480
+ else:
481
+ resume = False
482
+ logger.info(f'no checkpoint found in {ckptdir}, ignoring auto resume')
483
+
484
+ # model
485
+ model = instantiate_from_config(config.model)
486
+ model_ema = LitEma(model, decay_resume=config.model.params.get('ema_resume', 0.9999))
487
+
488
+ # data
489
+ data = instantiate_from_config(config.data)
490
+ # NOTE according to https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html
491
+ # calling these ourselves should not be necessary but it is.
492
+ # lightning still takes care of proper multiprocessing though
493
+ data.prepare_data()
494
+ data.setup()
495
+ data_loader_train = data.train_dataloader()
496
+ data_loader_val = data.val_dataloader()
497
+
498
+ print("#### Data #####")
499
+ for k in data.datasets:
500
+ print(f"{k}, {data.datasets[k].__class__.__name__}, {len(data.datasets[k])}")
501
+
502
+ # configure learning rate
503
+ bs, base_lr = config.data.params.batch_size, config.model.base_learning_rate
504
+ ngpu = dist.get_world_size()
505
+ if 'accumulate_grad_batches' in config.trainer:
506
+ accumulate_grad_batches = config.trainer.accumulate_grad_batches
507
+ else:
508
+ accumulate_grad_batches = 1
509
+ print(f"accumulate_grad_batches = {accumulate_grad_batches}")
510
+
511
+ if opt.scale_lr:
512
+ model.learning_rate = accumulate_grad_batches * ngpu * bs * base_lr
513
+ print(
514
+ "Setting learning rate to {:.2e} = {} (accumulate_grad_batches) * {} (num_gpus) * {} (batchsize) * {:.2e} (base_lr)".format(
515
+ model.learning_rate, accumulate_grad_batches, ngpu, bs, base_lr))
516
+ else:
517
+ model.learning_rate = base_lr
518
+ print("++++ NOT USING LR SCALING ++++")
519
+ print(f"Setting learning rate to {model.learning_rate:.2e}")
520
+
521
+ if not opt.amd:
522
+ model.cuda()
523
+
524
+ if config.model.params.fp16 and config.model.params.deepspeed == '':
525
+ scaler = amp.GradScaler()
526
+ param_groups = model.parameters()
527
+ else:
528
+ scaler = None
529
+ param_groups = model.parameters()
530
+
531
+ if config.model.params.deepspeed != '':
532
+ model, optimizer, _, _ = deepspeed.initialize(
533
+ args=config,
534
+ model=model,
535
+ model_parameters=param_groups,
536
+ dist_init_required=False,
537
+ )
538
+ for name, param in model.named_parameters():
539
+ param.global_name = name
540
+ model_without_ddp = model
541
+ lr_scheduler = None
542
+ model_ema = model_ema.to(next(model.parameters()).device)
543
+ else:
544
+ optimizer, lr_scheduler = model.configure_optimizers()
545
+ model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[opt.local_rank], broadcast_buffers=False)
546
+ model_without_ddp = model.module
547
+ # print(optimizer.param_groups[1])
548
+ if opt.resume != '':
549
+ resume_file = opt.resume
550
+ if resume_file:
551
+ _, start_epoch = load_checkpoint(resume_file, config, model_without_ddp, model_ema, optimizer, lr_scheduler, scaler, logger)
552
+ else:
553
+ start_epoch = 0
554
+
555
+ logger.info("Start training")
556
+ start_time = time.time()
557
+
558
+ for epoch in range(start_epoch, config.trainer.max_epochs):
559
+ data_loader_train.sampler.set_epoch(epoch)
560
+ train_one_epoch(config, model, model_ema, data_loader_train, data_loader_val, optimizer, epoch, lr_scheduler, scaler)
561
+ if epoch % config.trainer.save_freq == 0:
562
+ save_checkpoint(ckptdir, config, epoch, model_without_ddp, model_ema, 0., optimizer, lr_scheduler, scaler, logger)
563
+
564
+ total_time = time.time() - start_time
565
+ total_time_str = str(datetime.timedelta(seconds=int(total_time)))
566
+ logger.info('Training time {}'.format(total_time_str))
scripts/convert_ckpt.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft
3
+ # Licensed under the MIT License.
4
+ # Written by Zigang Geng (zigang@mail.ustc.edu.cn)
5
+ # ------------------------------------------------------------------------------
6
+
7
+ from __future__ import annotations
8
+
9
+ import sys
10
+ import torch
11
+ from argparse import ArgumentParser
12
+ from omegaconf import OmegaConf
13
+
14
+ sys.path.append("./stable_diffusion")
15
+
16
+ from stable_diffusion.ldm.util import instantiate_from_config
17
+
18
+
19
+ if __name__ == "__main__":
20
+ parser = ArgumentParser()
21
+ parser.add_argument("--config", default="configs/instruct_diffusion.yaml", type=str)
22
+ parser.add_argument("--ema-ckpt", default="logs/instruct_diffusion/checkpoints/ckpt_epoch_200/state.pth", type=str)
23
+ parser.add_argument("--vae-ckpt", default="stable_diffusion/models/ldm/stable-diffusion-v1/v1-5-pruned-emaonly.ckpt", type=str)
24
+ parser.add_argument("--out-ckpt", default="checkpoints/v1-5-pruned-emaonly-adaption-task.ckpt", type=str)
25
+
26
+ args = parser.parse_args()
27
+ config = OmegaConf.load(args.config)
28
+
29
+ model = instantiate_from_config(config.model)
30
+
31
+ ema_ckpt = torch.load(args.ema_ckpt, map_location="cpu")
32
+ all_keys = [key for key, value in model.named_parameters()]
33
+ all_keys_rmv = [key.replace('.','') for key in all_keys]
34
+ new_ema_ckpt = {}
35
+ for k, v in ema_ckpt['model_ema'].items():
36
+ try:
37
+ k_index = all_keys_rmv.index(k)
38
+ new_ema_ckpt[all_keys[k_index]] = v
39
+ except:
40
+ print(k+' is not in the list.')
41
+
42
+ vae_ckpt = torch.load(args.vae_ckpt, map_location="cpu")
43
+ for k, v in vae_ckpt['state_dict'].items():
44
+ if k not in new_ema_ckpt and k in all_keys:
45
+ new_ema_ckpt[k] = v
46
+
47
+ checkpoint = {'state_dict': new_ema_ckpt}
48
+ with open(args.out_ckpt, 'wb') as f:
49
+ torch.save(checkpoint, f)
50
+ f.flush()
51
+ print('Converted successfully, the new checkpoint has been saved to ' + str(args.out_ckpt))
scripts/download_pretrained_sd.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
4
+
5
+ mkdir -p $SCRIPT_DIR/../stable_diffusion/models/ldm/stable-diffusion-v1
6
+ curl -L https://huggingface.co/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.ckpt -o $SCRIPT_DIR/../stable_diffusion/models/ldm/stable-diffusion-v1/v1-5-pruned-emaonly.ckpt
7
+ curl -L https://huggingface.co/stabilityai/sd-vae-ft-mse-original/resolve/main/vae-ft-mse-840000-ema-pruned.ckpt -o $SCRIPT_DIR/../stable_diffusion/models/ldm/stable-diffusion-v1/vae-ft-mse-840000-ema-pruned.ckpt
scripts/inference_example.sh ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Example: Image Editing
2
+ python edit_cli.py --input figure/animals.png --edit "Transform it to van Gogh, starry night style." --resolution 768 --steps 100 --config configs/instruct_diffusion.yaml --ckpt checkpoints/v1-5-pruned-emaonly-adaption-task.ckpt --cfg-text 5.0 --cfg-image 1.25 --outdir logs/ --seed 93151
3
+ python edit_cli.py --input figure/animals.png --edit "Help the elephant wear a crown and maintain the appearance of others." --resolution 512 --steps 100 --config configs/instruct_diffusion.yaml --ckpt checkpoints/v1-5-pruned-emaonly-adaption-task.ckpt --cfg-text 5.0 --cfg-image 1.25 --outdir logs/ --seed 51557
4
+
5
+ # Example: Segmentation More prompts can be found in the dataset/prompts/prompt_seg.txt
6
+ python edit_cli.py --input figure/mirrorcat.jpg --edit "Mark the pixels of the cat in the mirror to blue and leave the rest unchanged." --resolution 512 --steps 100 --config configs/instruct_diffusion.yaml --ckpt checkpoints/v1-5-pruned-emaonly-adaption-task.ckpt --cfg-text 7.5 --cfg-image 1.5 --outdir logs/ --seed 94746
7
+
8
+ # Example: Keypoint Detection More prompts can be found in the dataset/prompts/prompt_pose.txt
9
+ python edit_cli.py --input figure/people.jpg --edit "Use yellow to encircle the left knee of the people on the far left and draw a blue circle over the nose of the tallest people." --resolution 512 --steps 100 --config configs/instruct_diffusion.yaml --ckpt checkpoints/v1-5-pruned-emaonly-adaption-task.ckpt --cfg-text 6.0 --cfg-image 0.5 --outdir logs/ --seed 27775
10
+
11
+ # Example: Watermark Removal More prompts can be found in the dataset/prompts/prompt_dewatermark.txt
12
+ python edit_cli.py --input figure/watermark.png --edit "Remove watermark from this picture." --resolution 512 --steps 100 --config configs/instruct_diffusion.yaml --ckpt checkpoints/v1-5-pruned-emaonly-adaption-task.ckpt --cfg-text 1.0 --cfg-image 1.0 --outdir logs/ --seed 54763
scripts/run_multinode.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ EXP=$1
2
+ NAME=$2
3
+ GPUMUM=$3
4
+ set -x
5
+
6
+ python -m torch.distributed.launch --nnodes=${GPUMUM} --nproc_per_node=8 --node_rank=$NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT main.py --name ${NAME} --base configs/${EXP}.yaml --train --logdir /mnt/data/readout_torch_output/
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/a-painting-of-a-fire.png ADDED
stable_diffusion/assets/a-photograph-of-a-fire.png ADDED
stable_diffusion/assets/a-shirt-with-a-fire-printed-on-it.png ADDED
stable_diffusion/assets/a-shirt-with-the-inscription-'fire'.png ADDED
stable_diffusion/assets/a-watercolor-painting-of-a-fire.png ADDED
stable_diffusion/assets/birdhouse.png ADDED
stable_diffusion/assets/fire.png ADDED
stable_diffusion/assets/inpainting.png ADDED
stable_diffusion/assets/modelfigure.png ADDED
stable_diffusion/assets/rdm-preview.jpg ADDED
stable_diffusion/assets/reconstruction1.png ADDED
stable_diffusion/assets/reconstruction2.png ADDED
stable_diffusion/assets/results.gif.REMOVED.git-id ADDED
@@ -0,0 +1 @@
 
 
1
+ 82b6590e670a32196093cc6333ea19e6547d07de