Spaces:
Running
on
Zero
Running
on
Zero
burningdust
commited on
Commit
·
d72c37e
0
Parent(s):
Initial commit
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +2 -0
- .gitignore +11 -0
- README.md +11 -0
- app.py +189 -0
- examples/001d15cacc774fce2b1d119180b43010.png +3 -0
- examples/1aa5fe395096f6e6f146eae2e195589a.png +3 -0
- examples/2491ca9b6488b09ba4e4b1b3cfa2d052.png +3 -0
- examples/43c73ce43d7a192932db0dda073016ca.png +3 -0
- examples/AdobeStock_5889655.jpeg +3 -0
- examples/AdobeStock_604103617.jpeg +3 -0
- examples/DSCF5565_squared.jpg +3 -0
- examples/Screenshot 2024-03-28 232607 pad.png +3 -0
- examples/ac0e4e91f8c2006c74b7e95c9611a8c3.png +3 -0
- examples/cbaf0b51beba2e66ca2833f6225646c1.png +3 -0
- examples/e607ace61c3fd81653b2f05d79ec1e42.png +3 -0
- examples/img_18.png +3 -0
- examples/sora_flowers.png +3 -0
- inference.py +245 -0
- matfusion.py +380 -0
- models/ldm/__init__.py +0 -0
- models/ldm/data/__init__.py +0 -0
- models/ldm/data/base.py +40 -0
- models/ldm/data/coco.py +253 -0
- models/ldm/data/decoder.py +497 -0
- models/ldm/data/dummy.py +34 -0
- models/ldm/data/imagenet.py +394 -0
- models/ldm/data/inpainting/__init__.py +0 -0
- models/ldm/data/inpainting/synthetic_mask.py +166 -0
- models/ldm/data/laion.py +537 -0
- models/ldm/data/legacy.py +196 -0
- models/ldm/data/lsun.py +92 -0
- models/ldm/data/nerf_like.py +165 -0
- models/ldm/data/objaverse_rendered.py +59 -0
- models/ldm/data/simple.py +567 -0
- models/ldm/extras.py +77 -0
- models/ldm/guidance.py +96 -0
- models/ldm/lr_scheduler.py +98 -0
- models/ldm/models/autoencoder.py +443 -0
- models/ldm/models/diffusion/__init__.py +0 -0
- models/ldm/models/diffusion/classifier.py +267 -0
- models/ldm/models/diffusion/ddim.py +324 -0
- models/ldm/models/diffusion/ddpm.py +2024 -0
- models/ldm/models/diffusion/plms.py +259 -0
- models/ldm/models/diffusion/sampling_util.py +50 -0
- models/ldm/modules/attention.py +278 -0
- models/ldm/modules/diffusionmodules/__init__.py +0 -0
- models/ldm/modules/diffusionmodules/model.py +835 -0
- models/ldm/modules/diffusionmodules/openaimodel.py +998 -0
- models/ldm/modules/diffusionmodules/util.py +267 -0
- models/ldm/modules/distributions/__init__.py +0 -0
.gitattributes
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
weights/** filter=lfs diff=lfs merge=lfs -text
|
2 |
+
examples/** filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
log/
|
2 |
+
out/
|
3 |
+
|
4 |
+
log
|
5 |
+
out
|
6 |
+
|
7 |
+
flagged
|
8 |
+
Synthetic4Relight
|
9 |
+
**/__pycache__/
|
10 |
+
vis_*/
|
11 |
+
src/
|
README.md
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: IntrinsicAnything
|
3 |
+
emoji: 🐸
|
4 |
+
colorFrom: green
|
5 |
+
colorTo: indigo
|
6 |
+
sdk: gradio
|
7 |
+
python_version: 3.10.13
|
8 |
+
sdk_version: 4.16.0
|
9 |
+
app_file: app.py
|
10 |
+
pinned: false
|
11 |
+
---
|
app.py
ADDED
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import torch
|
3 |
+
from PIL import Image
|
4 |
+
from torchvision import transforms
|
5 |
+
# from diffusers import StableDiffusionImageVariationPipeline
|
6 |
+
from inference import InferenceModel
|
7 |
+
from pytorch_lightning import seed_everything
|
8 |
+
import numpy as np
|
9 |
+
import os
|
10 |
+
import rembg
|
11 |
+
import spaces
|
12 |
+
import sys
|
13 |
+
from loguru import logger
|
14 |
+
|
15 |
+
_SAMPLE_TAB_ID_ = 0
|
16 |
+
_HIGHRES_TAB_ID_ = 1
|
17 |
+
_FOREGROUND_TAB_ID_ = 2
|
18 |
+
|
19 |
+
|
20 |
+
def set_loggers(level):
|
21 |
+
logger.remove()
|
22 |
+
logger.add(sys.stderr, level=level)
|
23 |
+
|
24 |
+
def on_guide_select(evt: gr.SelectData):
|
25 |
+
logger.debug(f"You selected {evt.value} at {evt.index} from {evt.target}")
|
26 |
+
return [evt.value["image"]['path'], f"Sample {evt.index}"]
|
27 |
+
|
28 |
+
def on_input_select(evt: gr.SelectData):
|
29 |
+
logger.debug(f"You selected {evt.value} at {evt.index} from {evt.target}")
|
30 |
+
return evt.value["image"]['path']
|
31 |
+
|
32 |
+
@spaces.GPU(duration=120)
|
33 |
+
def sample_fine(
|
34 |
+
input_im,
|
35 |
+
domain="Albedo",
|
36 |
+
require_mask=False,
|
37 |
+
steps=25,
|
38 |
+
n_samples=4,
|
39 |
+
seed=0,
|
40 |
+
guid_img=None,
|
41 |
+
vert_split=2,
|
42 |
+
hor_split=2,
|
43 |
+
overlaps=2,
|
44 |
+
guidance_scale=2,
|
45 |
+
):
|
46 |
+
if require_mask:
|
47 |
+
input_im = remove_bg(input_im)
|
48 |
+
|
49 |
+
seed_everything(int(seed))
|
50 |
+
model = model_dict[domain]
|
51 |
+
inp = tform(input_im).to(device).permute(1,2,0)
|
52 |
+
guid_img = tform(guid_img).to(device).permute(1,2,0)
|
53 |
+
images = model.generation((vert_split, hor_split), overlaps, guid_img[..., :3], inp[..., :3], inp[..., 3:], dps_scale=guidance_scale, uc_score=1.0, ddim_steps=steps, batch_size=1, n_samples=1)
|
54 |
+
images["guid_iamges"] = [(guid_img.detach().cpu().numpy() * 255).astype(np.uint8)]
|
55 |
+
output = images["out_images"][0]
|
56 |
+
return [[(output, "High-res")], gr.Tabs(selected=_HIGHRES_TAB_ID_)]
|
57 |
+
|
58 |
+
def remove_bg(input_im):
|
59 |
+
output = rembg.remove(input_im, session=model_dict["remove_bg"])
|
60 |
+
return output
|
61 |
+
|
62 |
+
@spaces.GPU()
|
63 |
+
def sampling(input_im, domain="Albedo", require_mask=False,
|
64 |
+
steps=25, n_samples=4, seed=0):
|
65 |
+
seed_everything(int(seed))
|
66 |
+
model = model_dict[domain]
|
67 |
+
if require_mask:
|
68 |
+
input_im = remove_bg(input_im)
|
69 |
+
|
70 |
+
inp = tform(input_im).to(device).permute(1,2,0)
|
71 |
+
|
72 |
+
images = model.generation((1, 1), 1, None, inp[..., :3], inp[..., 3:], dps_scale=0, uc_score=1, ddim_steps=steps, batch_size=1, n_samples=n_samples)
|
73 |
+
|
74 |
+
output = [[(images["input_image"][0], "Foreground Object"), (images["input_maskes"][0], "Foreground Maks")],
|
75 |
+
[(img,f"Sample {idx}") for idx, img in enumerate(images["out_images"])],
|
76 |
+
gr.Tabs(selected=_SAMPLE_TAB_ID_),
|
77 |
+
]
|
78 |
+
return output
|
79 |
+
|
80 |
+
title = "IntrinsicAnything: Learning Diffusion Priors for Inverse Rendering Under Unknown Illumination"
|
81 |
+
description = \
|
82 |
+
"""
|
83 |
+
#### Generate intrinsic images (Albedo, Specular Shading) from a single image.
|
84 |
+
|
85 |
+
##### Tips
|
86 |
+
- You can check the "Auto Mask" box if the input image requires a foreground mask. Or supply your mask with RGBA input.
|
87 |
+
- You can optionally generate a high-resolution sample if the input image is of high resolution. We split the original image into `Vertical Splits` by `Horizontal Splits` patches with some `Overlaps` in between. Due to computation constraints for the online demo, we recommend `Vertical Splits` x `Horizontal Splits` to be no more than 6 and to set 2 for `Overlaps`. The denoising steps should at least be set to 80 for high resolution samples.
|
88 |
+
|
89 |
+
"""
|
90 |
+
|
91 |
+
set_loggers("INFO")
|
92 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
93 |
+
logger.info(f"Loading Models...")
|
94 |
+
model_dict = {
|
95 |
+
"Albedo": InferenceModel(ckpt_path="weights/albedo",
|
96 |
+
use_ddim=True,
|
97 |
+
gpu_id=0),
|
98 |
+
"Specular": InferenceModel(ckpt_path="weights/specular",
|
99 |
+
use_ddim=True,
|
100 |
+
gpu_id=0),
|
101 |
+
"remove_bg": rembg.new_session(),
|
102 |
+
}
|
103 |
+
logger.info(f"All models Loaded!")
|
104 |
+
|
105 |
+
tform = transforms.Compose([
|
106 |
+
transforms.ToTensor()
|
107 |
+
])
|
108 |
+
|
109 |
+
examples_dir = "examples"
|
110 |
+
examples = [[os.path.join(examples_dir, img_name)] for img_name in os.listdir(examples_dir)]
|
111 |
+
|
112 |
+
|
113 |
+
# theme definition
|
114 |
+
theme = gr.Theme.from_hub("NoCrypt/miku")
|
115 |
+
|
116 |
+
theme.body_background_fill = "#FFFFFF "
|
117 |
+
theme.body_background_fill_dark = "#000000"
|
118 |
+
|
119 |
+
|
120 |
+
demo = gr.Blocks(title=title, theme=theme)
|
121 |
+
with demo:
|
122 |
+
with gr.Row():
|
123 |
+
with gr.Column(scale=1):
|
124 |
+
gr.Markdown('# ' + title)
|
125 |
+
gr.Markdown(description)
|
126 |
+
with gr.Column():
|
127 |
+
with gr.Row():
|
128 |
+
with gr.Column(scale=0.8):
|
129 |
+
image_input = [gr.Image(image_mode='RGBA', height=256)]
|
130 |
+
with gr.Column():
|
131 |
+
with gr.Tabs():
|
132 |
+
with gr.TabItem("Options"):
|
133 |
+
with gr.Column():
|
134 |
+
with gr.Row():
|
135 |
+
domain_box = gr.Radio([("Albedo", "Albedo"),("Specular", "Specular")],
|
136 |
+
value="Albedo",
|
137 |
+
label="Type")
|
138 |
+
with gr.Column():
|
139 |
+
gr.Markdown("### Automatic foreground segmentation")
|
140 |
+
mask_box = gr.Checkbox(False, label="Auto Mask")
|
141 |
+
options_tab = [
|
142 |
+
domain_box,
|
143 |
+
mask_box,
|
144 |
+
gr.Slider(5, 200, value=50, step=5, label="Denoising Steps (The larger the better results)"),
|
145 |
+
gr.Slider(1, 10, value=2, step=1, label="Number of Samples"),
|
146 |
+
gr.Number(75424, label="Seed", precision=0),
|
147 |
+
]
|
148 |
+
with gr.TabItem("Advanced (High-res)"):
|
149 |
+
with gr.Column():
|
150 |
+
guiding_img = gr.Image(image_mode='RGBA', label="Guiding Image", interactive=False, height=256, visible=False)
|
151 |
+
sample_idx = gr.Textbox(placeholder="Select one from the generate low-res samples", lines=1, interactive=False, label="Guiding Image")
|
152 |
+
options_advanced_tab = [
|
153 |
+
# high resolution options
|
154 |
+
guiding_img,
|
155 |
+
gr.Slider(1, 4, value=2, step=1, label="Vertical Splits"),
|
156 |
+
gr.Slider(1, 4, value=2, step=1, label="Horizontal Splits"),
|
157 |
+
gr.Slider(1, 5, value=2, step=1, label="Overlaps"),
|
158 |
+
gr.Slider(0, 5, value=3, step=1, label="Guidance Scale"),]
|
159 |
+
with gr.Column(scale=1.0):
|
160 |
+
with gr.Tabs() as res_tabs:
|
161 |
+
with gr.TabItem("Generated Samples", id=_SAMPLE_TAB_ID_):
|
162 |
+
image_output = gr.Gallery(label="Generated Samples", object_fit="contain", columns=[2], rows=[2],height=512, selected_index=0)
|
163 |
+
with gr.TabItem("High Resolution Sample", id=_HIGHRES_TAB_ID_):
|
164 |
+
image_output_high = gr.Gallery(label="High Resolution Sample", object_fit="contain", columns=[1], rows=[1],height=512, selected_index=0)
|
165 |
+
with gr.TabItem("Foreground Object", id=_FOREGROUND_TAB_ID_):
|
166 |
+
forground_output = gr.Gallery(label="Foreground Object", object_fit="contain", columns=[2], rows=[1],height=512, selected_index=0)
|
167 |
+
with gr.Row():
|
168 |
+
generate_button = gr.Button("Generate")
|
169 |
+
generate_button_fine = gr.Button("Generate High-Res")
|
170 |
+
|
171 |
+
examples_gr = gr.Examples(examples=examples, inputs=image_input,
|
172 |
+
cache_examples=False, examples_per_page=30,
|
173 |
+
label='Examples (Click one to start!)')
|
174 |
+
|
175 |
+
with gr.Row():
|
176 |
+
pass
|
177 |
+
# forground_output = gr.Gallery(label="Inputs", preview=False, columns=[2], rows=[1],height=512, selected_index=0)
|
178 |
+
# image_output = gr.Gallery(label="Generated Samples", object_fit="cover", columns=[1], rows=[6],height=512, selected_index=0)
|
179 |
+
# image_output_high = gr.Gallery(label="High Resolution Sample", object_fit="cover", columns=[1], rows=[1],height=512, selected_index=0)
|
180 |
+
|
181 |
+
generate_button.click(sampling, inputs=image_input+options_tab,
|
182 |
+
outputs=[forground_output, image_output, res_tabs])
|
183 |
+
generate_button_fine.click(sample_fine,
|
184 |
+
inputs=image_input+options_tab+options_advanced_tab,
|
185 |
+
outputs=[image_output_high, res_tabs])
|
186 |
+
image_output.select(on_guide_select, None, [guiding_img, sample_idx])
|
187 |
+
|
188 |
+
logger.info(f"Demo Initilized, Starting...")
|
189 |
+
demo.queue().launch()
|
examples/001d15cacc774fce2b1d119180b43010.png
ADDED
![]() |
Git LFS Details
|
examples/1aa5fe395096f6e6f146eae2e195589a.png
ADDED
![]() |
Git LFS Details
|
examples/2491ca9b6488b09ba4e4b1b3cfa2d052.png
ADDED
![]() |
Git LFS Details
|
examples/43c73ce43d7a192932db0dda073016ca.png
ADDED
![]() |
Git LFS Details
|
examples/AdobeStock_5889655.jpeg
ADDED
![]() |
Git LFS Details
|
examples/AdobeStock_604103617.jpeg
ADDED
![]() |
Git LFS Details
|
examples/DSCF5565_squared.jpg
ADDED
![]() |
Git LFS Details
|
examples/Screenshot 2024-03-28 232607 pad.png
ADDED
![]() |
Git LFS Details
|
examples/ac0e4e91f8c2006c74b7e95c9611a8c3.png
ADDED
![]() |
Git LFS Details
|
examples/cbaf0b51beba2e66ca2833f6225646c1.png
ADDED
![]() |
Git LFS Details
|
examples/e607ace61c3fd81653b2f05d79ec1e42.png
ADDED
![]() |
Git LFS Details
|
examples/img_18.png
ADDED
![]() |
Git LFS Details
|
examples/sora_flowers.png
ADDED
![]() |
Git LFS Details
|
inference.py
ADDED
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import imageio
|
3 |
+
import numpy as np
|
4 |
+
|
5 |
+
import glob
|
6 |
+
import sys
|
7 |
+
from typing import Any
|
8 |
+
sys.path.insert(1, '.')
|
9 |
+
|
10 |
+
import argparse
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from PIL import Image
|
13 |
+
import torch
|
14 |
+
from operators import GaussialBlurOperator
|
15 |
+
from utils import get_rank
|
16 |
+
from torchvision.ops import masks_to_boxes
|
17 |
+
from matfusion import MateralDiffusion
|
18 |
+
from loguru import logger
|
19 |
+
|
20 |
+
__MAX_BATCH__ = 4 # 4 for A10
|
21 |
+
|
22 |
+
def init_model(ckpt_path, ddim, gpu_id):
|
23 |
+
# find config
|
24 |
+
configs = os.listdir(f'{ckpt_path}/configs')
|
25 |
+
model_config = [config for config in configs if "project.yaml" in config][0]
|
26 |
+
sds_loss_class = MateralDiffusion(device=gpu_id, fp16=True,
|
27 |
+
config=f'{ckpt_path}/configs/{model_config}',
|
28 |
+
ckpt=f'{ckpt_path}/checkpoints/last.ckpt', vram_O=False,
|
29 |
+
t_range=[0.001, 0.02], opt=None, use_ddim=ddim)
|
30 |
+
return sds_loss_class
|
31 |
+
|
32 |
+
def images_spliter(image, seg_h, seg_w, padding_pixel, padding_val, overlaps=1):
|
33 |
+
# split the input images along height and weidth by
|
34 |
+
# return a list of images
|
35 |
+
h, w, c = image.shape
|
36 |
+
h = h - (h%(seg_h*overlaps))
|
37 |
+
w = w - (w%(seg_w*overlaps))
|
38 |
+
|
39 |
+
h_crop = h // seg_h
|
40 |
+
w_crop = w // seg_w
|
41 |
+
images = []
|
42 |
+
positions = []
|
43 |
+
img_padded = torch.zeros(h+padding_pixel*2, w+padding_pixel*2, 3, device=image.device) + padding_val
|
44 |
+
img_padded[padding_pixel:h+padding_pixel, padding_pixel:w+padding_pixel, :] = image[:h, :w]
|
45 |
+
|
46 |
+
# overlapped sampling
|
47 |
+
seg_h = np.round((h - h_crop) / h_crop * overlaps).astype(int) + 1
|
48 |
+
seg_w = np.round((w - w_crop) / w_crop * overlaps).astype(int) + 1
|
49 |
+
|
50 |
+
h_step = np.round(h_crop / overlaps).astype(int)
|
51 |
+
w_step = np.round(w_crop / overlaps).astype(int)
|
52 |
+
# print(f"h_step: {h_step}, seg_h: {seg_h}, w_step: {w_step}, seg_w: {seg_w}, img_padded: {img_padded.shape}, image[:h, :w]: {image[:h, :w].shape}")
|
53 |
+
|
54 |
+
for ind_i in range(0,seg_h):
|
55 |
+
i = ind_i * h_step
|
56 |
+
for ind_j in range(0,seg_w):
|
57 |
+
j = ind_j * w_step
|
58 |
+
img_ = img_padded[i:i+h_crop+padding_pixel*2, j:j+w_crop+padding_pixel*2, :]
|
59 |
+
images.append(img_)
|
60 |
+
positions.append(torch.FloatTensor([i-padding_pixel, j-padding_pixel]).reshape(2))
|
61 |
+
return torch.stack(images, dim=0), torch.stack(positions, dim=0), seg_h, seg_w
|
62 |
+
|
63 |
+
class InferenceModel():
|
64 |
+
def __init__(self, ckpt_path, use_ddim, gpu_id=0):
|
65 |
+
self.model = init_model(ckpt_path, use_ddim, gpu_id=gpu_id)
|
66 |
+
self.gpu_id = gpu_id
|
67 |
+
self.split_hw = [1,1]
|
68 |
+
|
69 |
+
self.padding = 0
|
70 |
+
self.padding_crop = 0
|
71 |
+
|
72 |
+
self.results_list = None
|
73 |
+
self.results_output_list = []
|
74 |
+
self.image_sizes_list = []
|
75 |
+
|
76 |
+
def parse_item(self, img_ori, mask_img_ori, guid_images):
|
77 |
+
# if mask_img_ori is None:
|
78 |
+
# mask_img_ori = read_img(input_name, read_alpha=True)
|
79 |
+
# # ensure background is white, same as training data
|
80 |
+
# img_ori[~(mask_img_ori[..., 0] > 0.5)] = 1
|
81 |
+
img_ori[~(mask_img_ori[..., 0] > 0.5)] = 1
|
82 |
+
use_true_mask = (self.split_hw[0] * self.split_hw[1]) <= 1
|
83 |
+
self.ori_hw = list(img_ori.shape)
|
84 |
+
|
85 |
+
# mask cropping
|
86 |
+
min_max_uv = masks_to_boxes(mask_img_ori[None, ..., -1] > 0.5).long()
|
87 |
+
self.min_uv, self.max_uv = min_max_uv[0, ..., [1,0]], min_max_uv[0, ..., [3,2]]+1
|
88 |
+
# print(self.min_uv, self.max_uv)
|
89 |
+
|
90 |
+
mask_img = mask_img_ori[self.min_uv[0]:self.max_uv[0], self.min_uv[1]:self.max_uv[1]]
|
91 |
+
img = img_ori[self.min_uv[0]:self.max_uv[0], self.min_uv[1]:self.max_uv[1]]
|
92 |
+
|
93 |
+
image_size = list(img.shape)
|
94 |
+
if not use_true_mask:
|
95 |
+
# for cropping boarder
|
96 |
+
self.max_uv[0] = self.max_uv[0] - ((self.max_uv[0]-self.min_uv[0])%(self.split_hw[0]*self.split_overlap))
|
97 |
+
self.max_uv[1] = self.max_uv[1] - ((self.max_uv[1]-self.min_uv[1])%(self.split_hw[1]*self.split_overlap))
|
98 |
+
|
99 |
+
mask_img = mask_img_ori[self.min_uv[0]:self.max_uv[0], self.min_uv[1]:self.max_uv[1]]
|
100 |
+
img = img_ori[self.min_uv[0]:self.max_uv[0], self.min_uv[1]:self.max_uv[1]]
|
101 |
+
|
102 |
+
image_size = list(img.shape)
|
103 |
+
|
104 |
+
|
105 |
+
if not use_true_mask:
|
106 |
+
mask_img = torch.ones_like(mask_img)
|
107 |
+
mask_img, _ = images_spliter(mask_img[..., [0, 0, 0]], self.split_hw[0], self.split_hw[1], self.padding, not use_true_mask, self.split_overlap)[:2]
|
108 |
+
|
109 |
+
img, position_indexes, seg_h, seg_w = images_spliter(img, self.split_hw[0], self.split_hw[1], self.padding, 1, self.split_overlap)
|
110 |
+
self.split_hw_overlapped = [seg_h, seg_w]
|
111 |
+
|
112 |
+
logger.info(f"Spliting Size: {image_size}, splits: {self.split_hw}, Overlapped: {self.split_hw_overlapped}")
|
113 |
+
|
114 |
+
if guid_images is None:
|
115 |
+
guid_images = torch.zeros_like(img)
|
116 |
+
else:
|
117 |
+
guid_images = guid_images[self.min_uv[0]:self.max_uv[0], self.min_uv[1]:self.max_uv[1]]
|
118 |
+
guid_images, _ = images_spliter(guid_images, self.split_hw[0], self.split_hw[1], self.padding, 1, self.split_overlap)[:2]
|
119 |
+
|
120 |
+
return guid_images, img, mask_img[..., :1], image_size, position_indexes
|
121 |
+
|
122 |
+
def prepare_batch(self, guid_img, img_ori, mask_img_ori, batch_size):
|
123 |
+
input_img = []
|
124 |
+
cond_img = []
|
125 |
+
mask_img = []
|
126 |
+
image_size = []
|
127 |
+
position_indexes = []
|
128 |
+
|
129 |
+
for i in range(batch_size):
|
130 |
+
_input_img, _cond_img, _mask_img, _image_size, _position_indexes = \
|
131 |
+
self.parse_item(img_ori, mask_img_ori, guid_img)
|
132 |
+
input_img.append(_input_img)
|
133 |
+
cond_img.append(_cond_img)
|
134 |
+
mask_img.append(_mask_img)
|
135 |
+
position_indexes.append(_position_indexes)
|
136 |
+
|
137 |
+
image_size += [_image_size] * _input_img.shape[0]
|
138 |
+
|
139 |
+
input_img = torch.cat(input_img, dim=0).to(self.gpu_id)
|
140 |
+
cond_img = torch.cat(cond_img, dim=0).to(self.gpu_id)
|
141 |
+
mask_img = torch.cat(mask_img, dim=0).to(self.gpu_id)
|
142 |
+
position_indexes = torch.cat(position_indexes, dim=0).to(self.gpu_id)
|
143 |
+
|
144 |
+
return input_img, cond_img, mask_img, image_size, position_indexes
|
145 |
+
|
146 |
+
|
147 |
+
def assemble_results(self, img_out, img_hw=None, position_index=None, default_val=1):
|
148 |
+
results_img = np.zeros((img_hw[0], img_hw[1], 3))
|
149 |
+
weight_img = np.zeros((img_hw[0], img_hw[1], 3)) + 1e-5
|
150 |
+
|
151 |
+
for i in range(position_index.shape[0]):
|
152 |
+
# crop out boarder
|
153 |
+
crop_h, crop_w = img_out[i].shape[:2]
|
154 |
+
pathed_img = img_out[i][self.padding_crop:crop_h-self.padding_crop, self.padding_crop:crop_w-self.padding_crop]
|
155 |
+
position_index[i] += self.padding_crop
|
156 |
+
crop_h, crop_w = pathed_img.shape[:2]
|
157 |
+
crop_x, crop_y = max(position_index[i][0], 0), max(position_index[i][1], 0)
|
158 |
+
shape_max = results_img[crop_x:crop_x+crop_h, crop_y:crop_y+crop_w].shape[:2]
|
159 |
+
start_crop_x, start_crop_y = abs(min(position_index[i][0], 0)), abs(min(position_index[i][1], 0))
|
160 |
+
# print(pathed_img[start_crop_x:shape_max[0], start_crop_y:shape_max[1]].shape, crop_x, crop_y, position_index[i])
|
161 |
+
results_img[crop_x:crop_x+shape_max[0]-start_crop_x, crop_y:crop_y+shape_max[1]-start_crop_y] += pathed_img[start_crop_x:shape_max[0], start_crop_y:shape_max[1]]
|
162 |
+
weight_img[crop_x:crop_x+crop_h-start_crop_x, crop_y:crop_y+shape_max[1]-start_crop_y] += 1
|
163 |
+
img_out = results_img / weight_img
|
164 |
+
img_out[weight_img[:,:,0] < 1] = 255
|
165 |
+
# print(img_out.shape, weight_img.shape, np.unique(weight_img), pathed_img.dtype)
|
166 |
+
img_out_ = (np.zeros((self.ori_hw[0], self.ori_hw[1], 3)) + default_val) * 255
|
167 |
+
img_out_[self.min_uv[0]:self.max_uv[0], self.min_uv[1]:self.max_uv[1]] = img_out
|
168 |
+
img_out = img_out_
|
169 |
+
return img_out
|
170 |
+
|
171 |
+
def write_batch_img(self, imgs, image_sizes, position_indexes):
|
172 |
+
cropped_batch = self.split_hw_overlapped[0] * self.split_hw_overlapped[1]
|
173 |
+
if self.results_list is None or self.results_list.shape[0] == 0:
|
174 |
+
self.results_list = imgs
|
175 |
+
self.position_indexes = position_indexes
|
176 |
+
else:
|
177 |
+
self.results_list = torch.cat([self.results_list, imgs], dim=0)
|
178 |
+
self.position_indexes = torch.cat([self.position_indexes, position_indexes], dim=0)
|
179 |
+
self.image_sizes_list += image_sizes
|
180 |
+
|
181 |
+
valid_len = self.results_list.shape[0] - (self.results_list.shape[0] % cropped_batch)
|
182 |
+
out_images = []
|
183 |
+
for ind in range(0, valid_len, cropped_batch):
|
184 |
+
# assemble results
|
185 |
+
img_out = (self.results_list[ind:ind+cropped_batch].detach().cpu().numpy() * 255).astype(np.uint8)
|
186 |
+
img_out = self.assemble_results(img_out, self.image_sizes_list[ind], self.position_indexes[ind:ind+cropped_batch].detach().cpu().numpy().astype(int))
|
187 |
+
# Image.fromarray(img_out.astype(np.uint8)).save(self.results_output_list[ind])
|
188 |
+
out_images.append(img_out.astype(np.uint8))
|
189 |
+
self.results_list = self.results_list[valid_len:]
|
190 |
+
|
191 |
+
self.position_indexes = self.position_indexes[valid_len:]
|
192 |
+
self.image_sizes_list = self.image_sizes_list[valid_len:]
|
193 |
+
|
194 |
+
return out_images
|
195 |
+
|
196 |
+
def write_batch_input(self, imgs, image_sizes, position_indexes, default_val=1):
|
197 |
+
cropped_batch = self.split_hw_overlapped[0] * self.split_hw_overlapped[1]
|
198 |
+
|
199 |
+
images = []
|
200 |
+
valid_len = imgs.shape[0]
|
201 |
+
for ind in range(0, valid_len, cropped_batch):
|
202 |
+
# assemble results
|
203 |
+
img_out = (imgs[ind:ind+cropped_batch].detach().cpu().numpy() * 255).astype(np.uint8)
|
204 |
+
img_out = self.assemble_results(img_out, image_sizes[ind], position_indexes.detach().cpu().numpy().astype(int), default_val).astype(np.uint8)
|
205 |
+
images.append(img_out)
|
206 |
+
return images
|
207 |
+
|
208 |
+
def generation(self, split_hw, split_overlap, guid_img, img_ori, mask_img_ori, dps_scale, uc_score, ddim_steps, batch_size=32, n_samples=1):
|
209 |
+
max_batch = __MAX_BATCH__
|
210 |
+
operator = GaussialBlurOperator(61, 3.0, self.gpu_id)
|
211 |
+
assert batch_size == 1
|
212 |
+
self.split_resolution = None
|
213 |
+
self.split_overlap = split_overlap
|
214 |
+
self.split_hw = split_hw
|
215 |
+
|
216 |
+
|
217 |
+
# get img hw
|
218 |
+
for src_img_id in range(0, 1, batch_size):
|
219 |
+
input_img, cond_img, mask_img, image_sizes, position_indexes = self.prepare_batch(guid_img, img_ori, mask_img_ori, 1)
|
220 |
+
|
221 |
+
input_masked = self.write_batch_input(cond_img, image_sizes, position_indexes)
|
222 |
+
input_maskes = self.write_batch_input(mask_img, image_sizes, position_indexes, 0)
|
223 |
+
|
224 |
+
results_all = []
|
225 |
+
for _ in range(n_samples):
|
226 |
+
for batch_id in range(0, input_img.shape[0], max_batch):
|
227 |
+
embeddings = {}
|
228 |
+
embeddings["cond_img"] = cond_img[batch_id:batch_id+max_batch]
|
229 |
+
|
230 |
+
if (mask_img[batch_id:batch_id+max_batch] > 0.5).sum() == 0:
|
231 |
+
results = torch.ones_like(cond_img[batch_id:batch_id+max_batch])
|
232 |
+
else:
|
233 |
+
results = self.model(embeddings, input_img[batch_id:batch_id+max_batch], mask_img[batch_id:batch_id+max_batch], ddim_steps=ddim_steps,
|
234 |
+
guidance_scale=uc_score, dps_scale=dps_scale, as_latent=False, grad_scale=1, operator=operator)
|
235 |
+
|
236 |
+
out_images = self.write_batch_img(results, image_sizes[batch_id:batch_id+max_batch], position_indexes[batch_id:batch_id+max_batch])
|
237 |
+
results_all += out_images
|
238 |
+
ret = {
|
239 |
+
"input_image": input_masked,
|
240 |
+
"input_maskes": input_maskes,
|
241 |
+
"out_images": results_all
|
242 |
+
}
|
243 |
+
return ret
|
244 |
+
|
245 |
+
|
matfusion.py
ADDED
@@ -0,0 +1,380 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import numpy as np
|
3 |
+
from omegaconf import OmegaConf
|
4 |
+
from pathlib import Path
|
5 |
+
import cv2
|
6 |
+
|
7 |
+
import torch
|
8 |
+
import torch.nn as nn
|
9 |
+
import torch.nn.functional as F
|
10 |
+
from torch.cuda.amp import custom_bwd, custom_fwd
|
11 |
+
from torchvision.utils import save_image
|
12 |
+
from torchvision.ops import masks_to_boxes
|
13 |
+
from torchvision.transforms import Resize
|
14 |
+
from diffusers import DDIMScheduler, DDPMScheduler
|
15 |
+
from einops import rearrange, repeat
|
16 |
+
from tqdm import tqdm
|
17 |
+
import sys
|
18 |
+
from os import path
|
19 |
+
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
|
20 |
+
sys.path.append("./models/")
|
21 |
+
from loguru import logger
|
22 |
+
|
23 |
+
from ldm.util import instantiate_from_config
|
24 |
+
from ldm.models.diffusion.ddim import DDIMSampler
|
25 |
+
from ldm.modules.diffusionmodules.util import extract_into_tensor
|
26 |
+
|
27 |
+
# load model
|
28 |
+
def load_model_from_config(config, ckpt, device, vram_O=False, verbose=True):
|
29 |
+
|
30 |
+
pl_sd = torch.load(ckpt, map_location='cpu')
|
31 |
+
|
32 |
+
if 'global_step' in pl_sd and verbose:
|
33 |
+
logger.info(f'Global Step: {pl_sd["global_step"]}')
|
34 |
+
|
35 |
+
sd = pl_sd['state_dict']
|
36 |
+
|
37 |
+
model = instantiate_from_config(config.model)
|
38 |
+
m, u = model.load_state_dict(sd, strict=False)
|
39 |
+
|
40 |
+
if len(m) > 0:
|
41 |
+
logger.warning('missing keys: \n', m)
|
42 |
+
if len(u) > 0:
|
43 |
+
logger.warning('unexpected keys: \n', u)
|
44 |
+
|
45 |
+
# manually load ema and delete it to save GPU memory
|
46 |
+
if model.use_ema:
|
47 |
+
logger.debug('loading EMA...')
|
48 |
+
model.model_ema.copy_to(model.model)
|
49 |
+
del model.model_ema
|
50 |
+
|
51 |
+
if vram_O:
|
52 |
+
# we don't need decoder
|
53 |
+
del model.first_stage_model.decoder
|
54 |
+
|
55 |
+
torch.cuda.empty_cache()
|
56 |
+
|
57 |
+
model.eval().to(device)
|
58 |
+
# model.first_stage_model.train = True
|
59 |
+
# model.first_stage_model.train()
|
60 |
+
for param in model.first_stage_model.parameters():
|
61 |
+
param.requires_grad = True
|
62 |
+
|
63 |
+
return model
|
64 |
+
|
65 |
+
class MateralDiffusion(nn.Module):
|
66 |
+
def __init__(self, device, fp16,
|
67 |
+
config=None,
|
68 |
+
ckpt=None, vram_O=False, t_range=[0.02, 0.98], opt=None, use_ddim=True):
|
69 |
+
super().__init__()
|
70 |
+
|
71 |
+
self.device = device
|
72 |
+
self.fp16 = fp16
|
73 |
+
self.vram_O = vram_O
|
74 |
+
self.t_range = t_range
|
75 |
+
self.opt = opt
|
76 |
+
|
77 |
+
self.config = OmegaConf.load(config)
|
78 |
+
# TODO: seems it cannot load into fp16...
|
79 |
+
self.model = load_model_from_config(self.config, ckpt, device=self.device, vram_O=vram_O, verbose=True)
|
80 |
+
|
81 |
+
# timesteps: use diffuser for convenience... hope it's alright.
|
82 |
+
self.num_train_timesteps = self.config.model.params.timesteps
|
83 |
+
|
84 |
+
self.use_ddim = use_ddim
|
85 |
+
|
86 |
+
if self.use_ddim:
|
87 |
+
self.scheduler = DDIMScheduler(
|
88 |
+
self.num_train_timesteps,
|
89 |
+
self.config.model.params.linear_start,
|
90 |
+
self.config.model.params.linear_end,
|
91 |
+
beta_schedule='scaled_linear',
|
92 |
+
clip_sample=False,
|
93 |
+
set_alpha_to_one=False,
|
94 |
+
steps_offset=1,
|
95 |
+
)
|
96 |
+
print("Using DDIM...")
|
97 |
+
else:
|
98 |
+
self.scheduler = DDPMScheduler(
|
99 |
+
self.num_train_timesteps,
|
100 |
+
self.config.model.params.linear_start,
|
101 |
+
self.config.model.params.linear_end,
|
102 |
+
beta_schedule='scaled_linear',
|
103 |
+
clip_sample=False,
|
104 |
+
)
|
105 |
+
print("Using DDPM...")
|
106 |
+
|
107 |
+
|
108 |
+
self.min_step = int(self.num_train_timesteps * t_range[0])
|
109 |
+
self.max_step = int(self.num_train_timesteps * t_range[1])
|
110 |
+
self.alphas = self.scheduler.alphas_cumprod.to(self.device) # for convenience
|
111 |
+
|
112 |
+
def get_input(self, x):
|
113 |
+
if len(x.shape) == 3:
|
114 |
+
x = x[..., None]
|
115 |
+
x = rearrange(x, 'b h w c -> b c h w')
|
116 |
+
x = x.to(memory_format=torch.contiguous_format).float()
|
117 |
+
return x
|
118 |
+
|
119 |
+
def center_crop(self, img, mask, return_uv=False, mask_ratio=.8, image_size=256):
|
120 |
+
margin = np.round((1 - mask_ratio) * image_size).astype(int)
|
121 |
+
resizer = Resize([np.round(image_size-margin*2).astype(int),
|
122 |
+
np.round(image_size-margin*2).astype(int)])
|
123 |
+
# img ~ batch, h, w, 3
|
124 |
+
# mask ~ batch, h, w, 3
|
125 |
+
# ensure border is 0, as grid sampler only support border or zeros padding
|
126 |
+
# But we need the one padding
|
127 |
+
batch_size = img.shape[0]
|
128 |
+
|
129 |
+
min_max_uv = masks_to_boxes(mask[..., -1] > 0.5)
|
130 |
+
min_uv, max_uv = min_max_uv[..., [1,0]].long(), (min_max_uv[..., [3,2]] + 1).long()
|
131 |
+
# fill back ground to ones
|
132 |
+
img = (img + (mask[..., -1:] <= 0.5)).clamp(0, 1)
|
133 |
+
|
134 |
+
img = rearrange(img, 'b h w c -> b c h w')
|
135 |
+
ori_size = torch.tensor(img.shape[-2:]).to(min_max_uv.device).reshape(1, 2).expand(img.shape[0], -1)
|
136 |
+
|
137 |
+
crooped_imgs = []
|
138 |
+
|
139 |
+
for batch_idx in range(batch_size):
|
140 |
+
# print(min_uv, max_uv, margin)
|
141 |
+
img_crop = img[batch_idx][:, min_uv[batch_idx, 0]:max_uv[batch_idx, 0],
|
142 |
+
min_uv[batch_idx,1]:max_uv[batch_idx, 1]]
|
143 |
+
img_crop = resizer(img_crop)
|
144 |
+
img_out = torch.ones(3, image_size, image_size).to(img.device)
|
145 |
+
img_out[:, margin:image_size-margin, margin:image_size-margin] = img_crop
|
146 |
+
crooped_imgs.append(img_out)
|
147 |
+
img_new = torch.stack(crooped_imgs, dim=0)
|
148 |
+
img_new = rearrange(img_new, 'b c h w -> b h w c')
|
149 |
+
crop_uv = torch.stack([ori_size[:, 0], ori_size[:, 1], min_uv[:, 0], min_uv[:, 1], max_uv[:, 0], max_uv[:, 1], max_uv[:, 1]*0+margin], dim=-1).float()
|
150 |
+
if return_uv:
|
151 |
+
return img_new, crop_uv
|
152 |
+
|
153 |
+
return img_new
|
154 |
+
|
155 |
+
def center_crop_aspect_ratio(self, img, mask, return_uv=False, mask_ratio=.8, image_size=256):
|
156 |
+
# img ~ batch, h, w, 3
|
157 |
+
# mask ~ batch, h, w, 3
|
158 |
+
# ensure border is 0, as grid sampler only support border or zeros padding
|
159 |
+
# But we need the one padding
|
160 |
+
boarder_mask = torch.zeros_like(mask)
|
161 |
+
boarder_mask[:, 1:-1, 1:-1] = 1
|
162 |
+
mask = mask * boarder_mask
|
163 |
+
# print(f"mask: {mask.shape}, {(mask[..., -1] > 0.5).sum}")
|
164 |
+
|
165 |
+
min_max_uv = masks_to_boxes(mask[..., -1] > 0.5)
|
166 |
+
min_uv, max_uv = min_max_uv[..., [1,0]], min_max_uv[..., [3,2]]
|
167 |
+
# fill back ground to ones
|
168 |
+
img = (img + (mask[..., -1:] <= 0.5)).clamp(0, 1)
|
169 |
+
|
170 |
+
img = rearrange(img, 'b h w c -> b c h w')
|
171 |
+
ori_size = torch.tensor(img.shape[-2:]).to(min_max_uv.device).reshape(1, 2).expand(img.shape[0], -1)
|
172 |
+
|
173 |
+
crop_length = torch.div((max_uv - min_uv), 2, rounding_mode='floor')
|
174 |
+
half_size = torch.max(crop_length, dim=-1, keepdim=True)[0]
|
175 |
+
center_uv = min_uv + crop_length
|
176 |
+
|
177 |
+
# generate grid
|
178 |
+
target_size = image_size
|
179 |
+
grid_x, grid_y = torch.meshgrid(torch.arange(0, target_size, 1, device=min_max_uv.device), \
|
180 |
+
torch.arange(0, target_size, 1, device=min_max_uv.device), \
|
181 |
+
indexing='ij')
|
182 |
+
normalized_xy = torch.stack([(grid_x) / (target_size - 1), grid_y / (target_size - 1)], dim=-1) # [0,1]
|
183 |
+
normalized_xy = (normalized_xy - 0.5) / mask_ratio + 0.5
|
184 |
+
|
185 |
+
normalized_xy = normalized_xy[None].expand(img.shape[0], -1, -1, -1)
|
186 |
+
|
187 |
+
ori_crop_size = 2 * half_size + 1
|
188 |
+
|
189 |
+
xy_scale = (ori_crop_size-1) / (ori_size - 1)
|
190 |
+
normalized_xy = normalized_xy * xy_scale.reshape(-1, 1, 1, 2)[..., [0,1]]
|
191 |
+
|
192 |
+
xy_shift = (center_uv - half_size) / (ori_size - 1)
|
193 |
+
normalized_xy = normalized_xy + xy_shift.reshape(-1, 1, 1, 2)[..., [0,1]]
|
194 |
+
|
195 |
+
normalized_xy = normalized_xy * 2 - 1 # [-1,1]
|
196 |
+
# normalized_xy = normalized_xy / mask_ratio
|
197 |
+
|
198 |
+
img_new = F.grid_sample(img, normalized_xy[..., [1,0]], padding_mode='border', align_corners=True)
|
199 |
+
|
200 |
+
crop_uv = torch.stack([ori_size[:, 0], ori_size[:, 1], half_size[..., 0]*0.0 + mask_ratio, half_size[..., 0], center_uv[:, 0], center_uv[:, 1]], dim=-1).float()
|
201 |
+
img_new = rearrange(img_new, 'b c h w -> b h w c')
|
202 |
+
|
203 |
+
if return_uv:
|
204 |
+
return img_new, crop_uv
|
205 |
+
|
206 |
+
return img_new
|
207 |
+
|
208 |
+
def restore_crop(self, img, img_ori, crop_idx):
|
209 |
+
ori_size, min_uv, max_uv, margin = crop_idx[:, :2].long(), crop_idx[:, 2:4].long(), crop_idx[:, 4:6].long(), crop_idx[0, 6].long().item()
|
210 |
+
batch_size = img.shape[0]
|
211 |
+
|
212 |
+
all_images = []
|
213 |
+
for batch_idx in range(batch_size):
|
214 |
+
img_out = torch.ones(3, ori_size[batch_idx][0], ori_size[batch_idx][1]).to(img.device)
|
215 |
+
cropped_size = max_uv[batch_idx] - min_uv[batch_idx]
|
216 |
+
resizer = Resize([cropped_size[0], cropped_size[1]])
|
217 |
+
net_size = img[batch_idx].shape[-1]
|
218 |
+
img_crop = resizer(img[batch_idx][:, margin:net_size-margin, margin:net_size-margin])
|
219 |
+
|
220 |
+
img_out[:, min_uv[batch_idx, 0]:max_uv[batch_idx, 0],
|
221 |
+
min_uv[batch_idx,1]:max_uv[batch_idx, 1]] = img_crop
|
222 |
+
all_images.append(img_out)
|
223 |
+
all_images = torch.stack(all_images, dim=0)
|
224 |
+
all_images = rearrange(all_images, 'b c h w -> b h w c')
|
225 |
+
return all_images
|
226 |
+
|
227 |
+
def restore_crop_aspect_ratio(self, img, img_ori, crop_idx):
|
228 |
+
ori_size, mask_ratio, half_size, center_uv = crop_idx[:, :2].long(), crop_idx[:, 2:3], crop_idx[:, 3:4].long(), crop_idx[:, 4:].long()
|
229 |
+
img[:, :, 0, :] = 1
|
230 |
+
img[:, :, -1, :] = 1
|
231 |
+
img[:, :, :, 0] = 1
|
232 |
+
img[:, :, :, -1] = 1
|
233 |
+
|
234 |
+
ori_crop_size = 2*half_size + 1
|
235 |
+
grid_x, grid_y = torch.meshgrid(torch.arange(0, ori_size[0, 0].item(), 1, device=img.device), \
|
236 |
+
torch.arange(0, ori_size[0, 1].item(), 1, device=img.device), \
|
237 |
+
indexing='ij')
|
238 |
+
normalized_xy = torch.stack([grid_x, grid_y], dim=-1)[None].expand(img.shape[0], -1, -1, -1) - \
|
239 |
+
(center_uv - half_size).reshape(-1, 1, 1, 2)[..., [0,1]]
|
240 |
+
|
241 |
+
normalized_xy = normalized_xy / (ori_crop_size-1).reshape(-1, 1, 1, 1)
|
242 |
+
|
243 |
+
normalized_xy = (2*normalized_xy - 1) * mask_ratio.reshape(-1, 1, 1, 1)
|
244 |
+
|
245 |
+
sample_start = (center_uv - half_size)
|
246 |
+
# print(normalized_xy[0][sample_start[0][0], sample_start[0][1]], mask_ratio)
|
247 |
+
|
248 |
+
img_out = F.grid_sample(img, normalized_xy[..., [1,0]], padding_mode='border', align_corners=True)
|
249 |
+
img_out = rearrange(img_out, 'b c h w -> b h w c')
|
250 |
+
|
251 |
+
return img_out
|
252 |
+
|
253 |
+
def _image2diffusion(self, embeddings, pred_rgb, mask, image_size=256):
|
254 |
+
# pred_rgb: tensor [1, 3, H, W] in [0, 1]
|
255 |
+
# assert pred_rgb.w
|
256 |
+
assert len(pred_rgb.shape) == 4, f"except 4 dim tensor, got: {pred_rgb.shape}"
|
257 |
+
|
258 |
+
cond_img = embeddings["cond_img"]
|
259 |
+
cond_img = self.center_crop(cond_img, mask, mask_ratio=1.0, image_size=image_size)
|
260 |
+
|
261 |
+
pred_rgb_256, crop_idx_all = self.center_crop(pred_rgb, mask, return_uv=True, mask_ratio=1.0, image_size=image_size)
|
262 |
+
|
263 |
+
# print(f"pred_rgb_256: {pred_rgb_256.min()} {pred_rgb_256.max()} {pred_rgb_256.shape} {cond_img.shape}")
|
264 |
+
|
265 |
+
mask_img = self.center_crop(1 - mask.expand(-1, -1, -1, 3), mask, mask_ratio=1.0, image_size=image_size)
|
266 |
+
|
267 |
+
xc = self.get_input(cond_img)
|
268 |
+
pred_rgb_256 = self.get_input(pred_rgb_256)
|
269 |
+
|
270 |
+
return pred_rgb_256, crop_idx_all, xc
|
271 |
+
|
272 |
+
def _get_condition(self, xc, with_uncondition=False):
|
273 |
+
# To support classifier-free guidance, randomly drop out only text conditioning 5%, only image conditioning 5%, and both 5%.
|
274 |
+
# z.shape: [8, 4, 64, 64]; c.shape: [8, 1, 768]
|
275 |
+
# print('=========== xc shape ===========', xc.shape)
|
276 |
+
|
277 |
+
# print(xc.shape, xc.min(), xc.max(), self.model.use_clip_embdding)
|
278 |
+
xc = xc * 2 - 1
|
279 |
+
cond = {}
|
280 |
+
clip_emb = self.model.get_learned_conditioning(xc if self.model.use_clip_embdding else [""]).detach()
|
281 |
+
c_concat = self.model.encode_first_stage((xc.to(self.device))).mode().detach()
|
282 |
+
# print(clip_emb.shape, clip_emb.min(), clip_emb.max(), self.model.use_clip_embdding)
|
283 |
+
if with_uncondition:
|
284 |
+
cond['c_crossattn'] = [torch.cat([torch.zeros_like(clip_emb).to(self.device), clip_emb], dim=0)]
|
285 |
+
cond['c_concat'] = [torch.cat([torch.zeros_like(c_concat).to(self.device), c_concat], dim=0)]
|
286 |
+
else:
|
287 |
+
cond['c_crossattn'] = [clip_emb]
|
288 |
+
cond['c_concat'] = [c_concat]
|
289 |
+
return cond
|
290 |
+
|
291 |
+
@torch.no_grad()
|
292 |
+
def __call__(self, embeddings, pred_rgb, mask, guidance_scale=3, dps_scale=0.2, as_latent=False, grad_scale=1, save_guidance_path:Path=None,
|
293 |
+
ddim_steps=200, ddim_eta=1, operator=None):
|
294 |
+
# todo: The upsacle is currectly hard-coded
|
295 |
+
upscale = 1
|
296 |
+
|
297 |
+
# with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
|
298 |
+
pred_rgb_256, crop_idx_all, xc = self._image2diffusion(embeddings, pred_rgb, mask, image_size=256*upscale)
|
299 |
+
cond = self._get_condition(xc, with_uncondition=True)
|
300 |
+
assert pred_rgb_256.shape[-1] == pred_rgb_256.shape[-2], f"Expect image of square size, get {pred_rgb.shape}"
|
301 |
+
|
302 |
+
latents = torch.randn_like(self.encode_imgs(pred_rgb_256))
|
303 |
+
|
304 |
+
if self.use_ddim:
|
305 |
+
self.scheduler.set_timesteps(ddim_steps)
|
306 |
+
else:
|
307 |
+
self.scheduler.set_timesteps(self.num_train_timesteps)
|
308 |
+
|
309 |
+
intermidates = []
|
310 |
+
|
311 |
+
for i, t in tqdm(enumerate(self.scheduler.timesteps)):
|
312 |
+
x_in = torch.cat([latents] * 2)
|
313 |
+
t_in = torch.cat([t.view(1).expand(latents.shape[0])] * 2).to(self.device)
|
314 |
+
|
315 |
+
noise_pred = self.model.apply_model(x_in, t_in, cond)
|
316 |
+
|
317 |
+
noise_pred_uncond, noise_pred_cond = noise_pred.chunk(2)
|
318 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_cond - noise_pred_uncond)
|
319 |
+
|
320 |
+
# dps
|
321 |
+
if dps_scale > 0:
|
322 |
+
with torch.enable_grad():
|
323 |
+
t_batch = torch.randint(self.min_step, self.max_step + 1, (latents.shape[0],), dtype=torch.long, device=self.device) * 0 + t
|
324 |
+
x_hat_latents = self.model.predict_start_from_noise(latents.requires_grad_(True), t_batch, noise_pred)
|
325 |
+
x_hat = self.decode_latents(x_hat_latents)
|
326 |
+
x_hat = operator.forward(x_hat)
|
327 |
+
norm = torch.linalg.norm((pred_rgb_256-x_hat).reshape(pred_rgb_256.shape[0], -1), dim=-1)
|
328 |
+
guidance_score = torch.autograd.grad(norm.sum(), latents, retain_graph=True)[0]
|
329 |
+
|
330 |
+
if (not save_guidance_path is None) and i % (len(self.scheduler.timesteps)//20) == 0:
|
331 |
+
x_t = self.decode_latents(latents)
|
332 |
+
intermidates.append(torch.cat([x_hat, x_t, pred_rgb_256, pred_rgb_256-x_hat], dim=-2).detach().cpu())
|
333 |
+
|
334 |
+
# print("before", noise_pred[0, 2, 10, 16:22], noise_pred.shape, dps_scale)
|
335 |
+
logger.debug(f"Guidance loss: {norm}")
|
336 |
+
noise_pred = noise_pred + dps_scale * guidance_score
|
337 |
+
|
338 |
+
|
339 |
+
if self.use_ddim:
|
340 |
+
latents = self.scheduler.step(noise_pred, t, latents, eta=ddim_eta)['prev_sample']
|
341 |
+
else:
|
342 |
+
latents = self.scheduler.step(noise_pred.clone().detach(), t, latents)['prev_sample']
|
343 |
+
if dps_scale > 0:
|
344 |
+
del x_hat
|
345 |
+
del guidance_score
|
346 |
+
del noise_pred
|
347 |
+
del x_hat_latents
|
348 |
+
del norm
|
349 |
+
|
350 |
+
imgs = self.decode_latents(latents)
|
351 |
+
viz_images = torch.cat([pred_rgb_256, imgs],dim=-1)[:1]
|
352 |
+
if not save_guidance_path is None and len(intermidates) > 0:
|
353 |
+
save_image(viz_images, save_guidance_path)
|
354 |
+
|
355 |
+
viz_images = torch.cat(intermidates,dim=-1)[:1]
|
356 |
+
save_image(viz_images, save_guidance_path+"all.jpg")
|
357 |
+
|
358 |
+
# transform back to original images
|
359 |
+
img_ori_size = self.restore_crop(imgs, pred_rgb, crop_idx_all)
|
360 |
+
if not save_guidance_path is None:
|
361 |
+
img_ori_size_save = rearrange(img_ori_size, 'b h w c -> b c h w')[:1]
|
362 |
+
save_image(img_ori_size_save, save_guidance_path+"_out.jpg")
|
363 |
+
return img_ori_size
|
364 |
+
|
365 |
+
def decode_latents(self, latents):
|
366 |
+
# zs: [B, 4, 32, 32] Latent space image
|
367 |
+
# with self.model.ema_scope():
|
368 |
+
imgs = self.model.decode_first_stage(latents)
|
369 |
+
imgs = (imgs / 2 + 0.5).clamp(0, 1)
|
370 |
+
|
371 |
+
return imgs # [B, 3, 256, 256] RGB space image
|
372 |
+
|
373 |
+
def encode_imgs(self, imgs):
|
374 |
+
# imgs: [B, 3, 256, 256] RGB space image
|
375 |
+
# with self.model.ema_scope():
|
376 |
+
imgs = imgs * 2 - 1
|
377 |
+
# latents = torch.cat([self.model.get_first_stage_encoding(self.model.encode_first_stage(img.unsqueeze(0))) for img in imgs], dim=0)
|
378 |
+
latents = self.model.get_first_stage_encoding(self.model.encode_first_stage(imgs))
|
379 |
+
|
380 |
+
return latents # [B, 4, 32, 32] Latent space image
|
models/ldm/__init__.py
ADDED
File without changes
|
models/ldm/data/__init__.py
ADDED
File without changes
|
models/ldm/data/base.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import numpy as np
|
3 |
+
from abc import abstractmethod
|
4 |
+
from torch.utils.data import Dataset, ConcatDataset, ChainDataset, IterableDataset
|
5 |
+
|
6 |
+
|
7 |
+
class Txt2ImgIterableBaseDataset(IterableDataset):
|
8 |
+
'''
|
9 |
+
Define an interface to make the IterableDatasets for text2img data chainable
|
10 |
+
'''
|
11 |
+
def __init__(self, num_records=0, valid_ids=None, size=256):
|
12 |
+
super().__init__()
|
13 |
+
self.num_records = num_records
|
14 |
+
self.valid_ids = valid_ids
|
15 |
+
self.sample_ids = valid_ids
|
16 |
+
self.size = size
|
17 |
+
|
18 |
+
print(f'{self.__class__.__name__} dataset contains {self.__len__()} examples.')
|
19 |
+
|
20 |
+
def __len__(self):
|
21 |
+
return self.num_records
|
22 |
+
|
23 |
+
@abstractmethod
|
24 |
+
def __iter__(self):
|
25 |
+
pass
|
26 |
+
|
27 |
+
|
28 |
+
class PRNGMixin(object):
|
29 |
+
"""
|
30 |
+
Adds a prng property which is a numpy RandomState which gets
|
31 |
+
reinitialized whenever the pid changes to avoid synchronized sampling
|
32 |
+
behavior when used in conjunction with multiprocessing.
|
33 |
+
"""
|
34 |
+
@property
|
35 |
+
def prng(self):
|
36 |
+
currentpid = os.getpid()
|
37 |
+
if getattr(self, "_initpid", None) != currentpid:
|
38 |
+
self._initpid = currentpid
|
39 |
+
self._prng = np.random.RandomState()
|
40 |
+
return self._prng
|
models/ldm/data/coco.py
ADDED
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import albumentations
|
4 |
+
import numpy as np
|
5 |
+
from PIL import Image
|
6 |
+
from tqdm import tqdm
|
7 |
+
from torch.utils.data import Dataset
|
8 |
+
from abc import abstractmethod
|
9 |
+
|
10 |
+
|
11 |
+
class CocoBase(Dataset):
|
12 |
+
"""needed for (image, caption, segmentation) pairs"""
|
13 |
+
def __init__(self, size=None, dataroot="", datajson="", onehot_segmentation=False, use_stuffthing=False,
|
14 |
+
crop_size=None, force_no_crop=False, given_files=None, use_segmentation=True,crop_type=None):
|
15 |
+
self.split = self.get_split()
|
16 |
+
self.size = size
|
17 |
+
if crop_size is None:
|
18 |
+
self.crop_size = size
|
19 |
+
else:
|
20 |
+
self.crop_size = crop_size
|
21 |
+
|
22 |
+
assert crop_type in [None, 'random', 'center']
|
23 |
+
self.crop_type = crop_type
|
24 |
+
self.use_segmenation = use_segmentation
|
25 |
+
self.onehot = onehot_segmentation # return segmentation as rgb or one hot
|
26 |
+
self.stuffthing = use_stuffthing # include thing in segmentation
|
27 |
+
if self.onehot and not self.stuffthing:
|
28 |
+
raise NotImplemented("One hot mode is only supported for the "
|
29 |
+
"stuffthings version because labels are stored "
|
30 |
+
"a bit different.")
|
31 |
+
|
32 |
+
data_json = datajson
|
33 |
+
with open(data_json) as json_file:
|
34 |
+
self.json_data = json.load(json_file)
|
35 |
+
self.img_id_to_captions = dict()
|
36 |
+
self.img_id_to_filepath = dict()
|
37 |
+
self.img_id_to_segmentation_filepath = dict()
|
38 |
+
|
39 |
+
assert data_json.split("/")[-1] in [f"captions_train{self.year()}.json",
|
40 |
+
f"captions_val{self.year()}.json"]
|
41 |
+
# TODO currently hardcoded paths, would be better to follow logic in
|
42 |
+
# cocstuff pixelmaps
|
43 |
+
if self.use_segmenation:
|
44 |
+
if self.stuffthing:
|
45 |
+
self.segmentation_prefix = (
|
46 |
+
f"data/cocostuffthings/val{self.year()}" if
|
47 |
+
data_json.endswith(f"captions_val{self.year()}.json") else
|
48 |
+
f"data/cocostuffthings/train{self.year()}")
|
49 |
+
else:
|
50 |
+
self.segmentation_prefix = (
|
51 |
+
f"data/coco/annotations/stuff_val{self.year()}_pixelmaps" if
|
52 |
+
data_json.endswith(f"captions_val{self.year()}.json") else
|
53 |
+
f"data/coco/annotations/stuff_train{self.year()}_pixelmaps")
|
54 |
+
|
55 |
+
imagedirs = self.json_data["images"]
|
56 |
+
self.labels = {"image_ids": list()}
|
57 |
+
for imgdir in tqdm(imagedirs, desc="ImgToPath"):
|
58 |
+
self.img_id_to_filepath[imgdir["id"]] = os.path.join(dataroot, imgdir["file_name"])
|
59 |
+
self.img_id_to_captions[imgdir["id"]] = list()
|
60 |
+
pngfilename = imgdir["file_name"].replace("jpg", "png")
|
61 |
+
if self.use_segmenation:
|
62 |
+
self.img_id_to_segmentation_filepath[imgdir["id"]] = os.path.join(
|
63 |
+
self.segmentation_prefix, pngfilename)
|
64 |
+
if given_files is not None:
|
65 |
+
if pngfilename in given_files:
|
66 |
+
self.labels["image_ids"].append(imgdir["id"])
|
67 |
+
else:
|
68 |
+
self.labels["image_ids"].append(imgdir["id"])
|
69 |
+
|
70 |
+
capdirs = self.json_data["annotations"]
|
71 |
+
for capdir in tqdm(capdirs, desc="ImgToCaptions"):
|
72 |
+
# there are in average 5 captions per image
|
73 |
+
#self.img_id_to_captions[capdir["image_id"]].append(np.array([capdir["caption"]]))
|
74 |
+
self.img_id_to_captions[capdir["image_id"]].append(capdir["caption"])
|
75 |
+
|
76 |
+
self.rescaler = albumentations.SmallestMaxSize(max_size=self.size)
|
77 |
+
if self.split=="validation":
|
78 |
+
self.cropper = albumentations.CenterCrop(height=self.crop_size, width=self.crop_size)
|
79 |
+
else:
|
80 |
+
# default option for train is random crop
|
81 |
+
if self.crop_type in [None, 'random']:
|
82 |
+
self.cropper = albumentations.RandomCrop(height=self.crop_size, width=self.crop_size)
|
83 |
+
else:
|
84 |
+
self.cropper = albumentations.CenterCrop(height=self.crop_size, width=self.crop_size)
|
85 |
+
self.preprocessor = albumentations.Compose(
|
86 |
+
[self.rescaler, self.cropper],
|
87 |
+
additional_targets={"segmentation": "image"})
|
88 |
+
if force_no_crop:
|
89 |
+
self.rescaler = albumentations.Resize(height=self.size, width=self.size)
|
90 |
+
self.preprocessor = albumentations.Compose(
|
91 |
+
[self.rescaler],
|
92 |
+
additional_targets={"segmentation": "image"})
|
93 |
+
|
94 |
+
@abstractmethod
|
95 |
+
def year(self):
|
96 |
+
raise NotImplementedError()
|
97 |
+
|
98 |
+
def __len__(self):
|
99 |
+
return len(self.labels["image_ids"])
|
100 |
+
|
101 |
+
def preprocess_image(self, image_path, segmentation_path=None):
|
102 |
+
image = Image.open(image_path)
|
103 |
+
if not image.mode == "RGB":
|
104 |
+
image = image.convert("RGB")
|
105 |
+
image = np.array(image).astype(np.uint8)
|
106 |
+
if segmentation_path:
|
107 |
+
segmentation = Image.open(segmentation_path)
|
108 |
+
if not self.onehot and not segmentation.mode == "RGB":
|
109 |
+
segmentation = segmentation.convert("RGB")
|
110 |
+
segmentation = np.array(segmentation).astype(np.uint8)
|
111 |
+
if self.onehot:
|
112 |
+
assert self.stuffthing
|
113 |
+
# stored in caffe format: unlabeled==255. stuff and thing from
|
114 |
+
# 0-181. to be compatible with the labels in
|
115 |
+
# https://github.com/nightrome/cocostuff/blob/master/labels.txt
|
116 |
+
# we shift stuffthing one to the right and put unlabeled in zero
|
117 |
+
# as long as segmentation is uint8 shifting to right handles the
|
118 |
+
# latter too
|
119 |
+
assert segmentation.dtype == np.uint8
|
120 |
+
segmentation = segmentation + 1
|
121 |
+
|
122 |
+
processed = self.preprocessor(image=image, segmentation=segmentation)
|
123 |
+
|
124 |
+
image, segmentation = processed["image"], processed["segmentation"]
|
125 |
+
else:
|
126 |
+
image = self.preprocessor(image=image,)['image']
|
127 |
+
|
128 |
+
image = (image / 127.5 - 1.0).astype(np.float32)
|
129 |
+
if segmentation_path:
|
130 |
+
if self.onehot:
|
131 |
+
assert segmentation.dtype == np.uint8
|
132 |
+
# make it one hot
|
133 |
+
n_labels = 183
|
134 |
+
flatseg = np.ravel(segmentation)
|
135 |
+
onehot = np.zeros((flatseg.size, n_labels), dtype=np.bool)
|
136 |
+
onehot[np.arange(flatseg.size), flatseg] = True
|
137 |
+
onehot = onehot.reshape(segmentation.shape + (n_labels,)).astype(int)
|
138 |
+
segmentation = onehot
|
139 |
+
else:
|
140 |
+
segmentation = (segmentation / 127.5 - 1.0).astype(np.float32)
|
141 |
+
return image, segmentation
|
142 |
+
else:
|
143 |
+
return image
|
144 |
+
|
145 |
+
def __getitem__(self, i):
|
146 |
+
img_path = self.img_id_to_filepath[self.labels["image_ids"][i]]
|
147 |
+
if self.use_segmenation:
|
148 |
+
seg_path = self.img_id_to_segmentation_filepath[self.labels["image_ids"][i]]
|
149 |
+
image, segmentation = self.preprocess_image(img_path, seg_path)
|
150 |
+
else:
|
151 |
+
image = self.preprocess_image(img_path)
|
152 |
+
captions = self.img_id_to_captions[self.labels["image_ids"][i]]
|
153 |
+
# randomly draw one of all available captions per image
|
154 |
+
caption = captions[np.random.randint(0, len(captions))]
|
155 |
+
example = {"image": image,
|
156 |
+
#"caption": [str(caption[0])],
|
157 |
+
"caption": caption,
|
158 |
+
"img_path": img_path,
|
159 |
+
"filename_": img_path.split(os.sep)[-1]
|
160 |
+
}
|
161 |
+
if self.use_segmenation:
|
162 |
+
example.update({"seg_path": seg_path, 'segmentation': segmentation})
|
163 |
+
return example
|
164 |
+
|
165 |
+
|
166 |
+
class CocoImagesAndCaptionsTrain2017(CocoBase):
|
167 |
+
"""returns a pair of (image, caption)"""
|
168 |
+
def __init__(self, size, onehot_segmentation=False, use_stuffthing=False, crop_size=None, force_no_crop=False,):
|
169 |
+
super().__init__(size=size,
|
170 |
+
dataroot="data/coco/train2017",
|
171 |
+
datajson="data/coco/annotations/captions_train2017.json",
|
172 |
+
onehot_segmentation=onehot_segmentation,
|
173 |
+
use_stuffthing=use_stuffthing, crop_size=crop_size, force_no_crop=force_no_crop)
|
174 |
+
|
175 |
+
def get_split(self):
|
176 |
+
return "train"
|
177 |
+
|
178 |
+
def year(self):
|
179 |
+
return '2017'
|
180 |
+
|
181 |
+
|
182 |
+
class CocoImagesAndCaptionsValidation2017(CocoBase):
|
183 |
+
"""returns a pair of (image, caption)"""
|
184 |
+
def __init__(self, size, onehot_segmentation=False, use_stuffthing=False, crop_size=None, force_no_crop=False,
|
185 |
+
given_files=None):
|
186 |
+
super().__init__(size=size,
|
187 |
+
dataroot="data/coco/val2017",
|
188 |
+
datajson="data/coco/annotations/captions_val2017.json",
|
189 |
+
onehot_segmentation=onehot_segmentation,
|
190 |
+
use_stuffthing=use_stuffthing, crop_size=crop_size, force_no_crop=force_no_crop,
|
191 |
+
given_files=given_files)
|
192 |
+
|
193 |
+
def get_split(self):
|
194 |
+
return "validation"
|
195 |
+
|
196 |
+
def year(self):
|
197 |
+
return '2017'
|
198 |
+
|
199 |
+
|
200 |
+
|
201 |
+
class CocoImagesAndCaptionsTrain2014(CocoBase):
|
202 |
+
"""returns a pair of (image, caption)"""
|
203 |
+
def __init__(self, size, onehot_segmentation=False, use_stuffthing=False, crop_size=None, force_no_crop=False,crop_type='random'):
|
204 |
+
super().__init__(size=size,
|
205 |
+
dataroot="data/coco/train2014",
|
206 |
+
datajson="data/coco/annotations2014/annotations/captions_train2014.json",
|
207 |
+
onehot_segmentation=onehot_segmentation,
|
208 |
+
use_stuffthing=use_stuffthing, crop_size=crop_size, force_no_crop=force_no_crop,
|
209 |
+
use_segmentation=False,
|
210 |
+
crop_type=crop_type)
|
211 |
+
|
212 |
+
def get_split(self):
|
213 |
+
return "train"
|
214 |
+
|
215 |
+
def year(self):
|
216 |
+
return '2014'
|
217 |
+
|
218 |
+
class CocoImagesAndCaptionsValidation2014(CocoBase):
|
219 |
+
"""returns a pair of (image, caption)"""
|
220 |
+
def __init__(self, size, onehot_segmentation=False, use_stuffthing=False, crop_size=None, force_no_crop=False,
|
221 |
+
given_files=None,crop_type='center',**kwargs):
|
222 |
+
super().__init__(size=size,
|
223 |
+
dataroot="data/coco/val2014",
|
224 |
+
datajson="data/coco/annotations2014/annotations/captions_val2014.json",
|
225 |
+
onehot_segmentation=onehot_segmentation,
|
226 |
+
use_stuffthing=use_stuffthing, crop_size=crop_size, force_no_crop=force_no_crop,
|
227 |
+
given_files=given_files,
|
228 |
+
use_segmentation=False,
|
229 |
+
crop_type=crop_type)
|
230 |
+
|
231 |
+
def get_split(self):
|
232 |
+
return "validation"
|
233 |
+
|
234 |
+
def year(self):
|
235 |
+
return '2014'
|
236 |
+
|
237 |
+
if __name__ == '__main__':
|
238 |
+
with open("data/coco/annotations2014/annotations/captions_val2014.json", "r") as json_file:
|
239 |
+
json_data = json.load(json_file)
|
240 |
+
capdirs = json_data["annotations"]
|
241 |
+
import pudb; pudb.set_trace()
|
242 |
+
#d2 = CocoImagesAndCaptionsTrain2014(size=256)
|
243 |
+
d2 = CocoImagesAndCaptionsValidation2014(size=256)
|
244 |
+
print("constructed dataset.")
|
245 |
+
print(f"length of {d2.__class__.__name__}: {len(d2)}")
|
246 |
+
|
247 |
+
ex2 = d2[0]
|
248 |
+
# ex3 = d3[0]
|
249 |
+
# print(ex1["image"].shape)
|
250 |
+
print(ex2["image"].shape)
|
251 |
+
# print(ex3["image"].shape)
|
252 |
+
# print(ex1["segmentation"].shape)
|
253 |
+
print(ex2["caption"].__class__.__name__)
|
models/ldm/data/decoder.py
ADDED
@@ -0,0 +1,497 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
sys.path.insert(1, '.')
|
3 |
+
import numpy as np
|
4 |
+
from omegaconf import DictConfig
|
5 |
+
import torch
|
6 |
+
from PIL import Image
|
7 |
+
import torchvision
|
8 |
+
import cv2
|
9 |
+
import matplotlib.pyplot as plt
|
10 |
+
from ldm.util import instantiate_from_config
|
11 |
+
import os
|
12 |
+
import io
|
13 |
+
import pickle
|
14 |
+
import webdataset as wds
|
15 |
+
import imageio
|
16 |
+
import time
|
17 |
+
from torch import distributed as dist
|
18 |
+
from itertools import chain
|
19 |
+
|
20 |
+
|
21 |
+
class ObjaverseDataDecoder:
|
22 |
+
def __init__(self,
|
23 |
+
target_name="albedo",
|
24 |
+
image_transforms=[],
|
25 |
+
default_trans=torch.zeros(3),
|
26 |
+
postprocess=None,
|
27 |
+
return_paths=False,
|
28 |
+
mask_name="alpha",
|
29 |
+
test=False,
|
30 |
+
condition_name=None,
|
31 |
+
bg_color="white",
|
32 |
+
target_name_pool=None,
|
33 |
+
**kargs
|
34 |
+
) -> None:
|
35 |
+
"""Create a dataset from blender rendering results.
|
36 |
+
If you pass in a root directory it will be searched for images
|
37 |
+
ending in ext (ext can be a list)
|
38 |
+
"""
|
39 |
+
# testing behaves differently
|
40 |
+
self.test = test
|
41 |
+
self.target_name = target_name
|
42 |
+
self.mask_name = mask_name
|
43 |
+
self.default_trans = default_trans
|
44 |
+
self.return_paths = return_paths
|
45 |
+
if isinstance(postprocess, DictConfig):
|
46 |
+
postprocess = instantiate_from_config(postprocess)
|
47 |
+
self.postprocess = postprocess
|
48 |
+
# extra condition
|
49 |
+
self.condition_name = condition_name
|
50 |
+
self.target_name_pool = target_name_pool if not target_name_pool is None else [target_name]
|
51 |
+
self.counter = 0
|
52 |
+
|
53 |
+
self.tform = image_transforms["totensor"]
|
54 |
+
self.img_size = image_transforms["size"]
|
55 |
+
self.tsize = torchvision.transforms.Compose([torchvision.transforms.Resize(self.img_size)])
|
56 |
+
if bg_color == "white":
|
57 |
+
self.bg_color = [1., 1., 1., 1.]
|
58 |
+
elif bg_color == "noise":
|
59 |
+
self.bg_color = "noise"
|
60 |
+
else:
|
61 |
+
raise NotImplementedError
|
62 |
+
|
63 |
+
def path_parsing(self, filename, cond_name=None):
|
64 |
+
# cached path loads albedo
|
65 |
+
if 'albedo' in filename:
|
66 |
+
filename = filename.replace('albedo', self.target_name)
|
67 |
+
if self.target_name=="gloss_shaded":
|
68 |
+
filename = filename.replace('gloss_direct', self.target_name).replace("exr", "jpg")
|
69 |
+
filename_targets = [filename.replace(self.target_name, "gloss_direct").replace("jpg", "exr"),
|
70 |
+
filename.replace(self.target_name, "gloss_color")]
|
71 |
+
elif self.target_name=="diffuse_shaded":
|
72 |
+
filename = filename.replace('diffuse_direct', self.target_name).replace("exr", "jpg")
|
73 |
+
filename_targets = [filename.replace(self.target_name, "diffuse_direct").replace("jpg", "exr"),
|
74 |
+
filename.replace(self.target_name, "albedo")]
|
75 |
+
else:
|
76 |
+
filename_targets = None
|
77 |
+
|
78 |
+
normal_condition_filename = None
|
79 |
+
if self.test and "images_train" in filename:
|
80 |
+
# Currently. "images_train" exists in test set, we write this for clearity
|
81 |
+
condition_filename = filename
|
82 |
+
mask_filename = filename.replace('images_train', 'masks')
|
83 |
+
if self.condition_name == "normal":
|
84 |
+
raise NotImplementedError("Testing with normal conditioning on custom data is not supported")
|
85 |
+
else:
|
86 |
+
cond_name_prefix = filename.split(".", 1)[0] + "." if cond_name is None else cond_name
|
87 |
+
condition_filename = cond_name_prefix + filename.rsplit('.', 1)[1]
|
88 |
+
mask_filename = filename.replace(self.target_name, self.mask_name)
|
89 |
+
if self.condition_name == "normal":
|
90 |
+
normal_condition_filename = filename.replace(self.target_name, "normal")
|
91 |
+
|
92 |
+
return filename, condition_filename, mask_filename, normal_condition_filename, filename_targets
|
93 |
+
|
94 |
+
def read_images(self, filename, condition_filename, normal_condition_filename):
|
95 |
+
# image reading
|
96 |
+
if self.target_name in ["gloss_shaded", "diffuse_shaded"]:
|
97 |
+
target_im_0 = np.array(self.normalized_read(filename[0]))
|
98 |
+
target_im_1 = np.array(self.normalized_read(filename[1]))
|
99 |
+
target_im = np.clip(target_im_0 * target_im_1, 0, 1)
|
100 |
+
else:
|
101 |
+
target_im = np.array(self.normalized_read(filename))
|
102 |
+
|
103 |
+
cond_im = np.array(self.normalized_read(condition_filename))
|
104 |
+
|
105 |
+
if self.condition_name == "normal":
|
106 |
+
normal_img = np.array(self.normalized_read(normal_condition_filename))
|
107 |
+
else:
|
108 |
+
normal_img = None
|
109 |
+
|
110 |
+
return target_im, cond_im, normal_img
|
111 |
+
|
112 |
+
|
113 |
+
def image_post_processing(self, img_mask, target_im, cond_im, normal_img):
|
114 |
+
# make sure image has 3 dimension
|
115 |
+
if len(img_mask.shape) == 2:
|
116 |
+
img_mask = img_mask[:, :, np.newaxis]
|
117 |
+
else:
|
118 |
+
img_mask = img_mask[:, :, :3]
|
119 |
+
|
120 |
+
# transform into desired format
|
121 |
+
target_im, crop_idx = self.load_im(target_im, img_mask, self.bg_color, crop_idx=True)
|
122 |
+
target_im = np.uint8(self.tsize(target_im))
|
123 |
+
cond_im = np.uint8(self.tsize(self.load_im(cond_im, img_mask, self.bg_color)))
|
124 |
+
|
125 |
+
if self.condition_name == "normal":
|
126 |
+
normal_img = np.uint8(self.tsize(self.load_im(normal_img, img_mask, self.bg_color)))
|
127 |
+
else:
|
128 |
+
normal_img = None
|
129 |
+
return target_im, cond_im, normal_img, crop_idx
|
130 |
+
|
131 |
+
# def cartesian_to_spherical(self, xyz):
|
132 |
+
# ptsnew = np.hstack((xyz, np.zeros(xyz.shape)))
|
133 |
+
# xy = xyz[:,0]**2 + xyz[:,1]**2
|
134 |
+
# z = np.sqrt(xy + xyz[:,2]**2)
|
135 |
+
# theta = np.arctan2(np.sqrt(xy), xyz[:,2]) # for elevation angle defined from Z-axis down
|
136 |
+
# #ptsnew[:,4] = np.arctan2(xyz[:,2], np.sqrt(xy)) # for elevation angle defined from XY-plane up
|
137 |
+
# azimuth = np.arctan2(xyz[:,1], xyz[:,0])
|
138 |
+
# return np.array([theta, azimuth, z])
|
139 |
+
|
140 |
+
|
141 |
+
def load_im(self, img, img_mask, color, crop_idx=False):
|
142 |
+
'''
|
143 |
+
replace background pixel with random color in rendering
|
144 |
+
'''
|
145 |
+
# our rendering do not have a valid alpha channel.
|
146 |
+
# We use a seperate mask, which also do not have a valid alpha
|
147 |
+
if img.shape[-1] == 3:
|
148 |
+
img = np.concatenate([img, np.ones_like(img[..., :1])], axis=-1)
|
149 |
+
|
150 |
+
# image maske shape align with image size
|
151 |
+
if (img.shape[0] != img_mask.shape[0]) or (img.shape[1] != img_mask.shape[1]):
|
152 |
+
img_mask = cv2.resize(img_mask,
|
153 |
+
(img.shape[1], img.shape[0]),
|
154 |
+
interpolation=cv2.INTER_NEAREST)[:, :, np.newaxis]
|
155 |
+
|
156 |
+
if isinstance(color, str):
|
157 |
+
random_img = np.random.rand(*(img.shape))
|
158 |
+
img[img_mask[:, :, -1] <= 0.5] = random_img[img_mask[:, :, -1] <= 0.5]
|
159 |
+
else:
|
160 |
+
img[img_mask[:, :, -1] <= 0.5] = color
|
161 |
+
|
162 |
+
if self.test:
|
163 |
+
# crop out valid_mask
|
164 |
+
img, crop_uv = self.center_crop(img[:, :, :3], img_mask)
|
165 |
+
else:
|
166 |
+
crop_uv = None
|
167 |
+
|
168 |
+
# center crop
|
169 |
+
if img.shape[0] > img.shape[1]:
|
170 |
+
margin = int((img.shape[0] - img.shape[1]) // 2)
|
171 |
+
img = img[margin:margin+img.shape[1]]
|
172 |
+
elif img.shape[1] > img.shape[0]:
|
173 |
+
margin = int((img.shape[1] - img.shape[0]) // 2)
|
174 |
+
img = img[:, margin:margin+img.shape[0]]
|
175 |
+
|
176 |
+
img = Image.fromarray(np.uint8(img[:, :, :3] * 255.))
|
177 |
+
if crop_idx:
|
178 |
+
return img, crop_uv
|
179 |
+
return img
|
180 |
+
|
181 |
+
def center_crop(self, img, mask, mask_ratio=.8):
|
182 |
+
mask_uvs = np.vstack(np.nonzero(mask[:, :, -1] > 0.5))
|
183 |
+
min_uv, max_uv = np.min(mask_uvs, axis=-1), np.max(mask_uvs, axis=-1)
|
184 |
+
img = img + (mask[..., -1:] <= 0.5)
|
185 |
+
|
186 |
+
half_size = int(max(max_uv - min_uv) // 2)
|
187 |
+
crop_length = (max_uv - min_uv) // 2
|
188 |
+
center_uv = min_uv + crop_length
|
189 |
+
expand_hasl_size = int(half_size / mask_ratio)
|
190 |
+
size = expand_hasl_size * 2 + 1
|
191 |
+
|
192 |
+
img_new = np.ones((size, size, 3))
|
193 |
+
img_new[expand_hasl_size-crop_length[0]:expand_hasl_size+crop_length[0]+1, expand_hasl_size-crop_length[1]:expand_hasl_size+crop_length[1]+1] = \
|
194 |
+
img[center_uv[0]-crop_length[0]:center_uv[0]+crop_length[0]+1, center_uv[1]-crop_length[1]:center_uv[1]+crop_length[1]+1]
|
195 |
+
crop_uv = np.array([expand_hasl_size, crop_length[0], crop_length[1], center_uv[0], center_uv[1], size], dtype=int)
|
196 |
+
return img_new, crop_uv
|
197 |
+
|
198 |
+
def transform_normal(self, normal_input, cam):
|
199 |
+
# load camera
|
200 |
+
img_mask = torch.linalg.norm(normal_input, dim=-1) > 1.5
|
201 |
+
extrinsic, K = cam
|
202 |
+
extrinsic = np.concatenate([extrinsic, np.zeros(4).reshape(1, 4)], axis=0)
|
203 |
+
extrinsic[3, 3] = 1
|
204 |
+
pose = np.linalg.inv(extrinsic)
|
205 |
+
temp = pose[1] + 0.0
|
206 |
+
pose[1] = -pose[2]
|
207 |
+
pose[2] = temp
|
208 |
+
extrinsic = torch.from_numpy(np.linalg.inv(pose)).float()
|
209 |
+
|
210 |
+
# to normal
|
211 |
+
normal_img = extrinsic[None, :3, :3] @ normal_input[..., :3].reshape(-1, 3, 1)
|
212 |
+
normal_img = normal_img.reshape(normal_input.shape[0], normal_input.shape[1], 3)
|
213 |
+
|
214 |
+
normal_img[img_mask] = 1.0
|
215 |
+
return normal_img
|
216 |
+
|
217 |
+
def parse_item(self, target_im, cond_img, normal_img, filename, target_ids, **args):
|
218 |
+
data = {}
|
219 |
+
|
220 |
+
# we need to transform normal to cmaera frame
|
221 |
+
if self.target_name == "normal":
|
222 |
+
target_im = self.transform_normal(target_im, self.get_camera(filename, **args))
|
223 |
+
|
224 |
+
# normal conditioning
|
225 |
+
if self.condition_name == "normal":
|
226 |
+
normal_img = self.transform_normal(normal_img, self.get_camera(filename, **args))
|
227 |
+
|
228 |
+
data["image_target"] = target_im
|
229 |
+
data["image_cond"] = cond_img
|
230 |
+
if self.condition_name == "normal":
|
231 |
+
data["img_normal"] = normal_img
|
232 |
+
|
233 |
+
if self.test or self.return_paths:
|
234 |
+
data["path"] = str(filename)
|
235 |
+
|
236 |
+
data["label"] = torch.zeros(1).reshape(1, 1, 1)+target_ids
|
237 |
+
|
238 |
+
if self.postprocess is not None:
|
239 |
+
data = self.postprocess(data)
|
240 |
+
return data
|
241 |
+
|
242 |
+
def normalized_read(self, imgpath):
|
243 |
+
img = np.array(imageio.imread(imgpath))
|
244 |
+
if img.dtype == np.uint8:
|
245 |
+
img = img / 255.0
|
246 |
+
else:
|
247 |
+
img = img ** (1 / 2.2)
|
248 |
+
return img
|
249 |
+
|
250 |
+
def process_im(self, im):
|
251 |
+
im = Image.fromarray(im)
|
252 |
+
im = im.convert("RGB")
|
253 |
+
return self.tform(im)
|
254 |
+
|
255 |
+
|
256 |
+
class ObjaverseDecoerWDS(ObjaverseDataDecoder):
|
257 |
+
def __init__(self, **kargs) -> None:
|
258 |
+
super().__init__(**kargs)
|
259 |
+
|
260 |
+
def dict2tuple(self, data):
|
261 |
+
returns = (data["image_target"], data["image_cond"],data["label"],)
|
262 |
+
if self.condition_name == "normal":
|
263 |
+
returns +=(data["img_normal"], )
|
264 |
+
if self.test or self.return_paths:
|
265 |
+
returns += (data["path"],)
|
266 |
+
return returns
|
267 |
+
|
268 |
+
def tuple2dict(self, data):
|
269 |
+
returns = {}
|
270 |
+
returns["image_target"] = data[0]
|
271 |
+
returns["image_cond"] = data[1]
|
272 |
+
returns["label"] = data[2]
|
273 |
+
|
274 |
+
if self.condition_name == "normal":
|
275 |
+
returns["img_normal"] = data[3]
|
276 |
+
|
277 |
+
if self.test or self.return_paths:
|
278 |
+
returns["path"] = data[-1]
|
279 |
+
|
280 |
+
return returns
|
281 |
+
|
282 |
+
def data_filter(self, albedo, spec, diffuse_shad, spec_shad):
|
283 |
+
returns = {}
|
284 |
+
returns["image_target"] = data[0]
|
285 |
+
returns["image_cond"] = data[1]
|
286 |
+
if self.condition_name == "normal":
|
287 |
+
returns["img_normal"] = data[2]
|
288 |
+
|
289 |
+
if self.test or self.return_paths:
|
290 |
+
returns["path"] = data[-1]
|
291 |
+
|
292 |
+
return returns
|
293 |
+
|
294 |
+
def get_camera(self, input_filename, sample):
|
295 |
+
camera_file = input_filename.replace(f'{self.target_name}0001', \
|
296 |
+
'camera').rsplit(".")[0] + ".pkl"
|
297 |
+
mask_filename_byte = io.BytesIO(sample[camera_file])
|
298 |
+
cam = pickle.load(mask_filename_byte)
|
299 |
+
return cam
|
300 |
+
|
301 |
+
def process_sample(self, sample):
|
302 |
+
# start_worker=time.time()
|
303 |
+
results = []
|
304 |
+
for target_ids, target_name in enumerate(self.target_name_pool):
|
305 |
+
_result = self.process_sample_single(sample, target_ids, target_name)
|
306 |
+
results.append(self.dict2tuple(_result))
|
307 |
+
results = wds.filters.default_collation_fn(results)
|
308 |
+
return results
|
309 |
+
|
310 |
+
def batch_reordering(self, sample):
|
311 |
+
batch_splits = []
|
312 |
+
for data_idx, _ in enumerate(sample):
|
313 |
+
batch_splits.append(
|
314 |
+
torch.cat(
|
315 |
+
torch.chunk(sample[data_idx], dim=1,
|
316 |
+
chunks=len(self.target_name_pool)),
|
317 |
+
dim=0)[:,0]
|
318 |
+
)
|
319 |
+
return self.tuple2dict(batch_splits)
|
320 |
+
|
321 |
+
def process_sample_single(self, sample, target_ids, target_name):
|
322 |
+
|
323 |
+
# get target image filename
|
324 |
+
self.target_name = target_name
|
325 |
+
target_file_name = self.target_name
|
326 |
+
if self.target_name=="gloss_shaded":
|
327 |
+
target_file_name = "gloss_direct"
|
328 |
+
elif self.target_name=="diffuse_shaded":
|
329 |
+
target_file_name = "diffuse_direct"
|
330 |
+
|
331 |
+
for k in list(sample.keys()):
|
332 |
+
if target_file_name not in k:
|
333 |
+
continue
|
334 |
+
target_key = k
|
335 |
+
break
|
336 |
+
|
337 |
+
# ##############
|
338 |
+
# prev_time = start_worker
|
339 |
+
# current_time = time.time()
|
340 |
+
# print(f"find target takes: {current_time - prev_time}")
|
341 |
+
# ##############
|
342 |
+
|
343 |
+
filename, condition_filename, \
|
344 |
+
mask_filename, normal_condition_filename, filename_targets = self.path_parsing(target_key, "")
|
345 |
+
|
346 |
+
# get file streams
|
347 |
+
if filename_targets is None:
|
348 |
+
filename_byte = io.BytesIO(sample[filename])
|
349 |
+
else:
|
350 |
+
filename_byte = [io.BytesIO(sample[filename_target]) for filename_target in filename_targets]
|
351 |
+
condition_filename_byte = io.BytesIO(sample[condition_filename])
|
352 |
+
normal_condition_filename_byte = io.BytesIO(sample[normal_condition_filename]) \
|
353 |
+
if self.condition_name == "normal" else None
|
354 |
+
mask_filename_byte = io.BytesIO(sample[mask_filename])
|
355 |
+
|
356 |
+
# image reading
|
357 |
+
target_im, cond_im, normal_img = self.read_images(filename_byte,
|
358 |
+
condition_filename_byte, normal_condition_filename_byte)
|
359 |
+
|
360 |
+
# mask reading
|
361 |
+
img_mask = np.array(self.normalized_read(mask_filename_byte))
|
362 |
+
|
363 |
+
# post processing
|
364 |
+
target_im, cond_im, normal_img, _ = self.image_post_processing(img_mask, target_im, cond_im, normal_img)
|
365 |
+
|
366 |
+
# transform
|
367 |
+
target_im = self.process_im(target_im)
|
368 |
+
cond_im = self.process_im(cond_im)
|
369 |
+
normal_img = self.process_im(normal_img) \
|
370 |
+
if self.condition_name == "normal" \
|
371 |
+
else None
|
372 |
+
|
373 |
+
data = self.parse_item(target_im, cond_im, normal_img, filename, target_ids, sample=sample)
|
374 |
+
# override for file path
|
375 |
+
if self.test or self.return_paths:
|
376 |
+
data["path"] = sample["__key__"]
|
377 |
+
|
378 |
+
result = dict(__key__=sample["__key__"])
|
379 |
+
result.update(data)
|
380 |
+
return result
|
381 |
+
|
382 |
+
|
383 |
+
if __name__=="__main__":
|
384 |
+
from torchvision import transforms
|
385 |
+
from einops import rearrange
|
386 |
+
torch.distributed.init_process_group(backend="nccl")
|
387 |
+
image_transforms = [transforms.ToTensor(),
|
388 |
+
transforms.Lambda(lambda x: rearrange(x * 2. - 1., 'c h w -> h w c'))]
|
389 |
+
image_transforms = torchvision.transforms.Compose(image_transforms)
|
390 |
+
image_transforms = {
|
391 |
+
"size": 256,
|
392 |
+
"totensor": image_transforms
|
393 |
+
}
|
394 |
+
|
395 |
+
data_list_dir = "/home/chenxi/code/material-diffusion/data/big_data_lists"
|
396 |
+
tar_name_list = sorted(os.listdir(data_list_dir))[1:4]
|
397 |
+
tar_list = [_name.rsplit("_num")[0]+".tar" for _name in tar_name_list]
|
398 |
+
tar_dir = "/home/chenxi/code/material-diffusion/data/big_data_transed"
|
399 |
+
tars = [os.path.join(tar_dir, _name) for _name in tar_list]
|
400 |
+
dataset_size = 0
|
401 |
+
imgperobj = 10
|
402 |
+
print("list dirs...")
|
403 |
+
for _name in tar_name_list:
|
404 |
+
num_obj = int(_name.rsplit("_num_")[1].rsplit(".")[0])
|
405 |
+
print(num_obj, " : ", _name)
|
406 |
+
dataset_size += num_obj * imgperobj
|
407 |
+
|
408 |
+
decoder = ObjaverseDecoerWDS(image_transforms=image_transforms,
|
409 |
+
return_paths=True)
|
410 |
+
batch_size = 8
|
411 |
+
|
412 |
+
print('============= length of training dataset %d =============' % (dataset_size // batch_size // 2))
|
413 |
+
dataset = (wds.WebDataset(tars,
|
414 |
+
repeat=0,
|
415 |
+
nodesplitter=wds.shardlists.split_by_node)
|
416 |
+
.shuffle(100)
|
417 |
+
.map(decoder.process_sample)
|
418 |
+
.map(decoder.dict2tuple)
|
419 |
+
.batched(batch_size, partial=False)
|
420 |
+
.map(decoder.tuple2dict)
|
421 |
+
.with_epoch(dataset_size // batch_size // 2)
|
422 |
+
.with_length(dataset_size // batch_size)
|
423 |
+
)
|
424 |
+
from torch.utils.data import DataLoader
|
425 |
+
# loader = DataLoader(dataset, batch_size=None, num_workers=8, shuffle=False)
|
426 |
+
loader = (wds.WebLoader(dataset, batch_size=None, num_workers=2, shuffle=False)
|
427 |
+
.map(decoder.dict2tuple)
|
428 |
+
.unbatched()
|
429 |
+
# .shuffle(100)
|
430 |
+
.batched(batch_size)
|
431 |
+
.map(decoder.tuple2dict)
|
432 |
+
)
|
433 |
+
|
434 |
+
|
435 |
+
print("# loader length", len(dataset))
|
436 |
+
|
437 |
+
for epoch in range(2):
|
438 |
+
ind = -1
|
439 |
+
for sample in loader:
|
440 |
+
assert "image_target" in sample
|
441 |
+
assert "image_cond" in sample
|
442 |
+
assert "path" in sample
|
443 |
+
ind += 1
|
444 |
+
if ind != 0:
|
445 |
+
continue
|
446 |
+
|
447 |
+
# replace to this for file path
|
448 |
+
# worker_info = torch.utils.data.get_worker_info()
|
449 |
+
# if worker_info is not None:
|
450 |
+
# worker = worker_info.id
|
451 |
+
# num_workers = worker_info.num_workers
|
452 |
+
# data["path"] = sample["__url__"]+"--"+sample["__key__"] +f".{worker}/{num_workers}"
|
453 |
+
|
454 |
+
# print(f"{ind}: shape {sample['image_target'].shape} {sample['path'][0].rsplit('/', 1)[-2]}")
|
455 |
+
print("##############")
|
456 |
+
for i in range(len(sample['path'])):
|
457 |
+
print(f"epoch {epoch}, it {ind}: shape {sample['image_target'].shape} {sample['path'][i].rsplit('--', 1)[0].rsplit('/', 2)[-1]} {sample['path'][i].rsplit('--', 1)[1].rsplit('/', 3)[-3]} {sample['path'][i].rsplit('--', 1)[1].rsplit('/',4)[-4]} {sample['path'][i].rsplit('.', 1)[-1]} rank: {dist.get_rank()}")
|
458 |
+
print("##############")
|
459 |
+
|
460 |
+
|
461 |
+
print(sample["path"])
|
462 |
+
|
463 |
+
print(sample["path"])
|
464 |
+
|
465 |
+
print(f"NUmber of samples: {ind} {dataset_size} {len(dataset)} rank: {dist.get_rank()}")
|
466 |
+
# 1. Remember samples are batched inside each worker, the outside data loader only sees one sample
|
467 |
+
# 2. All batch, epoch, and length settings are only visible within each worker
|
468 |
+
# 3. Unbatch and Suffle and then re-batch in loader result in between worker shuffle.
|
469 |
+
# This also allows to control of loader batching and worker batching for CPU optimization of worker-loader data transfer.
|
470 |
+
# https://github.com/webdataset/webdataset/issues/141#issuecomment-1043190147
|
471 |
+
# 4. It seems that data just repeat forever to satisfy with_epoch
|
472 |
+
# 5. Torch datalogger requires the dataset to have a len() method, which is used to schdule sample idx
|
473 |
+
# 6. DDP sampler will return its only length
|
474 |
+
# 7. WebLoader does not need length, it only raises the end of the iteration when data is running out
|
475 |
+
# 8. How does torch loader deal with datasets with fewer sizes than claims?
|
476 |
+
# 9. Set epoch will make sampling start from the beginning when a new epoch starts. Observed by disable shuffle and one batch repeat
|
477 |
+
# And each epoch will have a different sampling seed
|
478 |
+
# 10. DataLoader with IterableDataset: expected unspecified sampler option. DDP sampler will not be usable.
|
479 |
+
# !0. In summary:
|
480 |
+
# For ddp multi-worker training, the worker splitter and node splitter will make sure tars are splitted into each worker
|
481 |
+
# We have to manually adjust with_epoch with respect to num_worker and num_node and batch_size
|
482 |
+
|
483 |
+
def nodesplitter(src, group=None):
|
484 |
+
if torch.distributed.is_initialized():
|
485 |
+
if group is None:
|
486 |
+
group = torch.distributed.group.WORLD
|
487 |
+
rank = torch.distributed.get_rank(group=group)
|
488 |
+
size = torch.distributed.get_world_size(group=group)
|
489 |
+
print(f"nodesplitter: rank={rank} size={size}")
|
490 |
+
count = 0
|
491 |
+
for i, item in enumerate(src):
|
492 |
+
if i % size == rank:
|
493 |
+
yield item
|
494 |
+
count += 1
|
495 |
+
print(f"nodesplitter: rank={rank} size={size} count={count} DONE")
|
496 |
+
else:
|
497 |
+
yield from src
|
models/ldm/data/dummy.py
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import random
|
3 |
+
import string
|
4 |
+
from torch.utils.data import Dataset, Subset
|
5 |
+
|
6 |
+
class DummyData(Dataset):
|
7 |
+
def __init__(self, length, size):
|
8 |
+
self.length = length
|
9 |
+
self.size = size
|
10 |
+
|
11 |
+
def __len__(self):
|
12 |
+
return self.length
|
13 |
+
|
14 |
+
def __getitem__(self, i):
|
15 |
+
x = np.random.randn(*self.size)
|
16 |
+
letters = string.ascii_lowercase
|
17 |
+
y = ''.join(random.choice(string.ascii_lowercase) for i in range(10))
|
18 |
+
return {"jpg": x, "txt": y}
|
19 |
+
|
20 |
+
|
21 |
+
class DummyDataWithEmbeddings(Dataset):
|
22 |
+
def __init__(self, length, size, emb_size):
|
23 |
+
self.length = length
|
24 |
+
self.size = size
|
25 |
+
self.emb_size = emb_size
|
26 |
+
|
27 |
+
def __len__(self):
|
28 |
+
return self.length
|
29 |
+
|
30 |
+
def __getitem__(self, i):
|
31 |
+
x = np.random.randn(*self.size)
|
32 |
+
y = np.random.randn(*self.emb_size).astype(np.float32)
|
33 |
+
return {"jpg": x, "txt": y}
|
34 |
+
|
models/ldm/data/imagenet.py
ADDED
@@ -0,0 +1,394 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os, yaml, pickle, shutil, tarfile, glob
|
2 |
+
import cv2
|
3 |
+
import albumentations
|
4 |
+
import PIL
|
5 |
+
import numpy as np
|
6 |
+
import torchvision.transforms.functional as TF
|
7 |
+
from omegaconf import OmegaConf
|
8 |
+
from functools import partial
|
9 |
+
from PIL import Image
|
10 |
+
from tqdm import tqdm
|
11 |
+
from torch.utils.data import Dataset, Subset
|
12 |
+
|
13 |
+
import taming.data.utils as tdu
|
14 |
+
from taming.data.imagenet import str_to_indices, give_synsets_from_indices, download, retrieve
|
15 |
+
from taming.data.imagenet import ImagePaths
|
16 |
+
|
17 |
+
from ldm.modules.image_degradation import degradation_fn_bsr, degradation_fn_bsr_light
|
18 |
+
|
19 |
+
|
20 |
+
def synset2idx(path_to_yaml="data/index_synset.yaml"):
|
21 |
+
with open(path_to_yaml) as f:
|
22 |
+
di2s = yaml.load(f)
|
23 |
+
return dict((v,k) for k,v in di2s.items())
|
24 |
+
|
25 |
+
|
26 |
+
class ImageNetBase(Dataset):
|
27 |
+
def __init__(self, config=None):
|
28 |
+
self.config = config or OmegaConf.create()
|
29 |
+
if not type(self.config)==dict:
|
30 |
+
self.config = OmegaConf.to_container(self.config)
|
31 |
+
self.keep_orig_class_label = self.config.get("keep_orig_class_label", False)
|
32 |
+
self.process_images = True # if False we skip loading & processing images and self.data contains filepaths
|
33 |
+
self._prepare()
|
34 |
+
self._prepare_synset_to_human()
|
35 |
+
self._prepare_idx_to_synset()
|
36 |
+
self._prepare_human_to_integer_label()
|
37 |
+
self._load()
|
38 |
+
|
39 |
+
def __len__(self):
|
40 |
+
return len(self.data)
|
41 |
+
|
42 |
+
def __getitem__(self, i):
|
43 |
+
return self.data[i]
|
44 |
+
|
45 |
+
def _prepare(self):
|
46 |
+
raise NotImplementedError()
|
47 |
+
|
48 |
+
def _filter_relpaths(self, relpaths):
|
49 |
+
ignore = set([
|
50 |
+
"n06596364_9591.JPEG",
|
51 |
+
])
|
52 |
+
relpaths = [rpath for rpath in relpaths if not rpath.split("/")[-1] in ignore]
|
53 |
+
if "sub_indices" in self.config:
|
54 |
+
indices = str_to_indices(self.config["sub_indices"])
|
55 |
+
synsets = give_synsets_from_indices(indices, path_to_yaml=self.idx2syn) # returns a list of strings
|
56 |
+
self.synset2idx = synset2idx(path_to_yaml=self.idx2syn)
|
57 |
+
files = []
|
58 |
+
for rpath in relpaths:
|
59 |
+
syn = rpath.split("/")[0]
|
60 |
+
if syn in synsets:
|
61 |
+
files.append(rpath)
|
62 |
+
return files
|
63 |
+
else:
|
64 |
+
return relpaths
|
65 |
+
|
66 |
+
def _prepare_synset_to_human(self):
|
67 |
+
SIZE = 2655750
|
68 |
+
URL = "https://heibox.uni-heidelberg.de/f/9f28e956cd304264bb82/?dl=1"
|
69 |
+
self.human_dict = os.path.join(self.root, "synset_human.txt")
|
70 |
+
if (not os.path.exists(self.human_dict) or
|
71 |
+
not os.path.getsize(self.human_dict)==SIZE):
|
72 |
+
download(URL, self.human_dict)
|
73 |
+
|
74 |
+
def _prepare_idx_to_synset(self):
|
75 |
+
URL = "https://heibox.uni-heidelberg.de/f/d835d5b6ceda4d3aa910/?dl=1"
|
76 |
+
self.idx2syn = os.path.join(self.root, "index_synset.yaml")
|
77 |
+
if (not os.path.exists(self.idx2syn)):
|
78 |
+
download(URL, self.idx2syn)
|
79 |
+
|
80 |
+
def _prepare_human_to_integer_label(self):
|
81 |
+
URL = "https://heibox.uni-heidelberg.de/f/2362b797d5be43b883f6/?dl=1"
|
82 |
+
self.human2integer = os.path.join(self.root, "imagenet1000_clsidx_to_labels.txt")
|
83 |
+
if (not os.path.exists(self.human2integer)):
|
84 |
+
download(URL, self.human2integer)
|
85 |
+
with open(self.human2integer, "r") as f:
|
86 |
+
lines = f.read().splitlines()
|
87 |
+
assert len(lines) == 1000
|
88 |
+
self.human2integer_dict = dict()
|
89 |
+
for line in lines:
|
90 |
+
value, key = line.split(":")
|
91 |
+
self.human2integer_dict[key] = int(value)
|
92 |
+
|
93 |
+
def _load(self):
|
94 |
+
with open(self.txt_filelist, "r") as f:
|
95 |
+
self.relpaths = f.read().splitlines()
|
96 |
+
l1 = len(self.relpaths)
|
97 |
+
self.relpaths = self._filter_relpaths(self.relpaths)
|
98 |
+
print("Removed {} files from filelist during filtering.".format(l1 - len(self.relpaths)))
|
99 |
+
|
100 |
+
self.synsets = [p.split("/")[0] for p in self.relpaths]
|
101 |
+
self.abspaths = [os.path.join(self.datadir, p) for p in self.relpaths]
|
102 |
+
|
103 |
+
unique_synsets = np.unique(self.synsets)
|
104 |
+
class_dict = dict((synset, i) for i, synset in enumerate(unique_synsets))
|
105 |
+
if not self.keep_orig_class_label:
|
106 |
+
self.class_labels = [class_dict[s] for s in self.synsets]
|
107 |
+
else:
|
108 |
+
self.class_labels = [self.synset2idx[s] for s in self.synsets]
|
109 |
+
|
110 |
+
with open(self.human_dict, "r") as f:
|
111 |
+
human_dict = f.read().splitlines()
|
112 |
+
human_dict = dict(line.split(maxsplit=1) for line in human_dict)
|
113 |
+
|
114 |
+
self.human_labels = [human_dict[s] for s in self.synsets]
|
115 |
+
|
116 |
+
labels = {
|
117 |
+
"relpath": np.array(self.relpaths),
|
118 |
+
"synsets": np.array(self.synsets),
|
119 |
+
"class_label": np.array(self.class_labels),
|
120 |
+
"human_label": np.array(self.human_labels),
|
121 |
+
}
|
122 |
+
|
123 |
+
if self.process_images:
|
124 |
+
self.size = retrieve(self.config, "size", default=256)
|
125 |
+
self.data = ImagePaths(self.abspaths,
|
126 |
+
labels=labels,
|
127 |
+
size=self.size,
|
128 |
+
random_crop=self.random_crop,
|
129 |
+
)
|
130 |
+
else:
|
131 |
+
self.data = self.abspaths
|
132 |
+
|
133 |
+
|
134 |
+
class ImageNetTrain(ImageNetBase):
|
135 |
+
NAME = "ILSVRC2012_train"
|
136 |
+
URL = "http://www.image-net.org/challenges/LSVRC/2012/"
|
137 |
+
AT_HASH = "a306397ccf9c2ead27155983c254227c0fd938e2"
|
138 |
+
FILES = [
|
139 |
+
"ILSVRC2012_img_train.tar",
|
140 |
+
]
|
141 |
+
SIZES = [
|
142 |
+
147897477120,
|
143 |
+
]
|
144 |
+
|
145 |
+
def __init__(self, process_images=True, data_root=None, **kwargs):
|
146 |
+
self.process_images = process_images
|
147 |
+
self.data_root = data_root
|
148 |
+
super().__init__(**kwargs)
|
149 |
+
|
150 |
+
def _prepare(self):
|
151 |
+
if self.data_root:
|
152 |
+
self.root = os.path.join(self.data_root, self.NAME)
|
153 |
+
else:
|
154 |
+
cachedir = os.environ.get("XDG_CACHE_HOME", os.path.expanduser("~/.cache"))
|
155 |
+
self.root = os.path.join(cachedir, "autoencoders/data", self.NAME)
|
156 |
+
|
157 |
+
self.datadir = os.path.join(self.root, "data")
|
158 |
+
self.txt_filelist = os.path.join(self.root, "filelist.txt")
|
159 |
+
self.expected_length = 1281167
|
160 |
+
self.random_crop = retrieve(self.config, "ImageNetTrain/random_crop",
|
161 |
+
default=True)
|
162 |
+
if not tdu.is_prepared(self.root):
|
163 |
+
# prep
|
164 |
+
print("Preparing dataset {} in {}".format(self.NAME, self.root))
|
165 |
+
|
166 |
+
datadir = self.datadir
|
167 |
+
if not os.path.exists(datadir):
|
168 |
+
path = os.path.join(self.root, self.FILES[0])
|
169 |
+
if not os.path.exists(path) or not os.path.getsize(path)==self.SIZES[0]:
|
170 |
+
import academictorrents as at
|
171 |
+
atpath = at.get(self.AT_HASH, datastore=self.root)
|
172 |
+
assert atpath == path
|
173 |
+
|
174 |
+
print("Extracting {} to {}".format(path, datadir))
|
175 |
+
os.makedirs(datadir, exist_ok=True)
|
176 |
+
with tarfile.open(path, "r:") as tar:
|
177 |
+
tar.extractall(path=datadir)
|
178 |
+
|
179 |
+
print("Extracting sub-tars.")
|
180 |
+
subpaths = sorted(glob.glob(os.path.join(datadir, "*.tar")))
|
181 |
+
for subpath in tqdm(subpaths):
|
182 |
+
subdir = subpath[:-len(".tar")]
|
183 |
+
os.makedirs(subdir, exist_ok=True)
|
184 |
+
with tarfile.open(subpath, "r:") as tar:
|
185 |
+
tar.extractall(path=subdir)
|
186 |
+
|
187 |
+
filelist = glob.glob(os.path.join(datadir, "**", "*.JPEG"))
|
188 |
+
filelist = [os.path.relpath(p, start=datadir) for p in filelist]
|
189 |
+
filelist = sorted(filelist)
|
190 |
+
filelist = "\n".join(filelist)+"\n"
|
191 |
+
with open(self.txt_filelist, "w") as f:
|
192 |
+
f.write(filelist)
|
193 |
+
|
194 |
+
tdu.mark_prepared(self.root)
|
195 |
+
|
196 |
+
|
197 |
+
class ImageNetValidation(ImageNetBase):
|
198 |
+
NAME = "ILSVRC2012_validation"
|
199 |
+
URL = "http://www.image-net.org/challenges/LSVRC/2012/"
|
200 |
+
AT_HASH = "5d6d0df7ed81efd49ca99ea4737e0ae5e3a5f2e5"
|
201 |
+
VS_URL = "https://heibox.uni-heidelberg.de/f/3e0f6e9c624e45f2bd73/?dl=1"
|
202 |
+
FILES = [
|
203 |
+
"ILSVRC2012_img_val.tar",
|
204 |
+
"validation_synset.txt",
|
205 |
+
]
|
206 |
+
SIZES = [
|
207 |
+
6744924160,
|
208 |
+
1950000,
|
209 |
+
]
|
210 |
+
|
211 |
+
def __init__(self, process_images=True, data_root=None, **kwargs):
|
212 |
+
self.data_root = data_root
|
213 |
+
self.process_images = process_images
|
214 |
+
super().__init__(**kwargs)
|
215 |
+
|
216 |
+
def _prepare(self):
|
217 |
+
if self.data_root:
|
218 |
+
self.root = os.path.join(self.data_root, self.NAME)
|
219 |
+
else:
|
220 |
+
cachedir = os.environ.get("XDG_CACHE_HOME", os.path.expanduser("~/.cache"))
|
221 |
+
self.root = os.path.join(cachedir, "autoencoders/data", self.NAME)
|
222 |
+
self.datadir = os.path.join(self.root, "data")
|
223 |
+
self.txt_filelist = os.path.join(self.root, "filelist.txt")
|
224 |
+
self.expected_length = 50000
|
225 |
+
self.random_crop = retrieve(self.config, "ImageNetValidation/random_crop",
|
226 |
+
default=False)
|
227 |
+
if not tdu.is_prepared(self.root):
|
228 |
+
# prep
|
229 |
+
print("Preparing dataset {} in {}".format(self.NAME, self.root))
|
230 |
+
|
231 |
+
datadir = self.datadir
|
232 |
+
if not os.path.exists(datadir):
|
233 |
+
path = os.path.join(self.root, self.FILES[0])
|
234 |
+
if not os.path.exists(path) or not os.path.getsize(path)==self.SIZES[0]:
|
235 |
+
import academictorrents as at
|
236 |
+
atpath = at.get(self.AT_HASH, datastore=self.root)
|
237 |
+
assert atpath == path
|
238 |
+
|
239 |
+
print("Extracting {} to {}".format(path, datadir))
|
240 |
+
os.makedirs(datadir, exist_ok=True)
|
241 |
+
with tarfile.open(path, "r:") as tar:
|
242 |
+
tar.extractall(path=datadir)
|
243 |
+
|
244 |
+
vspath = os.path.join(self.root, self.FILES[1])
|
245 |
+
if not os.path.exists(vspath) or not os.path.getsize(vspath)==self.SIZES[1]:
|
246 |
+
download(self.VS_URL, vspath)
|
247 |
+
|
248 |
+
with open(vspath, "r") as f:
|
249 |
+
synset_dict = f.read().splitlines()
|
250 |
+
synset_dict = dict(line.split() for line in synset_dict)
|
251 |
+
|
252 |
+
print("Reorganizing into synset folders")
|
253 |
+
synsets = np.unique(list(synset_dict.values()))
|
254 |
+
for s in synsets:
|
255 |
+
os.makedirs(os.path.join(datadir, s), exist_ok=True)
|
256 |
+
for k, v in synset_dict.items():
|
257 |
+
src = os.path.join(datadir, k)
|
258 |
+
dst = os.path.join(datadir, v)
|
259 |
+
shutil.move(src, dst)
|
260 |
+
|
261 |
+
filelist = glob.glob(os.path.join(datadir, "**", "*.JPEG"))
|
262 |
+
filelist = [os.path.relpath(p, start=datadir) for p in filelist]
|
263 |
+
filelist = sorted(filelist)
|
264 |
+
filelist = "\n".join(filelist)+"\n"
|
265 |
+
with open(self.txt_filelist, "w") as f:
|
266 |
+
f.write(filelist)
|
267 |
+
|
268 |
+
tdu.mark_prepared(self.root)
|
269 |
+
|
270 |
+
|
271 |
+
|
272 |
+
class ImageNetSR(Dataset):
|
273 |
+
def __init__(self, size=None,
|
274 |
+
degradation=None, downscale_f=4, min_crop_f=0.5, max_crop_f=1.,
|
275 |
+
random_crop=True):
|
276 |
+
"""
|
277 |
+
Imagenet Superresolution Dataloader
|
278 |
+
Performs following ops in order:
|
279 |
+
1. crops a crop of size s from image either as random or center crop
|
280 |
+
2. resizes crop to size with cv2.area_interpolation
|
281 |
+
3. degrades resized crop with degradation_fn
|
282 |
+
|
283 |
+
:param size: resizing to size after cropping
|
284 |
+
:param degradation: degradation_fn, e.g. cv_bicubic or bsrgan_light
|
285 |
+
:param downscale_f: Low Resolution Downsample factor
|
286 |
+
:param min_crop_f: determines crop size s,
|
287 |
+
where s = c * min_img_side_len with c sampled from interval (min_crop_f, max_crop_f)
|
288 |
+
:param max_crop_f: ""
|
289 |
+
:param data_root:
|
290 |
+
:param random_crop:
|
291 |
+
"""
|
292 |
+
self.base = self.get_base()
|
293 |
+
assert size
|
294 |
+
assert (size / downscale_f).is_integer()
|
295 |
+
self.size = size
|
296 |
+
self.LR_size = int(size / downscale_f)
|
297 |
+
self.min_crop_f = min_crop_f
|
298 |
+
self.max_crop_f = max_crop_f
|
299 |
+
assert(max_crop_f <= 1.)
|
300 |
+
self.center_crop = not random_crop
|
301 |
+
|
302 |
+
self.image_rescaler = albumentations.SmallestMaxSize(max_size=size, interpolation=cv2.INTER_AREA)
|
303 |
+
|
304 |
+
self.pil_interpolation = False # gets reset later if incase interp_op is from pillow
|
305 |
+
|
306 |
+
if degradation == "bsrgan":
|
307 |
+
self.degradation_process = partial(degradation_fn_bsr, sf=downscale_f)
|
308 |
+
|
309 |
+
elif degradation == "bsrgan_light":
|
310 |
+
self.degradation_process = partial(degradation_fn_bsr_light, sf=downscale_f)
|
311 |
+
|
312 |
+
else:
|
313 |
+
interpolation_fn = {
|
314 |
+
"cv_nearest": cv2.INTER_NEAREST,
|
315 |
+
"cv_bilinear": cv2.INTER_LINEAR,
|
316 |
+
"cv_bicubic": cv2.INTER_CUBIC,
|
317 |
+
"cv_area": cv2.INTER_AREA,
|
318 |
+
"cv_lanczos": cv2.INTER_LANCZOS4,
|
319 |
+
"pil_nearest": PIL.Image.NEAREST,
|
320 |
+
"pil_bilinear": PIL.Image.BILINEAR,
|
321 |
+
"pil_bicubic": PIL.Image.BICUBIC,
|
322 |
+
"pil_box": PIL.Image.BOX,
|
323 |
+
"pil_hamming": PIL.Image.HAMMING,
|
324 |
+
"pil_lanczos": PIL.Image.LANCZOS,
|
325 |
+
}[degradation]
|
326 |
+
|
327 |
+
self.pil_interpolation = degradation.startswith("pil_")
|
328 |
+
|
329 |
+
if self.pil_interpolation:
|
330 |
+
self.degradation_process = partial(TF.resize, size=self.LR_size, interpolation=interpolation_fn)
|
331 |
+
|
332 |
+
else:
|
333 |
+
self.degradation_process = albumentations.SmallestMaxSize(max_size=self.LR_size,
|
334 |
+
interpolation=interpolation_fn)
|
335 |
+
|
336 |
+
def __len__(self):
|
337 |
+
return len(self.base)
|
338 |
+
|
339 |
+
def __getitem__(self, i):
|
340 |
+
example = self.base[i]
|
341 |
+
image = Image.open(example["file_path_"])
|
342 |
+
|
343 |
+
if not image.mode == "RGB":
|
344 |
+
image = image.convert("RGB")
|
345 |
+
|
346 |
+
image = np.array(image).astype(np.uint8)
|
347 |
+
|
348 |
+
min_side_len = min(image.shape[:2])
|
349 |
+
crop_side_len = min_side_len * np.random.uniform(self.min_crop_f, self.max_crop_f, size=None)
|
350 |
+
crop_side_len = int(crop_side_len)
|
351 |
+
|
352 |
+
if self.center_crop:
|
353 |
+
self.cropper = albumentations.CenterCrop(height=crop_side_len, width=crop_side_len)
|
354 |
+
|
355 |
+
else:
|
356 |
+
self.cropper = albumentations.RandomCrop(height=crop_side_len, width=crop_side_len)
|
357 |
+
|
358 |
+
image = self.cropper(image=image)["image"]
|
359 |
+
image = self.image_rescaler(image=image)["image"]
|
360 |
+
|
361 |
+
if self.pil_interpolation:
|
362 |
+
image_pil = PIL.Image.fromarray(image)
|
363 |
+
LR_image = self.degradation_process(image_pil)
|
364 |
+
LR_image = np.array(LR_image).astype(np.uint8)
|
365 |
+
|
366 |
+
else:
|
367 |
+
LR_image = self.degradation_process(image=image)["image"]
|
368 |
+
|
369 |
+
example["image"] = (image/127.5 - 1.0).astype(np.float32)
|
370 |
+
example["LR_image"] = (LR_image/127.5 - 1.0).astype(np.float32)
|
371 |
+
example["caption"] = example["human_label"] # dummy caption
|
372 |
+
return example
|
373 |
+
|
374 |
+
|
375 |
+
class ImageNetSRTrain(ImageNetSR):
|
376 |
+
def __init__(self, **kwargs):
|
377 |
+
super().__init__(**kwargs)
|
378 |
+
|
379 |
+
def get_base(self):
|
380 |
+
with open("data/imagenet_train_hr_indices.p", "rb") as f:
|
381 |
+
indices = pickle.load(f)
|
382 |
+
dset = ImageNetTrain(process_images=False,)
|
383 |
+
return Subset(dset, indices)
|
384 |
+
|
385 |
+
|
386 |
+
class ImageNetSRValidation(ImageNetSR):
|
387 |
+
def __init__(self, **kwargs):
|
388 |
+
super().__init__(**kwargs)
|
389 |
+
|
390 |
+
def get_base(self):
|
391 |
+
with open("data/imagenet_val_hr_indices.p", "rb") as f:
|
392 |
+
indices = pickle.load(f)
|
393 |
+
dset = ImageNetValidation(process_images=False,)
|
394 |
+
return Subset(dset, indices)
|
models/ldm/data/inpainting/__init__.py
ADDED
File without changes
|
models/ldm/data/inpainting/synthetic_mask.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from PIL import Image, ImageDraw
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
settings = {
|
5 |
+
"256narrow": {
|
6 |
+
"p_irr": 1,
|
7 |
+
"min_n_irr": 4,
|
8 |
+
"max_n_irr": 50,
|
9 |
+
"max_l_irr": 40,
|
10 |
+
"max_w_irr": 10,
|
11 |
+
"min_n_box": None,
|
12 |
+
"max_n_box": None,
|
13 |
+
"min_s_box": None,
|
14 |
+
"max_s_box": None,
|
15 |
+
"marg": None,
|
16 |
+
},
|
17 |
+
"256train": {
|
18 |
+
"p_irr": 0.5,
|
19 |
+
"min_n_irr": 1,
|
20 |
+
"max_n_irr": 5,
|
21 |
+
"max_l_irr": 200,
|
22 |
+
"max_w_irr": 100,
|
23 |
+
"min_n_box": 1,
|
24 |
+
"max_n_box": 4,
|
25 |
+
"min_s_box": 30,
|
26 |
+
"max_s_box": 150,
|
27 |
+
"marg": 10,
|
28 |
+
},
|
29 |
+
"512train": { # TODO: experimental
|
30 |
+
"p_irr": 0.5,
|
31 |
+
"min_n_irr": 1,
|
32 |
+
"max_n_irr": 5,
|
33 |
+
"max_l_irr": 450,
|
34 |
+
"max_w_irr": 250,
|
35 |
+
"min_n_box": 1,
|
36 |
+
"max_n_box": 4,
|
37 |
+
"min_s_box": 30,
|
38 |
+
"max_s_box": 300,
|
39 |
+
"marg": 10,
|
40 |
+
},
|
41 |
+
"512train-large": { # TODO: experimental
|
42 |
+
"p_irr": 0.5,
|
43 |
+
"min_n_irr": 1,
|
44 |
+
"max_n_irr": 5,
|
45 |
+
"max_l_irr": 450,
|
46 |
+
"max_w_irr": 400,
|
47 |
+
"min_n_box": 1,
|
48 |
+
"max_n_box": 4,
|
49 |
+
"min_s_box": 75,
|
50 |
+
"max_s_box": 450,
|
51 |
+
"marg": 10,
|
52 |
+
},
|
53 |
+
}
|
54 |
+
|
55 |
+
|
56 |
+
def gen_segment_mask(mask, start, end, brush_width):
|
57 |
+
mask = mask > 0
|
58 |
+
mask = (255 * mask).astype(np.uint8)
|
59 |
+
mask = Image.fromarray(mask)
|
60 |
+
draw = ImageDraw.Draw(mask)
|
61 |
+
draw.line([start, end], fill=255, width=brush_width, joint="curve")
|
62 |
+
mask = np.array(mask) / 255
|
63 |
+
return mask
|
64 |
+
|
65 |
+
|
66 |
+
def gen_box_mask(mask, masked):
|
67 |
+
x_0, y_0, w, h = masked
|
68 |
+
mask[y_0:y_0 + h, x_0:x_0 + w] = 1
|
69 |
+
return mask
|
70 |
+
|
71 |
+
|
72 |
+
def gen_round_mask(mask, masked, radius):
|
73 |
+
x_0, y_0, w, h = masked
|
74 |
+
xy = [(x_0, y_0), (x_0 + w, y_0 + w)]
|
75 |
+
|
76 |
+
mask = mask > 0
|
77 |
+
mask = (255 * mask).astype(np.uint8)
|
78 |
+
mask = Image.fromarray(mask)
|
79 |
+
draw = ImageDraw.Draw(mask)
|
80 |
+
draw.rounded_rectangle(xy, radius=radius, fill=255)
|
81 |
+
mask = np.array(mask) / 255
|
82 |
+
return mask
|
83 |
+
|
84 |
+
|
85 |
+
def gen_large_mask(prng, img_h, img_w,
|
86 |
+
marg, p_irr, min_n_irr, max_n_irr, max_l_irr, max_w_irr,
|
87 |
+
min_n_box, max_n_box, min_s_box, max_s_box):
|
88 |
+
"""
|
89 |
+
img_h: int, an image height
|
90 |
+
img_w: int, an image width
|
91 |
+
marg: int, a margin for a box starting coordinate
|
92 |
+
p_irr: float, 0 <= p_irr <= 1, a probability of a polygonal chain mask
|
93 |
+
|
94 |
+
min_n_irr: int, min number of segments
|
95 |
+
max_n_irr: int, max number of segments
|
96 |
+
max_l_irr: max length of a segment in polygonal chain
|
97 |
+
max_w_irr: max width of a segment in polygonal chain
|
98 |
+
|
99 |
+
min_n_box: int, min bound for the number of box primitives
|
100 |
+
max_n_box: int, max bound for the number of box primitives
|
101 |
+
min_s_box: int, min length of a box side
|
102 |
+
max_s_box: int, max length of a box side
|
103 |
+
"""
|
104 |
+
|
105 |
+
mask = np.zeros((img_h, img_w))
|
106 |
+
uniform = prng.randint
|
107 |
+
|
108 |
+
if np.random.uniform(0, 1) < p_irr: # generate polygonal chain
|
109 |
+
n = uniform(min_n_irr, max_n_irr) # sample number of segments
|
110 |
+
|
111 |
+
for _ in range(n):
|
112 |
+
y = uniform(0, img_h) # sample a starting point
|
113 |
+
x = uniform(0, img_w)
|
114 |
+
|
115 |
+
a = uniform(0, 360) # sample angle
|
116 |
+
l = uniform(10, max_l_irr) # sample segment length
|
117 |
+
w = uniform(5, max_w_irr) # sample a segment width
|
118 |
+
|
119 |
+
# draw segment starting from (x,y) to (x_,y_) using brush of width w
|
120 |
+
x_ = x + l * np.sin(a)
|
121 |
+
y_ = y + l * np.cos(a)
|
122 |
+
|
123 |
+
mask = gen_segment_mask(mask, start=(x, y), end=(x_, y_), brush_width=w)
|
124 |
+
x, y = x_, y_
|
125 |
+
else: # generate Box masks
|
126 |
+
n = uniform(min_n_box, max_n_box) # sample number of rectangles
|
127 |
+
|
128 |
+
for _ in range(n):
|
129 |
+
h = uniform(min_s_box, max_s_box) # sample box shape
|
130 |
+
w = uniform(min_s_box, max_s_box)
|
131 |
+
|
132 |
+
x_0 = uniform(marg, img_w - marg - w) # sample upper-left coordinates of box
|
133 |
+
y_0 = uniform(marg, img_h - marg - h)
|
134 |
+
|
135 |
+
if np.random.uniform(0, 1) < 0.5:
|
136 |
+
mask = gen_box_mask(mask, masked=(x_0, y_0, w, h))
|
137 |
+
else:
|
138 |
+
r = uniform(0, 60) # sample radius
|
139 |
+
mask = gen_round_mask(mask, masked=(x_0, y_0, w, h), radius=r)
|
140 |
+
return mask
|
141 |
+
|
142 |
+
|
143 |
+
make_lama_mask = lambda prng, h, w: gen_large_mask(prng, h, w, **settings["256train"])
|
144 |
+
make_narrow_lama_mask = lambda prng, h, w: gen_large_mask(prng, h, w, **settings["256narrow"])
|
145 |
+
make_512_lama_mask = lambda prng, h, w: gen_large_mask(prng, h, w, **settings["512train"])
|
146 |
+
make_512_lama_mask_large = lambda prng, h, w: gen_large_mask(prng, h, w, **settings["512train-large"])
|
147 |
+
|
148 |
+
|
149 |
+
MASK_MODES = {
|
150 |
+
"256train": make_lama_mask,
|
151 |
+
"256narrow": make_narrow_lama_mask,
|
152 |
+
"512train": make_512_lama_mask,
|
153 |
+
"512train-large": make_512_lama_mask_large
|
154 |
+
}
|
155 |
+
|
156 |
+
if __name__ == "__main__":
|
157 |
+
import sys
|
158 |
+
|
159 |
+
out = sys.argv[1]
|
160 |
+
|
161 |
+
prng = np.random.RandomState(1)
|
162 |
+
kwargs = settings["256train"]
|
163 |
+
mask = gen_large_mask(prng, 256, 256, **kwargs)
|
164 |
+
mask = (255 * mask).astype(np.uint8)
|
165 |
+
mask = Image.fromarray(mask)
|
166 |
+
mask.save(out)
|
models/ldm/data/laion.py
ADDED
@@ -0,0 +1,537 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import webdataset as wds
|
2 |
+
import kornia
|
3 |
+
from PIL import Image
|
4 |
+
import io
|
5 |
+
import os
|
6 |
+
import torchvision
|
7 |
+
from PIL import Image
|
8 |
+
import glob
|
9 |
+
import random
|
10 |
+
import numpy as np
|
11 |
+
import pytorch_lightning as pl
|
12 |
+
from tqdm import tqdm
|
13 |
+
from omegaconf import OmegaConf
|
14 |
+
from einops import rearrange
|
15 |
+
import torch
|
16 |
+
from webdataset.handlers import warn_and_continue
|
17 |
+
|
18 |
+
|
19 |
+
from ldm.util import instantiate_from_config
|
20 |
+
from ldm.data.inpainting.synthetic_mask import gen_large_mask, MASK_MODES
|
21 |
+
from ldm.data.base import PRNGMixin
|
22 |
+
|
23 |
+
|
24 |
+
class DataWithWings(torch.utils.data.IterableDataset):
|
25 |
+
def __init__(self, min_size, transform=None, target_transform=None):
|
26 |
+
self.min_size = min_size
|
27 |
+
self.transform = transform if transform is not None else nn.Identity()
|
28 |
+
self.target_transform = target_transform if target_transform is not None else nn.Identity()
|
29 |
+
self.kv = OnDiskKV(file='/home/ubuntu/laion5B-watermark-safety-ordered', key_format='q', value_format='ee')
|
30 |
+
self.kv_aesthetic = OnDiskKV(file='/home/ubuntu/laion5B-aesthetic-tags-kv', key_format='q', value_format='e')
|
31 |
+
self.pwatermark_threshold = 0.8
|
32 |
+
self.punsafe_threshold = 0.5
|
33 |
+
self.aesthetic_threshold = 5.
|
34 |
+
self.total_samples = 0
|
35 |
+
self.samples = 0
|
36 |
+
location = 'pipe:aws s3 cp --quiet s3://s-datasets/laion5b/laion2B-data/{000000..231349}.tar -'
|
37 |
+
|
38 |
+
self.inner_dataset = wds.DataPipeline(
|
39 |
+
wds.ResampledShards(location),
|
40 |
+
wds.tarfile_to_samples(handler=wds.warn_and_continue),
|
41 |
+
wds.shuffle(1000, handler=wds.warn_and_continue),
|
42 |
+
wds.decode('pilrgb', handler=wds.warn_and_continue),
|
43 |
+
wds.map(self._add_tags, handler=wds.ignore_and_continue),
|
44 |
+
wds.select(self._filter_predicate),
|
45 |
+
wds.map_dict(jpg=self.transform, txt=self.target_transform, punsafe=self._punsafe_to_class, handler=wds.warn_and_continue),
|
46 |
+
wds.to_tuple('jpg', 'txt', 'punsafe', handler=wds.warn_and_continue),
|
47 |
+
)
|
48 |
+
|
49 |
+
@staticmethod
|
50 |
+
def _compute_hash(url, text):
|
51 |
+
if url is None:
|
52 |
+
url = ''
|
53 |
+
if text is None:
|
54 |
+
text = ''
|
55 |
+
total = (url + text).encode('utf-8')
|
56 |
+
return mmh3.hash64(total)[0]
|
57 |
+
|
58 |
+
def _add_tags(self, x):
|
59 |
+
hsh = self._compute_hash(x['json']['url'], x['txt'])
|
60 |
+
pwatermark, punsafe = self.kv[hsh]
|
61 |
+
aesthetic = self.kv_aesthetic[hsh][0]
|
62 |
+
return {**x, 'pwatermark': pwatermark, 'punsafe': punsafe, 'aesthetic': aesthetic}
|
63 |
+
|
64 |
+
def _punsafe_to_class(self, punsafe):
|
65 |
+
return torch.tensor(punsafe >= self.punsafe_threshold).long()
|
66 |
+
|
67 |
+
def _filter_predicate(self, x):
|
68 |
+
try:
|
69 |
+
return x['pwatermark'] < self.pwatermark_threshold and x['aesthetic'] >= self.aesthetic_threshold and x['json']['original_width'] >= self.min_size and x['json']['original_height'] >= self.min_size
|
70 |
+
except:
|
71 |
+
return False
|
72 |
+
|
73 |
+
def __iter__(self):
|
74 |
+
return iter(self.inner_dataset)
|
75 |
+
|
76 |
+
|
77 |
+
def dict_collation_fn(samples, combine_tensors=True, combine_scalars=True):
|
78 |
+
"""Take a list of samples (as dictionary) and create a batch, preserving the keys.
|
79 |
+
If `tensors` is True, `ndarray` objects are combined into
|
80 |
+
tensor batches.
|
81 |
+
:param dict samples: list of samples
|
82 |
+
:param bool tensors: whether to turn lists of ndarrays into a single ndarray
|
83 |
+
:returns: single sample consisting of a batch
|
84 |
+
:rtype: dict
|
85 |
+
"""
|
86 |
+
keys = set.intersection(*[set(sample.keys()) for sample in samples])
|
87 |
+
batched = {key: [] for key in keys}
|
88 |
+
|
89 |
+
for s in samples:
|
90 |
+
[batched[key].append(s[key]) for key in batched]
|
91 |
+
|
92 |
+
result = {}
|
93 |
+
for key in batched:
|
94 |
+
if isinstance(batched[key][0], (int, float)):
|
95 |
+
if combine_scalars:
|
96 |
+
result[key] = np.array(list(batched[key]))
|
97 |
+
elif isinstance(batched[key][0], torch.Tensor):
|
98 |
+
if combine_tensors:
|
99 |
+
result[key] = torch.stack(list(batched[key]))
|
100 |
+
elif isinstance(batched[key][0], np.ndarray):
|
101 |
+
if combine_tensors:
|
102 |
+
result[key] = np.array(list(batched[key]))
|
103 |
+
else:
|
104 |
+
result[key] = list(batched[key])
|
105 |
+
return result
|
106 |
+
|
107 |
+
|
108 |
+
class WebDataModuleFromConfig(pl.LightningDataModule):
|
109 |
+
def __init__(self, tar_base, batch_size, train=None, validation=None,
|
110 |
+
test=None, num_workers=4, multinode=True, min_size=None,
|
111 |
+
max_pwatermark=1.0,
|
112 |
+
**kwargs):
|
113 |
+
super().__init__(self)
|
114 |
+
print(f'Setting tar base to {tar_base}')
|
115 |
+
self.tar_base = tar_base
|
116 |
+
self.batch_size = batch_size
|
117 |
+
self.num_workers = num_workers
|
118 |
+
self.train = train
|
119 |
+
self.validation = validation
|
120 |
+
self.test = test
|
121 |
+
self.multinode = multinode
|
122 |
+
self.min_size = min_size # filter out very small images
|
123 |
+
self.max_pwatermark = max_pwatermark # filter out watermarked images
|
124 |
+
|
125 |
+
def make_loader(self, dataset_config, train=True):
|
126 |
+
if 'image_transforms' in dataset_config:
|
127 |
+
image_transforms = [instantiate_from_config(tt) for tt in dataset_config.image_transforms]
|
128 |
+
else:
|
129 |
+
image_transforms = []
|
130 |
+
|
131 |
+
image_transforms.extend([torchvision.transforms.ToTensor(),
|
132 |
+
torchvision.transforms.Lambda(lambda x: rearrange(x * 2. - 1., 'c h w -> h w c'))])
|
133 |
+
image_transforms = torchvision.transforms.Compose(image_transforms)
|
134 |
+
|
135 |
+
if 'transforms' in dataset_config:
|
136 |
+
transforms_config = OmegaConf.to_container(dataset_config.transforms)
|
137 |
+
else:
|
138 |
+
transforms_config = dict()
|
139 |
+
|
140 |
+
transform_dict = {dkey: load_partial_from_config(transforms_config[dkey])
|
141 |
+
if transforms_config[dkey] != 'identity' else identity
|
142 |
+
for dkey in transforms_config}
|
143 |
+
img_key = dataset_config.get('image_key', 'jpeg')
|
144 |
+
transform_dict.update({img_key: image_transforms})
|
145 |
+
|
146 |
+
if 'postprocess' in dataset_config:
|
147 |
+
postprocess = instantiate_from_config(dataset_config['postprocess'])
|
148 |
+
else:
|
149 |
+
postprocess = None
|
150 |
+
|
151 |
+
shuffle = dataset_config.get('shuffle', 0)
|
152 |
+
shardshuffle = shuffle > 0
|
153 |
+
|
154 |
+
nodesplitter = wds.shardlists.split_by_node if self.multinode else wds.shardlists.single_node_only
|
155 |
+
|
156 |
+
if self.tar_base == "__improvedaesthetic__":
|
157 |
+
print("## Warning, loading the same improved aesthetic dataset "
|
158 |
+
"for all splits and ignoring shards parameter.")
|
159 |
+
tars = "pipe:aws s3 cp s3://s-laion/improved-aesthetics-laion-2B-en-subsets/aesthetics_tars/{000000..060207}.tar -"
|
160 |
+
else:
|
161 |
+
tars = os.path.join(self.tar_base, dataset_config.shards)
|
162 |
+
|
163 |
+
dset = wds.WebDataset(
|
164 |
+
tars,
|
165 |
+
nodesplitter=nodesplitter,
|
166 |
+
shardshuffle=shardshuffle,
|
167 |
+
handler=wds.warn_and_continue).repeat().shuffle(shuffle)
|
168 |
+
print(f'Loading webdataset with {len(dset.pipeline[0].urls)} shards.')
|
169 |
+
|
170 |
+
dset = (dset
|
171 |
+
.select(self.filter_keys)
|
172 |
+
.decode('pil', handler=wds.warn_and_continue)
|
173 |
+
.select(self.filter_size)
|
174 |
+
.map_dict(**transform_dict, handler=wds.warn_and_continue)
|
175 |
+
)
|
176 |
+
if postprocess is not None:
|
177 |
+
dset = dset.map(postprocess)
|
178 |
+
dset = (dset
|
179 |
+
.batched(self.batch_size, partial=False,
|
180 |
+
collation_fn=dict_collation_fn)
|
181 |
+
)
|
182 |
+
|
183 |
+
loader = wds.WebLoader(dset, batch_size=None, shuffle=False,
|
184 |
+
num_workers=self.num_workers)
|
185 |
+
|
186 |
+
return loader
|
187 |
+
|
188 |
+
def filter_size(self, x):
|
189 |
+
try:
|
190 |
+
valid = True
|
191 |
+
if self.min_size is not None and self.min_size > 1:
|
192 |
+
try:
|
193 |
+
valid = valid and x['json']['original_width'] >= self.min_size and x['json']['original_height'] >= self.min_size
|
194 |
+
except Exception:
|
195 |
+
valid = False
|
196 |
+
if self.max_pwatermark is not None and self.max_pwatermark < 1.0:
|
197 |
+
try:
|
198 |
+
valid = valid and x['json']['pwatermark'] <= self.max_pwatermark
|
199 |
+
except Exception:
|
200 |
+
valid = False
|
201 |
+
return valid
|
202 |
+
except Exception:
|
203 |
+
return False
|
204 |
+
|
205 |
+
def filter_keys(self, x):
|
206 |
+
try:
|
207 |
+
return ("jpg" in x) and ("txt" in x)
|
208 |
+
except Exception:
|
209 |
+
return False
|
210 |
+
|
211 |
+
def train_dataloader(self):
|
212 |
+
return self.make_loader(self.train)
|
213 |
+
|
214 |
+
def val_dataloader(self):
|
215 |
+
return self.make_loader(self.validation, train=False)
|
216 |
+
|
217 |
+
def test_dataloader(self):
|
218 |
+
return self.make_loader(self.test, train=False)
|
219 |
+
|
220 |
+
|
221 |
+
from ldm.modules.image_degradation import degradation_fn_bsr_light
|
222 |
+
import cv2
|
223 |
+
|
224 |
+
class AddLR(object):
|
225 |
+
def __init__(self, factor, output_size, initial_size=None, image_key="jpg"):
|
226 |
+
self.factor = factor
|
227 |
+
self.output_size = output_size
|
228 |
+
self.image_key = image_key
|
229 |
+
self.initial_size = initial_size
|
230 |
+
|
231 |
+
def pt2np(self, x):
|
232 |
+
x = ((x+1.0)*127.5).clamp(0, 255).to(dtype=torch.uint8).detach().cpu().numpy()
|
233 |
+
return x
|
234 |
+
|
235 |
+
def np2pt(self, x):
|
236 |
+
x = torch.from_numpy(x)/127.5-1.0
|
237 |
+
return x
|
238 |
+
|
239 |
+
def __call__(self, sample):
|
240 |
+
# sample['jpg'] is tensor hwc in [-1, 1] at this point
|
241 |
+
x = self.pt2np(sample[self.image_key])
|
242 |
+
if self.initial_size is not None:
|
243 |
+
x = cv2.resize(x, (self.initial_size, self.initial_size), interpolation=2)
|
244 |
+
x = degradation_fn_bsr_light(x, sf=self.factor)['image']
|
245 |
+
x = cv2.resize(x, (self.output_size, self.output_size), interpolation=2)
|
246 |
+
x = self.np2pt(x)
|
247 |
+
sample['lr'] = x
|
248 |
+
return sample
|
249 |
+
|
250 |
+
class AddBW(object):
|
251 |
+
def __init__(self, image_key="jpg"):
|
252 |
+
self.image_key = image_key
|
253 |
+
|
254 |
+
def pt2np(self, x):
|
255 |
+
x = ((x+1.0)*127.5).clamp(0, 255).to(dtype=torch.uint8).detach().cpu().numpy()
|
256 |
+
return x
|
257 |
+
|
258 |
+
def np2pt(self, x):
|
259 |
+
x = torch.from_numpy(x)/127.5-1.0
|
260 |
+
return x
|
261 |
+
|
262 |
+
def __call__(self, sample):
|
263 |
+
# sample['jpg'] is tensor hwc in [-1, 1] at this point
|
264 |
+
x = sample[self.image_key]
|
265 |
+
w = torch.rand(3, device=x.device)
|
266 |
+
w /= w.sum()
|
267 |
+
out = torch.einsum('hwc,c->hw', x, w)
|
268 |
+
|
269 |
+
# Keep as 3ch so we can pass to encoder, also we might want to add hints
|
270 |
+
sample['lr'] = out.unsqueeze(-1).tile(1,1,3)
|
271 |
+
return sample
|
272 |
+
|
273 |
+
class AddMask(PRNGMixin):
|
274 |
+
def __init__(self, mode="512train", p_drop=0.):
|
275 |
+
super().__init__()
|
276 |
+
assert mode in list(MASK_MODES.keys()), f'unknown mask generation mode "{mode}"'
|
277 |
+
self.make_mask = MASK_MODES[mode]
|
278 |
+
self.p_drop = p_drop
|
279 |
+
|
280 |
+
def __call__(self, sample):
|
281 |
+
# sample['jpg'] is tensor hwc in [-1, 1] at this point
|
282 |
+
x = sample['jpg']
|
283 |
+
mask = self.make_mask(self.prng, x.shape[0], x.shape[1])
|
284 |
+
if self.prng.choice(2, p=[1 - self.p_drop, self.p_drop]):
|
285 |
+
mask = np.ones_like(mask)
|
286 |
+
mask[mask < 0.5] = 0
|
287 |
+
mask[mask > 0.5] = 1
|
288 |
+
mask = torch.from_numpy(mask[..., None])
|
289 |
+
sample['mask'] = mask
|
290 |
+
sample['masked_image'] = x * (mask < 0.5)
|
291 |
+
return sample
|
292 |
+
|
293 |
+
|
294 |
+
class AddEdge(PRNGMixin):
|
295 |
+
def __init__(self, mode="512train", mask_edges=True):
|
296 |
+
super().__init__()
|
297 |
+
assert mode in list(MASK_MODES.keys()), f'unknown mask generation mode "{mode}"'
|
298 |
+
self.make_mask = MASK_MODES[mode]
|
299 |
+
self.n_down_choices = [0]
|
300 |
+
self.sigma_choices = [1, 2]
|
301 |
+
self.mask_edges = mask_edges
|
302 |
+
|
303 |
+
@torch.no_grad()
|
304 |
+
def __call__(self, sample):
|
305 |
+
# sample['jpg'] is tensor hwc in [-1, 1] at this point
|
306 |
+
x = sample['jpg']
|
307 |
+
|
308 |
+
mask = self.make_mask(self.prng, x.shape[0], x.shape[1])
|
309 |
+
mask[mask < 0.5] = 0
|
310 |
+
mask[mask > 0.5] = 1
|
311 |
+
mask = torch.from_numpy(mask[..., None])
|
312 |
+
sample['mask'] = mask
|
313 |
+
|
314 |
+
n_down_idx = self.prng.choice(len(self.n_down_choices))
|
315 |
+
sigma_idx = self.prng.choice(len(self.sigma_choices))
|
316 |
+
|
317 |
+
n_choices = len(self.n_down_choices)*len(self.sigma_choices)
|
318 |
+
raveled_idx = np.ravel_multi_index((n_down_idx, sigma_idx),
|
319 |
+
(len(self.n_down_choices), len(self.sigma_choices)))
|
320 |
+
normalized_idx = raveled_idx/max(1, n_choices-1)
|
321 |
+
|
322 |
+
n_down = self.n_down_choices[n_down_idx]
|
323 |
+
sigma = self.sigma_choices[sigma_idx]
|
324 |
+
|
325 |
+
kernel_size = 4*sigma+1
|
326 |
+
kernel_size = (kernel_size, kernel_size)
|
327 |
+
sigma = (sigma, sigma)
|
328 |
+
canny = kornia.filters.Canny(
|
329 |
+
low_threshold=0.1,
|
330 |
+
high_threshold=0.2,
|
331 |
+
kernel_size=kernel_size,
|
332 |
+
sigma=sigma,
|
333 |
+
hysteresis=True,
|
334 |
+
)
|
335 |
+
y = (x+1.0)/2.0 # in 01
|
336 |
+
y = y.unsqueeze(0).permute(0, 3, 1, 2).contiguous()
|
337 |
+
|
338 |
+
# down
|
339 |
+
for i_down in range(n_down):
|
340 |
+
size = min(y.shape[-2], y.shape[-1])//2
|
341 |
+
y = kornia.geometry.transform.resize(y, size, antialias=True)
|
342 |
+
|
343 |
+
# edge
|
344 |
+
_, y = canny(y)
|
345 |
+
|
346 |
+
if n_down > 0:
|
347 |
+
size = x.shape[0], x.shape[1]
|
348 |
+
y = kornia.geometry.transform.resize(y, size, interpolation="nearest")
|
349 |
+
|
350 |
+
y = y.permute(0, 2, 3, 1)[0].expand(-1, -1, 3).contiguous()
|
351 |
+
y = y*2.0-1.0
|
352 |
+
|
353 |
+
if self.mask_edges:
|
354 |
+
sample['masked_image'] = y * (mask < 0.5)
|
355 |
+
else:
|
356 |
+
sample['masked_image'] = y
|
357 |
+
sample['mask'] = torch.zeros_like(sample['mask'])
|
358 |
+
|
359 |
+
# concat normalized idx
|
360 |
+
sample['smoothing_strength'] = torch.ones_like(sample['mask'])*normalized_idx
|
361 |
+
|
362 |
+
return sample
|
363 |
+
|
364 |
+
|
365 |
+
def example00():
|
366 |
+
url = "pipe:aws s3 cp s3://s-datasets/laion5b/laion2B-data/000000.tar -"
|
367 |
+
dataset = wds.WebDataset(url)
|
368 |
+
example = next(iter(dataset))
|
369 |
+
for k in example:
|
370 |
+
print(k, type(example[k]))
|
371 |
+
|
372 |
+
print(example["__key__"])
|
373 |
+
for k in ["json", "txt"]:
|
374 |
+
print(example[k].decode())
|
375 |
+
|
376 |
+
image = Image.open(io.BytesIO(example["jpg"]))
|
377 |
+
outdir = "tmp"
|
378 |
+
os.makedirs(outdir, exist_ok=True)
|
379 |
+
image.save(os.path.join(outdir, example["__key__"] + ".png"))
|
380 |
+
|
381 |
+
|
382 |
+
def load_example(example):
|
383 |
+
return {
|
384 |
+
"key": example["__key__"],
|
385 |
+
"image": Image.open(io.BytesIO(example["jpg"])),
|
386 |
+
"text": example["txt"].decode(),
|
387 |
+
}
|
388 |
+
|
389 |
+
|
390 |
+
for i, example in tqdm(enumerate(dataset)):
|
391 |
+
ex = load_example(example)
|
392 |
+
print(ex["image"].size, ex["text"])
|
393 |
+
if i >= 100:
|
394 |
+
break
|
395 |
+
|
396 |
+
|
397 |
+
def example01():
|
398 |
+
# the first laion shards contain ~10k examples each
|
399 |
+
url = "pipe:aws s3 cp s3://s-datasets/laion5b/laion2B-data/{000000..000002}.tar -"
|
400 |
+
|
401 |
+
batch_size = 3
|
402 |
+
shuffle_buffer = 10000
|
403 |
+
dset = wds.WebDataset(
|
404 |
+
url,
|
405 |
+
nodesplitter=wds.shardlists.split_by_node,
|
406 |
+
shardshuffle=True,
|
407 |
+
)
|
408 |
+
dset = (dset
|
409 |
+
.shuffle(shuffle_buffer, initial=shuffle_buffer)
|
410 |
+
.decode('pil', handler=warn_and_continue)
|
411 |
+
.batched(batch_size, partial=False,
|
412 |
+
collation_fn=dict_collation_fn)
|
413 |
+
)
|
414 |
+
|
415 |
+
num_workers = 2
|
416 |
+
loader = wds.WebLoader(dset, batch_size=None, shuffle=False, num_workers=num_workers)
|
417 |
+
|
418 |
+
batch_sizes = list()
|
419 |
+
keys_per_epoch = list()
|
420 |
+
for epoch in range(5):
|
421 |
+
keys = list()
|
422 |
+
for batch in tqdm(loader):
|
423 |
+
batch_sizes.append(len(batch["__key__"]))
|
424 |
+
keys.append(batch["__key__"])
|
425 |
+
|
426 |
+
for bs in batch_sizes:
|
427 |
+
assert bs==batch_size
|
428 |
+
print(f"{len(batch_sizes)} batches of size {batch_size}.")
|
429 |
+
batch_sizes = list()
|
430 |
+
|
431 |
+
keys_per_epoch.append(keys)
|
432 |
+
for i_batch in [0, 1, -1]:
|
433 |
+
print(f"Batch {i_batch} of epoch {epoch}:")
|
434 |
+
print(keys[i_batch])
|
435 |
+
print("next epoch.")
|
436 |
+
|
437 |
+
|
438 |
+
def example02():
|
439 |
+
from omegaconf import OmegaConf
|
440 |
+
from torch.utils.data.distributed import DistributedSampler
|
441 |
+
from torch.utils.data import IterableDataset
|
442 |
+
from torch.utils.data import DataLoader, RandomSampler, Sampler, SequentialSampler
|
443 |
+
from pytorch_lightning.trainer.supporters import CombinedLoader, CycleIterator
|
444 |
+
|
445 |
+
#config = OmegaConf.load("configs/stable-diffusion/txt2img-1p4B-multinode-clip-encoder-high-res-512.yaml")
|
446 |
+
#config = OmegaConf.load("configs/stable-diffusion/txt2img-upscale-clip-encoder-f16-1024.yaml")
|
447 |
+
config = OmegaConf.load("configs/stable-diffusion/txt2img-v2-clip-encoder-improved_aesthetics-256.yaml")
|
448 |
+
datamod = WebDataModuleFromConfig(**config["data"]["params"])
|
449 |
+
dataloader = datamod.train_dataloader()
|
450 |
+
|
451 |
+
for batch in dataloader:
|
452 |
+
print(batch.keys())
|
453 |
+
print(batch["jpg"].shape)
|
454 |
+
break
|
455 |
+
|
456 |
+
|
457 |
+
def example03():
|
458 |
+
# improved aesthetics
|
459 |
+
tars = "pipe:aws s3 cp s3://s-laion/improved-aesthetics-laion-2B-en-subsets/aesthetics_tars/{000000..060207}.tar -"
|
460 |
+
dataset = wds.WebDataset(tars)
|
461 |
+
|
462 |
+
def filter_keys(x):
|
463 |
+
try:
|
464 |
+
return ("jpg" in x) and ("txt" in x)
|
465 |
+
except Exception:
|
466 |
+
return False
|
467 |
+
|
468 |
+
def filter_size(x):
|
469 |
+
try:
|
470 |
+
return x['json']['original_width'] >= 512 and x['json']['original_height'] >= 512
|
471 |
+
except Exception:
|
472 |
+
return False
|
473 |
+
|
474 |
+
def filter_watermark(x):
|
475 |
+
try:
|
476 |
+
return x['json']['pwatermark'] < 0.5
|
477 |
+
except Exception:
|
478 |
+
return False
|
479 |
+
|
480 |
+
dataset = (dataset
|
481 |
+
.select(filter_keys)
|
482 |
+
.decode('pil', handler=wds.warn_and_continue))
|
483 |
+
n_save = 20
|
484 |
+
n_total = 0
|
485 |
+
n_large = 0
|
486 |
+
n_large_nowm = 0
|
487 |
+
for i, example in enumerate(dataset):
|
488 |
+
n_total += 1
|
489 |
+
if filter_size(example):
|
490 |
+
n_large += 1
|
491 |
+
if filter_watermark(example):
|
492 |
+
n_large_nowm += 1
|
493 |
+
if n_large_nowm < n_save+1:
|
494 |
+
image = example["jpg"]
|
495 |
+
image.save(os.path.join("tmp", f"{n_large_nowm-1:06}.png"))
|
496 |
+
|
497 |
+
if i%500 == 0:
|
498 |
+
print(i)
|
499 |
+
print(f"Large: {n_large}/{n_total} | {n_large/n_total*100:.2f}%")
|
500 |
+
if n_large > 0:
|
501 |
+
print(f"No Watermark: {n_large_nowm}/{n_large} | {n_large_nowm/n_large*100:.2f}%")
|
502 |
+
|
503 |
+
|
504 |
+
|
505 |
+
def example04():
|
506 |
+
# improved aesthetics
|
507 |
+
for i_shard in range(60208)[::-1]:
|
508 |
+
print(i_shard)
|
509 |
+
tars = "pipe:aws s3 cp s3://s-laion/improved-aesthetics-laion-2B-en-subsets/aesthetics_tars/{:06}.tar -".format(i_shard)
|
510 |
+
dataset = wds.WebDataset(tars)
|
511 |
+
|
512 |
+
def filter_keys(x):
|
513 |
+
try:
|
514 |
+
return ("jpg" in x) and ("txt" in x)
|
515 |
+
except Exception:
|
516 |
+
return False
|
517 |
+
|
518 |
+
def filter_size(x):
|
519 |
+
try:
|
520 |
+
return x['json']['original_width'] >= 512 and x['json']['original_height'] >= 512
|
521 |
+
except Exception:
|
522 |
+
return False
|
523 |
+
|
524 |
+
dataset = (dataset
|
525 |
+
.select(filter_keys)
|
526 |
+
.decode('pil', handler=wds.warn_and_continue))
|
527 |
+
try:
|
528 |
+
example = next(iter(dataset))
|
529 |
+
except Exception:
|
530 |
+
print(f"Error @ {i_shard}")
|
531 |
+
|
532 |
+
|
533 |
+
if __name__ == "__main__":
|
534 |
+
#example01()
|
535 |
+
#example02()
|
536 |
+
example03()
|
537 |
+
#example04()
|
models/ldm/data/legacy.py
ADDED
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
class FolderData(Dataset):
|
3 |
+
def __init__(self,
|
4 |
+
root_dir,
|
5 |
+
caption_file=None,
|
6 |
+
image_transforms=[],
|
7 |
+
ext="jpg",
|
8 |
+
default_caption="",
|
9 |
+
postprocess=None,
|
10 |
+
return_paths=False,
|
11 |
+
) -> None:
|
12 |
+
"""Create a dataset from a folder of images.
|
13 |
+
If you pass in a root directory it will be searched for images
|
14 |
+
ending in ext (ext can be a list)
|
15 |
+
"""
|
16 |
+
self.root_dir = Path(root_dir)
|
17 |
+
self.default_caption = default_caption
|
18 |
+
self.return_paths = return_paths
|
19 |
+
if isinstance(postprocess, DictConfig):
|
20 |
+
postprocess = instantiate_from_config(postprocess)
|
21 |
+
self.postprocess = postprocess
|
22 |
+
if caption_file is not None:
|
23 |
+
with open(caption_file, "rt") as f:
|
24 |
+
ext = Path(caption_file).suffix.lower()
|
25 |
+
if ext == ".json":
|
26 |
+
captions = json.load(f)
|
27 |
+
elif ext == ".jsonl":
|
28 |
+
lines = f.readlines()
|
29 |
+
lines = [json.loads(x) for x in lines]
|
30 |
+
captions = {x["file_name"]: x["text"].strip("\n") for x in lines}
|
31 |
+
else:
|
32 |
+
raise ValueError(f"Unrecognised format: {ext}")
|
33 |
+
self.captions = captions
|
34 |
+
else:
|
35 |
+
self.captions = None
|
36 |
+
|
37 |
+
if not isinstance(ext, (tuple, list, ListConfig)):
|
38 |
+
ext = [ext]
|
39 |
+
|
40 |
+
# Only used if there is no caption file
|
41 |
+
self.paths = []
|
42 |
+
for e in ext:
|
43 |
+
self.paths.extend(sorted(list(self.root_dir.rglob(f"*.{e}"))))
|
44 |
+
self.tform = make_tranforms(image_transforms)
|
45 |
+
|
46 |
+
def __len__(self):
|
47 |
+
if self.captions is not None:
|
48 |
+
return len(self.captions.keys())
|
49 |
+
else:
|
50 |
+
return len(self.paths)
|
51 |
+
|
52 |
+
def __getitem__(self, index):
|
53 |
+
data = {}
|
54 |
+
if self.captions is not None:
|
55 |
+
chosen = list(self.captions.keys())[index]
|
56 |
+
caption = self.captions.get(chosen, None)
|
57 |
+
if caption is None:
|
58 |
+
caption = self.default_caption
|
59 |
+
filename = self.root_dir/chosen
|
60 |
+
else:
|
61 |
+
filename = self.paths[index]
|
62 |
+
|
63 |
+
if self.return_paths:
|
64 |
+
data["path"] = str(filename)
|
65 |
+
|
66 |
+
im = Image.open(filename).convert("RGB")
|
67 |
+
im = self.process_im(im)
|
68 |
+
data["image"] = im
|
69 |
+
|
70 |
+
if self.captions is not None:
|
71 |
+
data["txt"] = caption
|
72 |
+
else:
|
73 |
+
data["txt"] = self.default_caption
|
74 |
+
|
75 |
+
if self.postprocess is not None:
|
76 |
+
data = self.postprocess(data)
|
77 |
+
|
78 |
+
return data
|
79 |
+
|
80 |
+
def process_im(self, im):
|
81 |
+
im = im.convert("RGB")
|
82 |
+
return self.tform(im)
|
83 |
+
import random
|
84 |
+
|
85 |
+
class TransformDataset():
|
86 |
+
def __init__(self, ds, extra_label="sksbspic"):
|
87 |
+
self.ds = ds
|
88 |
+
self.extra_label = extra_label
|
89 |
+
self.transforms = {
|
90 |
+
"align": transforms.Resize(768),
|
91 |
+
"centerzoom": transforms.CenterCrop(768),
|
92 |
+
"randzoom": transforms.RandomCrop(768),
|
93 |
+
}
|
94 |
+
|
95 |
+
|
96 |
+
def __getitem__(self, index):
|
97 |
+
data = self.ds[index]
|
98 |
+
|
99 |
+
im = data['image']
|
100 |
+
im = im.permute(2,0,1)
|
101 |
+
# In case data is smaller than expected
|
102 |
+
im = transforms.Resize(1024)(im)
|
103 |
+
|
104 |
+
tform_name = random.choice(list(self.transforms.keys()))
|
105 |
+
im = self.transforms[tform_name](im)
|
106 |
+
|
107 |
+
im = im.permute(1,2,0)
|
108 |
+
|
109 |
+
data['image'] = im
|
110 |
+
data['txt'] = data['txt'] + f" {self.extra_label} {tform_name}"
|
111 |
+
|
112 |
+
return data
|
113 |
+
|
114 |
+
def __len__(self):
|
115 |
+
return len(self.ds)
|
116 |
+
|
117 |
+
def hf_dataset(
|
118 |
+
name,
|
119 |
+
image_transforms=[],
|
120 |
+
image_column="image",
|
121 |
+
text_column="text",
|
122 |
+
split='train',
|
123 |
+
image_key='image',
|
124 |
+
caption_key='txt',
|
125 |
+
):
|
126 |
+
"""Make huggingface dataset with appropriate list of transforms applied
|
127 |
+
"""
|
128 |
+
ds = load_dataset(name, split=split)
|
129 |
+
tform = make_tranforms(image_transforms)
|
130 |
+
|
131 |
+
assert image_column in ds.column_names, f"Didn't find column {image_column} in {ds.column_names}"
|
132 |
+
assert text_column in ds.column_names, f"Didn't find column {text_column} in {ds.column_names}"
|
133 |
+
|
134 |
+
def pre_process(examples):
|
135 |
+
processed = {}
|
136 |
+
processed[image_key] = [tform(im) for im in examples[image_column]]
|
137 |
+
processed[caption_key] = examples[text_column]
|
138 |
+
return processed
|
139 |
+
|
140 |
+
ds.set_transform(pre_process)
|
141 |
+
return ds
|
142 |
+
|
143 |
+
class TextOnly(Dataset):
|
144 |
+
def __init__(self, captions, output_size, image_key="image", caption_key="txt", n_gpus=1):
|
145 |
+
"""Returns only captions with dummy images"""
|
146 |
+
self.output_size = output_size
|
147 |
+
self.image_key = image_key
|
148 |
+
self.caption_key = caption_key
|
149 |
+
if isinstance(captions, Path):
|
150 |
+
self.captions = self._load_caption_file(captions)
|
151 |
+
else:
|
152 |
+
self.captions = captions
|
153 |
+
|
154 |
+
if n_gpus > 1:
|
155 |
+
# hack to make sure that all the captions appear on each gpu
|
156 |
+
repeated = [n_gpus*[x] for x in self.captions]
|
157 |
+
self.captions = []
|
158 |
+
[self.captions.extend(x) for x in repeated]
|
159 |
+
|
160 |
+
def __len__(self):
|
161 |
+
return len(self.captions)
|
162 |
+
|
163 |
+
def __getitem__(self, index):
|
164 |
+
dummy_im = torch.zeros(3, self.output_size, self.output_size)
|
165 |
+
dummy_im = rearrange(dummy_im * 2. - 1., 'c h w -> h w c')
|
166 |
+
return {self.image_key: dummy_im, self.caption_key: self.captions[index]}
|
167 |
+
|
168 |
+
def _load_caption_file(self, filename):
|
169 |
+
with open(filename, 'rt') as f:
|
170 |
+
captions = f.readlines()
|
171 |
+
return [x.strip('\n') for x in captions]
|
172 |
+
|
173 |
+
|
174 |
+
|
175 |
+
import random
|
176 |
+
import json
|
177 |
+
class IdRetreivalDataset(FolderData):
|
178 |
+
def __init__(self, ret_file, *args, **kwargs):
|
179 |
+
super().__init__(*args, **kwargs)
|
180 |
+
with open(ret_file, "rt") as f:
|
181 |
+
self.ret = json.load(f)
|
182 |
+
|
183 |
+
def __getitem__(self, index):
|
184 |
+
data = super().__getitem__(index)
|
185 |
+
key = self.paths[index].name
|
186 |
+
matches = self.ret[key]
|
187 |
+
if len(matches) > 0:
|
188 |
+
retreived = random.choice(matches)
|
189 |
+
else:
|
190 |
+
retreived = key
|
191 |
+
filename = self.root_dir/retreived
|
192 |
+
im = Image.open(filename).convert("RGB")
|
193 |
+
im = self.process_im(im)
|
194 |
+
# data["match"] = im
|
195 |
+
data["match"] = torch.cat((data["image"], im), dim=-1)
|
196 |
+
return data
|
models/ldm/data/lsun.py
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import numpy as np
|
3 |
+
import PIL
|
4 |
+
from PIL import Image
|
5 |
+
from torch.utils.data import Dataset
|
6 |
+
from torchvision import transforms
|
7 |
+
|
8 |
+
|
9 |
+
class LSUNBase(Dataset):
|
10 |
+
def __init__(self,
|
11 |
+
txt_file,
|
12 |
+
data_root,
|
13 |
+
size=None,
|
14 |
+
interpolation="bicubic",
|
15 |
+
flip_p=0.5
|
16 |
+
):
|
17 |
+
self.data_paths = txt_file
|
18 |
+
self.data_root = data_root
|
19 |
+
with open(self.data_paths, "r") as f:
|
20 |
+
self.image_paths = f.read().splitlines()
|
21 |
+
self._length = len(self.image_paths)
|
22 |
+
self.labels = {
|
23 |
+
"relative_file_path_": [l for l in self.image_paths],
|
24 |
+
"file_path_": [os.path.join(self.data_root, l)
|
25 |
+
for l in self.image_paths],
|
26 |
+
}
|
27 |
+
|
28 |
+
self.size = size
|
29 |
+
self.interpolation = {"linear": PIL.Image.LINEAR,
|
30 |
+
"bilinear": PIL.Image.BILINEAR,
|
31 |
+
"bicubic": PIL.Image.BICUBIC,
|
32 |
+
"lanczos": PIL.Image.LANCZOS,
|
33 |
+
}[interpolation]
|
34 |
+
self.flip = transforms.RandomHorizontalFlip(p=flip_p)
|
35 |
+
|
36 |
+
def __len__(self):
|
37 |
+
return self._length
|
38 |
+
|
39 |
+
def __getitem__(self, i):
|
40 |
+
example = dict((k, self.labels[k][i]) for k in self.labels)
|
41 |
+
image = Image.open(example["file_path_"])
|
42 |
+
if not image.mode == "RGB":
|
43 |
+
image = image.convert("RGB")
|
44 |
+
|
45 |
+
# default to score-sde preprocessing
|
46 |
+
img = np.array(image).astype(np.uint8)
|
47 |
+
crop = min(img.shape[0], img.shape[1])
|
48 |
+
h, w, = img.shape[0], img.shape[1]
|
49 |
+
img = img[(h - crop) // 2:(h + crop) // 2,
|
50 |
+
(w - crop) // 2:(w + crop) // 2]
|
51 |
+
|
52 |
+
image = Image.fromarray(img)
|
53 |
+
if self.size is not None:
|
54 |
+
image = image.resize((self.size, self.size), resample=self.interpolation)
|
55 |
+
|
56 |
+
image = self.flip(image)
|
57 |
+
image = np.array(image).astype(np.uint8)
|
58 |
+
example["image"] = (image / 127.5 - 1.0).astype(np.float32)
|
59 |
+
return example
|
60 |
+
|
61 |
+
|
62 |
+
class LSUNChurchesTrain(LSUNBase):
|
63 |
+
def __init__(self, **kwargs):
|
64 |
+
super().__init__(txt_file="data/lsun/church_outdoor_train.txt", data_root="data/lsun/churches", **kwargs)
|
65 |
+
|
66 |
+
|
67 |
+
class LSUNChurchesValidation(LSUNBase):
|
68 |
+
def __init__(self, flip_p=0., **kwargs):
|
69 |
+
super().__init__(txt_file="data/lsun/church_outdoor_val.txt", data_root="data/lsun/churches",
|
70 |
+
flip_p=flip_p, **kwargs)
|
71 |
+
|
72 |
+
|
73 |
+
class LSUNBedroomsTrain(LSUNBase):
|
74 |
+
def __init__(self, **kwargs):
|
75 |
+
super().__init__(txt_file="data/lsun/bedrooms_train.txt", data_root="data/lsun/bedrooms", **kwargs)
|
76 |
+
|
77 |
+
|
78 |
+
class LSUNBedroomsValidation(LSUNBase):
|
79 |
+
def __init__(self, flip_p=0.0, **kwargs):
|
80 |
+
super().__init__(txt_file="data/lsun/bedrooms_val.txt", data_root="data/lsun/bedrooms",
|
81 |
+
flip_p=flip_p, **kwargs)
|
82 |
+
|
83 |
+
|
84 |
+
class LSUNCatsTrain(LSUNBase):
|
85 |
+
def __init__(self, **kwargs):
|
86 |
+
super().__init__(txt_file="data/lsun/cat_train.txt", data_root="data/lsun/cats", **kwargs)
|
87 |
+
|
88 |
+
|
89 |
+
class LSUNCatsValidation(LSUNBase):
|
90 |
+
def __init__(self, flip_p=0., **kwargs):
|
91 |
+
super().__init__(txt_file="data/lsun/cat_val.txt", data_root="data/lsun/cats",
|
92 |
+
flip_p=flip_p, **kwargs)
|
models/ldm/data/nerf_like.py
ADDED
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from torch.utils.data import Dataset
|
2 |
+
import os
|
3 |
+
import json
|
4 |
+
import numpy as np
|
5 |
+
import torch
|
6 |
+
import imageio
|
7 |
+
import math
|
8 |
+
import cv2
|
9 |
+
from torchvision import transforms
|
10 |
+
|
11 |
+
def cartesian_to_spherical(xyz):
|
12 |
+
ptsnew = np.hstack((xyz, np.zeros(xyz.shape)))
|
13 |
+
xy = xyz[:,0]**2 + xyz[:,1]**2
|
14 |
+
z = np.sqrt(xy + xyz[:,2]**2)
|
15 |
+
theta = np.arctan2(np.sqrt(xy), xyz[:,2]) # for elevation angle defined from Z-axis down
|
16 |
+
#ptsnew[:,4] = np.arctan2(xyz[:,2], np.sqrt(xy)) # for elevation angle defined from XY-plane up
|
17 |
+
azimuth = np.arctan2(xyz[:,1], xyz[:,0])
|
18 |
+
return np.array([theta, azimuth, z])
|
19 |
+
|
20 |
+
|
21 |
+
def get_T(T_target, T_cond):
|
22 |
+
theta_cond, azimuth_cond, z_cond = cartesian_to_spherical(T_cond[None, :])
|
23 |
+
theta_target, azimuth_target, z_target = cartesian_to_spherical(T_target[None, :])
|
24 |
+
|
25 |
+
d_theta = theta_target - theta_cond
|
26 |
+
d_azimuth = (azimuth_target - azimuth_cond) % (2 * math.pi)
|
27 |
+
d_z = z_target - z_cond
|
28 |
+
|
29 |
+
d_T = torch.tensor([d_theta.item(), math.sin(d_azimuth.item()), math.cos(d_azimuth.item()), d_z.item()])
|
30 |
+
return d_T
|
31 |
+
|
32 |
+
def get_spherical(T_target, T_cond):
|
33 |
+
theta_cond, azimuth_cond, z_cond = cartesian_to_spherical(T_cond[None, :])
|
34 |
+
theta_target, azimuth_target, z_target = cartesian_to_spherical(T_target[None, :])
|
35 |
+
|
36 |
+
d_theta = theta_target - theta_cond
|
37 |
+
d_azimuth = (azimuth_target - azimuth_cond) % (2 * math.pi)
|
38 |
+
d_z = z_target - z_cond
|
39 |
+
|
40 |
+
d_T = torch.tensor([math.degrees(d_theta.item()), math.degrees(d_azimuth.item()), d_z.item()])
|
41 |
+
return d_T
|
42 |
+
|
43 |
+
class RTMV(Dataset):
|
44 |
+
def __init__(self, root_dir='datasets/RTMV/google_scanned',\
|
45 |
+
first_K=64, resolution=256, load_target=False):
|
46 |
+
self.root_dir = root_dir
|
47 |
+
self.scene_list = sorted(next(os.walk(root_dir))[1])
|
48 |
+
self.resolution = resolution
|
49 |
+
self.first_K = first_K
|
50 |
+
self.load_target = load_target
|
51 |
+
|
52 |
+
def __len__(self):
|
53 |
+
return len(self.scene_list)
|
54 |
+
|
55 |
+
def __getitem__(self, idx):
|
56 |
+
scene_dir = os.path.join(self.root_dir, self.scene_list[idx])
|
57 |
+
with open(os.path.join(scene_dir, 'transforms.json'), "r") as f:
|
58 |
+
meta = json.load(f)
|
59 |
+
imgs = []
|
60 |
+
poses = []
|
61 |
+
for i_img in range(self.first_K):
|
62 |
+
meta_img = meta['frames'][i_img]
|
63 |
+
|
64 |
+
if i_img == 0 or self.load_target:
|
65 |
+
img_path = os.path.join(scene_dir, meta_img['file_path'])
|
66 |
+
img = imageio.imread(img_path)
|
67 |
+
img = cv2.resize(img, (self.resolution, self.resolution), interpolation = cv2.INTER_LINEAR)
|
68 |
+
imgs.append(img)
|
69 |
+
|
70 |
+
c2w = meta_img['transform_matrix']
|
71 |
+
poses.append(c2w)
|
72 |
+
|
73 |
+
imgs = (np.array(imgs) / 255.).astype(np.float32) # (RGBA) imgs
|
74 |
+
imgs = torch.tensor(self.blend_rgba(imgs)).permute(0, 3, 1, 2)
|
75 |
+
imgs = imgs * 2 - 1. # convert to stable diffusion range
|
76 |
+
poses = torch.tensor(np.array(poses).astype(np.float32))
|
77 |
+
return imgs, poses
|
78 |
+
|
79 |
+
def blend_rgba(self, img):
|
80 |
+
img = img[..., :3] * img[..., -1:] + (1. - img[..., -1:]) # blend A to RGB
|
81 |
+
return img
|
82 |
+
|
83 |
+
|
84 |
+
class GSO(Dataset):
|
85 |
+
def __init__(self, root_dir='datasets/GoogleScannedObjects',\
|
86 |
+
split='val', first_K=5, resolution=256, load_target=False, name='render_mvs'):
|
87 |
+
self.root_dir = root_dir
|
88 |
+
with open(os.path.join(root_dir, '%s.json' % split), "r") as f:
|
89 |
+
self.scene_list = json.load(f)
|
90 |
+
self.resolution = resolution
|
91 |
+
self.first_K = first_K
|
92 |
+
self.load_target = load_target
|
93 |
+
self.name = name
|
94 |
+
|
95 |
+
def __len__(self):
|
96 |
+
return len(self.scene_list)
|
97 |
+
|
98 |
+
def __getitem__(self, idx):
|
99 |
+
scene_dir = os.path.join(self.root_dir, self.scene_list[idx])
|
100 |
+
with open(os.path.join(scene_dir, 'transforms_%s.json' % self.name), "r") as f:
|
101 |
+
meta = json.load(f)
|
102 |
+
imgs = []
|
103 |
+
poses = []
|
104 |
+
for i_img in range(self.first_K):
|
105 |
+
meta_img = meta['frames'][i_img]
|
106 |
+
|
107 |
+
if i_img == 0 or self.load_target:
|
108 |
+
img_path = os.path.join(scene_dir, meta_img['file_path'])
|
109 |
+
img = imageio.imread(img_path)
|
110 |
+
img = cv2.resize(img, (self.resolution, self.resolution), interpolation = cv2.INTER_LINEAR)
|
111 |
+
imgs.append(img)
|
112 |
+
|
113 |
+
c2w = meta_img['transform_matrix']
|
114 |
+
poses.append(c2w)
|
115 |
+
|
116 |
+
imgs = (np.array(imgs) / 255.).astype(np.float32) # (RGBA) imgs
|
117 |
+
mask = imgs[:, :, :, -1]
|
118 |
+
imgs = torch.tensor(self.blend_rgba(imgs)).permute(0, 3, 1, 2)
|
119 |
+
imgs = imgs * 2 - 1. # convert to stable diffusion range
|
120 |
+
poses = torch.tensor(np.array(poses).astype(np.float32))
|
121 |
+
return imgs, poses
|
122 |
+
|
123 |
+
def blend_rgba(self, img):
|
124 |
+
img = img[..., :3] * img[..., -1:] + (1. - img[..., -1:]) # blend A to RGB
|
125 |
+
return img
|
126 |
+
|
127 |
+
class WILD(Dataset):
|
128 |
+
def __init__(self, root_dir='data/nerf_wild',\
|
129 |
+
first_K=33, resolution=256, load_target=False):
|
130 |
+
self.root_dir = root_dir
|
131 |
+
self.scene_list = sorted(next(os.walk(root_dir))[1])
|
132 |
+
self.resolution = resolution
|
133 |
+
self.first_K = first_K
|
134 |
+
self.load_target = load_target
|
135 |
+
|
136 |
+
def __len__(self):
|
137 |
+
return len(self.scene_list)
|
138 |
+
|
139 |
+
def __getitem__(self, idx):
|
140 |
+
scene_dir = os.path.join(self.root_dir, self.scene_list[idx])
|
141 |
+
with open(os.path.join(scene_dir, 'transforms_train.json'), "r") as f:
|
142 |
+
meta = json.load(f)
|
143 |
+
imgs = []
|
144 |
+
poses = []
|
145 |
+
for i_img in range(self.first_K):
|
146 |
+
meta_img = meta['frames'][i_img]
|
147 |
+
|
148 |
+
if i_img == 0 or self.load_target:
|
149 |
+
img_path = os.path.join(scene_dir, meta_img['file_path'])
|
150 |
+
img = imageio.imread(img_path + '.png')
|
151 |
+
img = cv2.resize(img, (self.resolution, self.resolution), interpolation = cv2.INTER_LINEAR)
|
152 |
+
imgs.append(img)
|
153 |
+
|
154 |
+
c2w = meta_img['transform_matrix']
|
155 |
+
poses.append(c2w)
|
156 |
+
|
157 |
+
imgs = (np.array(imgs) / 255.).astype(np.float32) # (RGBA) imgs
|
158 |
+
imgs = torch.tensor(self.blend_rgba(imgs)).permute(0, 3, 1, 2)
|
159 |
+
imgs = imgs * 2 - 1. # convert to stable diffusion range
|
160 |
+
poses = torch.tensor(np.array(poses).astype(np.float32))
|
161 |
+
return imgs, poses
|
162 |
+
|
163 |
+
def blend_rgba(self, img):
|
164 |
+
img = img[..., :3] * img[..., -1:] + (1. - img[..., -1:]) # blend A to RGB
|
165 |
+
return img
|
models/ldm/data/objaverse_rendered.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from tqdm import tqdm
|
2 |
+
import os
|
3 |
+
import objaverse
|
4 |
+
import random
|
5 |
+
import numpy as np
|
6 |
+
def get_rendered_objaverse_list_v0(data_dir, target_name, exr, **kargs):
|
7 |
+
"This function is to fast obtain unfinined objaverse rendering images"
|
8 |
+
image_list_cache_path = kargs["image_list_cache_path"]
|
9 |
+
if os.path.exists(image_list_cache_path):
|
10 |
+
return np.load(image_list_cache_path)["image_list"].tolist()
|
11 |
+
random.seed(7564)
|
12 |
+
uids = objaverse.load_uids()
|
13 |
+
random.shuffle(uids)
|
14 |
+
|
15 |
+
obj_starts = kargs["obj_starts"]
|
16 |
+
obj_ends = kargs["obj_ends"]
|
17 |
+
num_envs = kargs["num_envs"]
|
18 |
+
num_imgs = kargs["num_imgs"]
|
19 |
+
|
20 |
+
|
21 |
+
selected_uids = []
|
22 |
+
for _start, _end in zip(obj_starts, obj_ends):
|
23 |
+
selected_uids += uids[_start:_end]
|
24 |
+
|
25 |
+
all_imgs = []
|
26 |
+
|
27 |
+
envpaths_all = os.listdir(os.path.join(data_dir, selected_uids[0]))
|
28 |
+
envpaths_raw = [_env for _env in envpaths_all if not ".txt" in _env]
|
29 |
+
|
30 |
+
for _uid in tqdm(selected_uids):
|
31 |
+
random.shuffle(envpaths_raw)
|
32 |
+
envpaths = envpaths_raw[:num_envs]
|
33 |
+
if not os.path.exists(os.path.join(data_dir, _uid)):
|
34 |
+
print(f"WARNING NONE EXIST OBJECT {os.path.join(data_dir, _uid)}")
|
35 |
+
continue
|
36 |
+
for _env in envpaths:
|
37 |
+
if not os.path.exists(os.path.join(data_dir, _uid, _env)):
|
38 |
+
print(f"WARNING NONE EXIST ENV {os.path.join(data_dir, _uid, _env)}")
|
39 |
+
continue
|
40 |
+
img_ids = list(range(int(len(os.listdir(os.path.join(data_dir, _uid, _env))) // 7)))
|
41 |
+
random.shuffle(img_ids)
|
42 |
+
img_ids = img_ids[:num_imgs]
|
43 |
+
|
44 |
+
for _img_ids in img_ids:
|
45 |
+
if not os.path.exists(os.path.join(data_dir, _uid, _env, f"{_img_ids}-{target_name}0001.{exr}")):
|
46 |
+
print(f"WARNING NONE EXIST IMAGE {os.path.join(data_dir, _uid, _env, f'{_img_ids}-{target_name}0001.{exr}')}")
|
47 |
+
continue
|
48 |
+
all_imgs += [os.path.join(data_dir, _uid, _env, f"{_img_ids}-{target_name}0001.{exr}")]
|
49 |
+
|
50 |
+
np.savez(image_list_cache_path, image_list=all_imgs)
|
51 |
+
return all_imgs
|
52 |
+
|
53 |
+
if __name__ == "__main__":
|
54 |
+
all_imgs = get_rendered_objaverse_list_v0("/home/chenxi/code/material-diffusion/data/objaverse_rendering/samll-dataset", "albedo", "png",
|
55 |
+
obj_starts=[20], obj_ends=[80], num_envs=100, num_imgs=1)
|
56 |
+
|
57 |
+
print(len(all_imgs), all_imgs[:10])
|
58 |
+
for img in all_imgs[:10]:
|
59 |
+
print(img, os.path.exists(img))
|
models/ldm/data/simple.py
ADDED
@@ -0,0 +1,567 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import sys
|
3 |
+
sys.path.insert(1, '.')
|
4 |
+
from typing import Dict
|
5 |
+
import webdataset as wds
|
6 |
+
import numpy as np
|
7 |
+
from omegaconf import DictConfig, ListConfig
|
8 |
+
import torch
|
9 |
+
from torch.utils.data import Dataset
|
10 |
+
from pathlib import Path
|
11 |
+
import json
|
12 |
+
from PIL import Image
|
13 |
+
from torchvision import transforms
|
14 |
+
import torchvision
|
15 |
+
from einops import rearrange
|
16 |
+
from ldm.util import instantiate_from_config
|
17 |
+
from datasets import load_dataset
|
18 |
+
import pytorch_lightning as pl
|
19 |
+
import copy
|
20 |
+
import csv
|
21 |
+
import cv2
|
22 |
+
import random
|
23 |
+
import matplotlib.pyplot as plt
|
24 |
+
from torch.utils.data import DataLoader
|
25 |
+
import json
|
26 |
+
import os, sys
|
27 |
+
import webdataset as wds
|
28 |
+
import math
|
29 |
+
from torch.utils.data.distributed import DistributedSampler
|
30 |
+
import glob
|
31 |
+
import pickle
|
32 |
+
from ldm.data.objaverse_rendered import get_rendered_objaverse_list_v0
|
33 |
+
from ldm.data.decoder import ObjaverseDataDecoder, ObjaverseDecoerWDS, nodesplitter
|
34 |
+
|
35 |
+
from loguru import logger
|
36 |
+
from torch import distributed as dist
|
37 |
+
from tqdm import tqdm
|
38 |
+
from multiprocessing.pool import ThreadPool
|
39 |
+
|
40 |
+
|
41 |
+
# Some hacky things to make experimentation easier
|
42 |
+
def make_transform_multi_folder_data(paths, caption_files=None, **kwargs):
|
43 |
+
ds = make_multi_folder_data(paths, caption_files, **kwargs)
|
44 |
+
return TransformDataset(ds)
|
45 |
+
|
46 |
+
def make_nfp_data(base_path):
|
47 |
+
dirs = list(Path(base_path).glob("*/"))
|
48 |
+
print(f"Found {len(dirs)} folders")
|
49 |
+
print(dirs)
|
50 |
+
tforms = [transforms.Resize(512), transforms.CenterCrop(512)]
|
51 |
+
datasets = [NfpDataset(x, image_transforms=copy.copy(tforms), default_caption="A view from a train window") for x in dirs]
|
52 |
+
return torch.utils.data.ConcatDataset(datasets)
|
53 |
+
|
54 |
+
|
55 |
+
class VideoDataset(Dataset):
|
56 |
+
def __init__(self, root_dir, image_transforms, caption_file, offset=8, n=2):
|
57 |
+
self.root_dir = Path(root_dir)
|
58 |
+
self.caption_file = caption_file
|
59 |
+
self.n = n
|
60 |
+
ext = "mp4"
|
61 |
+
self.paths = sorted(list(self.root_dir.rglob(f"*.{ext}")))
|
62 |
+
self.offset = offset
|
63 |
+
|
64 |
+
if isinstance(image_transforms, ListConfig):
|
65 |
+
image_transforms = [instantiate_from_config(tt) for tt in image_transforms]
|
66 |
+
image_transforms.extend([transforms.ToTensor(),
|
67 |
+
transforms.Lambda(lambda x: rearrange(x * 2. - 1., 'c h w -> h w c'))])
|
68 |
+
image_transforms = transforms.Compose(image_transforms)
|
69 |
+
self.tform = image_transforms
|
70 |
+
with open(self.caption_file) as f:
|
71 |
+
reader = csv.reader(f)
|
72 |
+
rows = [row for row in reader]
|
73 |
+
self.captions = dict(rows)
|
74 |
+
|
75 |
+
def __len__(self):
|
76 |
+
return len(self.paths)
|
77 |
+
|
78 |
+
def __getitem__(self, index):
|
79 |
+
for i in range(10):
|
80 |
+
try:
|
81 |
+
return self._load_sample(index)
|
82 |
+
except Exception:
|
83 |
+
# Not really good enough but...
|
84 |
+
print("uh oh")
|
85 |
+
|
86 |
+
def _load_sample(self, index):
|
87 |
+
n = self.n
|
88 |
+
filename = self.paths[index]
|
89 |
+
min_frame = 2*self.offset + 2
|
90 |
+
vid = cv2.VideoCapture(str(filename))
|
91 |
+
max_frames = int(vid.get(cv2.CAP_PROP_FRAME_COUNT))
|
92 |
+
curr_frame_n = random.randint(min_frame, max_frames)
|
93 |
+
vid.set(cv2.CAP_PROP_POS_FRAMES,curr_frame_n)
|
94 |
+
_, curr_frame = vid.read()
|
95 |
+
|
96 |
+
prev_frames = []
|
97 |
+
for i in range(n):
|
98 |
+
prev_frame_n = curr_frame_n - (i+1)*self.offset
|
99 |
+
vid.set(cv2.CAP_PROP_POS_FRAMES,prev_frame_n)
|
100 |
+
_, prev_frame = vid.read()
|
101 |
+
prev_frame = self.tform(Image.fromarray(prev_frame[...,::-1]))
|
102 |
+
prev_frames.append(prev_frame)
|
103 |
+
|
104 |
+
vid.release()
|
105 |
+
caption = self.captions[filename.name]
|
106 |
+
data = {
|
107 |
+
"image": self.tform(Image.fromarray(curr_frame[...,::-1])),
|
108 |
+
"prev": torch.cat(prev_frames, dim=-1),
|
109 |
+
"txt": caption
|
110 |
+
}
|
111 |
+
return data
|
112 |
+
|
113 |
+
# end hacky things
|
114 |
+
|
115 |
+
|
116 |
+
def make_tranforms(image_transforms):
|
117 |
+
# if isinstance(image_transforms, ListConfig):
|
118 |
+
# image_transforms = [instantiate_from_config(tt) for tt in image_transforms]
|
119 |
+
image_transforms = []
|
120 |
+
image_transforms.extend([transforms.ToTensor(),
|
121 |
+
transforms.Lambda(lambda x: rearrange(x * 2. - 1., 'c h w -> h w c'))])
|
122 |
+
image_transforms = transforms.Compose(image_transforms)
|
123 |
+
return image_transforms
|
124 |
+
|
125 |
+
|
126 |
+
def make_multi_folder_data(paths, caption_files=None, **kwargs):
|
127 |
+
"""Make a concat dataset from multiple folders
|
128 |
+
Don't suport captions yet
|
129 |
+
|
130 |
+
If paths is a list, that's ok, if it's a Dict interpret it as:
|
131 |
+
k=folder v=n_times to repeat that
|
132 |
+
"""
|
133 |
+
list_of_paths = []
|
134 |
+
if isinstance(paths, (Dict, DictConfig)):
|
135 |
+
assert caption_files is None, \
|
136 |
+
"Caption files not yet supported for repeats"
|
137 |
+
for folder_path, repeats in paths.items():
|
138 |
+
list_of_paths.extend([folder_path]*repeats)
|
139 |
+
paths = list_of_paths
|
140 |
+
|
141 |
+
if caption_files is not None:
|
142 |
+
datasets = [FolderData(p, caption_file=c, **kwargs) for (p, c) in zip(paths, caption_files)]
|
143 |
+
else:
|
144 |
+
datasets = [FolderData(p, **kwargs) for p in paths]
|
145 |
+
return torch.utils.data.ConcatDataset(datasets)
|
146 |
+
|
147 |
+
|
148 |
+
|
149 |
+
class NfpDataset(Dataset):
|
150 |
+
def __init__(self,
|
151 |
+
root_dir,
|
152 |
+
image_transforms=[],
|
153 |
+
ext="jpg",
|
154 |
+
default_caption="",
|
155 |
+
) -> None:
|
156 |
+
"""assume sequential frames and a deterministic transform"""
|
157 |
+
|
158 |
+
self.root_dir = Path(root_dir)
|
159 |
+
self.default_caption = default_caption
|
160 |
+
|
161 |
+
self.paths = sorted(list(self.root_dir.rglob(f"*.{ext}")))
|
162 |
+
self.tform = make_tranforms(image_transforms)
|
163 |
+
|
164 |
+
def __len__(self):
|
165 |
+
return len(self.paths) - 1
|
166 |
+
|
167 |
+
|
168 |
+
def __getitem__(self, index):
|
169 |
+
prev = self.paths[index]
|
170 |
+
curr = self.paths[index+1]
|
171 |
+
data = {}
|
172 |
+
data["image"] = self._load_im(curr)
|
173 |
+
data["prev"] = self._load_im(prev)
|
174 |
+
data["txt"] = self.default_caption
|
175 |
+
return data
|
176 |
+
|
177 |
+
def _load_im(self, filename):
|
178 |
+
im = Image.open(filename).convert("RGB")
|
179 |
+
return self.tform(im)
|
180 |
+
|
181 |
+
class ObjaverseDataModuleFromConfig(pl.LightningDataModule):
|
182 |
+
def __init__(self, root_dir, batch_size, train=None, validation=None,
|
183 |
+
test=None, num_workers=4, objaverse_data_list=None, ext="png",
|
184 |
+
target_name="albedo", use_wds=True, tar_config=None, **kwargs):
|
185 |
+
super().__init__(self)
|
186 |
+
self.root_dir = root_dir
|
187 |
+
self.batch_size = batch_size
|
188 |
+
self.num_workers = num_workers
|
189 |
+
self.kwargs = kwargs
|
190 |
+
self.tar_config = tar_config
|
191 |
+
self.use_wds = use_wds
|
192 |
+
|
193 |
+
if train is not None:
|
194 |
+
dataset_config = train
|
195 |
+
if validation is not None:
|
196 |
+
dataset_config = validation
|
197 |
+
|
198 |
+
|
199 |
+
image_transforms = [transforms.ToTensor(),
|
200 |
+
transforms.Lambda(lambda x: rearrange(x * 2. - 1., 'c h w -> h w c'))]
|
201 |
+
image_transforms = torchvision.transforms.Compose(image_transforms)
|
202 |
+
self.image_transforms = {
|
203 |
+
"size": dataset_config.image_transforms.size,
|
204 |
+
"totensor": image_transforms
|
205 |
+
}
|
206 |
+
|
207 |
+
self.target_name = target_name
|
208 |
+
self.objaverse_data_list = objaverse_data_list
|
209 |
+
self.ext = ext
|
210 |
+
|
211 |
+
def naive_setup(self):
|
212 |
+
# get object data list
|
213 |
+
if self.objaverse_data_list is None or \
|
214 |
+
self.objaverse_data_list["image_list_cache_path"] == "None":
|
215 |
+
# This is too slow..
|
216 |
+
self.paths = sorted(list(Path(self.root_dir).rglob(f"*{self.target_name}*.{self.ext}")))
|
217 |
+
if len(self.paths) == 0:
|
218 |
+
# colmap format
|
219 |
+
self.paths = sorted(list(Path(self.root_dir).rglob(f"*images_train/*.*")))
|
220 |
+
else:
|
221 |
+
self.paths = get_rendered_objaverse_list_v0(self.root_dir, self.target_name, self.ext, **self.objaverse_data_list)
|
222 |
+
random.shuffle(self.paths)
|
223 |
+
# train val split
|
224 |
+
total_objects = len(self.paths)
|
225 |
+
self.paths_val = self.paths[math.floor(total_objects / 100. * 99.):] # used last 1% as validation
|
226 |
+
self.paths_train = self.paths[:math.floor(total_objects / 100. * 99.)] # used first 99% as training
|
227 |
+
if self.rank == 0:
|
228 |
+
print('============= length of dataset %d =============' % len(self.paths))
|
229 |
+
print('============= length of training dataset %d =============' % len(self.paths_train))
|
230 |
+
print('============= length of Validation dataset %d =============' % len(self.paths_val))
|
231 |
+
|
232 |
+
# Split into each GPU
|
233 |
+
self.paths_train = self._get_local_split(self.paths_train, self.world_size, self.rank)
|
234 |
+
logger.info(
|
235 |
+
f"[rank {self.rank}]: {len(self.paths_train)} images assigned."
|
236 |
+
)
|
237 |
+
|
238 |
+
def _get_tar_length(self, tar_list, img_per_obj):
|
239 |
+
dataset_size = 0
|
240 |
+
for _name in tar_list:
|
241 |
+
num_obj = int(_name.rsplit("_num_")[1].rsplit(".")[0])
|
242 |
+
dataset_size += num_obj * img_per_obj
|
243 |
+
return dataset_size
|
244 |
+
|
245 |
+
def webdataset_setup(self, list_dir, tar_dir, img_per_obj, max_tars=None):
|
246 |
+
# read data list and calculate size
|
247 |
+
tar_name_list = sorted(os.listdir(list_dir))
|
248 |
+
if not max_tars is None:
|
249 |
+
# for debugging on small scale data
|
250 |
+
tar_name_list = tar_name_list[:max_tars]
|
251 |
+
total_tars = len(tar_name_list)
|
252 |
+
# random shuffle
|
253 |
+
random.shuffle(tar_name_list)
|
254 |
+
print(f"Rank {self.rank} shuffle: {tar_name_list}")
|
255 |
+
# train test split
|
256 |
+
self.test_tars = tar_name_list[math.floor(total_tars / 100. * 99.):]
|
257 |
+
# make sure each node has one tar
|
258 |
+
if len(self.test_tars) < self.world_size:
|
259 |
+
self.test_tars += [self.test_tars[0]]*(self.world_size-len(self.test_tars))
|
260 |
+
|
261 |
+
self.train_tars = tar_name_list[:math.floor(total_tars / 100. * 99.)]
|
262 |
+
|
263 |
+
# training tar truncation
|
264 |
+
total_workers = self.num_workers * self.world_size
|
265 |
+
num_tars_train = (len(self.train_tars) // total_workers) * total_workers
|
266 |
+
if num_tars_train != len(self.train_tars):
|
267 |
+
print(f"[WARNING] Total train tars: {len(self.train_tars)}, truncated: {len(self.train_tars)-num_tars_train}, remainnig: {num_tars_train}, total workers: {total_workers}")
|
268 |
+
|
269 |
+
self.test_length = self._get_tar_length(self.test_tars, img_per_obj)
|
270 |
+
self.train_length = self._get_tar_length(self.train_tars, img_per_obj)
|
271 |
+
|
272 |
+
# name replace
|
273 |
+
test_tars = [_name.rsplit("_num")[0]+".tar" for _name in self.test_tars]
|
274 |
+
self.test_tars = [os.path.join(tar_dir, _name) for _name in test_tars]
|
275 |
+
|
276 |
+
train_tars = [_name.rsplit("_num")[0]+".tar" for _name in self.train_tars]
|
277 |
+
self.train_tars = [os.path.join(tar_dir, _name) for _name in train_tars]
|
278 |
+
|
279 |
+
if self.rank == 0:
|
280 |
+
print('============= length of dataset %d =============' % (self.test_length+self.train_length))
|
281 |
+
print('============= length of training dataset %d =============' % (self.train_length))
|
282 |
+
print('============= length of Validation dataset %d =============' % (self.test_length))
|
283 |
+
|
284 |
+
def setup(self, stage=None):
|
285 |
+
try:
|
286 |
+
self.world_size = dist.get_world_size()
|
287 |
+
self.rank = dist.get_rank()
|
288 |
+
except:
|
289 |
+
self.world_size = 1
|
290 |
+
self.rank = 0
|
291 |
+
|
292 |
+
if self.rank == 0:
|
293 |
+
print("#### Data ####")
|
294 |
+
|
295 |
+
if self.use_wds:
|
296 |
+
self.webdataset_setup(**self.tar_config)
|
297 |
+
else:
|
298 |
+
self.naive_setup()
|
299 |
+
|
300 |
+
def _get_local_split(self, items: list, world_size: int, rank: int, seed: int = 6):
|
301 |
+
"""The local rank only loads a split of the dataset."""
|
302 |
+
n_items = len(items)
|
303 |
+
items_permute = np.random.RandomState(seed).permutation(items)
|
304 |
+
if n_items % world_size == 0:
|
305 |
+
padded_items = items_permute
|
306 |
+
else:
|
307 |
+
padding = np.random.RandomState(seed).choice(
|
308 |
+
items, world_size - (n_items % world_size), replace=True
|
309 |
+
)
|
310 |
+
padded_items = np.concatenate([items_permute, padding])
|
311 |
+
assert (
|
312 |
+
len(padded_items) % world_size == 0
|
313 |
+
), f"len(padded_items): {len(padded_items)}; world_size: {world_size}; len(padding): {len(padding)}"
|
314 |
+
n_per_rank = len(padded_items) // world_size
|
315 |
+
local_items = padded_items[n_per_rank * rank : n_per_rank * (rank + 1)]
|
316 |
+
|
317 |
+
return local_items
|
318 |
+
|
319 |
+
def train_dataloader(self):
|
320 |
+
if self.use_wds:
|
321 |
+
loader = self.train_dataloader_wds()
|
322 |
+
else:
|
323 |
+
loader = self.train_dataloader_naive()
|
324 |
+
return loader
|
325 |
+
|
326 |
+
def val_dataloader(self):
|
327 |
+
if self.use_wds:
|
328 |
+
loader = self.val_dataloader_wds()
|
329 |
+
else:
|
330 |
+
loader = self.val_dataloader_naive()
|
331 |
+
return loader
|
332 |
+
|
333 |
+
def train_dataloader_naive(self):
|
334 |
+
dataset = ObjaverseData(root_dir=self.root_dir, \
|
335 |
+
image_transforms=self.image_transforms,
|
336 |
+
image_list = self.paths_train, target_name=self.target_name,
|
337 |
+
**self.kwargs)
|
338 |
+
return wds.WebLoader(dataset, batch_size=self.batch_size, num_workers=self.num_workers, shuffle=True)
|
339 |
+
|
340 |
+
def val_dataloader_naive(self):
|
341 |
+
dataset = ObjaverseData(root_dir=self.root_dir, \
|
342 |
+
image_transforms=self.image_transforms,
|
343 |
+
image_list = self.paths_val, target_name=self.target_name,
|
344 |
+
**self.kwargs)
|
345 |
+
return wds.WebLoader(dataset, batch_size=self.batch_size, num_workers=self.num_workers, shuffle=False)
|
346 |
+
|
347 |
+
|
348 |
+
def train_dataloader_wds(self):
|
349 |
+
decoder = ObjaverseDecoerWDS(root_dir=self.root_dir, \
|
350 |
+
image_transforms=self.image_transforms,
|
351 |
+
image_list = None, target_name=self.target_name,
|
352 |
+
**self.kwargs)
|
353 |
+
|
354 |
+
worker_batch = self.batch_size
|
355 |
+
epoch_length = self.train_length // worker_batch // self.num_workers // self.world_size
|
356 |
+
dataset = (wds.WebDataset(self.train_tars,
|
357 |
+
shardshuffle=min(1000, len(self.train_tars)),
|
358 |
+
nodesplitter=wds.shardlists.split_by_node)
|
359 |
+
.shuffle(5000, initial=1000)
|
360 |
+
.map(decoder.process_sample)
|
361 |
+
# .map(decoder.dict2tuple)
|
362 |
+
.batched(worker_batch, partial=False)
|
363 |
+
# .map(decoder.tuple2dict)
|
364 |
+
.map(decoder.batch_reordering)
|
365 |
+
.with_epoch(epoch_length)
|
366 |
+
.with_length(epoch_length)
|
367 |
+
)
|
368 |
+
loader = (wds.WebLoader(dataset, batch_size=None, num_workers=self.num_workers, shuffle=False)
|
369 |
+
# .unbatched()
|
370 |
+
# .shuffle(1000)
|
371 |
+
# .batched(self.batch_size)
|
372 |
+
# .map(decoder.tuple2dict)
|
373 |
+
)
|
374 |
+
|
375 |
+
print(f"# Training loader length for single worker {epoch_length} with {self.num_workers} workers")
|
376 |
+
|
377 |
+
return loader
|
378 |
+
|
379 |
+
def val_dataloader_wds(self):
|
380 |
+
decoder = ObjaverseDecoerWDS(root_dir=self.root_dir, \
|
381 |
+
image_transforms=self.image_transforms,
|
382 |
+
image_list = None, target_name=self.target_name,
|
383 |
+
**self.kwargs)
|
384 |
+
|
385 |
+
# adjust worker number, as test has much much fewer tars
|
386 |
+
val_workers = min(self.num_workers, len(self.test_tars) // self.world_size)
|
387 |
+
epoch_length = max(self.test_length // self.batch_size // val_workers // self.world_size, 1)
|
388 |
+
dataset = (wds.WebDataset(self.test_tars,
|
389 |
+
shardshuffle=min(1000, len(self.test_tars)),
|
390 |
+
handler=wds.ignore_and_continue,
|
391 |
+
nodesplitter=wds.shardlists.split_by_node)
|
392 |
+
.shuffle(1000)
|
393 |
+
.map(decoder.process_sample)
|
394 |
+
# .map(decoder.dict2tuple)
|
395 |
+
.batched(self.batch_size, partial=False)
|
396 |
+
.with_epoch(epoch_length)
|
397 |
+
.with_length(epoch_length)
|
398 |
+
)
|
399 |
+
loader = (wds.WebLoader(dataset, batch_size=None, num_workers=val_workers, shuffle=False)
|
400 |
+
.unbatched()
|
401 |
+
.shuffle(1000)
|
402 |
+
.batched(self.batch_size)
|
403 |
+
# .map(decoder.tuple2dict)
|
404 |
+
.map(decoder.batch_reordering)
|
405 |
+
)
|
406 |
+
|
407 |
+
print(f"# Validation loader length for single worker {epoch_length} with {val_workers} workers")
|
408 |
+
|
409 |
+
return loader
|
410 |
+
|
411 |
+
def test_dataloader(self):
|
412 |
+
# testing will use all given data
|
413 |
+
return wds.WebLoader(ObjaverseData(root_dir=self.root_dir, test=True,
|
414 |
+
image_transforms=self.image_transforms,
|
415 |
+
image_list = self.paths, target_name=self.target_name,
|
416 |
+
**self.kwargs),
|
417 |
+
batch_size=32, num_workers=self.num_workers, shuffle=False,
|
418 |
+
)
|
419 |
+
|
420 |
+
|
421 |
+
class ObjaverseData(ObjaverseDataDecoder, Dataset):
|
422 |
+
def __init__(self,
|
423 |
+
root_dir='.objaverse/hf-objaverse-v1/views',
|
424 |
+
image_list=None,
|
425 |
+
threads=64,
|
426 |
+
**kargs
|
427 |
+
) -> None:
|
428 |
+
"""Create a dataset from blender rendering results.
|
429 |
+
If you pass in a root directory it will be searched for images
|
430 |
+
ending in ext (ext can be a list)
|
431 |
+
"""
|
432 |
+
self.paths = image_list
|
433 |
+
self.root_dir = Path(root_dir)
|
434 |
+
ObjaverseDataDecoder.__init__(self, **kargs)
|
435 |
+
# pre-load data
|
436 |
+
print(f"Data pre loading start with {threads}...")
|
437 |
+
self.all_target_im = np.zeros((len(self.paths), self.img_size, self.img_size, 3), dtype=np.uint8) + 0
|
438 |
+
self.all_cond_im = np.zeros((len(self.paths), self.img_size, self.img_size, 3), dtype=np.uint8) + 0
|
439 |
+
self.all_filename = ["empty"] * len(self.paths)
|
440 |
+
if self.condition_name == "normal":
|
441 |
+
self.all_normal_img = np.zeros((len(self.paths), self.img_size, self.img_size, 3), dtype=np.uint8) + 0
|
442 |
+
self.all_crop_idx = np.zeros((len(self.paths), 6), dtype=int) + 0
|
443 |
+
|
444 |
+
print("Array allocated..")
|
445 |
+
|
446 |
+
def parallel_load(index):
|
447 |
+
pbar.update(1)
|
448 |
+
self.preload_item(index)
|
449 |
+
|
450 |
+
pbar = tqdm(total=len(self.paths))
|
451 |
+
with ThreadPool(threads) as pool:
|
452 |
+
pool.map(parallel_load, range(len(self.paths)))
|
453 |
+
pool.close()
|
454 |
+
pool.join()
|
455 |
+
|
456 |
+
print("Data pre loading done...")
|
457 |
+
|
458 |
+
def __len__(self):
|
459 |
+
return len(self.paths)
|
460 |
+
|
461 |
+
def load_mask(self, mask_filename, cond_im):
|
462 |
+
# auto image file extention
|
463 |
+
glob_files = glob.glob(mask_filename.rsplit(".", 1)[0] + ".*")
|
464 |
+
if len(glob_files) == 0:
|
465 |
+
print("Warning: no mask image find")
|
466 |
+
img_mask = np.ones_like(cond_im)
|
467 |
+
|
468 |
+
if cond_im.shape[-1] == 4:
|
469 |
+
print("Use image mask")
|
470 |
+
img_mask = img_mask * cond_im[:, :, -1:]
|
471 |
+
elif len(glob_files) == 1:
|
472 |
+
img_mask = np.array(self.normalized_read(glob_files[0]))
|
473 |
+
else:
|
474 |
+
raise NotImplementedError("Too many mask images found! {}")
|
475 |
+
return img_mask
|
476 |
+
|
477 |
+
def preload_item(self, index):
|
478 |
+
path = self.paths[index]
|
479 |
+
filename = os.path.join(path)
|
480 |
+
filename, condition_filename, \
|
481 |
+
mask_filename, normal_condition_filename, filename_targets = self.path_parsing(filename)
|
482 |
+
|
483 |
+
# get file streams
|
484 |
+
if filename_targets is None:
|
485 |
+
filename_read = filename
|
486 |
+
else:
|
487 |
+
filename_read = filename_targets
|
488 |
+
|
489 |
+
# image reading
|
490 |
+
target_im, cond_im, normal_img = self.read_images(filename_read,
|
491 |
+
condition_filename, normal_condition_filename)
|
492 |
+
|
493 |
+
# mask reading
|
494 |
+
img_mask = self.load_mask(mask_filename, cond_im)
|
495 |
+
|
496 |
+
# post processing
|
497 |
+
target_im, cond_im, normal_img, crop_idx = self.image_post_processing(img_mask, target_im, cond_im, normal_img)
|
498 |
+
if self.test:
|
499 |
+
# crop out valid_mask
|
500 |
+
self.all_crop_idx[index] = crop_idx
|
501 |
+
|
502 |
+
# put results
|
503 |
+
self.all_target_im[index] = target_im
|
504 |
+
self.all_cond_im[index] = cond_im
|
505 |
+
self.all_filename[index] = filename
|
506 |
+
if self.condition_name == "normal":
|
507 |
+
self.all_normal_img[index] = normal_img
|
508 |
+
|
509 |
+
def get_camera(self, input_filename):
|
510 |
+
camera_file = input_filename.replace(f'{self.target_name}0001', \
|
511 |
+
'camera').rsplit(".")[0] + ".pkl"
|
512 |
+
cam_dir, cam_name = camera_file.rsplit("/", 1)
|
513 |
+
cam_name = f"{cam_name:>15}"
|
514 |
+
camera_file = os.path.join(cam_dir, cam_name)
|
515 |
+
cam = pickle.load(open(camera_file, 'rb'))
|
516 |
+
return cam
|
517 |
+
|
518 |
+
|
519 |
+
def __getitem__(self, index):
|
520 |
+
target_im = self.process_im(self.all_target_im[index])
|
521 |
+
cond_img = self.process_im(self.all_cond_im[index])
|
522 |
+
filename = self.all_filename[index]
|
523 |
+
normal_img = self.process_im(self.all_normal_img[index]) \
|
524 |
+
if self.condition_name == "normal" \
|
525 |
+
else None
|
526 |
+
|
527 |
+
sample = self.parse_item(target_im, cond_img, normal_img, filename)
|
528 |
+
if self.test:
|
529 |
+
sample["crop_idx"] = self.all_crop_idx[index]
|
530 |
+
return sample
|
531 |
+
|
532 |
+
|
533 |
+
if __name__ == "__main__":
|
534 |
+
import pyhocon
|
535 |
+
|
536 |
+
class DictAsMember(dict):
|
537 |
+
def __getattr__(self, name):
|
538 |
+
value = self[name]
|
539 |
+
if isinstance(value, dict):
|
540 |
+
value = DictAsMember(value)
|
541 |
+
return value
|
542 |
+
|
543 |
+
def ConfigAsMember(config):
|
544 |
+
config_dict = DictAsMember(config)
|
545 |
+
for key in config_dict.keys():
|
546 |
+
if isinstance(config_dict[key], pyhocon.config_tree.ConfigTree):
|
547 |
+
config_dict[key] = ConfigAsMember(config_dict[key])
|
548 |
+
return config_dict
|
549 |
+
|
550 |
+
train_config = DictAsMember({
|
551 |
+
"validation": False,
|
552 |
+
"image_transforms": {"size": 256}
|
553 |
+
})
|
554 |
+
val_config = DictAsMember({
|
555 |
+
"validation": True,
|
556 |
+
"image_transforms": {"size": 256}
|
557 |
+
})
|
558 |
+
objaverse_data_list = DictAsMember({
|
559 |
+
"image_list_cache_path": "image_lists/half_400000_image_list.npz",
|
560 |
+
})
|
561 |
+
data_module = ObjaverseDataModuleFromConfig(root_dir='/mnt/volumes/perception/hujunkang/codes/renders/material-diffusion/data/objaverse_rendering',
|
562 |
+
batch_size=4, train=train_config, validation=val_config,
|
563 |
+
test=None, num_workers=1, objaverse_data_list=objaverse_data_list, ext="png",
|
564 |
+
target_name="albedo", use_wds=False, tar_config=None)
|
565 |
+
|
566 |
+
data_module.setup()
|
567 |
+
train_dataloader_naive = data_module.train_dataloader_naive()
|
models/ldm/extras.py
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pathlib import Path
|
2 |
+
from omegaconf import OmegaConf
|
3 |
+
import torch
|
4 |
+
from ldm.util import instantiate_from_config
|
5 |
+
import logging
|
6 |
+
from contextlib import contextmanager
|
7 |
+
|
8 |
+
from contextlib import contextmanager
|
9 |
+
import logging
|
10 |
+
|
11 |
+
@contextmanager
|
12 |
+
def all_logging_disabled(highest_level=logging.CRITICAL):
|
13 |
+
"""
|
14 |
+
A context manager that will prevent any logging messages
|
15 |
+
triggered during the body from being processed.
|
16 |
+
|
17 |
+
:param highest_level: the maximum logging level in use.
|
18 |
+
This would only need to be changed if a custom level greater than CRITICAL
|
19 |
+
is defined.
|
20 |
+
|
21 |
+
https://gist.github.com/simon-weber/7853144
|
22 |
+
"""
|
23 |
+
# two kind-of hacks here:
|
24 |
+
# * can't get the highest logging level in effect => delegate to the user
|
25 |
+
# * can't get the current module-level override => use an undocumented
|
26 |
+
# (but non-private!) interface
|
27 |
+
|
28 |
+
previous_level = logging.root.manager.disable
|
29 |
+
|
30 |
+
logging.disable(highest_level)
|
31 |
+
|
32 |
+
try:
|
33 |
+
yield
|
34 |
+
finally:
|
35 |
+
logging.disable(previous_level)
|
36 |
+
|
37 |
+
def load_training_dir(train_dir, device, epoch="last"):
|
38 |
+
"""Load a checkpoint and config from training directory"""
|
39 |
+
train_dir = Path(train_dir)
|
40 |
+
ckpt = list(train_dir.rglob(f"*{epoch}.ckpt"))
|
41 |
+
assert len(ckpt) == 1, f"found {len(ckpt)} matching ckpt files"
|
42 |
+
config = list(train_dir.rglob(f"*-project.yaml"))
|
43 |
+
assert len(ckpt) > 0, f"didn't find any config in {train_dir}"
|
44 |
+
if len(config) > 1:
|
45 |
+
print(f"found {len(config)} matching config files")
|
46 |
+
config = sorted(config)[-1]
|
47 |
+
print(f"selecting {config}")
|
48 |
+
else:
|
49 |
+
config = config[0]
|
50 |
+
|
51 |
+
|
52 |
+
config = OmegaConf.load(config)
|
53 |
+
return load_model_from_config(config, ckpt[0], device)
|
54 |
+
|
55 |
+
def load_model_from_config(config, ckpt, device="cpu", verbose=False):
|
56 |
+
"""Loads a model from config and a ckpt
|
57 |
+
if config is a path will use omegaconf to load
|
58 |
+
"""
|
59 |
+
if isinstance(config, (str, Path)):
|
60 |
+
config = OmegaConf.load(config)
|
61 |
+
|
62 |
+
with all_logging_disabled():
|
63 |
+
print(f"Loading model from {ckpt}")
|
64 |
+
pl_sd = torch.load(ckpt, map_location="cpu")
|
65 |
+
global_step = pl_sd["global_step"]
|
66 |
+
sd = pl_sd["state_dict"]
|
67 |
+
model = instantiate_from_config(config.model)
|
68 |
+
m, u = model.load_state_dict(sd, strict=False)
|
69 |
+
if len(m) > 0 and verbose:
|
70 |
+
print("missing keys:")
|
71 |
+
print(m)
|
72 |
+
if len(u) > 0 and verbose:
|
73 |
+
print("unexpected keys:")
|
74 |
+
model.to(device)
|
75 |
+
model.eval()
|
76 |
+
model.cond_stage_model.device = device
|
77 |
+
return model
|
models/ldm/guidance.py
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import List, Tuple
|
2 |
+
from scipy import interpolate
|
3 |
+
import numpy as np
|
4 |
+
import torch
|
5 |
+
import matplotlib.pyplot as plt
|
6 |
+
from IPython.display import clear_output
|
7 |
+
import abc
|
8 |
+
|
9 |
+
|
10 |
+
class GuideModel(torch.nn.Module, abc.ABC):
|
11 |
+
def __init__(self) -> None:
|
12 |
+
super().__init__()
|
13 |
+
|
14 |
+
@abc.abstractmethod
|
15 |
+
def preprocess(self, x_img):
|
16 |
+
pass
|
17 |
+
|
18 |
+
@abc.abstractmethod
|
19 |
+
def compute_loss(self, inp):
|
20 |
+
pass
|
21 |
+
|
22 |
+
|
23 |
+
class Guider(torch.nn.Module):
|
24 |
+
def __init__(self, sampler, guide_model, scale=1.0, verbose=False):
|
25 |
+
"""Apply classifier guidance
|
26 |
+
|
27 |
+
Specify a guidance scale as either a scalar
|
28 |
+
Or a schedule as a list of tuples t = 0->1 and scale, e.g.
|
29 |
+
[(0, 10), (0.5, 20), (1, 50)]
|
30 |
+
"""
|
31 |
+
super().__init__()
|
32 |
+
self.sampler = sampler
|
33 |
+
self.index = 0
|
34 |
+
self.show = verbose
|
35 |
+
self.guide_model = guide_model
|
36 |
+
self.history = []
|
37 |
+
|
38 |
+
if isinstance(scale, (Tuple, List)):
|
39 |
+
times = np.array([x[0] for x in scale])
|
40 |
+
values = np.array([x[1] for x in scale])
|
41 |
+
self.scale_schedule = {"times": times, "values": values}
|
42 |
+
else:
|
43 |
+
self.scale_schedule = float(scale)
|
44 |
+
|
45 |
+
self.ddim_timesteps = sampler.ddim_timesteps
|
46 |
+
self.ddpm_num_timesteps = sampler.ddpm_num_timesteps
|
47 |
+
|
48 |
+
|
49 |
+
def get_scales(self):
|
50 |
+
if isinstance(self.scale_schedule, float):
|
51 |
+
return len(self.ddim_timesteps)*[self.scale_schedule]
|
52 |
+
|
53 |
+
interpolater = interpolate.interp1d(self.scale_schedule["times"], self.scale_schedule["values"])
|
54 |
+
fractional_steps = np.array(self.ddim_timesteps)/self.ddpm_num_timesteps
|
55 |
+
return interpolater(fractional_steps)
|
56 |
+
|
57 |
+
def modify_score(self, model, e_t, x, t, c):
|
58 |
+
|
59 |
+
# TODO look up index by t
|
60 |
+
scale = self.get_scales()[self.index]
|
61 |
+
|
62 |
+
if (scale == 0):
|
63 |
+
return e_t
|
64 |
+
|
65 |
+
sqrt_1ma = self.sampler.ddim_sqrt_one_minus_alphas[self.index].to(x.device)
|
66 |
+
with torch.enable_grad():
|
67 |
+
x_in = x.detach().requires_grad_(True)
|
68 |
+
pred_x0 = model.predict_start_from_noise(x_in, t=t, noise=e_t)
|
69 |
+
x_img = model.first_stage_model.decode((1/0.18215)*pred_x0)
|
70 |
+
|
71 |
+
inp = self.guide_model.preprocess(x_img)
|
72 |
+
loss = self.guide_model.compute_loss(inp)
|
73 |
+
grads = torch.autograd.grad(loss.sum(), x_in)[0]
|
74 |
+
correction = grads * scale
|
75 |
+
|
76 |
+
if self.show:
|
77 |
+
clear_output(wait=True)
|
78 |
+
print(loss.item(), scale, correction.abs().max().item(), e_t.abs().max().item())
|
79 |
+
self.history.append([loss.item(), scale, correction.min().item(), correction.max().item()])
|
80 |
+
plt.imshow((inp[0].detach().permute(1,2,0).clamp(-1,1).cpu()+1)/2)
|
81 |
+
plt.axis('off')
|
82 |
+
plt.show()
|
83 |
+
plt.imshow(correction[0][0].detach().cpu())
|
84 |
+
plt.axis('off')
|
85 |
+
plt.show()
|
86 |
+
|
87 |
+
|
88 |
+
e_t_mod = e_t - sqrt_1ma*correction
|
89 |
+
if self.show:
|
90 |
+
fig, axs = plt.subplots(1, 3)
|
91 |
+
axs[0].imshow(e_t[0][0].detach().cpu(), vmin=-2, vmax=+2)
|
92 |
+
axs[1].imshow(e_t_mod[0][0].detach().cpu(), vmin=-2, vmax=+2)
|
93 |
+
axs[2].imshow(correction[0][0].detach().cpu(), vmin=-2, vmax=+2)
|
94 |
+
plt.show()
|
95 |
+
self.index += 1
|
96 |
+
return e_t_mod
|
models/ldm/lr_scheduler.py
ADDED
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
|
3 |
+
|
4 |
+
class LambdaWarmUpCosineScheduler:
|
5 |
+
"""
|
6 |
+
note: use with a base_lr of 1.0
|
7 |
+
"""
|
8 |
+
def __init__(self, warm_up_steps, lr_min, lr_max, lr_start, max_decay_steps, verbosity_interval=0):
|
9 |
+
self.lr_warm_up_steps = warm_up_steps
|
10 |
+
self.lr_start = lr_start
|
11 |
+
self.lr_min = lr_min
|
12 |
+
self.lr_max = lr_max
|
13 |
+
self.lr_max_decay_steps = max_decay_steps
|
14 |
+
self.last_lr = 0.
|
15 |
+
self.verbosity_interval = verbosity_interval
|
16 |
+
|
17 |
+
def schedule(self, n, **kwargs):
|
18 |
+
if self.verbosity_interval > 0:
|
19 |
+
if n % self.verbosity_interval == 0: print(f"current step: {n}, recent lr-multiplier: {self.last_lr}")
|
20 |
+
if n < self.lr_warm_up_steps:
|
21 |
+
lr = (self.lr_max - self.lr_start) / self.lr_warm_up_steps * n + self.lr_start
|
22 |
+
self.last_lr = lr
|
23 |
+
return lr
|
24 |
+
else:
|
25 |
+
t = (n - self.lr_warm_up_steps) / (self.lr_max_decay_steps - self.lr_warm_up_steps)
|
26 |
+
t = min(t, 1.0)
|
27 |
+
lr = self.lr_min + 0.5 * (self.lr_max - self.lr_min) * (
|
28 |
+
1 + np.cos(t * np.pi))
|
29 |
+
self.last_lr = lr
|
30 |
+
return lr
|
31 |
+
|
32 |
+
def __call__(self, n, **kwargs):
|
33 |
+
return self.schedule(n,**kwargs)
|
34 |
+
|
35 |
+
|
36 |
+
class LambdaWarmUpCosineScheduler2:
|
37 |
+
"""
|
38 |
+
supports repeated iterations, configurable via lists
|
39 |
+
note: use with a base_lr of 1.0.
|
40 |
+
"""
|
41 |
+
def __init__(self, warm_up_steps, f_min, f_max, f_start, cycle_lengths, verbosity_interval=0):
|
42 |
+
assert len(warm_up_steps) == len(f_min) == len(f_max) == len(f_start) == len(cycle_lengths)
|
43 |
+
self.lr_warm_up_steps = warm_up_steps
|
44 |
+
self.f_start = f_start
|
45 |
+
self.f_min = f_min
|
46 |
+
self.f_max = f_max
|
47 |
+
self.cycle_lengths = cycle_lengths
|
48 |
+
self.cum_cycles = np.cumsum([0] + list(self.cycle_lengths))
|
49 |
+
self.last_f = 0.
|
50 |
+
self.verbosity_interval = verbosity_interval
|
51 |
+
|
52 |
+
def find_in_interval(self, n):
|
53 |
+
interval = 0
|
54 |
+
for cl in self.cum_cycles[1:]:
|
55 |
+
if n <= cl:
|
56 |
+
return interval
|
57 |
+
interval += 1
|
58 |
+
|
59 |
+
def schedule(self, n, **kwargs):
|
60 |
+
cycle = self.find_in_interval(n)
|
61 |
+
n = n - self.cum_cycles[cycle]
|
62 |
+
if self.verbosity_interval > 0:
|
63 |
+
if n % self.verbosity_interval == 0: print(f"current step: {n}, recent lr-multiplier: {self.last_f}, "
|
64 |
+
f"current cycle {cycle}")
|
65 |
+
if n < self.lr_warm_up_steps[cycle]:
|
66 |
+
f = (self.f_max[cycle] - self.f_start[cycle]) / self.lr_warm_up_steps[cycle] * n + self.f_start[cycle]
|
67 |
+
self.last_f = f
|
68 |
+
return f
|
69 |
+
else:
|
70 |
+
t = (n - self.lr_warm_up_steps[cycle]) / (self.cycle_lengths[cycle] - self.lr_warm_up_steps[cycle])
|
71 |
+
t = min(t, 1.0)
|
72 |
+
f = self.f_min[cycle] + 0.5 * (self.f_max[cycle] - self.f_min[cycle]) * (
|
73 |
+
1 + np.cos(t * np.pi))
|
74 |
+
self.last_f = f
|
75 |
+
return f
|
76 |
+
|
77 |
+
def __call__(self, n, **kwargs):
|
78 |
+
return self.schedule(n, **kwargs)
|
79 |
+
|
80 |
+
|
81 |
+
class LambdaLinearScheduler(LambdaWarmUpCosineScheduler2):
|
82 |
+
|
83 |
+
def schedule(self, n, **kwargs):
|
84 |
+
cycle = self.find_in_interval(n)
|
85 |
+
n = n - self.cum_cycles[cycle]
|
86 |
+
if self.verbosity_interval > 0:
|
87 |
+
if n % self.verbosity_interval == 0: print(f"current step: {n}, recent lr-multiplier: {self.last_f}, "
|
88 |
+
f"current cycle {cycle}")
|
89 |
+
|
90 |
+
if n < self.lr_warm_up_steps[cycle]:
|
91 |
+
f = (self.f_max[cycle] - self.f_start[cycle]) / self.lr_warm_up_steps[cycle] * n + self.f_start[cycle]
|
92 |
+
self.last_f = f
|
93 |
+
return f
|
94 |
+
else:
|
95 |
+
f = self.f_min[cycle] + (self.f_max[cycle] - self.f_min[cycle]) * (self.cycle_lengths[cycle] - n) / (self.cycle_lengths[cycle])
|
96 |
+
self.last_f = f
|
97 |
+
return f
|
98 |
+
|
models/ldm/models/autoencoder.py
ADDED
@@ -0,0 +1,443 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import pytorch_lightning as pl
|
3 |
+
import torch.nn.functional as F
|
4 |
+
from contextlib import contextmanager
|
5 |
+
|
6 |
+
from taming.modules.vqvae.quantize import VectorQuantizer2 as VectorQuantizer
|
7 |
+
|
8 |
+
from ldm.modules.diffusionmodules.model import Encoder, Decoder
|
9 |
+
from ldm.modules.distributions.distributions import DiagonalGaussianDistribution
|
10 |
+
|
11 |
+
from ldm.util import instantiate_from_config
|
12 |
+
|
13 |
+
|
14 |
+
class VQModel(pl.LightningModule):
|
15 |
+
def __init__(self,
|
16 |
+
ddconfig,
|
17 |
+
lossconfig,
|
18 |
+
n_embed,
|
19 |
+
embed_dim,
|
20 |
+
ckpt_path=None,
|
21 |
+
ignore_keys=[],
|
22 |
+
image_key="image",
|
23 |
+
colorize_nlabels=None,
|
24 |
+
monitor=None,
|
25 |
+
batch_resize_range=None,
|
26 |
+
scheduler_config=None,
|
27 |
+
lr_g_factor=1.0,
|
28 |
+
remap=None,
|
29 |
+
sane_index_shape=False, # tell vector quantizer to return indices as bhw
|
30 |
+
use_ema=False
|
31 |
+
):
|
32 |
+
super().__init__()
|
33 |
+
self.embed_dim = embed_dim
|
34 |
+
self.n_embed = n_embed
|
35 |
+
self.image_key = image_key
|
36 |
+
self.encoder = Encoder(**ddconfig)
|
37 |
+
self.decoder = Decoder(**ddconfig)
|
38 |
+
self.loss = instantiate_from_config(lossconfig)
|
39 |
+
self.quantize = VectorQuantizer(n_embed, embed_dim, beta=0.25,
|
40 |
+
remap=remap,
|
41 |
+
sane_index_shape=sane_index_shape)
|
42 |
+
self.quant_conv = torch.nn.Conv2d(ddconfig["z_channels"], embed_dim, 1)
|
43 |
+
self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
|
44 |
+
if colorize_nlabels is not None:
|
45 |
+
assert type(colorize_nlabels)==int
|
46 |
+
self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
|
47 |
+
if monitor is not None:
|
48 |
+
self.monitor = monitor
|
49 |
+
self.batch_resize_range = batch_resize_range
|
50 |
+
if self.batch_resize_range is not None:
|
51 |
+
print(f"{self.__class__.__name__}: Using per-batch resizing in range {batch_resize_range}.")
|
52 |
+
|
53 |
+
self.use_ema = use_ema
|
54 |
+
if self.use_ema:
|
55 |
+
self.model_ema = LitEma(self)
|
56 |
+
print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
|
57 |
+
|
58 |
+
if ckpt_path is not None:
|
59 |
+
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
|
60 |
+
self.scheduler_config = scheduler_config
|
61 |
+
self.lr_g_factor = lr_g_factor
|
62 |
+
|
63 |
+
@contextmanager
|
64 |
+
def ema_scope(self, context=None):
|
65 |
+
if self.use_ema:
|
66 |
+
self.model_ema.store(self.parameters())
|
67 |
+
self.model_ema.copy_to(self)
|
68 |
+
if context is not None:
|
69 |
+
print(f"{context}: Switched to EMA weights")
|
70 |
+
try:
|
71 |
+
yield None
|
72 |
+
finally:
|
73 |
+
if self.use_ema:
|
74 |
+
self.model_ema.restore(self.parameters())
|
75 |
+
if context is not None:
|
76 |
+
print(f"{context}: Restored training weights")
|
77 |
+
|
78 |
+
def init_from_ckpt(self, path, ignore_keys=list()):
|
79 |
+
sd = torch.load(path, map_location="cpu")["state_dict"]
|
80 |
+
keys = list(sd.keys())
|
81 |
+
for k in keys:
|
82 |
+
for ik in ignore_keys:
|
83 |
+
if k.startswith(ik):
|
84 |
+
print("Deleting key {} from state_dict.".format(k))
|
85 |
+
del sd[k]
|
86 |
+
missing, unexpected = self.load_state_dict(sd, strict=False)
|
87 |
+
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
88 |
+
if len(missing) > 0:
|
89 |
+
print(f"Missing Keys: {missing}")
|
90 |
+
print(f"Unexpected Keys: {unexpected}")
|
91 |
+
|
92 |
+
def on_train_batch_end(self, *args, **kwargs):
|
93 |
+
if self.use_ema:
|
94 |
+
self.model_ema(self)
|
95 |
+
|
96 |
+
def encode(self, x):
|
97 |
+
h = self.encoder(x)
|
98 |
+
h = self.quant_conv(h)
|
99 |
+
quant, emb_loss, info = self.quantize(h)
|
100 |
+
return quant, emb_loss, info
|
101 |
+
|
102 |
+
def encode_to_prequant(self, x):
|
103 |
+
h = self.encoder(x)
|
104 |
+
h = self.quant_conv(h)
|
105 |
+
return h
|
106 |
+
|
107 |
+
def decode(self, quant):
|
108 |
+
quant = self.post_quant_conv(quant)
|
109 |
+
dec = self.decoder(quant)
|
110 |
+
return dec
|
111 |
+
|
112 |
+
def decode_code(self, code_b):
|
113 |
+
quant_b = self.quantize.embed_code(code_b)
|
114 |
+
dec = self.decode(quant_b)
|
115 |
+
return dec
|
116 |
+
|
117 |
+
def forward(self, input, return_pred_indices=False):
|
118 |
+
quant, diff, (_,_,ind) = self.encode(input)
|
119 |
+
dec = self.decode(quant)
|
120 |
+
if return_pred_indices:
|
121 |
+
return dec, diff, ind
|
122 |
+
return dec, diff
|
123 |
+
|
124 |
+
def get_input(self, batch, k):
|
125 |
+
x = batch[k]
|
126 |
+
if len(x.shape) == 3:
|
127 |
+
x = x[..., None]
|
128 |
+
x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
|
129 |
+
if self.batch_resize_range is not None:
|
130 |
+
lower_size = self.batch_resize_range[0]
|
131 |
+
upper_size = self.batch_resize_range[1]
|
132 |
+
if self.global_step <= 4:
|
133 |
+
# do the first few batches with max size to avoid later oom
|
134 |
+
new_resize = upper_size
|
135 |
+
else:
|
136 |
+
new_resize = np.random.choice(np.arange(lower_size, upper_size+16, 16))
|
137 |
+
if new_resize != x.shape[2]:
|
138 |
+
x = F.interpolate(x, size=new_resize, mode="bicubic")
|
139 |
+
x = x.detach()
|
140 |
+
return x
|
141 |
+
|
142 |
+
def training_step(self, batch, batch_idx, optimizer_idx):
|
143 |
+
# https://github.com/pytorch/pytorch/issues/37142
|
144 |
+
# try not to fool the heuristics
|
145 |
+
x = self.get_input(batch, self.image_key)
|
146 |
+
xrec, qloss, ind = self(x, return_pred_indices=True)
|
147 |
+
|
148 |
+
if optimizer_idx == 0:
|
149 |
+
# autoencode
|
150 |
+
aeloss, log_dict_ae = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
|
151 |
+
last_layer=self.get_last_layer(), split="train",
|
152 |
+
predicted_indices=ind)
|
153 |
+
|
154 |
+
self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=True)
|
155 |
+
return aeloss
|
156 |
+
|
157 |
+
if optimizer_idx == 1:
|
158 |
+
# discriminator
|
159 |
+
discloss, log_dict_disc = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
|
160 |
+
last_layer=self.get_last_layer(), split="train")
|
161 |
+
self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=True)
|
162 |
+
return discloss
|
163 |
+
|
164 |
+
def validation_step(self, batch, batch_idx):
|
165 |
+
log_dict = self._validation_step(batch, batch_idx)
|
166 |
+
with self.ema_scope():
|
167 |
+
log_dict_ema = self._validation_step(batch, batch_idx, suffix="_ema")
|
168 |
+
return log_dict
|
169 |
+
|
170 |
+
def _validation_step(self, batch, batch_idx, suffix=""):
|
171 |
+
x = self.get_input(batch, self.image_key)
|
172 |
+
xrec, qloss, ind = self(x, return_pred_indices=True)
|
173 |
+
aeloss, log_dict_ae = self.loss(qloss, x, xrec, 0,
|
174 |
+
self.global_step,
|
175 |
+
last_layer=self.get_last_layer(),
|
176 |
+
split="val"+suffix,
|
177 |
+
predicted_indices=ind
|
178 |
+
)
|
179 |
+
|
180 |
+
discloss, log_dict_disc = self.loss(qloss, x, xrec, 1,
|
181 |
+
self.global_step,
|
182 |
+
last_layer=self.get_last_layer(),
|
183 |
+
split="val"+suffix,
|
184 |
+
predicted_indices=ind
|
185 |
+
)
|
186 |
+
rec_loss = log_dict_ae[f"val{suffix}/rec_loss"]
|
187 |
+
self.log(f"val{suffix}/rec_loss", rec_loss,
|
188 |
+
prog_bar=True, logger=True, on_step=False, on_epoch=True, sync_dist=True)
|
189 |
+
self.log(f"val{suffix}/aeloss", aeloss,
|
190 |
+
prog_bar=True, logger=True, on_step=False, on_epoch=True, sync_dist=True)
|
191 |
+
if version.parse(pl.__version__) >= version.parse('1.4.0'):
|
192 |
+
del log_dict_ae[f"val{suffix}/rec_loss"]
|
193 |
+
self.log_dict(log_dict_ae)
|
194 |
+
self.log_dict(log_dict_disc)
|
195 |
+
return self.log_dict
|
196 |
+
|
197 |
+
def configure_optimizers(self):
|
198 |
+
lr_d = self.learning_rate
|
199 |
+
lr_g = self.lr_g_factor*self.learning_rate
|
200 |
+
print("lr_d", lr_d)
|
201 |
+
print("lr_g", lr_g)
|
202 |
+
opt_ae = torch.optim.Adam(list(self.encoder.parameters())+
|
203 |
+
list(self.decoder.parameters())+
|
204 |
+
list(self.quantize.parameters())+
|
205 |
+
list(self.quant_conv.parameters())+
|
206 |
+
list(self.post_quant_conv.parameters()),
|
207 |
+
lr=lr_g, betas=(0.5, 0.9))
|
208 |
+
opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
|
209 |
+
lr=lr_d, betas=(0.5, 0.9))
|
210 |
+
|
211 |
+
if self.scheduler_config is not None:
|
212 |
+
scheduler = instantiate_from_config(self.scheduler_config)
|
213 |
+
|
214 |
+
print("Setting up LambdaLR scheduler...")
|
215 |
+
scheduler = [
|
216 |
+
{
|
217 |
+
'scheduler': LambdaLR(opt_ae, lr_lambda=scheduler.schedule),
|
218 |
+
'interval': 'step',
|
219 |
+
'frequency': 1
|
220 |
+
},
|
221 |
+
{
|
222 |
+
'scheduler': LambdaLR(opt_disc, lr_lambda=scheduler.schedule),
|
223 |
+
'interval': 'step',
|
224 |
+
'frequency': 1
|
225 |
+
},
|
226 |
+
]
|
227 |
+
return [opt_ae, opt_disc], scheduler
|
228 |
+
return [opt_ae, opt_disc], []
|
229 |
+
|
230 |
+
def get_last_layer(self):
|
231 |
+
return self.decoder.conv_out.weight
|
232 |
+
|
233 |
+
def log_images(self, batch, only_inputs=False, plot_ema=False, **kwargs):
|
234 |
+
log = dict()
|
235 |
+
x = self.get_input(batch, self.image_key)
|
236 |
+
x = x.to(self.device)
|
237 |
+
if only_inputs:
|
238 |
+
log["inputs"] = x
|
239 |
+
return log
|
240 |
+
xrec, _ = self(x)
|
241 |
+
if x.shape[1] > 3:
|
242 |
+
# colorize with random projection
|
243 |
+
assert xrec.shape[1] > 3
|
244 |
+
x = self.to_rgb(x)
|
245 |
+
xrec = self.to_rgb(xrec)
|
246 |
+
log["inputs"] = x
|
247 |
+
log["reconstructions"] = xrec
|
248 |
+
if plot_ema:
|
249 |
+
with self.ema_scope():
|
250 |
+
xrec_ema, _ = self(x)
|
251 |
+
if x.shape[1] > 3: xrec_ema = self.to_rgb(xrec_ema)
|
252 |
+
log["reconstructions_ema"] = xrec_ema
|
253 |
+
return log
|
254 |
+
|
255 |
+
def to_rgb(self, x):
|
256 |
+
assert self.image_key == "segmentation"
|
257 |
+
if not hasattr(self, "colorize"):
|
258 |
+
self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
|
259 |
+
x = F.conv2d(x, weight=self.colorize)
|
260 |
+
x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
|
261 |
+
return x
|
262 |
+
|
263 |
+
|
264 |
+
class VQModelInterface(VQModel):
|
265 |
+
def __init__(self, embed_dim, *args, **kwargs):
|
266 |
+
super().__init__(embed_dim=embed_dim, *args, **kwargs)
|
267 |
+
self.embed_dim = embed_dim
|
268 |
+
|
269 |
+
def encode(self, x):
|
270 |
+
h = self.encoder(x)
|
271 |
+
h = self.quant_conv(h)
|
272 |
+
return h
|
273 |
+
|
274 |
+
def decode(self, h, force_not_quantize=False):
|
275 |
+
# also go through quantization layer
|
276 |
+
if not force_not_quantize:
|
277 |
+
quant, emb_loss, info = self.quantize(h)
|
278 |
+
else:
|
279 |
+
quant = h
|
280 |
+
quant = self.post_quant_conv(quant)
|
281 |
+
dec = self.decoder(quant)
|
282 |
+
return dec
|
283 |
+
|
284 |
+
|
285 |
+
class AutoencoderKL(pl.LightningModule):
|
286 |
+
def __init__(self,
|
287 |
+
ddconfig,
|
288 |
+
lossconfig,
|
289 |
+
embed_dim,
|
290 |
+
ckpt_path=None,
|
291 |
+
ignore_keys=[],
|
292 |
+
image_key="image",
|
293 |
+
colorize_nlabels=None,
|
294 |
+
monitor=None,
|
295 |
+
):
|
296 |
+
super().__init__()
|
297 |
+
self.image_key = image_key
|
298 |
+
self.encoder = Encoder(**ddconfig)
|
299 |
+
self.decoder = Decoder(**ddconfig)
|
300 |
+
self.loss = instantiate_from_config(lossconfig)
|
301 |
+
assert ddconfig["double_z"]
|
302 |
+
self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1)
|
303 |
+
self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
|
304 |
+
self.embed_dim = embed_dim
|
305 |
+
if colorize_nlabels is not None:
|
306 |
+
assert type(colorize_nlabels)==int
|
307 |
+
self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
|
308 |
+
if monitor is not None:
|
309 |
+
self.monitor = monitor
|
310 |
+
if ckpt_path is not None:
|
311 |
+
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
|
312 |
+
|
313 |
+
def init_from_ckpt(self, path, ignore_keys=list()):
|
314 |
+
sd = torch.load(path, map_location="cpu")["state_dict"]
|
315 |
+
keys = list(sd.keys())
|
316 |
+
for k in keys:
|
317 |
+
for ik in ignore_keys:
|
318 |
+
if k.startswith(ik):
|
319 |
+
print("Deleting key {} from state_dict.".format(k))
|
320 |
+
del sd[k]
|
321 |
+
self.load_state_dict(sd, strict=False)
|
322 |
+
print(f"Restored from {path}")
|
323 |
+
|
324 |
+
def encode(self, x):
|
325 |
+
h = self.encoder(x)
|
326 |
+
moments = self.quant_conv(h)
|
327 |
+
posterior = DiagonalGaussianDistribution(moments)
|
328 |
+
return posterior
|
329 |
+
|
330 |
+
def decode(self, z):
|
331 |
+
z = self.post_quant_conv(z)
|
332 |
+
dec = self.decoder(z)
|
333 |
+
return dec
|
334 |
+
|
335 |
+
def forward(self, input, sample_posterior=True):
|
336 |
+
posterior = self.encode(input)
|
337 |
+
if sample_posterior:
|
338 |
+
z = posterior.sample()
|
339 |
+
else:
|
340 |
+
z = posterior.mode()
|
341 |
+
dec = self.decode(z)
|
342 |
+
return dec, posterior
|
343 |
+
|
344 |
+
def get_input(self, batch, k):
|
345 |
+
x = batch[k]
|
346 |
+
if len(x.shape) == 3:
|
347 |
+
x = x[..., None]
|
348 |
+
x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
|
349 |
+
return x
|
350 |
+
|
351 |
+
def training_step(self, batch, batch_idx, optimizer_idx):
|
352 |
+
inputs = self.get_input(batch, self.image_key)
|
353 |
+
reconstructions, posterior = self(inputs)
|
354 |
+
|
355 |
+
if optimizer_idx == 0:
|
356 |
+
# train encoder+decoder+logvar
|
357 |
+
aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
|
358 |
+
last_layer=self.get_last_layer(), split="train")
|
359 |
+
self.log("aeloss", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
|
360 |
+
self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False)
|
361 |
+
return aeloss
|
362 |
+
|
363 |
+
if optimizer_idx == 1:
|
364 |
+
# train the discriminator
|
365 |
+
discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
|
366 |
+
last_layer=self.get_last_layer(), split="train")
|
367 |
+
|
368 |
+
self.log("discloss", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
|
369 |
+
self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False)
|
370 |
+
return discloss
|
371 |
+
|
372 |
+
def validation_step(self, batch, batch_idx):
|
373 |
+
inputs = self.get_input(batch, self.image_key)
|
374 |
+
reconstructions, posterior = self(inputs)
|
375 |
+
aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, 0, self.global_step,
|
376 |
+
last_layer=self.get_last_layer(), split="val")
|
377 |
+
|
378 |
+
discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, 1, self.global_step,
|
379 |
+
last_layer=self.get_last_layer(), split="val")
|
380 |
+
|
381 |
+
self.log("val/rec_loss", log_dict_ae["val/rec_loss"])
|
382 |
+
self.log_dict(log_dict_ae)
|
383 |
+
self.log_dict(log_dict_disc)
|
384 |
+
return self.log_dict
|
385 |
+
|
386 |
+
def configure_optimizers(self):
|
387 |
+
lr = self.learning_rate
|
388 |
+
opt_ae = torch.optim.Adam(list(self.encoder.parameters())+
|
389 |
+
list(self.decoder.parameters())+
|
390 |
+
list(self.quant_conv.parameters())+
|
391 |
+
list(self.post_quant_conv.parameters()),
|
392 |
+
lr=lr, betas=(0.5, 0.9))
|
393 |
+
opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
|
394 |
+
lr=lr, betas=(0.5, 0.9))
|
395 |
+
return [opt_ae, opt_disc], []
|
396 |
+
|
397 |
+
def get_last_layer(self):
|
398 |
+
return self.decoder.conv_out.weight
|
399 |
+
|
400 |
+
@torch.no_grad()
|
401 |
+
def log_images(self, batch, only_inputs=False, **kwargs):
|
402 |
+
log = dict()
|
403 |
+
x = self.get_input(batch, self.image_key)
|
404 |
+
x = x.to(self.device)
|
405 |
+
if not only_inputs:
|
406 |
+
xrec, posterior = self(x)
|
407 |
+
if x.shape[1] > 3:
|
408 |
+
# colorize with random projection
|
409 |
+
assert xrec.shape[1] > 3
|
410 |
+
x = self.to_rgb(x)
|
411 |
+
xrec = self.to_rgb(xrec)
|
412 |
+
log["samples"] = self.decode(torch.randn_like(posterior.sample()))
|
413 |
+
log["reconstructions"] = xrec
|
414 |
+
log["inputs"] = x
|
415 |
+
return log
|
416 |
+
|
417 |
+
def to_rgb(self, x):
|
418 |
+
assert self.image_key == "segmentation"
|
419 |
+
if not hasattr(self, "colorize"):
|
420 |
+
self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
|
421 |
+
x = F.conv2d(x, weight=self.colorize)
|
422 |
+
x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
|
423 |
+
return x
|
424 |
+
|
425 |
+
|
426 |
+
class IdentityFirstStage(torch.nn.Module):
|
427 |
+
def __init__(self, *args, vq_interface=False, **kwargs):
|
428 |
+
self.vq_interface = vq_interface # TODO: Should be true by default but check to not break older stuff
|
429 |
+
super().__init__()
|
430 |
+
|
431 |
+
def encode(self, x, *args, **kwargs):
|
432 |
+
return x
|
433 |
+
|
434 |
+
def decode(self, x, *args, **kwargs):
|
435 |
+
return x
|
436 |
+
|
437 |
+
def quantize(self, x, *args, **kwargs):
|
438 |
+
if self.vq_interface:
|
439 |
+
return x, None, [None, None, None]
|
440 |
+
return x
|
441 |
+
|
442 |
+
def forward(self, x, *args, **kwargs):
|
443 |
+
return x
|
models/ldm/models/diffusion/__init__.py
ADDED
File without changes
|
models/ldm/models/diffusion/classifier.py
ADDED
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import torch
|
3 |
+
import pytorch_lightning as pl
|
4 |
+
from omegaconf import OmegaConf
|
5 |
+
from torch.nn import functional as F
|
6 |
+
from torch.optim import AdamW
|
7 |
+
from torch.optim.lr_scheduler import LambdaLR
|
8 |
+
from copy import deepcopy
|
9 |
+
from einops import rearrange
|
10 |
+
from glob import glob
|
11 |
+
from natsort import natsorted
|
12 |
+
|
13 |
+
from ldm.modules.diffusionmodules.openaimodel import EncoderUNetModel, UNetModel
|
14 |
+
from ldm.util import log_txt_as_img, default, ismap, instantiate_from_config
|
15 |
+
|
16 |
+
__models__ = {
|
17 |
+
'class_label': EncoderUNetModel,
|
18 |
+
'segmentation': UNetModel
|
19 |
+
}
|
20 |
+
|
21 |
+
|
22 |
+
def disabled_train(self, mode=True):
|
23 |
+
"""Overwrite model.train with this function to make sure train/eval mode
|
24 |
+
does not change anymore."""
|
25 |
+
return self
|
26 |
+
|
27 |
+
|
28 |
+
class NoisyLatentImageClassifier(pl.LightningModule):
|
29 |
+
|
30 |
+
def __init__(self,
|
31 |
+
diffusion_path,
|
32 |
+
num_classes,
|
33 |
+
ckpt_path=None,
|
34 |
+
pool='attention',
|
35 |
+
label_key=None,
|
36 |
+
diffusion_ckpt_path=None,
|
37 |
+
scheduler_config=None,
|
38 |
+
weight_decay=1.e-2,
|
39 |
+
log_steps=10,
|
40 |
+
monitor='val/loss',
|
41 |
+
*args,
|
42 |
+
**kwargs):
|
43 |
+
super().__init__(*args, **kwargs)
|
44 |
+
self.num_classes = num_classes
|
45 |
+
# get latest config of diffusion model
|
46 |
+
diffusion_config = natsorted(glob(os.path.join(diffusion_path, 'configs', '*-project.yaml')))[-1]
|
47 |
+
self.diffusion_config = OmegaConf.load(diffusion_config).model
|
48 |
+
self.diffusion_config.params.ckpt_path = diffusion_ckpt_path
|
49 |
+
self.load_diffusion()
|
50 |
+
|
51 |
+
self.monitor = monitor
|
52 |
+
self.numd = self.diffusion_model.first_stage_model.encoder.num_resolutions - 1
|
53 |
+
self.log_time_interval = self.diffusion_model.num_timesteps // log_steps
|
54 |
+
self.log_steps = log_steps
|
55 |
+
|
56 |
+
self.label_key = label_key if not hasattr(self.diffusion_model, 'cond_stage_key') \
|
57 |
+
else self.diffusion_model.cond_stage_key
|
58 |
+
|
59 |
+
assert self.label_key is not None, 'label_key neither in diffusion model nor in model.params'
|
60 |
+
|
61 |
+
if self.label_key not in __models__:
|
62 |
+
raise NotImplementedError()
|
63 |
+
|
64 |
+
self.load_classifier(ckpt_path, pool)
|
65 |
+
|
66 |
+
self.scheduler_config = scheduler_config
|
67 |
+
self.use_scheduler = self.scheduler_config is not None
|
68 |
+
self.weight_decay = weight_decay
|
69 |
+
|
70 |
+
def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
|
71 |
+
sd = torch.load(path, map_location="cpu")
|
72 |
+
if "state_dict" in list(sd.keys()):
|
73 |
+
sd = sd["state_dict"]
|
74 |
+
keys = list(sd.keys())
|
75 |
+
for k in keys:
|
76 |
+
for ik in ignore_keys:
|
77 |
+
if k.startswith(ik):
|
78 |
+
print("Deleting key {} from state_dict.".format(k))
|
79 |
+
del sd[k]
|
80 |
+
missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
|
81 |
+
sd, strict=False)
|
82 |
+
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
83 |
+
if len(missing) > 0:
|
84 |
+
print(f"Missing Keys: {missing}")
|
85 |
+
if len(unexpected) > 0:
|
86 |
+
print(f"Unexpected Keys: {unexpected}")
|
87 |
+
|
88 |
+
def load_diffusion(self):
|
89 |
+
model = instantiate_from_config(self.diffusion_config)
|
90 |
+
self.diffusion_model = model.eval()
|
91 |
+
self.diffusion_model.train = disabled_train
|
92 |
+
for param in self.diffusion_model.parameters():
|
93 |
+
param.requires_grad = False
|
94 |
+
|
95 |
+
def load_classifier(self, ckpt_path, pool):
|
96 |
+
model_config = deepcopy(self.diffusion_config.params.unet_config.params)
|
97 |
+
model_config.in_channels = self.diffusion_config.params.unet_config.params.out_channels
|
98 |
+
model_config.out_channels = self.num_classes
|
99 |
+
if self.label_key == 'class_label':
|
100 |
+
model_config.pool = pool
|
101 |
+
|
102 |
+
self.model = __models__[self.label_key](**model_config)
|
103 |
+
if ckpt_path is not None:
|
104 |
+
print('#####################################################################')
|
105 |
+
print(f'load from ckpt "{ckpt_path}"')
|
106 |
+
print('#####################################################################')
|
107 |
+
self.init_from_ckpt(ckpt_path)
|
108 |
+
|
109 |
+
@torch.no_grad()
|
110 |
+
def get_x_noisy(self, x, t, noise=None):
|
111 |
+
noise = default(noise, lambda: torch.randn_like(x))
|
112 |
+
continuous_sqrt_alpha_cumprod = None
|
113 |
+
if self.diffusion_model.use_continuous_noise:
|
114 |
+
continuous_sqrt_alpha_cumprod = self.diffusion_model.sample_continuous_noise_level(x.shape[0], t + 1)
|
115 |
+
# todo: make sure t+1 is correct here
|
116 |
+
|
117 |
+
return self.diffusion_model.q_sample(x_start=x, t=t, noise=noise,
|
118 |
+
continuous_sqrt_alpha_cumprod=continuous_sqrt_alpha_cumprod)
|
119 |
+
|
120 |
+
def forward(self, x_noisy, t, *args, **kwargs):
|
121 |
+
return self.model(x_noisy, t)
|
122 |
+
|
123 |
+
@torch.no_grad()
|
124 |
+
def get_input(self, batch, k):
|
125 |
+
x = batch[k]
|
126 |
+
if len(x.shape) == 3:
|
127 |
+
x = x[..., None]
|
128 |
+
x = rearrange(x, 'b h w c -> b c h w')
|
129 |
+
x = x.to(memory_format=torch.contiguous_format).float()
|
130 |
+
return x
|
131 |
+
|
132 |
+
@torch.no_grad()
|
133 |
+
def get_conditioning(self, batch, k=None):
|
134 |
+
if k is None:
|
135 |
+
k = self.label_key
|
136 |
+
assert k is not None, 'Needs to provide label key'
|
137 |
+
|
138 |
+
targets = batch[k].to(self.device)
|
139 |
+
|
140 |
+
if self.label_key == 'segmentation':
|
141 |
+
targets = rearrange(targets, 'b h w c -> b c h w')
|
142 |
+
for down in range(self.numd):
|
143 |
+
h, w = targets.shape[-2:]
|
144 |
+
targets = F.interpolate(targets, size=(h // 2, w // 2), mode='nearest')
|
145 |
+
|
146 |
+
# targets = rearrange(targets,'b c h w -> b h w c')
|
147 |
+
|
148 |
+
return targets
|
149 |
+
|
150 |
+
def compute_top_k(self, logits, labels, k, reduction="mean"):
|
151 |
+
_, top_ks = torch.topk(logits, k, dim=1)
|
152 |
+
if reduction == "mean":
|
153 |
+
return (top_ks == labels[:, None]).float().sum(dim=-1).mean().item()
|
154 |
+
elif reduction == "none":
|
155 |
+
return (top_ks == labels[:, None]).float().sum(dim=-1)
|
156 |
+
|
157 |
+
def on_train_epoch_start(self):
|
158 |
+
# save some memory
|
159 |
+
self.diffusion_model.model.to('cpu')
|
160 |
+
|
161 |
+
@torch.no_grad()
|
162 |
+
def write_logs(self, loss, logits, targets):
|
163 |
+
log_prefix = 'train' if self.training else 'val'
|
164 |
+
log = {}
|
165 |
+
log[f"{log_prefix}/loss"] = loss.mean()
|
166 |
+
log[f"{log_prefix}/acc@1"] = self.compute_top_k(
|
167 |
+
logits, targets, k=1, reduction="mean"
|
168 |
+
)
|
169 |
+
log[f"{log_prefix}/acc@5"] = self.compute_top_k(
|
170 |
+
logits, targets, k=5, reduction="mean"
|
171 |
+
)
|
172 |
+
|
173 |
+
self.log_dict(log, prog_bar=False, logger=True, on_step=self.training, on_epoch=True)
|
174 |
+
self.log('loss', log[f"{log_prefix}/loss"], prog_bar=True, logger=False)
|
175 |
+
self.log('global_step', self.global_step, logger=False, on_epoch=False, prog_bar=True)
|
176 |
+
lr = self.optimizers().param_groups[0]['lr']
|
177 |
+
self.log('lr_abs', lr, on_step=True, logger=True, on_epoch=False, prog_bar=True)
|
178 |
+
|
179 |
+
def shared_step(self, batch, t=None):
|
180 |
+
x, *_ = self.diffusion_model.get_input(batch, k=self.diffusion_model.first_stage_key)
|
181 |
+
targets = self.get_conditioning(batch)
|
182 |
+
if targets.dim() == 4:
|
183 |
+
targets = targets.argmax(dim=1)
|
184 |
+
if t is None:
|
185 |
+
t = torch.randint(0, self.diffusion_model.num_timesteps, (x.shape[0],), device=self.device).long()
|
186 |
+
else:
|
187 |
+
t = torch.full(size=(x.shape[0],), fill_value=t, device=self.device).long()
|
188 |
+
x_noisy = self.get_x_noisy(x, t)
|
189 |
+
logits = self(x_noisy, t)
|
190 |
+
|
191 |
+
loss = F.cross_entropy(logits, targets, reduction='none')
|
192 |
+
|
193 |
+
self.write_logs(loss.detach(), logits.detach(), targets.detach())
|
194 |
+
|
195 |
+
loss = loss.mean()
|
196 |
+
return loss, logits, x_noisy, targets
|
197 |
+
|
198 |
+
def training_step(self, batch, batch_idx):
|
199 |
+
loss, *_ = self.shared_step(batch)
|
200 |
+
return loss
|
201 |
+
|
202 |
+
def reset_noise_accs(self):
|
203 |
+
self.noisy_acc = {t: {'acc@1': [], 'acc@5': []} for t in
|
204 |
+
range(0, self.diffusion_model.num_timesteps, self.diffusion_model.log_every_t)}
|
205 |
+
|
206 |
+
def on_validation_start(self):
|
207 |
+
self.reset_noise_accs()
|
208 |
+
|
209 |
+
@torch.no_grad()
|
210 |
+
def validation_step(self, batch, batch_idx):
|
211 |
+
loss, *_ = self.shared_step(batch)
|
212 |
+
|
213 |
+
for t in self.noisy_acc:
|
214 |
+
_, logits, _, targets = self.shared_step(batch, t)
|
215 |
+
self.noisy_acc[t]['acc@1'].append(self.compute_top_k(logits, targets, k=1, reduction='mean'))
|
216 |
+
self.noisy_acc[t]['acc@5'].append(self.compute_top_k(logits, targets, k=5, reduction='mean'))
|
217 |
+
|
218 |
+
return loss
|
219 |
+
|
220 |
+
def configure_optimizers(self):
|
221 |
+
optimizer = AdamW(self.model.parameters(), lr=self.learning_rate, weight_decay=self.weight_decay)
|
222 |
+
|
223 |
+
if self.use_scheduler:
|
224 |
+
scheduler = instantiate_from_config(self.scheduler_config)
|
225 |
+
|
226 |
+
print("Setting up LambdaLR scheduler...")
|
227 |
+
scheduler = [
|
228 |
+
{
|
229 |
+
'scheduler': LambdaLR(optimizer, lr_lambda=scheduler.schedule),
|
230 |
+
'interval': 'step',
|
231 |
+
'frequency': 1
|
232 |
+
}]
|
233 |
+
return [optimizer], scheduler
|
234 |
+
|
235 |
+
return optimizer
|
236 |
+
|
237 |
+
@torch.no_grad()
|
238 |
+
def log_images(self, batch, N=8, *args, **kwargs):
|
239 |
+
log = dict()
|
240 |
+
x = self.get_input(batch, self.diffusion_model.first_stage_key)
|
241 |
+
log['inputs'] = x
|
242 |
+
|
243 |
+
y = self.get_conditioning(batch)
|
244 |
+
|
245 |
+
if self.label_key == 'class_label':
|
246 |
+
y = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"])
|
247 |
+
log['labels'] = y
|
248 |
+
|
249 |
+
if ismap(y):
|
250 |
+
log['labels'] = self.diffusion_model.to_rgb(y)
|
251 |
+
|
252 |
+
for step in range(self.log_steps):
|
253 |
+
current_time = step * self.log_time_interval
|
254 |
+
|
255 |
+
_, logits, x_noisy, _ = self.shared_step(batch, t=current_time)
|
256 |
+
|
257 |
+
log[f'inputs@t{current_time}'] = x_noisy
|
258 |
+
|
259 |
+
pred = F.one_hot(logits.argmax(dim=1), num_classes=self.num_classes)
|
260 |
+
pred = rearrange(pred, 'b h w c -> b c h w')
|
261 |
+
|
262 |
+
log[f'pred@t{current_time}'] = self.diffusion_model.to_rgb(pred)
|
263 |
+
|
264 |
+
for key in log:
|
265 |
+
log[key] = log[key][:N]
|
266 |
+
|
267 |
+
return log
|
models/ldm/models/diffusion/ddim.py
ADDED
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""SAMPLING ONLY."""
|
2 |
+
|
3 |
+
import torch
|
4 |
+
import numpy as np
|
5 |
+
from tqdm import tqdm
|
6 |
+
from functools import partial
|
7 |
+
from einops import rearrange
|
8 |
+
|
9 |
+
from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, extract_into_tensor
|
10 |
+
from ldm.models.diffusion.sampling_util import renorm_thresholding, norm_thresholding, spatial_norm_thresholding
|
11 |
+
|
12 |
+
|
13 |
+
class DDIMSampler(object):
|
14 |
+
def __init__(self, model, schedule="linear", **kwargs):
|
15 |
+
super().__init__()
|
16 |
+
self.model = model
|
17 |
+
self.ddpm_num_timesteps = model.num_timesteps
|
18 |
+
self.schedule = schedule
|
19 |
+
|
20 |
+
def to(self, device):
|
21 |
+
"""Same as to in torch module
|
22 |
+
Don't really underestand why this isn't a module in the first place"""
|
23 |
+
for k, v in self.__dict__.items():
|
24 |
+
if isinstance(v, torch.Tensor):
|
25 |
+
new_v = getattr(self, k).to(device)
|
26 |
+
setattr(self, k, new_v)
|
27 |
+
|
28 |
+
|
29 |
+
def register_buffer(self, name, attr):
|
30 |
+
if type(attr) == torch.Tensor:
|
31 |
+
if attr.device != torch.device("cuda"):
|
32 |
+
attr = attr.to(torch.device("cuda"))
|
33 |
+
setattr(self, name, attr)
|
34 |
+
|
35 |
+
def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
|
36 |
+
self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
|
37 |
+
num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
|
38 |
+
alphas_cumprod = self.model.alphas_cumprod
|
39 |
+
assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
|
40 |
+
to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
|
41 |
+
|
42 |
+
self.register_buffer('betas', to_torch(self.model.betas))
|
43 |
+
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
|
44 |
+
self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
|
45 |
+
|
46 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
47 |
+
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
|
48 |
+
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
|
49 |
+
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
|
50 |
+
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
|
51 |
+
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
|
52 |
+
|
53 |
+
# ddim sampling parameters
|
54 |
+
ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
|
55 |
+
ddim_timesteps=self.ddim_timesteps,
|
56 |
+
eta=ddim_eta,verbose=verbose)
|
57 |
+
self.register_buffer('ddim_sigmas', ddim_sigmas)
|
58 |
+
self.register_buffer('ddim_alphas', ddim_alphas)
|
59 |
+
self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
|
60 |
+
self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
|
61 |
+
sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
|
62 |
+
(1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
|
63 |
+
1 - self.alphas_cumprod / self.alphas_cumprod_prev))
|
64 |
+
self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
|
65 |
+
|
66 |
+
@torch.no_grad()
|
67 |
+
def sample(self,
|
68 |
+
S,
|
69 |
+
batch_size,
|
70 |
+
shape,
|
71 |
+
conditioning=None,
|
72 |
+
callback=None,
|
73 |
+
normals_sequence=None,
|
74 |
+
img_callback=None,
|
75 |
+
quantize_x0=False,
|
76 |
+
eta=0.,
|
77 |
+
mask=None,
|
78 |
+
x0=None,
|
79 |
+
temperature=1.,
|
80 |
+
noise_dropout=0.,
|
81 |
+
score_corrector=None,
|
82 |
+
corrector_kwargs=None,
|
83 |
+
verbose=True,
|
84 |
+
x_T=None,
|
85 |
+
log_every_t=100,
|
86 |
+
unconditional_guidance_scale=1.,
|
87 |
+
unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
|
88 |
+
dynamic_threshold=None,
|
89 |
+
**kwargs
|
90 |
+
):
|
91 |
+
if conditioning is not None:
|
92 |
+
if isinstance(conditioning, dict):
|
93 |
+
ctmp = conditioning[list(conditioning.keys())[0]]
|
94 |
+
while isinstance(ctmp, list): ctmp = ctmp[0]
|
95 |
+
cbs = ctmp.shape[0]
|
96 |
+
if cbs != batch_size:
|
97 |
+
print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
|
98 |
+
|
99 |
+
else:
|
100 |
+
if conditioning.shape[0] != batch_size:
|
101 |
+
print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
|
102 |
+
|
103 |
+
self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
|
104 |
+
# sampling
|
105 |
+
C, H, W = shape
|
106 |
+
size = (batch_size, C, H, W)
|
107 |
+
print(f'Data shape for DDIM sampling is {size}, eta {eta}')
|
108 |
+
|
109 |
+
samples, intermediates = self.ddim_sampling(conditioning, size,
|
110 |
+
callback=callback,
|
111 |
+
img_callback=img_callback,
|
112 |
+
quantize_denoised=quantize_x0,
|
113 |
+
mask=mask, x0=x0,
|
114 |
+
ddim_use_original_steps=False,
|
115 |
+
noise_dropout=noise_dropout,
|
116 |
+
temperature=temperature,
|
117 |
+
score_corrector=score_corrector,
|
118 |
+
corrector_kwargs=corrector_kwargs,
|
119 |
+
x_T=x_T,
|
120 |
+
log_every_t=log_every_t,
|
121 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
122 |
+
unconditional_conditioning=unconditional_conditioning,
|
123 |
+
dynamic_threshold=dynamic_threshold,
|
124 |
+
)
|
125 |
+
return samples, intermediates
|
126 |
+
|
127 |
+
@torch.no_grad()
|
128 |
+
def ddim_sampling(self, cond, shape,
|
129 |
+
x_T=None, ddim_use_original_steps=False,
|
130 |
+
callback=None, timesteps=None, quantize_denoised=False,
|
131 |
+
mask=None, x0=None, img_callback=None, log_every_t=100,
|
132 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
|
133 |
+
unconditional_guidance_scale=1., unconditional_conditioning=None, dynamic_threshold=None,
|
134 |
+
t_start=-1):
|
135 |
+
device = self.model.betas.device
|
136 |
+
b = shape[0]
|
137 |
+
if x_T is None:
|
138 |
+
img = torch.randn(shape, device=device)
|
139 |
+
else:
|
140 |
+
img = x_T
|
141 |
+
|
142 |
+
if timesteps is None:
|
143 |
+
timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
|
144 |
+
elif timesteps is not None and not ddim_use_original_steps:
|
145 |
+
subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
|
146 |
+
timesteps = self.ddim_timesteps[:subset_end]
|
147 |
+
|
148 |
+
timesteps = timesteps[:t_start]
|
149 |
+
|
150 |
+
intermediates = {'x_inter': [img], 'pred_x0': [img]}
|
151 |
+
time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
|
152 |
+
total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
|
153 |
+
print(f"Running DDIM Sampling with {total_steps} timesteps")
|
154 |
+
|
155 |
+
iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
|
156 |
+
|
157 |
+
for i, step in enumerate(iterator):
|
158 |
+
index = total_steps - i - 1
|
159 |
+
ts = torch.full((b,), step, device=device, dtype=torch.long)
|
160 |
+
|
161 |
+
if mask is not None:
|
162 |
+
assert x0 is not None
|
163 |
+
img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
|
164 |
+
img = img_orig * mask + (1. - mask) * img
|
165 |
+
|
166 |
+
outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
|
167 |
+
quantize_denoised=quantize_denoised, temperature=temperature,
|
168 |
+
noise_dropout=noise_dropout, score_corrector=score_corrector,
|
169 |
+
corrector_kwargs=corrector_kwargs,
|
170 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
171 |
+
unconditional_conditioning=unconditional_conditioning,
|
172 |
+
dynamic_threshold=dynamic_threshold)
|
173 |
+
img, pred_x0 = outs
|
174 |
+
if callback:
|
175 |
+
img = callback(i, img, pred_x0)
|
176 |
+
if img_callback: img_callback(pred_x0, i)
|
177 |
+
|
178 |
+
if index % log_every_t == 0 or index == total_steps - 1:
|
179 |
+
intermediates['x_inter'].append(img)
|
180 |
+
intermediates['pred_x0'].append(pred_x0)
|
181 |
+
|
182 |
+
return img, intermediates
|
183 |
+
|
184 |
+
@torch.no_grad()
|
185 |
+
def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
|
186 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
|
187 |
+
unconditional_guidance_scale=1., unconditional_conditioning=None,
|
188 |
+
dynamic_threshold=None):
|
189 |
+
b, *_, device = *x.shape, x.device
|
190 |
+
|
191 |
+
if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
|
192 |
+
e_t = self.model.apply_model(x, t, c)
|
193 |
+
else:
|
194 |
+
x_in = torch.cat([x] * 2)
|
195 |
+
t_in = torch.cat([t] * 2)
|
196 |
+
if isinstance(c, dict):
|
197 |
+
assert isinstance(unconditional_conditioning, dict)
|
198 |
+
c_in = dict()
|
199 |
+
for k in c:
|
200 |
+
if isinstance(c[k], list):
|
201 |
+
c_in[k] = [torch.cat([
|
202 |
+
unconditional_conditioning[k][i],
|
203 |
+
c[k][i]]) for i in range(len(c[k]))]
|
204 |
+
else:
|
205 |
+
c_in[k] = torch.cat([
|
206 |
+
unconditional_conditioning[k],
|
207 |
+
c[k]])
|
208 |
+
else:
|
209 |
+
c_in = torch.cat([unconditional_conditioning, c])
|
210 |
+
e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)
|
211 |
+
e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)
|
212 |
+
|
213 |
+
if score_corrector is not None:
|
214 |
+
assert self.model.parameterization == "eps"
|
215 |
+
e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
|
216 |
+
|
217 |
+
alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
|
218 |
+
alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
|
219 |
+
sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
|
220 |
+
sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
|
221 |
+
# select parameters corresponding to the currently considered timestep
|
222 |
+
a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
|
223 |
+
a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
|
224 |
+
sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
|
225 |
+
sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
|
226 |
+
|
227 |
+
# current prediction for x_0
|
228 |
+
pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
|
229 |
+
if quantize_denoised:
|
230 |
+
pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
|
231 |
+
|
232 |
+
if dynamic_threshold is not None:
|
233 |
+
pred_x0 = norm_thresholding(pred_x0, dynamic_threshold)
|
234 |
+
|
235 |
+
# direction pointing to x_t
|
236 |
+
dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
|
237 |
+
noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
|
238 |
+
if noise_dropout > 0.:
|
239 |
+
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
|
240 |
+
x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
|
241 |
+
return x_prev, pred_x0
|
242 |
+
|
243 |
+
@torch.no_grad()
|
244 |
+
def encode(self, x0, c, t_enc, use_original_steps=False, return_intermediates=None,
|
245 |
+
unconditional_guidance_scale=1.0, unconditional_conditioning=None):
|
246 |
+
num_reference_steps = self.ddpm_num_timesteps if use_original_steps else self.ddim_timesteps.shape[0]
|
247 |
+
|
248 |
+
assert t_enc <= num_reference_steps
|
249 |
+
num_steps = t_enc
|
250 |
+
|
251 |
+
if use_original_steps:
|
252 |
+
alphas_next = self.alphas_cumprod[:num_steps]
|
253 |
+
alphas = self.alphas_cumprod_prev[:num_steps]
|
254 |
+
else:
|
255 |
+
alphas_next = self.ddim_alphas[:num_steps]
|
256 |
+
alphas = torch.tensor(self.ddim_alphas_prev[:num_steps])
|
257 |
+
|
258 |
+
x_next = x0
|
259 |
+
intermediates = []
|
260 |
+
inter_steps = []
|
261 |
+
for i in tqdm(range(num_steps), desc='Encoding Image'):
|
262 |
+
t = torch.full((x0.shape[0],), i, device=self.model.device, dtype=torch.long)
|
263 |
+
if unconditional_guidance_scale == 1.:
|
264 |
+
noise_pred = self.model.apply_model(x_next, t, c)
|
265 |
+
else:
|
266 |
+
assert unconditional_conditioning is not None
|
267 |
+
e_t_uncond, noise_pred = torch.chunk(
|
268 |
+
self.model.apply_model(torch.cat((x_next, x_next)), torch.cat((t, t)),
|
269 |
+
torch.cat((unconditional_conditioning, c))), 2)
|
270 |
+
noise_pred = e_t_uncond + unconditional_guidance_scale * (noise_pred - e_t_uncond)
|
271 |
+
|
272 |
+
xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next
|
273 |
+
weighted_noise_pred = alphas_next[i].sqrt() * (
|
274 |
+
(1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) * noise_pred
|
275 |
+
x_next = xt_weighted + weighted_noise_pred
|
276 |
+
if return_intermediates and i % (
|
277 |
+
num_steps // return_intermediates) == 0 and i < num_steps - 1:
|
278 |
+
intermediates.append(x_next)
|
279 |
+
inter_steps.append(i)
|
280 |
+
elif return_intermediates and i >= num_steps - 2:
|
281 |
+
intermediates.append(x_next)
|
282 |
+
inter_steps.append(i)
|
283 |
+
|
284 |
+
out = {'x_encoded': x_next, 'intermediate_steps': inter_steps}
|
285 |
+
if return_intermediates:
|
286 |
+
out.update({'intermediates': intermediates})
|
287 |
+
return x_next, out
|
288 |
+
|
289 |
+
@torch.no_grad()
|
290 |
+
def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):
|
291 |
+
# fast, but does not allow for exact reconstruction
|
292 |
+
# t serves as an index to gather the correct alphas
|
293 |
+
if use_original_steps:
|
294 |
+
sqrt_alphas_cumprod = self.sqrt_alphas_cumprod
|
295 |
+
sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod
|
296 |
+
else:
|
297 |
+
sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)
|
298 |
+
sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas
|
299 |
+
|
300 |
+
if noise is None:
|
301 |
+
noise = torch.randn_like(x0)
|
302 |
+
return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +
|
303 |
+
extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)
|
304 |
+
|
305 |
+
@torch.no_grad()
|
306 |
+
def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,
|
307 |
+
use_original_steps=False):
|
308 |
+
|
309 |
+
timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
|
310 |
+
timesteps = timesteps[:t_start]
|
311 |
+
|
312 |
+
time_range = np.flip(timesteps)
|
313 |
+
total_steps = timesteps.shape[0]
|
314 |
+
print(f"Running DDIM Sampling with {total_steps} timesteps")
|
315 |
+
|
316 |
+
iterator = tqdm(time_range, desc='Decoding image', total=total_steps)
|
317 |
+
x_dec = x_latent
|
318 |
+
for i, step in enumerate(iterator):
|
319 |
+
index = total_steps - i - 1
|
320 |
+
ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)
|
321 |
+
x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,
|
322 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
323 |
+
unconditional_conditioning=unconditional_conditioning)
|
324 |
+
return x_dec
|
models/ldm/models/diffusion/ddpm.py
ADDED
@@ -0,0 +1,2024 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
wild mixture of
|
3 |
+
https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
|
4 |
+
https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py
|
5 |
+
https://github.com/CompVis/taming-transformers
|
6 |
+
-- merci
|
7 |
+
"""
|
8 |
+
|
9 |
+
import torch
|
10 |
+
import torch.nn as nn
|
11 |
+
import numpy as np
|
12 |
+
import pytorch_lightning as pl
|
13 |
+
from torch.optim.lr_scheduler import LambdaLR
|
14 |
+
from einops import rearrange, repeat
|
15 |
+
from contextlib import contextmanager, nullcontext
|
16 |
+
from functools import partial
|
17 |
+
import itertools
|
18 |
+
from tqdm import tqdm
|
19 |
+
from torchvision.utils import make_grid
|
20 |
+
from pytorch_lightning.utilities.distributed import rank_zero_only
|
21 |
+
from omegaconf import ListConfig
|
22 |
+
|
23 |
+
from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config
|
24 |
+
from ldm.modules.ema import LitEma
|
25 |
+
from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution
|
26 |
+
from ldm.models.autoencoder import VQModelInterface, IdentityFirstStage, AutoencoderKL
|
27 |
+
from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like
|
28 |
+
from ldm.models.diffusion.ddim import DDIMSampler
|
29 |
+
from ldm.modules.attention import CrossAttention
|
30 |
+
|
31 |
+
|
32 |
+
__conditioning_keys__ = {'concat': 'c_concat',
|
33 |
+
'crossattn': 'c_crossattn',
|
34 |
+
'adm': 'y'}
|
35 |
+
|
36 |
+
|
37 |
+
def disabled_train(self, mode=True):
|
38 |
+
"""Overwrite model.train with this function to make sure train/eval mode
|
39 |
+
does not change anymore."""
|
40 |
+
return self
|
41 |
+
|
42 |
+
|
43 |
+
def uniform_on_device(r1, r2, shape, device):
|
44 |
+
return (r1 - r2) * torch.rand(*shape, device=device) + r2
|
45 |
+
|
46 |
+
|
47 |
+
class DDPM(pl.LightningModule):
|
48 |
+
# classic DDPM with Gaussian diffusion, in image space
|
49 |
+
def __init__(self,
|
50 |
+
unet_config,
|
51 |
+
timesteps=1000,
|
52 |
+
beta_schedule="linear",
|
53 |
+
loss_type="l2",
|
54 |
+
ckpt_path=None,
|
55 |
+
ignore_keys=[],
|
56 |
+
load_only_unet=False,
|
57 |
+
monitor="val/loss",
|
58 |
+
use_ema=True,
|
59 |
+
first_stage_key="image",
|
60 |
+
image_size=256,
|
61 |
+
channels=3,
|
62 |
+
log_every_t=100,
|
63 |
+
clip_denoised=True,
|
64 |
+
linear_start=1e-4,
|
65 |
+
linear_end=2e-2,
|
66 |
+
cosine_s=8e-3,
|
67 |
+
given_betas=None,
|
68 |
+
original_elbo_weight=0.,
|
69 |
+
v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
|
70 |
+
l_simple_weight=1.,
|
71 |
+
conditioning_key=None,
|
72 |
+
parameterization="eps", # all assuming fixed variance schedules
|
73 |
+
scheduler_config=None,
|
74 |
+
use_positional_encodings=False,
|
75 |
+
learn_logvar=False,
|
76 |
+
logvar_init=0.,
|
77 |
+
make_it_fit=False,
|
78 |
+
ucg_training=None,
|
79 |
+
):
|
80 |
+
super().__init__()
|
81 |
+
assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"'
|
82 |
+
self.parameterization = parameterization
|
83 |
+
print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
|
84 |
+
self.cond_stage_model = None
|
85 |
+
self.clip_denoised = clip_denoised
|
86 |
+
self.log_every_t = log_every_t
|
87 |
+
self.first_stage_key = first_stage_key
|
88 |
+
self.image_size = image_size # try conv?
|
89 |
+
self.channels = channels
|
90 |
+
self.use_positional_encodings = use_positional_encodings
|
91 |
+
self.model = DiffusionWrapper(unet_config, conditioning_key)
|
92 |
+
count_params(self.model, verbose=True)
|
93 |
+
self.use_ema = use_ema
|
94 |
+
if self.use_ema:
|
95 |
+
self.model_ema = LitEma(self.model)
|
96 |
+
print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
|
97 |
+
|
98 |
+
self.use_scheduler = scheduler_config is not None
|
99 |
+
if self.use_scheduler:
|
100 |
+
self.scheduler_config = scheduler_config
|
101 |
+
|
102 |
+
self.v_posterior = v_posterior
|
103 |
+
self.original_elbo_weight = original_elbo_weight
|
104 |
+
self.l_simple_weight = l_simple_weight
|
105 |
+
|
106 |
+
if monitor is not None:
|
107 |
+
self.monitor = monitor
|
108 |
+
self.make_it_fit = make_it_fit
|
109 |
+
if ckpt_path is not None:
|
110 |
+
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet)
|
111 |
+
|
112 |
+
self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
|
113 |
+
linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
|
114 |
+
|
115 |
+
self.loss_type = loss_type
|
116 |
+
|
117 |
+
self.learn_logvar = learn_logvar
|
118 |
+
self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
|
119 |
+
if self.learn_logvar:
|
120 |
+
self.logvar = nn.Parameter(self.logvar, requires_grad=True)
|
121 |
+
|
122 |
+
self.ucg_training = ucg_training or dict()
|
123 |
+
if self.ucg_training:
|
124 |
+
self.ucg_prng = np.random.RandomState()
|
125 |
+
|
126 |
+
def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
|
127 |
+
linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
|
128 |
+
if exists(given_betas):
|
129 |
+
betas = given_betas
|
130 |
+
else:
|
131 |
+
betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
|
132 |
+
cosine_s=cosine_s)
|
133 |
+
alphas = 1. - betas
|
134 |
+
alphas_cumprod = np.cumprod(alphas, axis=0)
|
135 |
+
alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
|
136 |
+
|
137 |
+
timesteps, = betas.shape
|
138 |
+
self.num_timesteps = int(timesteps)
|
139 |
+
self.linear_start = linear_start
|
140 |
+
self.linear_end = linear_end
|
141 |
+
assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
|
142 |
+
|
143 |
+
to_torch = partial(torch.tensor, dtype=torch.float32)
|
144 |
+
|
145 |
+
self.register_buffer('betas', to_torch(betas))
|
146 |
+
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
|
147 |
+
self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
|
148 |
+
|
149 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
150 |
+
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
|
151 |
+
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
|
152 |
+
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
|
153 |
+
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
|
154 |
+
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
|
155 |
+
|
156 |
+
# calculations for posterior q(x_{t-1} | x_t, x_0)
|
157 |
+
posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / (
|
158 |
+
1. - alphas_cumprod) + self.v_posterior * betas
|
159 |
+
# above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
|
160 |
+
self.register_buffer('posterior_variance', to_torch(posterior_variance))
|
161 |
+
# below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
|
162 |
+
self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
|
163 |
+
self.register_buffer('posterior_mean_coef1', to_torch(
|
164 |
+
betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
|
165 |
+
self.register_buffer('posterior_mean_coef2', to_torch(
|
166 |
+
(1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
|
167 |
+
|
168 |
+
if self.parameterization == "eps":
|
169 |
+
lvlb_weights = self.betas ** 2 / (
|
170 |
+
2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))
|
171 |
+
elif self.parameterization == "x0":
|
172 |
+
lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod))
|
173 |
+
else:
|
174 |
+
raise NotImplementedError("mu not supported")
|
175 |
+
# TODO how to choose this term
|
176 |
+
lvlb_weights[0] = lvlb_weights[1]
|
177 |
+
self.register_buffer('lvlb_weights', lvlb_weights, persistent=False)
|
178 |
+
assert not torch.isnan(self.lvlb_weights).all()
|
179 |
+
|
180 |
+
@contextmanager
|
181 |
+
def ema_scope(self, context=None):
|
182 |
+
if self.use_ema:
|
183 |
+
self.model_ema.store(self.model.parameters())
|
184 |
+
self.model_ema.copy_to(self.model)
|
185 |
+
if context is not None:
|
186 |
+
print(f"{context}: Switched to EMA weights")
|
187 |
+
try:
|
188 |
+
yield None
|
189 |
+
finally:
|
190 |
+
if self.use_ema:
|
191 |
+
self.model_ema.restore(self.model.parameters())
|
192 |
+
if context is not None:
|
193 |
+
print(f"{context}: Restored training weights")
|
194 |
+
|
195 |
+
@torch.no_grad()
|
196 |
+
def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
|
197 |
+
sd = torch.load(path, map_location="cpu")
|
198 |
+
if "state_dict" in list(sd.keys()):
|
199 |
+
sd = sd["state_dict"]
|
200 |
+
keys = list(sd.keys())
|
201 |
+
|
202 |
+
if self.make_it_fit:
|
203 |
+
n_params = len([name for name, _ in
|
204 |
+
itertools.chain(self.named_parameters(),
|
205 |
+
self.named_buffers())])
|
206 |
+
for name, param in tqdm(
|
207 |
+
itertools.chain(self.named_parameters(),
|
208 |
+
self.named_buffers()),
|
209 |
+
desc="Fitting old weights to new weights",
|
210 |
+
total=n_params
|
211 |
+
):
|
212 |
+
if not name in sd:
|
213 |
+
continue
|
214 |
+
old_shape = sd[name].shape
|
215 |
+
new_shape = param.shape
|
216 |
+
assert len(old_shape)==len(new_shape)
|
217 |
+
if len(new_shape) > 2:
|
218 |
+
# we only modify first two axes
|
219 |
+
assert new_shape[2:] == old_shape[2:]
|
220 |
+
# assumes first axis corresponds to output dim
|
221 |
+
if not new_shape == old_shape:
|
222 |
+
new_param = param.clone()
|
223 |
+
old_param = sd[name]
|
224 |
+
if len(new_shape) == 1:
|
225 |
+
for i in range(new_param.shape[0]):
|
226 |
+
new_param[i] = old_param[i % old_shape[0]]
|
227 |
+
elif len(new_shape) >= 2:
|
228 |
+
for i in range(new_param.shape[0]):
|
229 |
+
for j in range(new_param.shape[1]):
|
230 |
+
new_param[i, j] = old_param[i % old_shape[0], j % old_shape[1]]
|
231 |
+
|
232 |
+
n_used_old = torch.ones(old_shape[1])
|
233 |
+
for j in range(new_param.shape[1]):
|
234 |
+
n_used_old[j % old_shape[1]] += 1
|
235 |
+
n_used_new = torch.zeros(new_shape[1])
|
236 |
+
for j in range(new_param.shape[1]):
|
237 |
+
n_used_new[j] = n_used_old[j % old_shape[1]]
|
238 |
+
|
239 |
+
n_used_new = n_used_new[None, :]
|
240 |
+
while len(n_used_new.shape) < len(new_shape):
|
241 |
+
n_used_new = n_used_new.unsqueeze(-1)
|
242 |
+
new_param /= n_used_new
|
243 |
+
|
244 |
+
sd[name] = new_param
|
245 |
+
|
246 |
+
missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
|
247 |
+
sd, strict=False)
|
248 |
+
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
249 |
+
if len(missing) > 0:
|
250 |
+
print(f"Missing Keys: {missing}")
|
251 |
+
if len(unexpected) > 0:
|
252 |
+
print(f"Unexpected Keys: {unexpected}")
|
253 |
+
|
254 |
+
def q_mean_variance(self, x_start, t):
|
255 |
+
"""
|
256 |
+
Get the distribution q(x_t | x_0).
|
257 |
+
:param x_start: the [N x C x ...] tensor of noiseless inputs.
|
258 |
+
:param t: the number of diffusion steps (minus 1). Here, 0 means one step.
|
259 |
+
:return: A tuple (mean, variance, log_variance), all of x_start's shape.
|
260 |
+
"""
|
261 |
+
mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
|
262 |
+
variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
|
263 |
+
log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
|
264 |
+
return mean, variance, log_variance
|
265 |
+
|
266 |
+
def predict_start_from_noise(self, x_t, t, noise):
|
267 |
+
return (
|
268 |
+
extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
|
269 |
+
extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
|
270 |
+
)
|
271 |
+
|
272 |
+
def q_posterior(self, x_start, x_t, t):
|
273 |
+
posterior_mean = (
|
274 |
+
extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start +
|
275 |
+
extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
|
276 |
+
)
|
277 |
+
posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape)
|
278 |
+
posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
|
279 |
+
return posterior_mean, posterior_variance, posterior_log_variance_clipped
|
280 |
+
|
281 |
+
def p_mean_variance(self, x, t, clip_denoised: bool):
|
282 |
+
model_out = self.model(x, t)
|
283 |
+
if self.parameterization == "eps":
|
284 |
+
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
|
285 |
+
elif self.parameterization == "x0":
|
286 |
+
x_recon = model_out
|
287 |
+
if clip_denoised:
|
288 |
+
x_recon.clamp_(-1., 1.)
|
289 |
+
|
290 |
+
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
|
291 |
+
return model_mean, posterior_variance, posterior_log_variance
|
292 |
+
|
293 |
+
@torch.no_grad()
|
294 |
+
def p_sample(self, x, t, clip_denoised=True, repeat_noise=False):
|
295 |
+
b, *_, device = *x.shape, x.device
|
296 |
+
model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
|
297 |
+
noise = noise_like(x.shape, device, repeat_noise)
|
298 |
+
# no noise when t == 0
|
299 |
+
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
|
300 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
|
301 |
+
|
302 |
+
@torch.no_grad()
|
303 |
+
def p_sample_loop(self, shape, return_intermediates=False):
|
304 |
+
device = self.betas.device
|
305 |
+
b = shape[0]
|
306 |
+
img = torch.randn(shape, device=device)
|
307 |
+
intermediates = [img]
|
308 |
+
for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps):
|
309 |
+
img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long),
|
310 |
+
clip_denoised=self.clip_denoised)
|
311 |
+
if i % self.log_every_t == 0 or i == self.num_timesteps - 1:
|
312 |
+
intermediates.append(img)
|
313 |
+
if return_intermediates:
|
314 |
+
return img, intermediates
|
315 |
+
return img
|
316 |
+
|
317 |
+
@torch.no_grad()
|
318 |
+
def sample(self, batch_size=16, return_intermediates=False):
|
319 |
+
image_size = self.image_size
|
320 |
+
channels = self.channels
|
321 |
+
return self.p_sample_loop((batch_size, channels, image_size, image_size),
|
322 |
+
return_intermediates=return_intermediates)
|
323 |
+
|
324 |
+
def q_sample(self, x_start, t, noise=None):
|
325 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
326 |
+
return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
|
327 |
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
|
328 |
+
|
329 |
+
def get_loss(self, pred, target, mean=True):
|
330 |
+
if self.loss_type == 'l1':
|
331 |
+
loss = (target - pred).abs()
|
332 |
+
if mean:
|
333 |
+
loss = loss.mean()
|
334 |
+
elif self.loss_type == 'l2':
|
335 |
+
if mean:
|
336 |
+
loss = torch.nn.functional.mse_loss(target, pred)
|
337 |
+
else:
|
338 |
+
loss = torch.nn.functional.mse_loss(target, pred, reduction='none')
|
339 |
+
else:
|
340 |
+
raise NotImplementedError("unknown loss type '{loss_type}'")
|
341 |
+
|
342 |
+
return loss
|
343 |
+
|
344 |
+
def p_losses(self, x_start, t, noise=None):
|
345 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
346 |
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
347 |
+
model_out = self.model(x_noisy, t)
|
348 |
+
|
349 |
+
loss_dict = {}
|
350 |
+
if self.parameterization == "eps":
|
351 |
+
target = noise
|
352 |
+
elif self.parameterization == "x0":
|
353 |
+
target = x_start
|
354 |
+
else:
|
355 |
+
raise NotImplementedError(f"Paramterization {self.parameterization} not yet supported")
|
356 |
+
|
357 |
+
loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3])
|
358 |
+
|
359 |
+
log_prefix = 'train' if self.training else 'val'
|
360 |
+
|
361 |
+
loss_dict.update({f'{log_prefix}/loss_simple': loss.mean().item()})
|
362 |
+
loss_simple = loss.mean() * self.l_simple_weight
|
363 |
+
|
364 |
+
loss_vlb = (self.lvlb_weights[t] * loss).mean()
|
365 |
+
loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb.item()})
|
366 |
+
|
367 |
+
loss = loss_simple + self.original_elbo_weight * loss_vlb
|
368 |
+
|
369 |
+
loss_dict.update({f'{log_prefix}/loss': loss.item()})
|
370 |
+
|
371 |
+
return loss, loss_dict
|
372 |
+
|
373 |
+
def forward(self, x, *args, **kwargs):
|
374 |
+
# b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size
|
375 |
+
# assert h == img_size and w == img_size, f'height and width of image must be {img_size}'
|
376 |
+
t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
|
377 |
+
return self.p_losses(x, t, *args, **kwargs)
|
378 |
+
|
379 |
+
def get_input(self, batch, k):
|
380 |
+
x = batch[k]
|
381 |
+
if len(x.shape) == 3:
|
382 |
+
x = x[..., None]
|
383 |
+
x = rearrange(x, 'b h w c -> b c h w')
|
384 |
+
x = x.to(memory_format=torch.contiguous_format).float()
|
385 |
+
return x
|
386 |
+
|
387 |
+
def shared_step(self, batch):
|
388 |
+
x = self.get_input(batch, self.first_stage_key)
|
389 |
+
loss, loss_dict = self(x)
|
390 |
+
return loss, loss_dict
|
391 |
+
|
392 |
+
def training_step(self, batch, batch_idx):
|
393 |
+
for k in self.ucg_training:
|
394 |
+
p = self.ucg_training[k]["p"]
|
395 |
+
val = self.ucg_training[k]["val"]
|
396 |
+
if val is None:
|
397 |
+
val = ""
|
398 |
+
for i in range(len(batch[k])):
|
399 |
+
if self.ucg_prng.choice(2, p=[1-p, p]):
|
400 |
+
batch[k][i] = val
|
401 |
+
|
402 |
+
loss, loss_dict = self.shared_step(batch)
|
403 |
+
|
404 |
+
self.log_dict(loss_dict, prog_bar=True,
|
405 |
+
logger=True, on_step=True, on_epoch=True)
|
406 |
+
|
407 |
+
self.log("global_step", self.global_step,
|
408 |
+
prog_bar=True, logger=True, on_step=True, on_epoch=False)
|
409 |
+
|
410 |
+
if self.use_scheduler:
|
411 |
+
lr = self.optimizers().param_groups[0]['lr'].item()
|
412 |
+
self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False)
|
413 |
+
|
414 |
+
return loss
|
415 |
+
|
416 |
+
@torch.no_grad()
|
417 |
+
def validation_step(self, batch, batch_idx):
|
418 |
+
_, loss_dict_no_ema = self.shared_step(batch)
|
419 |
+
with self.ema_scope():
|
420 |
+
_, loss_dict_ema = self.shared_step(batch)
|
421 |
+
loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema}
|
422 |
+
self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
|
423 |
+
self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
|
424 |
+
|
425 |
+
def on_train_batch_end(self, *args, **kwargs):
|
426 |
+
if self.use_ema:
|
427 |
+
self.model_ema(self.model)
|
428 |
+
|
429 |
+
def _get_rows_from_list(self, samples):
|
430 |
+
n_imgs_per_row = len(samples)
|
431 |
+
denoise_grid = rearrange(samples, 'n b c h w -> b n c h w')
|
432 |
+
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
|
433 |
+
denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
|
434 |
+
return denoise_grid
|
435 |
+
|
436 |
+
@torch.no_grad()
|
437 |
+
def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
|
438 |
+
log = dict()
|
439 |
+
x = self.get_input(batch, self.first_stage_key)
|
440 |
+
N = min(x.shape[0], N)
|
441 |
+
n_row = min(x.shape[0], n_row)
|
442 |
+
x = x.to(self.device)[:N]
|
443 |
+
log["inputs"] = x
|
444 |
+
|
445 |
+
# get diffusion row
|
446 |
+
diffusion_row = list()
|
447 |
+
x_start = x[:n_row]
|
448 |
+
|
449 |
+
for t in range(self.num_timesteps):
|
450 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
451 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
452 |
+
t = t.to(self.device).long()
|
453 |
+
noise = torch.randn_like(x_start)
|
454 |
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
455 |
+
diffusion_row.append(x_noisy)
|
456 |
+
|
457 |
+
log["diffusion_row"] = self._get_rows_from_list(diffusion_row)
|
458 |
+
|
459 |
+
if sample:
|
460 |
+
# get denoise row
|
461 |
+
with self.ema_scope("Plotting"):
|
462 |
+
samples, denoise_row = self.sample(batch_size=N, return_intermediates=True)
|
463 |
+
|
464 |
+
log["samples"] = samples
|
465 |
+
log["denoise_row"] = self._get_rows_from_list(denoise_row)
|
466 |
+
|
467 |
+
if return_keys:
|
468 |
+
if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
|
469 |
+
return log
|
470 |
+
else:
|
471 |
+
return {key: log[key] for key in return_keys}
|
472 |
+
return log
|
473 |
+
|
474 |
+
def configure_optimizers(self):
|
475 |
+
lr = self.learning_rate
|
476 |
+
params = list(self.model.parameters())
|
477 |
+
if self.learn_logvar:
|
478 |
+
params = params + [self.logvar]
|
479 |
+
opt = torch.optim.AdamW(params, lr=lr)
|
480 |
+
return opt
|
481 |
+
|
482 |
+
|
483 |
+
class LatentDiffusion(DDPM):
|
484 |
+
"""main class"""
|
485 |
+
def __init__(self,
|
486 |
+
first_stage_config,
|
487 |
+
cond_stage_config,
|
488 |
+
num_timesteps_cond=None,
|
489 |
+
cond_stage_key="image",
|
490 |
+
cond_stage_trainable=False,
|
491 |
+
concat_mode=True,
|
492 |
+
cat_key=None,
|
493 |
+
cond_stage_forward=None,
|
494 |
+
conditioning_key=None,
|
495 |
+
scale_factor=1.0,
|
496 |
+
scale_by_std=False,
|
497 |
+
unet_trainable=True,
|
498 |
+
use_clip_embdding=True,
|
499 |
+
*args, **kwargs):
|
500 |
+
self.use_clip_embdding = use_clip_embdding
|
501 |
+
self.num_timesteps_cond = default(num_timesteps_cond, 1)
|
502 |
+
self.scale_by_std = scale_by_std
|
503 |
+
assert self.num_timesteps_cond <= kwargs['timesteps']
|
504 |
+
# for backwards compatibility after implementation of DiffusionWrapper
|
505 |
+
if conditioning_key is None:
|
506 |
+
conditioning_key = 'concat' if concat_mode else 'crossattn'
|
507 |
+
if cond_stage_config == '__is_unconditional__':
|
508 |
+
conditioning_key = None
|
509 |
+
ckpt_path = kwargs.pop("ckpt_path", None)
|
510 |
+
ignore_keys = kwargs.pop("ignore_keys", [])
|
511 |
+
super().__init__(conditioning_key=conditioning_key, *args, **kwargs)
|
512 |
+
self.concat_mode = concat_mode
|
513 |
+
# additional concat keys
|
514 |
+
self.cat_key = cat_key
|
515 |
+
self.cond_stage_trainable = cond_stage_trainable
|
516 |
+
self.unet_trainable = unet_trainable
|
517 |
+
self.cond_stage_key = cond_stage_key
|
518 |
+
try:
|
519 |
+
self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
|
520 |
+
except:
|
521 |
+
self.num_downs = 0
|
522 |
+
if not scale_by_std:
|
523 |
+
self.scale_factor = scale_factor
|
524 |
+
else:
|
525 |
+
self.register_buffer('scale_factor', torch.tensor(scale_factor))
|
526 |
+
self.instantiate_first_stage(first_stage_config)
|
527 |
+
self.instantiate_cond_stage(cond_stage_config)
|
528 |
+
self.cond_stage_forward = cond_stage_forward
|
529 |
+
|
530 |
+
# construct linear projection layer for concatenating image CLIP embedding and RT
|
531 |
+
# self.cc_projection = nn.Linear(772, 768)
|
532 |
+
# nn.init.eye_(list(self.cc_projection.parameters())[0][:768, :768])
|
533 |
+
# nn.init.zeros_(list(self.cc_projection.parameters())[1])
|
534 |
+
# self.cc_projection.requires_grad_(True)
|
535 |
+
|
536 |
+
self.clip_denoised = False
|
537 |
+
self.bbox_tokenizer = None
|
538 |
+
|
539 |
+
self.restarted_from_ckpt = False
|
540 |
+
if ckpt_path is not None:
|
541 |
+
self.init_from_ckpt(ckpt_path, ignore_keys)
|
542 |
+
self.restarted_from_ckpt = True
|
543 |
+
|
544 |
+
def make_cond_schedule(self, ):
|
545 |
+
self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)
|
546 |
+
ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()
|
547 |
+
self.cond_ids[:self.num_timesteps_cond] = ids
|
548 |
+
|
549 |
+
@rank_zero_only
|
550 |
+
@torch.no_grad()
|
551 |
+
def on_train_batch_start(self, batch, batch_idx, dataloader_idx):
|
552 |
+
# only for very first batch
|
553 |
+
if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt:
|
554 |
+
assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously'
|
555 |
+
# set rescale weight to 1./std of encodings
|
556 |
+
print("### USING STD-RESCALING ###")
|
557 |
+
x = super().get_input(batch, self.first_stage_key)
|
558 |
+
x = x.to(self.device)
|
559 |
+
encoder_posterior = self.encode_first_stage(x)
|
560 |
+
z = self.get_first_stage_encoding(encoder_posterior).detach()
|
561 |
+
del self.scale_factor
|
562 |
+
self.register_buffer('scale_factor', 1. / z.flatten().std())
|
563 |
+
print(f"setting self.scale_factor to {self.scale_factor}")
|
564 |
+
print("### USING STD-RESCALING ###")
|
565 |
+
|
566 |
+
def register_schedule(self,
|
567 |
+
given_betas=None, beta_schedule="linear", timesteps=1000,
|
568 |
+
linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
|
569 |
+
super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)
|
570 |
+
|
571 |
+
self.shorten_cond_schedule = self.num_timesteps_cond > 1
|
572 |
+
if self.shorten_cond_schedule:
|
573 |
+
self.make_cond_schedule()
|
574 |
+
|
575 |
+
def instantiate_first_stage(self, config):
|
576 |
+
model = instantiate_from_config(config)
|
577 |
+
self.first_stage_model = model.eval()
|
578 |
+
self.first_stage_model.train = disabled_train
|
579 |
+
for param in self.first_stage_model.parameters():
|
580 |
+
param.requires_grad = False
|
581 |
+
|
582 |
+
def instantiate_cond_stage(self, config):
|
583 |
+
if not self.cond_stage_trainable:
|
584 |
+
if config == "__is_first_stage__":
|
585 |
+
print("Using first stage also as cond stage.")
|
586 |
+
self.cond_stage_model = self.first_stage_model
|
587 |
+
elif config == "__is_unconditional__":
|
588 |
+
print(f"Training {self.__class__.__name__} as an unconditional model.")
|
589 |
+
self.cond_stage_model = None
|
590 |
+
# self.be_unconditional = True
|
591 |
+
else:
|
592 |
+
model = instantiate_from_config(config)
|
593 |
+
self.cond_stage_model = model.eval()
|
594 |
+
self.cond_stage_model.train = disabled_train
|
595 |
+
for param in self.cond_stage_model.parameters():
|
596 |
+
param.requires_grad = False
|
597 |
+
else:
|
598 |
+
assert config != '__is_first_stage__'
|
599 |
+
assert config != '__is_unconditional__'
|
600 |
+
model = instantiate_from_config(config)
|
601 |
+
self.cond_stage_model = model
|
602 |
+
|
603 |
+
def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False):
|
604 |
+
denoise_row = []
|
605 |
+
for zd in tqdm(samples, desc=desc):
|
606 |
+
denoise_row.append(self.decode_first_stage(zd.to(self.device),
|
607 |
+
force_not_quantize=force_no_decoder_quantization))
|
608 |
+
n_imgs_per_row = len(denoise_row)
|
609 |
+
denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W
|
610 |
+
denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')
|
611 |
+
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
|
612 |
+
denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
|
613 |
+
return denoise_grid
|
614 |
+
|
615 |
+
def get_first_stage_encoding(self, encoder_posterior):
|
616 |
+
if isinstance(encoder_posterior, DiagonalGaussianDistribution):
|
617 |
+
z = encoder_posterior.sample()
|
618 |
+
elif isinstance(encoder_posterior, torch.Tensor):
|
619 |
+
z = encoder_posterior
|
620 |
+
else:
|
621 |
+
raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented")
|
622 |
+
return self.scale_factor * z
|
623 |
+
|
624 |
+
def get_learned_conditioning(self, c):
|
625 |
+
if self.cond_stage_forward is None:
|
626 |
+
if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):
|
627 |
+
c = self.cond_stage_model.encode(c)
|
628 |
+
if isinstance(c, DiagonalGaussianDistribution):
|
629 |
+
c = c.mode()
|
630 |
+
else:
|
631 |
+
c = self.cond_stage_model(c)
|
632 |
+
else:
|
633 |
+
assert hasattr(self.cond_stage_model, self.cond_stage_forward)
|
634 |
+
c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)
|
635 |
+
return c
|
636 |
+
|
637 |
+
def meshgrid(self, h, w):
|
638 |
+
y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)
|
639 |
+
x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)
|
640 |
+
|
641 |
+
arr = torch.cat([y, x], dim=-1)
|
642 |
+
return arr
|
643 |
+
|
644 |
+
def delta_border(self, h, w):
|
645 |
+
"""
|
646 |
+
:param h: height
|
647 |
+
:param w: width
|
648 |
+
:return: normalized distance to image border,
|
649 |
+
wtith min distance = 0 at border and max dist = 0.5 at image center
|
650 |
+
"""
|
651 |
+
lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
|
652 |
+
arr = self.meshgrid(h, w) / lower_right_corner
|
653 |
+
dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]
|
654 |
+
dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]
|
655 |
+
edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0]
|
656 |
+
return edge_dist
|
657 |
+
|
658 |
+
def get_weighting(self, h, w, Ly, Lx, device):
|
659 |
+
weighting = self.delta_border(h, w)
|
660 |
+
weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"],
|
661 |
+
self.split_input_params["clip_max_weight"], )
|
662 |
+
weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)
|
663 |
+
|
664 |
+
if self.split_input_params["tie_braker"]:
|
665 |
+
L_weighting = self.delta_border(Ly, Lx)
|
666 |
+
L_weighting = torch.clip(L_weighting,
|
667 |
+
self.split_input_params["clip_min_tie_weight"],
|
668 |
+
self.split_input_params["clip_max_tie_weight"])
|
669 |
+
|
670 |
+
L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)
|
671 |
+
weighting = weighting * L_weighting
|
672 |
+
return weighting
|
673 |
+
|
674 |
+
def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code
|
675 |
+
"""
|
676 |
+
:param x: img of size (bs, c, h, w)
|
677 |
+
:return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])
|
678 |
+
"""
|
679 |
+
bs, nc, h, w = x.shape
|
680 |
+
|
681 |
+
# number of crops in image
|
682 |
+
Ly = (h - kernel_size[0]) // stride[0] + 1
|
683 |
+
Lx = (w - kernel_size[1]) // stride[1] + 1
|
684 |
+
|
685 |
+
if uf == 1 and df == 1:
|
686 |
+
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
|
687 |
+
unfold = torch.nn.Unfold(**fold_params)
|
688 |
+
|
689 |
+
fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)
|
690 |
+
|
691 |
+
weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype)
|
692 |
+
normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap
|
693 |
+
weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))
|
694 |
+
|
695 |
+
elif uf > 1 and df == 1:
|
696 |
+
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
|
697 |
+
unfold = torch.nn.Unfold(**fold_params)
|
698 |
+
|
699 |
+
fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),
|
700 |
+
dilation=1, padding=0,
|
701 |
+
stride=(stride[0] * uf, stride[1] * uf))
|
702 |
+
fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2)
|
703 |
+
|
704 |
+
weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype)
|
705 |
+
normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap
|
706 |
+
weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx))
|
707 |
+
|
708 |
+
elif df > 1 and uf == 1:
|
709 |
+
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
|
710 |
+
unfold = torch.nn.Unfold(**fold_params)
|
711 |
+
|
712 |
+
fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df),
|
713 |
+
dilation=1, padding=0,
|
714 |
+
stride=(stride[0] // df, stride[1] // df))
|
715 |
+
fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2)
|
716 |
+
|
717 |
+
weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype)
|
718 |
+
normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap
|
719 |
+
weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx))
|
720 |
+
|
721 |
+
else:
|
722 |
+
raise NotImplementedError
|
723 |
+
|
724 |
+
return fold, unfold, normalization, weighting
|
725 |
+
|
726 |
+
|
727 |
+
@torch.no_grad()
|
728 |
+
def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False,
|
729 |
+
cond_key=None, return_original_cond=False, bs=None, uncond=0.05):
|
730 |
+
x = super().get_input(batch, k)
|
731 |
+
|
732 |
+
if bs is not None:
|
733 |
+
x = x[:bs]
|
734 |
+
|
735 |
+
x = x.to(self.device)
|
736 |
+
encoder_posterior = self.encode_first_stage(x)
|
737 |
+
z = self.get_first_stage_encoding(encoder_posterior).detach()
|
738 |
+
cond_key = cond_key or self.cond_stage_key
|
739 |
+
xc = super().get_input(batch, cond_key).to(self.device)
|
740 |
+
if bs is not None:
|
741 |
+
xc = xc[:bs]
|
742 |
+
cond = {}
|
743 |
+
|
744 |
+
if not self.cat_key is None:
|
745 |
+
cat_add = super().get_input(batch, self.cat_key).to(self.device)
|
746 |
+
if bs is not None:
|
747 |
+
cat_add = cat_add[:bs]
|
748 |
+
|
749 |
+
# To support classifier-free guidance, randomly drop out only text conditioning 5%, only image conditioning 5%, and both 5%.
|
750 |
+
random = torch.rand(x.size(0), device=x.device)
|
751 |
+
prompt_mask = rearrange(random < 2 * uncond, "n -> n 1 1")
|
752 |
+
input_mask = 1 - rearrange((random >= uncond).float() * (random < 3 * uncond).float(), "n -> n 1 1 1")
|
753 |
+
null_prompt = self.get_learned_conditioning([""])
|
754 |
+
|
755 |
+
# z.shape: [8, 4, 64, 64]; c.shape: [8, 1, 768]
|
756 |
+
# print('=========== xc shape ===========', xc.shape)
|
757 |
+
with torch.enable_grad():
|
758 |
+
clip_emb = self.get_learned_conditioning(xc if self.use_clip_embdding else [""]).detach()
|
759 |
+
null_prompt = self.get_learned_conditioning([""]).detach()
|
760 |
+
cond["c_crossattn"] = [torch.where(prompt_mask, null_prompt, clip_emb)]
|
761 |
+
cond["c_concat"] = [input_mask * self.encode_first_stage((xc.to(self.device))).mode().detach()]
|
762 |
+
if not self.cat_key is None:
|
763 |
+
cond["c_concat"] += [input_mask * self.encode_first_stage((cat_add.to(self.device))).mode().detach()]
|
764 |
+
out = [z, cond]
|
765 |
+
|
766 |
+
# domain vector
|
767 |
+
domain_ids = super().get_input(batch, "label").to(self.device).reshape(-1) # batch, 1
|
768 |
+
if bs is not None:
|
769 |
+
domain_ids = domain_ids[:bs]
|
770 |
+
cond["c_adm"] = domain_ids.long()
|
771 |
+
|
772 |
+
# print(f'conditioning shapes: z{z.shape}, encoder_posterior{encoder_posterior.mode().shape} cond["c_concat"]{cond["c_concat"][0].shape}')
|
773 |
+
if return_first_stage_outputs:
|
774 |
+
xrec = self.decode_first_stage(z)
|
775 |
+
out.extend([x, xrec])
|
776 |
+
if return_original_cond:
|
777 |
+
out.append(xc)
|
778 |
+
return out
|
779 |
+
|
780 |
+
# @torch.no_grad()
|
781 |
+
def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
|
782 |
+
if predict_cids:
|
783 |
+
if z.dim() == 4:
|
784 |
+
z = torch.argmax(z.exp(), dim=1).long()
|
785 |
+
z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
|
786 |
+
z = rearrange(z, 'b h w c -> b c h w').contiguous()
|
787 |
+
|
788 |
+
z = 1. / self.scale_factor * z
|
789 |
+
|
790 |
+
if hasattr(self, "split_input_params"):
|
791 |
+
if self.split_input_params["patch_distributed_vq"]:
|
792 |
+
ks = self.split_input_params["ks"] # eg. (128, 128)
|
793 |
+
stride = self.split_input_params["stride"] # eg. (64, 64)
|
794 |
+
uf = self.split_input_params["vqf"]
|
795 |
+
bs, nc, h, w = z.shape
|
796 |
+
if ks[0] > h or ks[1] > w:
|
797 |
+
ks = (min(ks[0], h), min(ks[1], w))
|
798 |
+
print("reducing Kernel")
|
799 |
+
|
800 |
+
if stride[0] > h or stride[1] > w:
|
801 |
+
stride = (min(stride[0], h), min(stride[1], w))
|
802 |
+
print("reducing stride")
|
803 |
+
|
804 |
+
fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf)
|
805 |
+
|
806 |
+
z = unfold(z) # (bn, nc * prod(**ks), L)
|
807 |
+
# 1. Reshape to img shape
|
808 |
+
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
|
809 |
+
|
810 |
+
# 2. apply model loop over last dim
|
811 |
+
if isinstance(self.first_stage_model, VQModelInterface):
|
812 |
+
output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
|
813 |
+
force_not_quantize=predict_cids or force_not_quantize)
|
814 |
+
for i in range(z.shape[-1])]
|
815 |
+
else:
|
816 |
+
|
817 |
+
output_list = [self.first_stage_model.decode(z[:, :, :, :, i])
|
818 |
+
for i in range(z.shape[-1])]
|
819 |
+
|
820 |
+
o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)
|
821 |
+
o = o * weighting
|
822 |
+
# Reverse 1. reshape to img shape
|
823 |
+
o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
|
824 |
+
# stitch crops together
|
825 |
+
decoded = fold(o)
|
826 |
+
decoded = decoded / normalization # norm is shape (1, 1, h, w)
|
827 |
+
return decoded
|
828 |
+
else:
|
829 |
+
if isinstance(self.first_stage_model, VQModelInterface):
|
830 |
+
return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
|
831 |
+
else:
|
832 |
+
return self.first_stage_model.decode(z)
|
833 |
+
|
834 |
+
else:
|
835 |
+
if isinstance(self.first_stage_model, VQModelInterface):
|
836 |
+
return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
|
837 |
+
else:
|
838 |
+
return self.first_stage_model.decode(z)
|
839 |
+
|
840 |
+
@torch.no_grad()
|
841 |
+
def encode_first_stage(self, x):
|
842 |
+
if hasattr(self, "split_input_params"):
|
843 |
+
if self.split_input_params["patch_distributed_vq"]:
|
844 |
+
ks = self.split_input_params["ks"] # eg. (128, 128)
|
845 |
+
stride = self.split_input_params["stride"] # eg. (64, 64)
|
846 |
+
df = self.split_input_params["vqf"]
|
847 |
+
self.split_input_params['original_image_size'] = x.shape[-2:]
|
848 |
+
bs, nc, h, w = x.shape
|
849 |
+
if ks[0] > h or ks[1] > w:
|
850 |
+
ks = (min(ks[0], h), min(ks[1], w))
|
851 |
+
print("reducing Kernel")
|
852 |
+
|
853 |
+
if stride[0] > h or stride[1] > w:
|
854 |
+
stride = (min(stride[0], h), min(stride[1], w))
|
855 |
+
print("reducing stride")
|
856 |
+
|
857 |
+
fold, unfold, normalization, weighting = self.get_fold_unfold(x, ks, stride, df=df)
|
858 |
+
z = unfold(x) # (bn, nc * prod(**ks), L)
|
859 |
+
# Reshape to img shape
|
860 |
+
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
|
861 |
+
|
862 |
+
output_list = [self.first_stage_model.encode(z[:, :, :, :, i])
|
863 |
+
for i in range(z.shape[-1])]
|
864 |
+
|
865 |
+
o = torch.stack(output_list, axis=-1)
|
866 |
+
o = o * weighting
|
867 |
+
|
868 |
+
# Reverse reshape to img shape
|
869 |
+
o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
|
870 |
+
# stitch crops together
|
871 |
+
decoded = fold(o)
|
872 |
+
decoded = decoded / normalization
|
873 |
+
return decoded
|
874 |
+
|
875 |
+
else:
|
876 |
+
return self.first_stage_model.encode(x)
|
877 |
+
else:
|
878 |
+
return self.first_stage_model.encode(x)
|
879 |
+
|
880 |
+
def shared_step(self, batch, **kwargs):
|
881 |
+
x, c = self.get_input(batch, self.first_stage_key)
|
882 |
+
loss = self(x, c)
|
883 |
+
return loss
|
884 |
+
|
885 |
+
def forward(self, x, c, *args, **kwargs):
|
886 |
+
t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
|
887 |
+
if self.model.conditioning_key is not None:
|
888 |
+
assert c is not None
|
889 |
+
# if self.cond_stage_trainable:
|
890 |
+
# c = self.get_learned_conditioning(c)
|
891 |
+
if self.shorten_cond_schedule: # TODO: drop this option
|
892 |
+
tc = self.cond_ids[t].to(self.device)
|
893 |
+
c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))
|
894 |
+
return self.p_losses(x, c, t, *args, **kwargs)
|
895 |
+
|
896 |
+
def _rescale_annotations(self, bboxes, crop_coordinates): # TODO: move to dataset
|
897 |
+
def rescale_bbox(bbox):
|
898 |
+
x0 = clamp((bbox[0] - crop_coordinates[0]) / crop_coordinates[2])
|
899 |
+
y0 = clamp((bbox[1] - crop_coordinates[1]) / crop_coordinates[3])
|
900 |
+
w = min(bbox[2] / crop_coordinates[2], 1 - x0)
|
901 |
+
h = min(bbox[3] / crop_coordinates[3], 1 - y0)
|
902 |
+
return x0, y0, w, h
|
903 |
+
|
904 |
+
return [rescale_bbox(b) for b in bboxes]
|
905 |
+
|
906 |
+
def apply_model(self, x_noisy, t, cond, return_ids=False):
|
907 |
+
|
908 |
+
if isinstance(cond, dict):
|
909 |
+
# hybrid case, cond is exptected to be a dict
|
910 |
+
pass
|
911 |
+
else:
|
912 |
+
if not isinstance(cond, list):
|
913 |
+
cond = [cond]
|
914 |
+
key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'
|
915 |
+
cond = {key: cond}
|
916 |
+
|
917 |
+
if hasattr(self, "split_input_params"):
|
918 |
+
assert len(cond) == 1 # todo can only deal with one conditioning atm
|
919 |
+
assert not return_ids
|
920 |
+
ks = self.split_input_params["ks"] # eg. (128, 128)
|
921 |
+
stride = self.split_input_params["stride"] # eg. (64, 64)
|
922 |
+
|
923 |
+
h, w = x_noisy.shape[-2:]
|
924 |
+
|
925 |
+
fold, unfold, normalization, weighting = self.get_fold_unfold(x_noisy, ks, stride)
|
926 |
+
|
927 |
+
z = unfold(x_noisy) # (bn, nc * prod(**ks), L)
|
928 |
+
# Reshape to img shape
|
929 |
+
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
|
930 |
+
z_list = [z[:, :, :, :, i] for i in range(z.shape[-1])]
|
931 |
+
|
932 |
+
if self.cond_stage_key in ["image", "LR_image", "segmentation",
|
933 |
+
'bbox_img'] and self.model.conditioning_key: # todo check for completeness
|
934 |
+
c_key = next(iter(cond.keys())) # get key
|
935 |
+
c = next(iter(cond.values())) # get value
|
936 |
+
assert (len(c) == 1) # todo extend to list with more than one elem
|
937 |
+
c = c[0] # get element
|
938 |
+
|
939 |
+
c = unfold(c)
|
940 |
+
c = c.view((c.shape[0], -1, ks[0], ks[1], c.shape[-1])) # (bn, nc, ks[0], ks[1], L )
|
941 |
+
|
942 |
+
cond_list = [{c_key: [c[:, :, :, :, i]]} for i in range(c.shape[-1])]
|
943 |
+
|
944 |
+
elif self.cond_stage_key == 'coordinates_bbox':
|
945 |
+
assert 'original_image_size' in self.split_input_params, 'BoudingBoxRescaling is missing original_image_size'
|
946 |
+
|
947 |
+
# assuming padding of unfold is always 0 and its dilation is always 1
|
948 |
+
n_patches_per_row = int((w - ks[0]) / stride[0] + 1)
|
949 |
+
full_img_h, full_img_w = self.split_input_params['original_image_size']
|
950 |
+
# as we are operating on latents, we need the factor from the original image size to the
|
951 |
+
# spatial latent size to properly rescale the crops for regenerating the bbox annotations
|
952 |
+
num_downs = self.first_stage_model.encoder.num_resolutions - 1
|
953 |
+
rescale_latent = 2 ** (num_downs)
|
954 |
+
|
955 |
+
# get top left postions of patches as conforming for the bbbox tokenizer, therefore we
|
956 |
+
# need to rescale the tl patch coordinates to be in between (0,1)
|
957 |
+
tl_patch_coordinates = [(rescale_latent * stride[0] * (patch_nr % n_patches_per_row) / full_img_w,
|
958 |
+
rescale_latent * stride[1] * (patch_nr // n_patches_per_row) / full_img_h)
|
959 |
+
for patch_nr in range(z.shape[-1])]
|
960 |
+
|
961 |
+
# patch_limits are tl_coord, width and height coordinates as (x_tl, y_tl, h, w)
|
962 |
+
patch_limits = [(x_tl, y_tl,
|
963 |
+
rescale_latent * ks[0] / full_img_w,
|
964 |
+
rescale_latent * ks[1] / full_img_h) for x_tl, y_tl in tl_patch_coordinates]
|
965 |
+
# patch_values = [(np.arange(x_tl,min(x_tl+ks, 1.)),np.arange(y_tl,min(y_tl+ks, 1.))) for x_tl, y_tl in tl_patch_coordinates]
|
966 |
+
|
967 |
+
# tokenize crop coordinates for the bounding boxes of the respective patches
|
968 |
+
patch_limits_tknzd = [torch.LongTensor(self.bbox_tokenizer._crop_encoder(bbox))[None].to(self.device)
|
969 |
+
for bbox in patch_limits] # list of length l with tensors of shape (1, 2)
|
970 |
+
# cut tknzd crop position from conditioning
|
971 |
+
assert isinstance(cond, dict), 'cond must be dict to be fed into model'
|
972 |
+
cut_cond = cond['c_crossattn'][0][..., :-2].to(self.device)
|
973 |
+
|
974 |
+
adapted_cond = torch.stack([torch.cat([cut_cond, p], dim=1) for p in patch_limits_tknzd])
|
975 |
+
adapted_cond = rearrange(adapted_cond, 'l b n -> (l b) n')
|
976 |
+
adapted_cond = self.get_learned_conditioning(adapted_cond)
|
977 |
+
adapted_cond = rearrange(adapted_cond, '(l b) n d -> l b n d', l=z.shape[-1])
|
978 |
+
|
979 |
+
cond_list = [{'c_crossattn': [e]} for e in adapted_cond]
|
980 |
+
|
981 |
+
else:
|
982 |
+
cond_list = [cond for i in range(z.shape[-1])] # Todo make this more efficient
|
983 |
+
|
984 |
+
# apply model by loop over crops
|
985 |
+
output_list = [self.model(z_list[i], t, **cond_list[i]) for i in range(z.shape[-1])]
|
986 |
+
assert not isinstance(output_list[0],
|
987 |
+
tuple) # todo cant deal with multiple model outputs check this never happens
|
988 |
+
|
989 |
+
o = torch.stack(output_list, axis=-1)
|
990 |
+
o = o * weighting
|
991 |
+
# Reverse reshape to img shape
|
992 |
+
o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
|
993 |
+
# stitch crops together
|
994 |
+
x_recon = fold(o) / normalization
|
995 |
+
|
996 |
+
else:
|
997 |
+
x_recon = self.model(x_noisy, t, **cond)
|
998 |
+
|
999 |
+
if isinstance(x_recon, tuple) and not return_ids:
|
1000 |
+
return x_recon[0]
|
1001 |
+
else:
|
1002 |
+
return x_recon
|
1003 |
+
|
1004 |
+
def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
|
1005 |
+
return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \
|
1006 |
+
extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
|
1007 |
+
|
1008 |
+
def _prior_bpd(self, x_start):
|
1009 |
+
"""
|
1010 |
+
Get the prior KL term for the variational lower-bound, measured in
|
1011 |
+
bits-per-dim.
|
1012 |
+
This term can't be optimized, as it only depends on the encoder.
|
1013 |
+
:param x_start: the [N x C x ...] tensor of inputs.
|
1014 |
+
:return: a batch of [N] KL values (in bits), one per batch element.
|
1015 |
+
"""
|
1016 |
+
batch_size = x_start.shape[0]
|
1017 |
+
t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
|
1018 |
+
qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
|
1019 |
+
kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
|
1020 |
+
return mean_flat(kl_prior) / np.log(2.0)
|
1021 |
+
|
1022 |
+
def p_losses(self, x_start, cond, t, noise=None):
|
1023 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
1024 |
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
1025 |
+
model_output = self.apply_model(x_noisy, t, cond)
|
1026 |
+
|
1027 |
+
loss_dict = {}
|
1028 |
+
prefix = 'train' if self.training else 'val'
|
1029 |
+
|
1030 |
+
if self.parameterization == "x0":
|
1031 |
+
target = x_start
|
1032 |
+
elif self.parameterization == "eps":
|
1033 |
+
target = noise
|
1034 |
+
else:
|
1035 |
+
raise NotImplementedError()
|
1036 |
+
|
1037 |
+
loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3])
|
1038 |
+
loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})
|
1039 |
+
|
1040 |
+
logvar_t = self.logvar[t].to(self.device)
|
1041 |
+
loss = loss_simple / torch.exp(logvar_t) + logvar_t
|
1042 |
+
# loss = loss_simple / torch.exp(self.logvar) + self.logvar
|
1043 |
+
if self.learn_logvar:
|
1044 |
+
loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})
|
1045 |
+
loss_dict.update({'logvar': self.logvar.data.mean()})
|
1046 |
+
|
1047 |
+
loss = self.l_simple_weight * loss.mean()
|
1048 |
+
|
1049 |
+
loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3))
|
1050 |
+
loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()
|
1051 |
+
loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})
|
1052 |
+
loss += (self.original_elbo_weight * loss_vlb)
|
1053 |
+
loss_dict.update({f'{prefix}/loss': loss})
|
1054 |
+
|
1055 |
+
return loss, loss_dict
|
1056 |
+
|
1057 |
+
def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False,
|
1058 |
+
return_x0=False, score_corrector=None, corrector_kwargs=None):
|
1059 |
+
t_in = t
|
1060 |
+
model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)
|
1061 |
+
|
1062 |
+
if score_corrector is not None:
|
1063 |
+
assert self.parameterization == "eps"
|
1064 |
+
model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)
|
1065 |
+
|
1066 |
+
if return_codebook_ids:
|
1067 |
+
model_out, logits = model_out
|
1068 |
+
|
1069 |
+
if self.parameterization == "eps":
|
1070 |
+
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
|
1071 |
+
elif self.parameterization == "x0":
|
1072 |
+
x_recon = model_out
|
1073 |
+
else:
|
1074 |
+
raise NotImplementedError()
|
1075 |
+
|
1076 |
+
if clip_denoised:
|
1077 |
+
x_recon.clamp_(-1., 1.)
|
1078 |
+
if quantize_denoised:
|
1079 |
+
x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)
|
1080 |
+
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
|
1081 |
+
if return_codebook_ids:
|
1082 |
+
return model_mean, posterior_variance, posterior_log_variance, logits
|
1083 |
+
elif return_x0:
|
1084 |
+
return model_mean, posterior_variance, posterior_log_variance, x_recon
|
1085 |
+
else:
|
1086 |
+
return model_mean, posterior_variance, posterior_log_variance
|
1087 |
+
|
1088 |
+
@torch.no_grad()
|
1089 |
+
def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False,
|
1090 |
+
return_codebook_ids=False, quantize_denoised=False, return_x0=False,
|
1091 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):
|
1092 |
+
b, *_, device = *x.shape, x.device
|
1093 |
+
outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised,
|
1094 |
+
return_codebook_ids=return_codebook_ids,
|
1095 |
+
quantize_denoised=quantize_denoised,
|
1096 |
+
return_x0=return_x0,
|
1097 |
+
score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
|
1098 |
+
if return_codebook_ids:
|
1099 |
+
raise DeprecationWarning("Support dropped.")
|
1100 |
+
model_mean, _, model_log_variance, logits = outputs
|
1101 |
+
elif return_x0:
|
1102 |
+
model_mean, _, model_log_variance, x0 = outputs
|
1103 |
+
else:
|
1104 |
+
model_mean, _, model_log_variance = outputs
|
1105 |
+
|
1106 |
+
noise = noise_like(x.shape, device, repeat_noise) * temperature
|
1107 |
+
if noise_dropout > 0.:
|
1108 |
+
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
|
1109 |
+
# no noise when t == 0
|
1110 |
+
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
|
1111 |
+
|
1112 |
+
if return_codebook_ids:
|
1113 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1)
|
1114 |
+
if return_x0:
|
1115 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0
|
1116 |
+
else:
|
1117 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
|
1118 |
+
|
1119 |
+
@torch.no_grad()
|
1120 |
+
def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False,
|
1121 |
+
img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0.,
|
1122 |
+
score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None,
|
1123 |
+
log_every_t=None):
|
1124 |
+
if not log_every_t:
|
1125 |
+
log_every_t = self.log_every_t
|
1126 |
+
timesteps = self.num_timesteps
|
1127 |
+
if batch_size is not None:
|
1128 |
+
b = batch_size if batch_size is not None else shape[0]
|
1129 |
+
shape = [batch_size] + list(shape)
|
1130 |
+
else:
|
1131 |
+
b = batch_size = shape[0]
|
1132 |
+
if x_T is None:
|
1133 |
+
img = torch.randn(shape, device=self.device)
|
1134 |
+
else:
|
1135 |
+
img = x_T
|
1136 |
+
intermediates = []
|
1137 |
+
if cond is not None:
|
1138 |
+
if isinstance(cond, dict):
|
1139 |
+
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
|
1140 |
+
list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
|
1141 |
+
else:
|
1142 |
+
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
|
1143 |
+
|
1144 |
+
if start_T is not None:
|
1145 |
+
timesteps = min(timesteps, start_T)
|
1146 |
+
iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation',
|
1147 |
+
total=timesteps) if verbose else reversed(
|
1148 |
+
range(0, timesteps))
|
1149 |
+
if type(temperature) == float:
|
1150 |
+
temperature = [temperature] * timesteps
|
1151 |
+
|
1152 |
+
for i in iterator:
|
1153 |
+
ts = torch.full((b,), i, device=self.device, dtype=torch.long)
|
1154 |
+
if self.shorten_cond_schedule:
|
1155 |
+
assert self.model.conditioning_key != 'hybrid'
|
1156 |
+
tc = self.cond_ids[ts].to(cond.device)
|
1157 |
+
cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
|
1158 |
+
|
1159 |
+
img, x0_partial = self.p_sample(img, cond, ts,
|
1160 |
+
clip_denoised=self.clip_denoised,
|
1161 |
+
quantize_denoised=quantize_denoised, return_x0=True,
|
1162 |
+
temperature=temperature[i], noise_dropout=noise_dropout,
|
1163 |
+
score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
|
1164 |
+
if mask is not None:
|
1165 |
+
assert x0 is not None
|
1166 |
+
img_orig = self.q_sample(x0, ts)
|
1167 |
+
img = img_orig * mask + (1. - mask) * img
|
1168 |
+
|
1169 |
+
if i % log_every_t == 0 or i == timesteps - 1:
|
1170 |
+
intermediates.append(x0_partial)
|
1171 |
+
if callback: callback(i)
|
1172 |
+
if img_callback: img_callback(img, i)
|
1173 |
+
return img, intermediates
|
1174 |
+
|
1175 |
+
@torch.no_grad()
|
1176 |
+
def p_sample_loop(self, cond, shape, return_intermediates=False,
|
1177 |
+
x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False,
|
1178 |
+
mask=None, x0=None, img_callback=None, start_T=None,
|
1179 |
+
log_every_t=None):
|
1180 |
+
|
1181 |
+
if not log_every_t:
|
1182 |
+
log_every_t = self.log_every_t
|
1183 |
+
device = self.betas.device
|
1184 |
+
b = shape[0]
|
1185 |
+
if x_T is None:
|
1186 |
+
img = torch.randn(shape, device=device)
|
1187 |
+
else:
|
1188 |
+
img = x_T
|
1189 |
+
|
1190 |
+
intermediates = [img]
|
1191 |
+
if timesteps is None:
|
1192 |
+
timesteps = self.num_timesteps
|
1193 |
+
|
1194 |
+
if start_T is not None:
|
1195 |
+
timesteps = min(timesteps, start_T)
|
1196 |
+
iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(
|
1197 |
+
range(0, timesteps))
|
1198 |
+
|
1199 |
+
if mask is not None:
|
1200 |
+
assert x0 is not None
|
1201 |
+
assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match
|
1202 |
+
|
1203 |
+
for i in iterator:
|
1204 |
+
ts = torch.full((b,), i, device=device, dtype=torch.long)
|
1205 |
+
if self.shorten_cond_schedule:
|
1206 |
+
assert self.model.conditioning_key != 'hybrid'
|
1207 |
+
tc = self.cond_ids[ts].to(cond.device)
|
1208 |
+
cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
|
1209 |
+
|
1210 |
+
img = self.p_sample(img, cond, ts,
|
1211 |
+
clip_denoised=self.clip_denoised,
|
1212 |
+
quantize_denoised=quantize_denoised)
|
1213 |
+
if mask is not None:
|
1214 |
+
img_orig = self.q_sample(x0, ts)
|
1215 |
+
img = img_orig * mask + (1. - mask) * img
|
1216 |
+
|
1217 |
+
if i % log_every_t == 0 or i == timesteps - 1:
|
1218 |
+
intermediates.append(img)
|
1219 |
+
if callback: callback(i)
|
1220 |
+
if img_callback: img_callback(img, i)
|
1221 |
+
|
1222 |
+
if return_intermediates:
|
1223 |
+
return img, intermediates
|
1224 |
+
return img
|
1225 |
+
|
1226 |
+
@torch.no_grad()
|
1227 |
+
def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None,
|
1228 |
+
verbose=True, timesteps=None, quantize_denoised=False,
|
1229 |
+
mask=None, x0=None, shape=None,**kwargs):
|
1230 |
+
if shape is None:
|
1231 |
+
shape = (batch_size, self.channels, self.image_size, self.image_size)
|
1232 |
+
if cond is not None:
|
1233 |
+
if isinstance(cond, dict):
|
1234 |
+
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
|
1235 |
+
list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
|
1236 |
+
else:
|
1237 |
+
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
|
1238 |
+
return self.p_sample_loop(cond,
|
1239 |
+
shape,
|
1240 |
+
return_intermediates=return_intermediates, x_T=x_T,
|
1241 |
+
verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised,
|
1242 |
+
mask=mask, x0=x0)
|
1243 |
+
|
1244 |
+
@torch.no_grad()
|
1245 |
+
def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs):
|
1246 |
+
if ddim:
|
1247 |
+
ddim_sampler = DDIMSampler(self)
|
1248 |
+
shape = (self.channels, self.image_size, self.image_size)
|
1249 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size,
|
1250 |
+
shape, cond, verbose=False, **kwargs)
|
1251 |
+
|
1252 |
+
else:
|
1253 |
+
samples, intermediates = self.sample(cond=cond, batch_size=batch_size,
|
1254 |
+
return_intermediates=True, **kwargs)
|
1255 |
+
|
1256 |
+
return samples, intermediates
|
1257 |
+
|
1258 |
+
@torch.no_grad()
|
1259 |
+
def get_unconditional_conditioning(self, batch_size, null_label=None, image_size=512):
|
1260 |
+
if null_label is not None:
|
1261 |
+
xc = null_label
|
1262 |
+
if isinstance(xc, ListConfig):
|
1263 |
+
xc = list(xc)
|
1264 |
+
if isinstance(xc, dict) or isinstance(xc, list):
|
1265 |
+
c = self.get_learned_conditioning(xc)
|
1266 |
+
else:
|
1267 |
+
if hasattr(xc, "to"):
|
1268 |
+
xc = xc.to(self.device)
|
1269 |
+
c = self.get_learned_conditioning(xc)
|
1270 |
+
else:
|
1271 |
+
# todo: get null label from cond_stage_model
|
1272 |
+
raise NotImplementedError()
|
1273 |
+
c = repeat(c, '1 ... -> b ...', b=batch_size).to(self.device)
|
1274 |
+
cond = {}
|
1275 |
+
cond["c_crossattn"] = [c]
|
1276 |
+
cond["c_concat"] = [torch.zeros([batch_size, 4, image_size // 8, image_size // 8]).to(self.device)]
|
1277 |
+
if not self.cat_key is None:
|
1278 |
+
cond["c_concat"] += [torch.zeros([batch_size, 4, image_size // 8, image_size // 8]).to(self.device)]
|
1279 |
+
|
1280 |
+
return cond
|
1281 |
+
|
1282 |
+
def test_step(self, batch, batch_idx):
|
1283 |
+
"Testing in image logger. We will save results in the future"
|
1284 |
+
pass
|
1285 |
+
|
1286 |
+
@torch.no_grad()
|
1287 |
+
def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
|
1288 |
+
quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
|
1289 |
+
plot_diffusion_rows=True, unconditional_guidance_scale=1., unconditional_guidance_label=None,
|
1290 |
+
use_ema_scope=True,
|
1291 |
+
**kwargs):
|
1292 |
+
ema_scope = self.ema_scope if use_ema_scope else nullcontext
|
1293 |
+
use_ddim = ddim_steps is not None
|
1294 |
+
|
1295 |
+
log = dict()
|
1296 |
+
z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,
|
1297 |
+
return_first_stage_outputs=True,
|
1298 |
+
force_c_encode=True,
|
1299 |
+
return_original_cond=True,
|
1300 |
+
bs=N)
|
1301 |
+
N = min(x.shape[0], N)
|
1302 |
+
n_row = min(x.shape[0], n_row)
|
1303 |
+
log["inputs"] = x
|
1304 |
+
log["reconstruction"] = xrec
|
1305 |
+
if self.model.conditioning_key is not None:
|
1306 |
+
if hasattr(self.cond_stage_model, "decode"):
|
1307 |
+
xc = self.cond_stage_model.decode(c)
|
1308 |
+
log["conditioning"] = xc
|
1309 |
+
elif self.cond_stage_key in ["caption", "txt"]:
|
1310 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2]//25)
|
1311 |
+
log["conditioning"] = xc
|
1312 |
+
elif self.cond_stage_key == 'class_label':
|
1313 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2]//25)
|
1314 |
+
log['conditioning'] = xc
|
1315 |
+
elif isimage(xc):
|
1316 |
+
log["conditioning"] = xc
|
1317 |
+
if ismap(xc):
|
1318 |
+
log["original_conditioning"] = self.to_rgb(xc)
|
1319 |
+
|
1320 |
+
if plot_diffusion_rows:
|
1321 |
+
# get diffusion row
|
1322 |
+
diffusion_row = list()
|
1323 |
+
z_start = z[:n_row]
|
1324 |
+
for t in range(self.num_timesteps):
|
1325 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
1326 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
1327 |
+
t = t.to(self.device).long()
|
1328 |
+
noise = torch.randn_like(z_start)
|
1329 |
+
z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
|
1330 |
+
diffusion_row.append(self.decode_first_stage(z_noisy))
|
1331 |
+
|
1332 |
+
diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
|
1333 |
+
diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
|
1334 |
+
diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
|
1335 |
+
diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
|
1336 |
+
log["diffusion_row"] = diffusion_grid
|
1337 |
+
|
1338 |
+
if sample:
|
1339 |
+
# get denoise row
|
1340 |
+
with ema_scope("Sampling"):
|
1341 |
+
samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim,
|
1342 |
+
ddim_steps=ddim_steps,eta=ddim_eta)
|
1343 |
+
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
|
1344 |
+
x_samples = self.decode_first_stage(samples)
|
1345 |
+
log["samples"] = x_samples
|
1346 |
+
if plot_denoise_rows:
|
1347 |
+
denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
|
1348 |
+
log["denoise_row"] = denoise_grid
|
1349 |
+
|
1350 |
+
if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(
|
1351 |
+
self.first_stage_model, IdentityFirstStage):
|
1352 |
+
# also display when quantizing x0 while sampling
|
1353 |
+
with ema_scope("Plotting Quantized Denoised"):
|
1354 |
+
samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim,
|
1355 |
+
ddim_steps=ddim_steps,eta=ddim_eta,
|
1356 |
+
quantize_denoised=True)
|
1357 |
+
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,
|
1358 |
+
# quantize_denoised=True)
|
1359 |
+
x_samples = self.decode_first_stage(samples.to(self.device))
|
1360 |
+
log["samples_x0_quantized"] = x_samples
|
1361 |
+
|
1362 |
+
if not isinstance(unconditional_guidance_scale, list):
|
1363 |
+
unconditional_guidance_scale = [unconditional_guidance_scale]
|
1364 |
+
for cfg_scale in unconditional_guidance_scale:
|
1365 |
+
if cfg_scale <= 1.0:
|
1366 |
+
break
|
1367 |
+
uc = self.get_unconditional_conditioning(N, unconditional_guidance_label, image_size=x.shape[-1])
|
1368 |
+
uc['c_adm'] = c['c_adm']
|
1369 |
+
# uc = torch.zeros_like(c)
|
1370 |
+
with ema_scope("Sampling with classifier-free guidance"):
|
1371 |
+
samples_cfg, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
1372 |
+
ddim_steps=ddim_steps, eta=ddim_eta,
|
1373 |
+
unconditional_guidance_scale=cfg_scale,
|
1374 |
+
unconditional_conditioning=uc,
|
1375 |
+
)
|
1376 |
+
x_samples_cfg = self.decode_first_stage(samples_cfg)
|
1377 |
+
log[f"samples_cfg_scale_{cfg_scale:.2f}"] = x_samples_cfg
|
1378 |
+
|
1379 |
+
if inpaint:
|
1380 |
+
# make a simple center square
|
1381 |
+
b, h, w = z.shape[0], z.shape[2], z.shape[3]
|
1382 |
+
mask = torch.ones(N, h, w).to(self.device)
|
1383 |
+
# zeros will be filled in
|
1384 |
+
mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.
|
1385 |
+
mask = mask[:, None, ...]
|
1386 |
+
with ema_scope("Plotting Inpaint"):
|
1387 |
+
|
1388 |
+
samples, _ = self.sample_log(cond=c,batch_size=N,ddim=use_ddim, eta=ddim_eta,
|
1389 |
+
ddim_steps=ddim_steps, x0=z[:N], mask=mask)
|
1390 |
+
x_samples = self.decode_first_stage(samples.to(self.device))
|
1391 |
+
log["samples_inpainting"] = x_samples
|
1392 |
+
log["mask"] = mask
|
1393 |
+
|
1394 |
+
# outpaint
|
1395 |
+
mask = 1. - mask
|
1396 |
+
with ema_scope("Plotting Outpaint"):
|
1397 |
+
samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,eta=ddim_eta,
|
1398 |
+
ddim_steps=ddim_steps, x0=z[:N], mask=mask)
|
1399 |
+
x_samples = self.decode_first_stage(samples.to(self.device))
|
1400 |
+
log["samples_outpainting"] = x_samples
|
1401 |
+
|
1402 |
+
if plot_progressive_rows:
|
1403 |
+
with ema_scope("Plotting Progressives"):
|
1404 |
+
img, progressives = self.progressive_denoising(c,
|
1405 |
+
shape=(self.channels, self.image_size, self.image_size),
|
1406 |
+
batch_size=N)
|
1407 |
+
prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
|
1408 |
+
log["progressive_row"] = prog_row
|
1409 |
+
|
1410 |
+
if return_keys:
|
1411 |
+
if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
|
1412 |
+
return log
|
1413 |
+
else:
|
1414 |
+
return {key: log[key] for key in return_keys}
|
1415 |
+
return log
|
1416 |
+
|
1417 |
+
def configure_optimizers(self):
|
1418 |
+
lr = self.learning_rate
|
1419 |
+
params = []
|
1420 |
+
if self.unet_trainable == "attn":
|
1421 |
+
print("Training only unet attention layers")
|
1422 |
+
for n, m in self.model.named_modules():
|
1423 |
+
if isinstance(m, CrossAttention) and n.endswith('attn2'):
|
1424 |
+
params.extend(m.parameters())
|
1425 |
+
if self.unet_trainable == "conv_in":
|
1426 |
+
print("Training only unet input conv layers")
|
1427 |
+
params = list(self.model.diffusion_model.input_blocks[0][0].parameters())
|
1428 |
+
elif self.unet_trainable is True or self.unet_trainable == "all":
|
1429 |
+
print("Training the full unet")
|
1430 |
+
params = list(self.model.parameters())
|
1431 |
+
else:
|
1432 |
+
raise ValueError(f"Unrecognised setting for unet_trainable: {self.unet_trainable}")
|
1433 |
+
|
1434 |
+
if self.cond_stage_trainable:
|
1435 |
+
print(f"{self.__class__.__name__}: Also optimizing conditioner params!")
|
1436 |
+
params = params + list(self.cond_stage_model.parameters())
|
1437 |
+
if self.learn_logvar:
|
1438 |
+
print('Diffusion model optimizing logvar')
|
1439 |
+
params.append(self.logvar)
|
1440 |
+
|
1441 |
+
# if self.cc_projection is not None:
|
1442 |
+
# params = params + list(self.cc_projection.parameters())
|
1443 |
+
# print('========== optimizing for cc projection weight ==========')
|
1444 |
+
|
1445 |
+
opt = torch.optim.AdamW([{"params": self.model.parameters(), "lr": lr},
|
1446 |
+
], lr=lr)
|
1447 |
+
if self.use_scheduler:
|
1448 |
+
assert 'target' in self.scheduler_config
|
1449 |
+
scheduler = instantiate_from_config(self.scheduler_config)
|
1450 |
+
|
1451 |
+
print("Setting up LambdaLR scheduler...")
|
1452 |
+
scheduler = [
|
1453 |
+
{
|
1454 |
+
'scheduler': LambdaLR(opt, lr_lambda=scheduler.schedule),
|
1455 |
+
'interval': 'step',
|
1456 |
+
'frequency': 1
|
1457 |
+
}]
|
1458 |
+
return [opt], scheduler
|
1459 |
+
return opt
|
1460 |
+
|
1461 |
+
@torch.no_grad()
|
1462 |
+
def to_rgb(self, x):
|
1463 |
+
x = x.float()
|
1464 |
+
if not hasattr(self, "colorize"):
|
1465 |
+
self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)
|
1466 |
+
x = nn.functional.conv2d(x, weight=self.colorize)
|
1467 |
+
x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.
|
1468 |
+
return x
|
1469 |
+
|
1470 |
+
|
1471 |
+
class DiffusionWrapper(pl.LightningModule):
|
1472 |
+
def __init__(self, diff_model_config, conditioning_key):
|
1473 |
+
super().__init__()
|
1474 |
+
self.diffusion_model = instantiate_from_config(diff_model_config)
|
1475 |
+
self.conditioning_key = conditioning_key
|
1476 |
+
assert self.conditioning_key in [None, 'concat', 'crossattn', 'hybrid', 'adm', 'hybrid-adm']
|
1477 |
+
|
1478 |
+
def forward(self, x, t, c_concat: list = None, c_crossattn: list = None, c_adm=None):
|
1479 |
+
if self.conditioning_key is None:
|
1480 |
+
out = self.diffusion_model(x, t)
|
1481 |
+
elif self.conditioning_key == 'concat':
|
1482 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1483 |
+
out = self.diffusion_model(xc, t)
|
1484 |
+
elif self.conditioning_key == 'crossattn':
|
1485 |
+
# c_crossattn dimension: torch.Size([8, 1, 768]) 1
|
1486 |
+
# cc dimension: torch.Size([8, 1, 768]
|
1487 |
+
cc = torch.cat(c_crossattn, 1)
|
1488 |
+
out = self.diffusion_model(x, t, context=cc)
|
1489 |
+
elif self.conditioning_key == 'hybrid':
|
1490 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1491 |
+
cc = torch.cat(c_crossattn, 1)
|
1492 |
+
out = self.diffusion_model(xc, t, context=cc)
|
1493 |
+
elif self.conditioning_key == 'hybrid-adm':
|
1494 |
+
assert c_adm is not None
|
1495 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1496 |
+
cc = torch.cat(c_crossattn, 1)
|
1497 |
+
out = self.diffusion_model(xc, t, context=cc, y=c_adm)
|
1498 |
+
elif self.conditioning_key == 'adm':
|
1499 |
+
cc = c_crossattn[0]
|
1500 |
+
out = self.diffusion_model(x, t, y=cc)
|
1501 |
+
else:
|
1502 |
+
raise NotImplementedError()
|
1503 |
+
|
1504 |
+
return out
|
1505 |
+
|
1506 |
+
|
1507 |
+
class LatentUpscaleDiffusion(LatentDiffusion):
|
1508 |
+
def __init__(self, *args, low_scale_config, low_scale_key="LR", **kwargs):
|
1509 |
+
super().__init__(*args, **kwargs)
|
1510 |
+
# assumes that neither the cond_stage nor the low_scale_model contain trainable params
|
1511 |
+
assert not self.cond_stage_trainable
|
1512 |
+
self.instantiate_low_stage(low_scale_config)
|
1513 |
+
self.low_scale_key = low_scale_key
|
1514 |
+
|
1515 |
+
def instantiate_low_stage(self, config):
|
1516 |
+
model = instantiate_from_config(config)
|
1517 |
+
self.low_scale_model = model.eval()
|
1518 |
+
self.low_scale_model.train = disabled_train
|
1519 |
+
for param in self.low_scale_model.parameters():
|
1520 |
+
param.requires_grad = False
|
1521 |
+
|
1522 |
+
@torch.no_grad()
|
1523 |
+
def get_input(self, batch, k, cond_key=None, bs=None, log_mode=False):
|
1524 |
+
if not log_mode:
|
1525 |
+
z, c = super().get_input(batch, k, force_c_encode=True, bs=bs)
|
1526 |
+
else:
|
1527 |
+
z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
|
1528 |
+
force_c_encode=True, return_original_cond=True, bs=bs)
|
1529 |
+
x_low = batch[self.low_scale_key][:bs]
|
1530 |
+
x_low = rearrange(x_low, 'b h w c -> b c h w')
|
1531 |
+
x_low = x_low.to(memory_format=torch.contiguous_format).float()
|
1532 |
+
zx, noise_level = self.low_scale_model(x_low)
|
1533 |
+
all_conds = {"c_concat": [zx], "c_crossattn": [c], "c_adm": noise_level}
|
1534 |
+
#import pudb; pu.db
|
1535 |
+
if log_mode:
|
1536 |
+
# TODO: maybe disable if too expensive
|
1537 |
+
interpretability = False
|
1538 |
+
if interpretability:
|
1539 |
+
zx = zx[:, :, ::2, ::2]
|
1540 |
+
x_low_rec = self.low_scale_model.decode(zx)
|
1541 |
+
return z, all_conds, x, xrec, xc, x_low, x_low_rec, noise_level
|
1542 |
+
return z, all_conds
|
1543 |
+
|
1544 |
+
@torch.no_grad()
|
1545 |
+
def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
|
1546 |
+
plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=True,
|
1547 |
+
unconditional_guidance_scale=1., unconditional_guidance_label=None, use_ema_scope=True,
|
1548 |
+
**kwargs):
|
1549 |
+
ema_scope = self.ema_scope if use_ema_scope else nullcontext
|
1550 |
+
use_ddim = ddim_steps is not None
|
1551 |
+
|
1552 |
+
log = dict()
|
1553 |
+
z, c, x, xrec, xc, x_low, x_low_rec, noise_level = self.get_input(batch, self.first_stage_key, bs=N,
|
1554 |
+
log_mode=True)
|
1555 |
+
N = min(x.shape[0], N)
|
1556 |
+
n_row = min(x.shape[0], n_row)
|
1557 |
+
log["inputs"] = x
|
1558 |
+
log["reconstruction"] = xrec
|
1559 |
+
log["x_lr"] = x_low
|
1560 |
+
log[f"x_lr_rec_@noise_levels{'-'.join(map(lambda x: str(x), list(noise_level.cpu().numpy())))}"] = x_low_rec
|
1561 |
+
if self.model.conditioning_key is not None:
|
1562 |
+
if hasattr(self.cond_stage_model, "decode"):
|
1563 |
+
xc = self.cond_stage_model.decode(c)
|
1564 |
+
log["conditioning"] = xc
|
1565 |
+
elif self.cond_stage_key in ["caption", "txt"]:
|
1566 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2]//25)
|
1567 |
+
log["conditioning"] = xc
|
1568 |
+
elif self.cond_stage_key == 'class_label':
|
1569 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2]//25)
|
1570 |
+
log['conditioning'] = xc
|
1571 |
+
elif isimage(xc):
|
1572 |
+
log["conditioning"] = xc
|
1573 |
+
if ismap(xc):
|
1574 |
+
log["original_conditioning"] = self.to_rgb(xc)
|
1575 |
+
|
1576 |
+
if plot_diffusion_rows:
|
1577 |
+
# get diffusion row
|
1578 |
+
diffusion_row = list()
|
1579 |
+
z_start = z[:n_row]
|
1580 |
+
for t in range(self.num_timesteps):
|
1581 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
1582 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
1583 |
+
t = t.to(self.device).long()
|
1584 |
+
noise = torch.randn_like(z_start)
|
1585 |
+
z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
|
1586 |
+
diffusion_row.append(self.decode_first_stage(z_noisy))
|
1587 |
+
|
1588 |
+
diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
|
1589 |
+
diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
|
1590 |
+
diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
|
1591 |
+
diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
|
1592 |
+
log["diffusion_row"] = diffusion_grid
|
1593 |
+
|
1594 |
+
if sample:
|
1595 |
+
# get denoise row
|
1596 |
+
with ema_scope("Sampling"):
|
1597 |
+
samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
1598 |
+
ddim_steps=ddim_steps, eta=ddim_eta)
|
1599 |
+
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
|
1600 |
+
x_samples = self.decode_first_stage(samples)
|
1601 |
+
log["samples"] = x_samples
|
1602 |
+
if plot_denoise_rows:
|
1603 |
+
denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
|
1604 |
+
log["denoise_row"] = denoise_grid
|
1605 |
+
|
1606 |
+
if unconditional_guidance_scale > 1.0:
|
1607 |
+
uc_tmp = self.get_unconditional_conditioning(N, unconditional_guidance_label)
|
1608 |
+
# TODO explore better "unconditional" choices for the other keys
|
1609 |
+
# maybe guide away from empty text label and highest noise level and maximally degraded zx?
|
1610 |
+
uc = dict()
|
1611 |
+
for k in c:
|
1612 |
+
if k == "c_crossattn":
|
1613 |
+
assert isinstance(c[k], list) and len(c[k]) == 1
|
1614 |
+
uc[k] = [uc_tmp]
|
1615 |
+
elif k == "c_adm": # todo: only run with text-based guidance?
|
1616 |
+
assert isinstance(c[k], torch.Tensor)
|
1617 |
+
uc[k] = torch.ones_like(c[k]) * self.low_scale_model.max_noise_level
|
1618 |
+
elif isinstance(c[k], list):
|
1619 |
+
uc[k] = [c[k][i] for i in range(len(c[k]))]
|
1620 |
+
else:
|
1621 |
+
uc[k] = c[k]
|
1622 |
+
|
1623 |
+
with ema_scope("Sampling with classifier-free guidance"):
|
1624 |
+
samples_cfg, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
1625 |
+
ddim_steps=ddim_steps, eta=ddim_eta,
|
1626 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
1627 |
+
unconditional_conditioning=uc,
|
1628 |
+
)
|
1629 |
+
x_samples_cfg = self.decode_first_stage(samples_cfg)
|
1630 |
+
log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
|
1631 |
+
|
1632 |
+
if plot_progressive_rows:
|
1633 |
+
with ema_scope("Plotting Progressives"):
|
1634 |
+
img, progressives = self.progressive_denoising(c,
|
1635 |
+
shape=(self.channels, self.image_size, self.image_size),
|
1636 |
+
batch_size=N)
|
1637 |
+
prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
|
1638 |
+
log["progressive_row"] = prog_row
|
1639 |
+
|
1640 |
+
return log
|
1641 |
+
|
1642 |
+
|
1643 |
+
class LatentInpaintDiffusion(LatentDiffusion):
|
1644 |
+
"""
|
1645 |
+
can either run as pure inpainting model (only concat mode) or with mixed conditionings,
|
1646 |
+
e.g. mask as concat and text via cross-attn.
|
1647 |
+
To disable finetuning mode, set finetune_keys to None
|
1648 |
+
"""
|
1649 |
+
def __init__(self,
|
1650 |
+
finetune_keys=("model.diffusion_model.input_blocks.0.0.weight",
|
1651 |
+
"model_ema.diffusion_modelinput_blocks00weight"
|
1652 |
+
),
|
1653 |
+
concat_keys=("mask", "masked_image"),
|
1654 |
+
masked_image_key="masked_image",
|
1655 |
+
keep_finetune_dims=4, # if model was trained without concat mode before and we would like to keep these channels
|
1656 |
+
c_concat_log_start=None, # to log reconstruction of c_concat codes
|
1657 |
+
c_concat_log_end=None,
|
1658 |
+
*args, **kwargs
|
1659 |
+
):
|
1660 |
+
ckpt_path = kwargs.pop("ckpt_path", None)
|
1661 |
+
ignore_keys = kwargs.pop("ignore_keys", list())
|
1662 |
+
super().__init__(*args, **kwargs)
|
1663 |
+
self.masked_image_key = masked_image_key
|
1664 |
+
assert self.masked_image_key in concat_keys
|
1665 |
+
self.finetune_keys = finetune_keys
|
1666 |
+
self.concat_keys = concat_keys
|
1667 |
+
self.keep_dims = keep_finetune_dims
|
1668 |
+
self.c_concat_log_start = c_concat_log_start
|
1669 |
+
self.c_concat_log_end = c_concat_log_end
|
1670 |
+
if exists(self.finetune_keys): assert exists(ckpt_path), 'can only finetune from a given checkpoint'
|
1671 |
+
if exists(ckpt_path):
|
1672 |
+
self.init_from_ckpt(ckpt_path, ignore_keys)
|
1673 |
+
|
1674 |
+
def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
|
1675 |
+
sd = torch.load(path, map_location="cpu")
|
1676 |
+
if "state_dict" in list(sd.keys()):
|
1677 |
+
sd = sd["state_dict"]
|
1678 |
+
keys = list(sd.keys())
|
1679 |
+
for k in keys:
|
1680 |
+
for ik in ignore_keys:
|
1681 |
+
if k.startswith(ik):
|
1682 |
+
print("Deleting key {} from state_dict.".format(k))
|
1683 |
+
del sd[k]
|
1684 |
+
|
1685 |
+
# make it explicit, finetune by including extra input channels
|
1686 |
+
if exists(self.finetune_keys) and k in self.finetune_keys:
|
1687 |
+
new_entry = None
|
1688 |
+
for name, param in self.named_parameters():
|
1689 |
+
if name in self.finetune_keys:
|
1690 |
+
print(f"modifying key '{name}' and keeping its original {self.keep_dims} (channels) dimensions only")
|
1691 |
+
new_entry = torch.zeros_like(param) # zero init
|
1692 |
+
assert exists(new_entry), 'did not find matching parameter to modify'
|
1693 |
+
new_entry[:, :self.keep_dims, ...] = sd[k]
|
1694 |
+
sd[k] = new_entry
|
1695 |
+
|
1696 |
+
missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(sd, strict=False)
|
1697 |
+
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
1698 |
+
if len(missing) > 0:
|
1699 |
+
print(f"Missing Keys: {missing}")
|
1700 |
+
if len(unexpected) > 0:
|
1701 |
+
print(f"Unexpected Keys: {unexpected}")
|
1702 |
+
|
1703 |
+
@torch.no_grad()
|
1704 |
+
def get_input(self, batch, k, cond_key=None, bs=None, return_first_stage_outputs=False):
|
1705 |
+
# note: restricted to non-trainable encoders currently
|
1706 |
+
assert not self.cond_stage_trainable, 'trainable cond stages not yet supported for inpainting'
|
1707 |
+
z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
|
1708 |
+
force_c_encode=True, return_original_cond=True, bs=bs)
|
1709 |
+
|
1710 |
+
assert exists(self.concat_keys)
|
1711 |
+
c_cat = list()
|
1712 |
+
for ck in self.concat_keys:
|
1713 |
+
cc = rearrange(batch[ck], 'b h w c -> b c h w').to(memory_format=torch.contiguous_format).float()
|
1714 |
+
if bs is not None:
|
1715 |
+
cc = cc[:bs]
|
1716 |
+
cc = cc.to(self.device)
|
1717 |
+
bchw = z.shape
|
1718 |
+
if ck != self.masked_image_key:
|
1719 |
+
cc = torch.nn.functional.interpolate(cc, size=bchw[-2:])
|
1720 |
+
else:
|
1721 |
+
cc = self.get_first_stage_encoding(self.encode_first_stage(cc))
|
1722 |
+
c_cat.append(cc)
|
1723 |
+
c_cat = torch.cat(c_cat, dim=1)
|
1724 |
+
all_conds = {"c_concat": [c_cat], "c_crossattn": [c]}
|
1725 |
+
if return_first_stage_outputs:
|
1726 |
+
return z, all_conds, x, xrec, xc
|
1727 |
+
return z, all_conds
|
1728 |
+
|
1729 |
+
@torch.no_grad()
|
1730 |
+
def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
|
1731 |
+
quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
|
1732 |
+
plot_diffusion_rows=True, unconditional_guidance_scale=1., unconditional_guidance_label=None,
|
1733 |
+
use_ema_scope=True,
|
1734 |
+
**kwargs):
|
1735 |
+
ema_scope = self.ema_scope if use_ema_scope else nullcontext
|
1736 |
+
use_ddim = ddim_steps is not None
|
1737 |
+
|
1738 |
+
log = dict()
|
1739 |
+
z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key, bs=N, return_first_stage_outputs=True)
|
1740 |
+
c_cat, c = c["c_concat"][0], c["c_crossattn"][0]
|
1741 |
+
N = min(x.shape[0], N)
|
1742 |
+
n_row = min(x.shape[0], n_row)
|
1743 |
+
log["inputs"] = x
|
1744 |
+
log["reconstruction"] = xrec
|
1745 |
+
if self.model.conditioning_key is not None:
|
1746 |
+
if hasattr(self.cond_stage_model, "decode"):
|
1747 |
+
xc = self.cond_stage_model.decode(c)
|
1748 |
+
log["conditioning"] = xc
|
1749 |
+
elif self.cond_stage_key in ["caption", "txt"]:
|
1750 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25)
|
1751 |
+
log["conditioning"] = xc
|
1752 |
+
elif self.cond_stage_key == 'class_label':
|
1753 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2] // 25)
|
1754 |
+
log['conditioning'] = xc
|
1755 |
+
elif isimage(xc):
|
1756 |
+
log["conditioning"] = xc
|
1757 |
+
if ismap(xc):
|
1758 |
+
log["original_conditioning"] = self.to_rgb(xc)
|
1759 |
+
|
1760 |
+
if not (self.c_concat_log_start is None and self.c_concat_log_end is None):
|
1761 |
+
log["c_concat_decoded"] = self.decode_first_stage(c_cat[:,self.c_concat_log_start:self.c_concat_log_end])
|
1762 |
+
|
1763 |
+
if plot_diffusion_rows:
|
1764 |
+
# get diffusion row
|
1765 |
+
diffusion_row = list()
|
1766 |
+
z_start = z[:n_row]
|
1767 |
+
for t in range(self.num_timesteps):
|
1768 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
1769 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
1770 |
+
t = t.to(self.device).long()
|
1771 |
+
noise = torch.randn_like(z_start)
|
1772 |
+
z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
|
1773 |
+
diffusion_row.append(self.decode_first_stage(z_noisy))
|
1774 |
+
|
1775 |
+
diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
|
1776 |
+
diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
|
1777 |
+
diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
|
1778 |
+
diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
|
1779 |
+
log["diffusion_row"] = diffusion_grid
|
1780 |
+
|
1781 |
+
if sample:
|
1782 |
+
# get denoise row
|
1783 |
+
with ema_scope("Sampling"):
|
1784 |
+
samples, z_denoise_row = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},
|
1785 |
+
batch_size=N, ddim=use_ddim,
|
1786 |
+
ddim_steps=ddim_steps, eta=ddim_eta)
|
1787 |
+
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
|
1788 |
+
x_samples = self.decode_first_stage(samples)
|
1789 |
+
log["samples"] = x_samples
|
1790 |
+
if plot_denoise_rows:
|
1791 |
+
denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
|
1792 |
+
log["denoise_row"] = denoise_grid
|
1793 |
+
|
1794 |
+
if unconditional_guidance_scale > 1.0:
|
1795 |
+
uc_cross = self.get_unconditional_conditioning(N, unconditional_guidance_label)
|
1796 |
+
uc_cat = c_cat
|
1797 |
+
uc_full = {"c_concat": [uc_cat], "c_crossattn": [uc_cross]}
|
1798 |
+
with ema_scope("Sampling with classifier-free guidance"):
|
1799 |
+
samples_cfg, _ = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},
|
1800 |
+
batch_size=N, ddim=use_ddim,
|
1801 |
+
ddim_steps=ddim_steps, eta=ddim_eta,
|
1802 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
1803 |
+
unconditional_conditioning=uc_full,
|
1804 |
+
)
|
1805 |
+
x_samples_cfg = self.decode_first_stage(samples_cfg)
|
1806 |
+
log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
|
1807 |
+
|
1808 |
+
log["masked_image"] = rearrange(batch["masked_image"],
|
1809 |
+
'b h w c -> b c h w').to(memory_format=torch.contiguous_format).float()
|
1810 |
+
return log
|
1811 |
+
|
1812 |
+
|
1813 |
+
class Layout2ImgDiffusion(LatentDiffusion):
|
1814 |
+
# TODO: move all layout-specific hacks to this class
|
1815 |
+
def __init__(self, cond_stage_key, *args, **kwargs):
|
1816 |
+
assert cond_stage_key == 'coordinates_bbox', 'Layout2ImgDiffusion only for cond_stage_key="coordinates_bbox"'
|
1817 |
+
super().__init__(cond_stage_key=cond_stage_key, *args, **kwargs)
|
1818 |
+
|
1819 |
+
def log_images(self, batch, N=8, *args, **kwargs):
|
1820 |
+
logs = super().log_images(batch=batch, N=N, *args, **kwargs)
|
1821 |
+
|
1822 |
+
key = 'train' if self.training else 'validation'
|
1823 |
+
dset = self.trainer.datamodule.datasets[key]
|
1824 |
+
mapper = dset.conditional_builders[self.cond_stage_key]
|
1825 |
+
|
1826 |
+
bbox_imgs = []
|
1827 |
+
map_fn = lambda catno: dset.get_textual_label(dset.get_category_id(catno))
|
1828 |
+
for tknzd_bbox in batch[self.cond_stage_key][:N]:
|
1829 |
+
bboximg = mapper.plot(tknzd_bbox.detach().cpu(), map_fn, (256, 256))
|
1830 |
+
bbox_imgs.append(bboximg)
|
1831 |
+
|
1832 |
+
cond_img = torch.stack(bbox_imgs, dim=0)
|
1833 |
+
logs['bbox_image'] = cond_img
|
1834 |
+
return logs
|
1835 |
+
|
1836 |
+
|
1837 |
+
class SimpleUpscaleDiffusion(LatentDiffusion):
|
1838 |
+
def __init__(self, *args, low_scale_key="LR", **kwargs):
|
1839 |
+
super().__init__(*args, **kwargs)
|
1840 |
+
# assumes that neither the cond_stage nor the low_scale_model contain trainable params
|
1841 |
+
assert not self.cond_stage_trainable
|
1842 |
+
self.low_scale_key = low_scale_key
|
1843 |
+
|
1844 |
+
@torch.no_grad()
|
1845 |
+
def get_input(self, batch, k, cond_key=None, bs=None, log_mode=False):
|
1846 |
+
if not log_mode:
|
1847 |
+
z, c = super().get_input(batch, k, force_c_encode=True, bs=bs)
|
1848 |
+
else:
|
1849 |
+
z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
|
1850 |
+
force_c_encode=True, return_original_cond=True, bs=bs)
|
1851 |
+
x_low = batch[self.low_scale_key][:bs]
|
1852 |
+
x_low = rearrange(x_low, 'b h w c -> b c h w')
|
1853 |
+
x_low = x_low.to(memory_format=torch.contiguous_format).float()
|
1854 |
+
|
1855 |
+
encoder_posterior = self.encode_first_stage(x_low)
|
1856 |
+
zx = self.get_first_stage_encoding(encoder_posterior).detach()
|
1857 |
+
all_conds = {"c_concat": [zx], "c_crossattn": [c]}
|
1858 |
+
|
1859 |
+
if log_mode:
|
1860 |
+
# TODO: maybe disable if too expensive
|
1861 |
+
interpretability = False
|
1862 |
+
if interpretability:
|
1863 |
+
zx = zx[:, :, ::2, ::2]
|
1864 |
+
return z, all_conds, x, xrec, xc, x_low
|
1865 |
+
return z, all_conds
|
1866 |
+
|
1867 |
+
@torch.no_grad()
|
1868 |
+
def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
|
1869 |
+
plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=True,
|
1870 |
+
unconditional_guidance_scale=1., unconditional_guidance_label=None, use_ema_scope=True,
|
1871 |
+
**kwargs):
|
1872 |
+
ema_scope = self.ema_scope if use_ema_scope else nullcontext
|
1873 |
+
use_ddim = ddim_steps is not None
|
1874 |
+
|
1875 |
+
log = dict()
|
1876 |
+
z, c, x, xrec, xc, x_low = self.get_input(batch, self.first_stage_key, bs=N, log_mode=True)
|
1877 |
+
N = min(x.shape[0], N)
|
1878 |
+
n_row = min(x.shape[0], n_row)
|
1879 |
+
log["inputs"] = x
|
1880 |
+
log["reconstruction"] = xrec
|
1881 |
+
log["x_lr"] = x_low
|
1882 |
+
|
1883 |
+
if self.model.conditioning_key is not None:
|
1884 |
+
if hasattr(self.cond_stage_model, "decode"):
|
1885 |
+
xc = self.cond_stage_model.decode(c)
|
1886 |
+
log["conditioning"] = xc
|
1887 |
+
elif self.cond_stage_key in ["caption", "txt"]:
|
1888 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2]//25)
|
1889 |
+
log["conditioning"] = xc
|
1890 |
+
elif self.cond_stage_key == 'class_label':
|
1891 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2]//25)
|
1892 |
+
log['conditioning'] = xc
|
1893 |
+
elif isimage(xc):
|
1894 |
+
log["conditioning"] = xc
|
1895 |
+
if ismap(xc):
|
1896 |
+
log["original_conditioning"] = self.to_rgb(xc)
|
1897 |
+
|
1898 |
+
if sample:
|
1899 |
+
# get denoise row
|
1900 |
+
with ema_scope("Sampling"):
|
1901 |
+
samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
1902 |
+
ddim_steps=ddim_steps, eta=ddim_eta)
|
1903 |
+
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
|
1904 |
+
x_samples = self.decode_first_stage(samples)
|
1905 |
+
log["samples"] = x_samples
|
1906 |
+
|
1907 |
+
if unconditional_guidance_scale > 1.0:
|
1908 |
+
uc_tmp = self.get_unconditional_conditioning(N, unconditional_guidance_label)
|
1909 |
+
uc = dict()
|
1910 |
+
for k in c:
|
1911 |
+
if k == "c_crossattn":
|
1912 |
+
assert isinstance(c[k], list) and len(c[k]) == 1
|
1913 |
+
uc[k] = [uc_tmp]
|
1914 |
+
elif isinstance(c[k], list):
|
1915 |
+
uc[k] = [c[k][i] for i in range(len(c[k]))]
|
1916 |
+
else:
|
1917 |
+
uc[k] = c[k]
|
1918 |
+
|
1919 |
+
with ema_scope("Sampling with classifier-free guidance"):
|
1920 |
+
samples_cfg, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
1921 |
+
ddim_steps=ddim_steps, eta=ddim_eta,
|
1922 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
1923 |
+
unconditional_conditioning=uc,
|
1924 |
+
)
|
1925 |
+
x_samples_cfg = self.decode_first_stage(samples_cfg)
|
1926 |
+
log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
|
1927 |
+
return log
|
1928 |
+
|
1929 |
+
class MultiCatFrameDiffusion(LatentDiffusion):
|
1930 |
+
def __init__(self, *args, low_scale_key="LR", **kwargs):
|
1931 |
+
super().__init__(*args, **kwargs)
|
1932 |
+
# assumes that neither the cond_stage nor the low_scale_model contain trainable params
|
1933 |
+
assert not self.cond_stage_trainable
|
1934 |
+
self.low_scale_key = low_scale_key
|
1935 |
+
|
1936 |
+
@torch.no_grad()
|
1937 |
+
def get_input(self, batch, k, cond_key=None, bs=None, log_mode=False):
|
1938 |
+
n = 2
|
1939 |
+
if not log_mode:
|
1940 |
+
z, c = super().get_input(batch, k, force_c_encode=True, bs=bs)
|
1941 |
+
else:
|
1942 |
+
z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
|
1943 |
+
force_c_encode=True, return_original_cond=True, bs=bs)
|
1944 |
+
cat_conds = batch[self.low_scale_key][:bs]
|
1945 |
+
cats = []
|
1946 |
+
for i in range(n):
|
1947 |
+
x_low = cat_conds[:,:,:,3*i:3*(i+1)]
|
1948 |
+
x_low = rearrange(x_low, 'b h w c -> b c h w')
|
1949 |
+
x_low = x_low.to(memory_format=torch.contiguous_format).float()
|
1950 |
+
encoder_posterior = self.encode_first_stage(x_low)
|
1951 |
+
zx = self.get_first_stage_encoding(encoder_posterior).detach()
|
1952 |
+
cats.append(zx)
|
1953 |
+
|
1954 |
+
all_conds = {"c_concat": [torch.cat(cats, dim=1)], "c_crossattn": [c]}
|
1955 |
+
|
1956 |
+
if log_mode:
|
1957 |
+
# TODO: maybe disable if too expensive
|
1958 |
+
interpretability = False
|
1959 |
+
if interpretability:
|
1960 |
+
zx = zx[:, :, ::2, ::2]
|
1961 |
+
return z, all_conds, x, xrec, xc, x_low
|
1962 |
+
return z, all_conds
|
1963 |
+
|
1964 |
+
@torch.no_grad()
|
1965 |
+
def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
|
1966 |
+
plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=True,
|
1967 |
+
unconditional_guidance_scale=1., unconditional_guidance_label=None, use_ema_scope=True,
|
1968 |
+
**kwargs):
|
1969 |
+
ema_scope = self.ema_scope if use_ema_scope else nullcontext
|
1970 |
+
use_ddim = ddim_steps is not None
|
1971 |
+
|
1972 |
+
log = dict()
|
1973 |
+
z, c, x, xrec, xc, x_low = self.get_input(batch, self.first_stage_key, bs=N, log_mode=True)
|
1974 |
+
N = min(x.shape[0], N)
|
1975 |
+
n_row = min(x.shape[0], n_row)
|
1976 |
+
log["inputs"] = x
|
1977 |
+
log["reconstruction"] = xrec
|
1978 |
+
log["x_lr"] = x_low
|
1979 |
+
|
1980 |
+
if self.model.conditioning_key is not None:
|
1981 |
+
if hasattr(self.cond_stage_model, "decode"):
|
1982 |
+
xc = self.cond_stage_model.decode(c)
|
1983 |
+
log["conditioning"] = xc
|
1984 |
+
elif self.cond_stage_key in ["caption", "txt"]:
|
1985 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2]//25)
|
1986 |
+
log["conditioning"] = xc
|
1987 |
+
elif self.cond_stage_key == 'class_label':
|
1988 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2]//25)
|
1989 |
+
log['conditioning'] = xc
|
1990 |
+
elif isimage(xc):
|
1991 |
+
log["conditioning"] = xc
|
1992 |
+
if ismap(xc):
|
1993 |
+
log["original_conditioning"] = self.to_rgb(xc)
|
1994 |
+
|
1995 |
+
if sample:
|
1996 |
+
# get denoise row
|
1997 |
+
with ema_scope("Sampling"):
|
1998 |
+
samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
1999 |
+
ddim_steps=ddim_steps, eta=ddim_eta)
|
2000 |
+
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
|
2001 |
+
x_samples = self.decode_first_stage(samples)
|
2002 |
+
log["samples"] = x_samples
|
2003 |
+
|
2004 |
+
if unconditional_guidance_scale > 1.0:
|
2005 |
+
uc_tmp = self.get_unconditional_conditioning(N, unconditional_guidance_label)
|
2006 |
+
uc = dict()
|
2007 |
+
for k in c:
|
2008 |
+
if k == "c_crossattn":
|
2009 |
+
assert isinstance(c[k], list) and len(c[k]) == 1
|
2010 |
+
uc[k] = [uc_tmp]
|
2011 |
+
elif isinstance(c[k], list):
|
2012 |
+
uc[k] = [c[k][i] for i in range(len(c[k]))]
|
2013 |
+
else:
|
2014 |
+
uc[k] = c[k]
|
2015 |
+
|
2016 |
+
with ema_scope("Sampling with classifier-free guidance"):
|
2017 |
+
samples_cfg, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
2018 |
+
ddim_steps=ddim_steps, eta=ddim_eta,
|
2019 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
2020 |
+
unconditional_conditioning=uc,
|
2021 |
+
)
|
2022 |
+
x_samples_cfg = self.decode_first_stage(samples_cfg)
|
2023 |
+
log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
|
2024 |
+
return log
|
models/ldm/models/diffusion/plms.py
ADDED
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""SAMPLING ONLY."""
|
2 |
+
|
3 |
+
import torch
|
4 |
+
import numpy as np
|
5 |
+
from tqdm import tqdm
|
6 |
+
from functools import partial
|
7 |
+
|
8 |
+
from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like
|
9 |
+
from ldm.models.diffusion.sampling_util import norm_thresholding
|
10 |
+
|
11 |
+
|
12 |
+
class PLMSSampler(object):
|
13 |
+
def __init__(self, model, schedule="linear", **kwargs):
|
14 |
+
super().__init__()
|
15 |
+
self.model = model
|
16 |
+
self.ddpm_num_timesteps = model.num_timesteps
|
17 |
+
self.schedule = schedule
|
18 |
+
|
19 |
+
def register_buffer(self, name, attr):
|
20 |
+
if type(attr) == torch.Tensor:
|
21 |
+
if attr.device != torch.device("cuda"):
|
22 |
+
attr = attr.to(torch.device("cuda"))
|
23 |
+
setattr(self, name, attr)
|
24 |
+
|
25 |
+
def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
|
26 |
+
if ddim_eta != 0:
|
27 |
+
raise ValueError('ddim_eta must be 0 for PLMS')
|
28 |
+
self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
|
29 |
+
num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
|
30 |
+
alphas_cumprod = self.model.alphas_cumprod
|
31 |
+
assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
|
32 |
+
to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
|
33 |
+
|
34 |
+
self.register_buffer('betas', to_torch(self.model.betas))
|
35 |
+
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
|
36 |
+
self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
|
37 |
+
|
38 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
39 |
+
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
|
40 |
+
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
|
41 |
+
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
|
42 |
+
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
|
43 |
+
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
|
44 |
+
|
45 |
+
# ddim sampling parameters
|
46 |
+
ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
|
47 |
+
ddim_timesteps=self.ddim_timesteps,
|
48 |
+
eta=ddim_eta,verbose=verbose)
|
49 |
+
self.register_buffer('ddim_sigmas', ddim_sigmas)
|
50 |
+
self.register_buffer('ddim_alphas', ddim_alphas)
|
51 |
+
self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
|
52 |
+
self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
|
53 |
+
sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
|
54 |
+
(1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
|
55 |
+
1 - self.alphas_cumprod / self.alphas_cumprod_prev))
|
56 |
+
self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
|
57 |
+
|
58 |
+
@torch.no_grad()
|
59 |
+
def sample(self,
|
60 |
+
S,
|
61 |
+
batch_size,
|
62 |
+
shape,
|
63 |
+
conditioning=None,
|
64 |
+
callback=None,
|
65 |
+
normals_sequence=None,
|
66 |
+
img_callback=None,
|
67 |
+
quantize_x0=False,
|
68 |
+
eta=0.,
|
69 |
+
mask=None,
|
70 |
+
x0=None,
|
71 |
+
temperature=1.,
|
72 |
+
noise_dropout=0.,
|
73 |
+
score_corrector=None,
|
74 |
+
corrector_kwargs=None,
|
75 |
+
verbose=True,
|
76 |
+
x_T=None,
|
77 |
+
log_every_t=100,
|
78 |
+
unconditional_guidance_scale=1.,
|
79 |
+
unconditional_conditioning=None,
|
80 |
+
# this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
|
81 |
+
dynamic_threshold=None,
|
82 |
+
**kwargs
|
83 |
+
):
|
84 |
+
if conditioning is not None:
|
85 |
+
if isinstance(conditioning, dict):
|
86 |
+
ctmp = conditioning[list(conditioning.keys())[0]]
|
87 |
+
while isinstance(ctmp, list): ctmp = ctmp[0]
|
88 |
+
cbs = ctmp.shape[0]
|
89 |
+
if cbs != batch_size:
|
90 |
+
print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
|
91 |
+
else:
|
92 |
+
if conditioning.shape[0] != batch_size:
|
93 |
+
print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
|
94 |
+
|
95 |
+
self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
|
96 |
+
# sampling
|
97 |
+
C, H, W = shape
|
98 |
+
size = (batch_size, C, H, W)
|
99 |
+
print(f'Data shape for PLMS sampling is {size}')
|
100 |
+
|
101 |
+
samples, intermediates = self.plms_sampling(conditioning, size,
|
102 |
+
callback=callback,
|
103 |
+
img_callback=img_callback,
|
104 |
+
quantize_denoised=quantize_x0,
|
105 |
+
mask=mask, x0=x0,
|
106 |
+
ddim_use_original_steps=False,
|
107 |
+
noise_dropout=noise_dropout,
|
108 |
+
temperature=temperature,
|
109 |
+
score_corrector=score_corrector,
|
110 |
+
corrector_kwargs=corrector_kwargs,
|
111 |
+
x_T=x_T,
|
112 |
+
log_every_t=log_every_t,
|
113 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
114 |
+
unconditional_conditioning=unconditional_conditioning,
|
115 |
+
dynamic_threshold=dynamic_threshold,
|
116 |
+
)
|
117 |
+
return samples, intermediates
|
118 |
+
|
119 |
+
@torch.no_grad()
|
120 |
+
def plms_sampling(self, cond, shape,
|
121 |
+
x_T=None, ddim_use_original_steps=False,
|
122 |
+
callback=None, timesteps=None, quantize_denoised=False,
|
123 |
+
mask=None, x0=None, img_callback=None, log_every_t=100,
|
124 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
|
125 |
+
unconditional_guidance_scale=1., unconditional_conditioning=None,
|
126 |
+
dynamic_threshold=None):
|
127 |
+
device = self.model.betas.device
|
128 |
+
b = shape[0]
|
129 |
+
if x_T is None:
|
130 |
+
img = torch.randn(shape, device=device)
|
131 |
+
else:
|
132 |
+
img = x_T
|
133 |
+
|
134 |
+
if timesteps is None:
|
135 |
+
timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
|
136 |
+
elif timesteps is not None and not ddim_use_original_steps:
|
137 |
+
subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
|
138 |
+
timesteps = self.ddim_timesteps[:subset_end]
|
139 |
+
|
140 |
+
intermediates = {'x_inter': [img], 'pred_x0': [img]}
|
141 |
+
time_range = list(reversed(range(0,timesteps))) if ddim_use_original_steps else np.flip(timesteps)
|
142 |
+
total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
|
143 |
+
print(f"Running PLMS Sampling with {total_steps} timesteps")
|
144 |
+
|
145 |
+
iterator = tqdm(time_range, desc='PLMS Sampler', total=total_steps)
|
146 |
+
old_eps = []
|
147 |
+
|
148 |
+
for i, step in enumerate(iterator):
|
149 |
+
index = total_steps - i - 1
|
150 |
+
ts = torch.full((b,), step, device=device, dtype=torch.long)
|
151 |
+
ts_next = torch.full((b,), time_range[min(i + 1, len(time_range) - 1)], device=device, dtype=torch.long)
|
152 |
+
|
153 |
+
if mask is not None:
|
154 |
+
assert x0 is not None
|
155 |
+
img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
|
156 |
+
img = img_orig * mask + (1. - mask) * img
|
157 |
+
|
158 |
+
outs = self.p_sample_plms(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
|
159 |
+
quantize_denoised=quantize_denoised, temperature=temperature,
|
160 |
+
noise_dropout=noise_dropout, score_corrector=score_corrector,
|
161 |
+
corrector_kwargs=corrector_kwargs,
|
162 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
163 |
+
unconditional_conditioning=unconditional_conditioning,
|
164 |
+
old_eps=old_eps, t_next=ts_next,
|
165 |
+
dynamic_threshold=dynamic_threshold)
|
166 |
+
img, pred_x0, e_t = outs
|
167 |
+
old_eps.append(e_t)
|
168 |
+
if len(old_eps) >= 4:
|
169 |
+
old_eps.pop(0)
|
170 |
+
if callback: callback(i)
|
171 |
+
if img_callback: img_callback(pred_x0, i)
|
172 |
+
|
173 |
+
if index % log_every_t == 0 or index == total_steps - 1:
|
174 |
+
intermediates['x_inter'].append(img)
|
175 |
+
intermediates['pred_x0'].append(pred_x0)
|
176 |
+
|
177 |
+
return img, intermediates
|
178 |
+
|
179 |
+
@torch.no_grad()
|
180 |
+
def p_sample_plms(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
|
181 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
|
182 |
+
unconditional_guidance_scale=1., unconditional_conditioning=None, old_eps=None, t_next=None,
|
183 |
+
dynamic_threshold=None):
|
184 |
+
b, *_, device = *x.shape, x.device
|
185 |
+
|
186 |
+
def get_model_output(x, t):
|
187 |
+
if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
|
188 |
+
e_t = self.model.apply_model(x, t, c)
|
189 |
+
else:
|
190 |
+
x_in = torch.cat([x] * 2)
|
191 |
+
t_in = torch.cat([t] * 2)
|
192 |
+
if isinstance(c, dict):
|
193 |
+
assert isinstance(unconditional_conditioning, dict)
|
194 |
+
c_in = dict()
|
195 |
+
for k in c:
|
196 |
+
if isinstance(c[k], list):
|
197 |
+
c_in[k] = [torch.cat([
|
198 |
+
unconditional_conditioning[k][i],
|
199 |
+
c[k][i]]) for i in range(len(c[k]))]
|
200 |
+
else:
|
201 |
+
c_in[k] = torch.cat([
|
202 |
+
unconditional_conditioning[k],
|
203 |
+
c[k]])
|
204 |
+
else:
|
205 |
+
c_in = torch.cat([unconditional_conditioning, c])
|
206 |
+
e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)
|
207 |
+
e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)
|
208 |
+
|
209 |
+
if score_corrector is not None:
|
210 |
+
assert self.model.parameterization == "eps"
|
211 |
+
e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
|
212 |
+
|
213 |
+
return e_t
|
214 |
+
|
215 |
+
alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
|
216 |
+
alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
|
217 |
+
sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
|
218 |
+
sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
|
219 |
+
|
220 |
+
def get_x_prev_and_pred_x0(e_t, index):
|
221 |
+
# select parameters corresponding to the currently considered timestep
|
222 |
+
a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
|
223 |
+
a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
|
224 |
+
sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
|
225 |
+
sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
|
226 |
+
|
227 |
+
# current prediction for x_0
|
228 |
+
pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
|
229 |
+
if quantize_denoised:
|
230 |
+
pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
|
231 |
+
if dynamic_threshold is not None:
|
232 |
+
pred_x0 = norm_thresholding(pred_x0, dynamic_threshold)
|
233 |
+
# direction pointing to x_t
|
234 |
+
dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
|
235 |
+
noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
|
236 |
+
if noise_dropout > 0.:
|
237 |
+
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
|
238 |
+
x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
|
239 |
+
return x_prev, pred_x0
|
240 |
+
|
241 |
+
e_t = get_model_output(x, t)
|
242 |
+
if len(old_eps) == 0:
|
243 |
+
# Pseudo Improved Euler (2nd order)
|
244 |
+
x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t, index)
|
245 |
+
e_t_next = get_model_output(x_prev, t_next)
|
246 |
+
e_t_prime = (e_t + e_t_next) / 2
|
247 |
+
elif len(old_eps) == 1:
|
248 |
+
# 2nd order Pseudo Linear Multistep (Adams-Bashforth)
|
249 |
+
e_t_prime = (3 * e_t - old_eps[-1]) / 2
|
250 |
+
elif len(old_eps) == 2:
|
251 |
+
# 3nd order Pseudo Linear Multistep (Adams-Bashforth)
|
252 |
+
e_t_prime = (23 * e_t - 16 * old_eps[-1] + 5 * old_eps[-2]) / 12
|
253 |
+
elif len(old_eps) >= 3:
|
254 |
+
# 4nd order Pseudo Linear Multistep (Adams-Bashforth)
|
255 |
+
e_t_prime = (55 * e_t - 59 * old_eps[-1] + 37 * old_eps[-2] - 9 * old_eps[-3]) / 24
|
256 |
+
|
257 |
+
x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t_prime, index)
|
258 |
+
|
259 |
+
return x_prev, pred_x0, e_t
|
models/ldm/models/diffusion/sampling_util.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
|
5 |
+
def append_dims(x, target_dims):
|
6 |
+
"""Appends dimensions to the end of a tensor until it has target_dims dimensions.
|
7 |
+
From https://github.com/crowsonkb/k-diffusion/blob/master/k_diffusion/utils.py"""
|
8 |
+
dims_to_append = target_dims - x.ndim
|
9 |
+
if dims_to_append < 0:
|
10 |
+
raise ValueError(f'input has {x.ndim} dims but target_dims is {target_dims}, which is less')
|
11 |
+
return x[(...,) + (None,) * dims_to_append]
|
12 |
+
|
13 |
+
|
14 |
+
def renorm_thresholding(x0, value):
|
15 |
+
# renorm
|
16 |
+
pred_max = x0.max()
|
17 |
+
pred_min = x0.min()
|
18 |
+
pred_x0 = (x0 - pred_min) / (pred_max - pred_min) # 0 ... 1
|
19 |
+
pred_x0 = 2 * pred_x0 - 1. # -1 ... 1
|
20 |
+
|
21 |
+
s = torch.quantile(
|
22 |
+
rearrange(pred_x0, 'b ... -> b (...)').abs(),
|
23 |
+
value,
|
24 |
+
dim=-1
|
25 |
+
)
|
26 |
+
s.clamp_(min=1.0)
|
27 |
+
s = s.view(-1, *((1,) * (pred_x0.ndim - 1)))
|
28 |
+
|
29 |
+
# clip by threshold
|
30 |
+
# pred_x0 = pred_x0.clamp(-s, s) / s # needs newer pytorch # TODO bring back to pure-gpu with min/max
|
31 |
+
|
32 |
+
# temporary hack: numpy on cpu
|
33 |
+
pred_x0 = np.clip(pred_x0.cpu().numpy(), -s.cpu().numpy(), s.cpu().numpy()) / s.cpu().numpy()
|
34 |
+
pred_x0 = torch.tensor(pred_x0).to(self.model.device)
|
35 |
+
|
36 |
+
# re.renorm
|
37 |
+
pred_x0 = (pred_x0 + 1.) / 2. # 0 ... 1
|
38 |
+
pred_x0 = (pred_max - pred_min) * pred_x0 + pred_min # orig range
|
39 |
+
return pred_x0
|
40 |
+
|
41 |
+
|
42 |
+
def norm_thresholding(x0, value):
|
43 |
+
s = append_dims(x0.pow(2).flatten(1).mean(1).sqrt().clamp(min=value), x0.ndim)
|
44 |
+
return x0 * (value / s)
|
45 |
+
|
46 |
+
|
47 |
+
def spatial_norm_thresholding(x0, value):
|
48 |
+
# b c h w
|
49 |
+
s = x0.pow(2).mean(1, keepdim=True).sqrt().clamp(min=value)
|
50 |
+
return x0 * (value / s)
|
models/ldm/modules/attention.py
ADDED
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from inspect import isfunction
|
2 |
+
import math
|
3 |
+
import torch
|
4 |
+
import torch.nn.functional as F
|
5 |
+
from torch import nn, einsum
|
6 |
+
from einops import rearrange, repeat
|
7 |
+
|
8 |
+
from ldm.modules.diffusionmodules.util import checkpoint
|
9 |
+
|
10 |
+
|
11 |
+
def exists(val):
|
12 |
+
return val is not None
|
13 |
+
|
14 |
+
|
15 |
+
def uniq(arr):
|
16 |
+
return{el: True for el in arr}.keys()
|
17 |
+
|
18 |
+
|
19 |
+
def default(val, d):
|
20 |
+
if exists(val):
|
21 |
+
return val
|
22 |
+
return d() if isfunction(d) else d
|
23 |
+
|
24 |
+
|
25 |
+
def max_neg_value(t):
|
26 |
+
return -torch.finfo(t.dtype).max
|
27 |
+
|
28 |
+
|
29 |
+
def init_(tensor):
|
30 |
+
dim = tensor.shape[-1]
|
31 |
+
std = 1 / math.sqrt(dim)
|
32 |
+
tensor.uniform_(-std, std)
|
33 |
+
return tensor
|
34 |
+
|
35 |
+
|
36 |
+
# feedforward
|
37 |
+
class GEGLU(nn.Module):
|
38 |
+
def __init__(self, dim_in, dim_out):
|
39 |
+
super().__init__()
|
40 |
+
self.proj = nn.Linear(dim_in, dim_out * 2)
|
41 |
+
|
42 |
+
def forward(self, x):
|
43 |
+
x, gate = self.proj(x).chunk(2, dim=-1)
|
44 |
+
return x * F.gelu(gate)
|
45 |
+
|
46 |
+
|
47 |
+
class FeedForward(nn.Module):
|
48 |
+
def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
|
49 |
+
super().__init__()
|
50 |
+
inner_dim = int(dim * mult)
|
51 |
+
dim_out = default(dim_out, dim)
|
52 |
+
project_in = nn.Sequential(
|
53 |
+
nn.Linear(dim, inner_dim),
|
54 |
+
nn.GELU()
|
55 |
+
) if not glu else GEGLU(dim, inner_dim)
|
56 |
+
|
57 |
+
self.net = nn.Sequential(
|
58 |
+
project_in,
|
59 |
+
nn.Dropout(dropout),
|
60 |
+
nn.Linear(inner_dim, dim_out)
|
61 |
+
)
|
62 |
+
|
63 |
+
def forward(self, x):
|
64 |
+
return self.net(x)
|
65 |
+
|
66 |
+
|
67 |
+
def zero_module(module):
|
68 |
+
"""
|
69 |
+
Zero out the parameters of a module and return it.
|
70 |
+
"""
|
71 |
+
for p in module.parameters():
|
72 |
+
p.detach().zero_()
|
73 |
+
return module
|
74 |
+
|
75 |
+
|
76 |
+
def Normalize(in_channels):
|
77 |
+
return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
|
78 |
+
|
79 |
+
|
80 |
+
class LinearAttention(nn.Module):
|
81 |
+
def __init__(self, dim, heads=4, dim_head=32):
|
82 |
+
super().__init__()
|
83 |
+
self.heads = heads
|
84 |
+
hidden_dim = dim_head * heads
|
85 |
+
self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias = False)
|
86 |
+
self.to_out = nn.Conv2d(hidden_dim, dim, 1)
|
87 |
+
|
88 |
+
def forward(self, x):
|
89 |
+
b, c, h, w = x.shape
|
90 |
+
qkv = self.to_qkv(x)
|
91 |
+
q, k, v = rearrange(qkv, 'b (qkv heads c) h w -> qkv b heads c (h w)', heads = self.heads, qkv=3)
|
92 |
+
k = k.softmax(dim=-1)
|
93 |
+
context = torch.einsum('bhdn,bhen->bhde', k, v)
|
94 |
+
out = torch.einsum('bhde,bhdn->bhen', context, q)
|
95 |
+
out = rearrange(out, 'b heads c (h w) -> b (heads c) h w', heads=self.heads, h=h, w=w)
|
96 |
+
return self.to_out(out)
|
97 |
+
|
98 |
+
|
99 |
+
class SpatialSelfAttention(nn.Module):
|
100 |
+
def __init__(self, in_channels):
|
101 |
+
super().__init__()
|
102 |
+
self.in_channels = in_channels
|
103 |
+
|
104 |
+
self.norm = Normalize(in_channels)
|
105 |
+
self.q = torch.nn.Conv2d(in_channels,
|
106 |
+
in_channels,
|
107 |
+
kernel_size=1,
|
108 |
+
stride=1,
|
109 |
+
padding=0)
|
110 |
+
self.k = torch.nn.Conv2d(in_channels,
|
111 |
+
in_channels,
|
112 |
+
kernel_size=1,
|
113 |
+
stride=1,
|
114 |
+
padding=0)
|
115 |
+
self.v = torch.nn.Conv2d(in_channels,
|
116 |
+
in_channels,
|
117 |
+
kernel_size=1,
|
118 |
+
stride=1,
|
119 |
+
padding=0)
|
120 |
+
self.proj_out = torch.nn.Conv2d(in_channels,
|
121 |
+
in_channels,
|
122 |
+
kernel_size=1,
|
123 |
+
stride=1,
|
124 |
+
padding=0)
|
125 |
+
|
126 |
+
def forward(self, x):
|
127 |
+
h_ = x
|
128 |
+
h_ = self.norm(h_)
|
129 |
+
q = self.q(h_)
|
130 |
+
k = self.k(h_)
|
131 |
+
v = self.v(h_)
|
132 |
+
|
133 |
+
# compute attention
|
134 |
+
b,c,h,w = q.shape
|
135 |
+
q = rearrange(q, 'b c h w -> b (h w) c')
|
136 |
+
k = rearrange(k, 'b c h w -> b c (h w)')
|
137 |
+
w_ = torch.einsum('bij,bjk->bik', q, k)
|
138 |
+
|
139 |
+
w_ = w_ * (int(c)**(-0.5))
|
140 |
+
w_ = torch.nn.functional.softmax(w_, dim=2)
|
141 |
+
|
142 |
+
# attend to values
|
143 |
+
v = rearrange(v, 'b c h w -> b c (h w)')
|
144 |
+
w_ = rearrange(w_, 'b i j -> b j i')
|
145 |
+
h_ = torch.einsum('bij,bjk->bik', v, w_)
|
146 |
+
h_ = rearrange(h_, 'b c (h w) -> b c h w', h=h)
|
147 |
+
h_ = self.proj_out(h_)
|
148 |
+
|
149 |
+
return x+h_
|
150 |
+
|
151 |
+
|
152 |
+
class CrossAttention(nn.Module):
|
153 |
+
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.):
|
154 |
+
super().__init__()
|
155 |
+
inner_dim = dim_head * heads
|
156 |
+
context_dim = default(context_dim, query_dim)
|
157 |
+
|
158 |
+
self.scale = dim_head ** -0.5
|
159 |
+
self.heads = heads
|
160 |
+
|
161 |
+
self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
|
162 |
+
self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
|
163 |
+
self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
|
164 |
+
|
165 |
+
self.to_out = nn.Sequential(
|
166 |
+
nn.Linear(inner_dim, query_dim),
|
167 |
+
nn.Dropout(dropout)
|
168 |
+
)
|
169 |
+
|
170 |
+
def forward(self, x, context=None, mask=None):
|
171 |
+
h = self.heads
|
172 |
+
|
173 |
+
q = self.to_q(x)
|
174 |
+
context = default(context, x)
|
175 |
+
k = self.to_k(context)
|
176 |
+
v = self.to_v(context)
|
177 |
+
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
|
178 |
+
|
179 |
+
sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
|
180 |
+
|
181 |
+
if exists(mask):
|
182 |
+
mask = rearrange(mask, 'b ... -> b (...)')
|
183 |
+
max_neg_value = -torch.finfo(sim.dtype).max
|
184 |
+
mask = repeat(mask, 'b j -> (b h) () j', h=h)
|
185 |
+
sim.masked_fill_(~mask, max_neg_value)
|
186 |
+
|
187 |
+
# attention, what we cannot get enough of
|
188 |
+
attn = sim.softmax(dim=-1)
|
189 |
+
|
190 |
+
out = einsum('b i j, b j d -> b i d', attn, v)
|
191 |
+
out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
|
192 |
+
return self.to_out(out)
|
193 |
+
|
194 |
+
|
195 |
+
class BasicTransformerBlock(nn.Module):
|
196 |
+
def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True,
|
197 |
+
disable_self_attn=False, cross_domain_cfg=None):
|
198 |
+
super().__init__()
|
199 |
+
self.disable_self_attn = disable_self_attn
|
200 |
+
self.cross_domain_cfg = cross_domain_cfg
|
201 |
+
self.attn1 = CrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout,
|
202 |
+
context_dim=context_dim if self.disable_self_attn else None) # is a self-attention if not self.disable_self_attn
|
203 |
+
self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
|
204 |
+
self.attn2 = CrossAttention(query_dim=dim, context_dim=context_dim,
|
205 |
+
heads=n_heads, dim_head=d_head, dropout=dropout) # is self-attn if context is none
|
206 |
+
self.norm1 = nn.LayerNorm(dim)
|
207 |
+
self.norm2 = nn.LayerNorm(dim)
|
208 |
+
self.norm3 = nn.LayerNorm(dim)
|
209 |
+
self.checkpoint = checkpoint
|
210 |
+
|
211 |
+
def _parse_domain(self, k, v):
|
212 |
+
|
213 |
+
assert self.domain_attention_num_tasks == 2 # only support two tasks now
|
214 |
+
|
215 |
+
key_0, key_1 = torch.chunk(k, dim=0, chunks=self.domain_attention_num_tasks) # keys shape (b t) d c
|
216 |
+
value_0, value_1 = torch.chunk(v, dim=0, chunks=self.domain_attention_num_tasks)
|
217 |
+
key = torch.cat([key_0, key_1], dim=1) # (b t) 2d c
|
218 |
+
value = torch.cat([value_0, value_1], dim=1) # (b t) 2d c
|
219 |
+
key = torch.cat([key]*self.domain_attention_num_tasks, dim=0) # ( 2 b t) 2d c
|
220 |
+
value = torch.cat([value]*self.domain_attention_num_tasks, dim=0) # (2 b t) 2d c
|
221 |
+
return key, value
|
222 |
+
|
223 |
+
def forward(self, x, context=None):
|
224 |
+
return checkpoint(self._forward, (x, context), self.parameters(), self.checkpoint)
|
225 |
+
|
226 |
+
def _forward(self, x, context=None):
|
227 |
+
x = self.attn1(self.norm1(x), context=context if self.disable_self_attn else None) + x
|
228 |
+
x = self.attn2(self.norm2(x), context=context) + x
|
229 |
+
x = self.ff(self.norm3(x)) + x
|
230 |
+
return x
|
231 |
+
|
232 |
+
|
233 |
+
class SpatialTransformer(nn.Module):
|
234 |
+
"""
|
235 |
+
Transformer block for image-like data.
|
236 |
+
First, project the input (aka embedding)
|
237 |
+
and reshape to b, t, d.
|
238 |
+
Then apply standard transformer action.
|
239 |
+
Finally, reshape to image
|
240 |
+
"""
|
241 |
+
def __init__(self, in_channels, n_heads, d_head,
|
242 |
+
depth=1, dropout=0., context_dim=None,
|
243 |
+
disable_self_attn=False, cross_domain_cfg=None):
|
244 |
+
super().__init__()
|
245 |
+
self.in_channels = in_channels
|
246 |
+
inner_dim = n_heads * d_head
|
247 |
+
self.norm = Normalize(in_channels)
|
248 |
+
|
249 |
+
self.proj_in = nn.Conv2d(in_channels,
|
250 |
+
inner_dim,
|
251 |
+
kernel_size=1,
|
252 |
+
stride=1,
|
253 |
+
padding=0)
|
254 |
+
|
255 |
+
self.transformer_blocks = nn.ModuleList(
|
256 |
+
[BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim,
|
257 |
+
disable_self_attn=disable_self_attn, cross_domain_cfg=cross_domain_cfg,)
|
258 |
+
for d in range(depth)]
|
259 |
+
)
|
260 |
+
|
261 |
+
self.proj_out = zero_module(nn.Conv2d(inner_dim,
|
262 |
+
in_channels,
|
263 |
+
kernel_size=1,
|
264 |
+
stride=1,
|
265 |
+
padding=0))
|
266 |
+
|
267 |
+
def forward(self, x, context=None):
|
268 |
+
# note: if no context is given, cross-attention defaults to self-attention
|
269 |
+
b, c, h, w = x.shape
|
270 |
+
x_in = x
|
271 |
+
x = self.norm(x)
|
272 |
+
x = self.proj_in(x)
|
273 |
+
x = rearrange(x, 'b c h w -> b (h w) c').contiguous()
|
274 |
+
for block in self.transformer_blocks:
|
275 |
+
x = block(x, context=context)
|
276 |
+
x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()
|
277 |
+
x = self.proj_out(x)
|
278 |
+
return x + x_in
|
models/ldm/modules/diffusionmodules/__init__.py
ADDED
File without changes
|
models/ldm/modules/diffusionmodules/model.py
ADDED
@@ -0,0 +1,835 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# pytorch_diffusion + derived encoder decoder
|
2 |
+
import math
|
3 |
+
import torch
|
4 |
+
import torch.nn as nn
|
5 |
+
import numpy as np
|
6 |
+
from einops import rearrange
|
7 |
+
|
8 |
+
from ldm.util import instantiate_from_config
|
9 |
+
from ldm.modules.attention import LinearAttention
|
10 |
+
|
11 |
+
|
12 |
+
def get_timestep_embedding(timesteps, embedding_dim):
|
13 |
+
"""
|
14 |
+
This matches the implementation in Denoising Diffusion Probabilistic Models:
|
15 |
+
From Fairseq.
|
16 |
+
Build sinusoidal embeddings.
|
17 |
+
This matches the implementation in tensor2tensor, but differs slightly
|
18 |
+
from the description in Section 3.5 of "Attention Is All You Need".
|
19 |
+
"""
|
20 |
+
assert len(timesteps.shape) == 1
|
21 |
+
|
22 |
+
half_dim = embedding_dim // 2
|
23 |
+
emb = math.log(10000) / (half_dim - 1)
|
24 |
+
emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb)
|
25 |
+
emb = emb.to(device=timesteps.device)
|
26 |
+
emb = timesteps.float()[:, None] * emb[None, :]
|
27 |
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
28 |
+
if embedding_dim % 2 == 1: # zero pad
|
29 |
+
emb = torch.nn.functional.pad(emb, (0,1,0,0))
|
30 |
+
return emb
|
31 |
+
|
32 |
+
|
33 |
+
def nonlinearity(x):
|
34 |
+
# swish
|
35 |
+
return x*torch.sigmoid(x)
|
36 |
+
|
37 |
+
|
38 |
+
def Normalize(in_channels, num_groups=32):
|
39 |
+
return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True)
|
40 |
+
|
41 |
+
|
42 |
+
class Upsample(nn.Module):
|
43 |
+
def __init__(self, in_channels, with_conv):
|
44 |
+
super().__init__()
|
45 |
+
self.with_conv = with_conv
|
46 |
+
if self.with_conv:
|
47 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
48 |
+
in_channels,
|
49 |
+
kernel_size=3,
|
50 |
+
stride=1,
|
51 |
+
padding=1)
|
52 |
+
|
53 |
+
def forward(self, x):
|
54 |
+
x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
|
55 |
+
if self.with_conv:
|
56 |
+
x = self.conv(x)
|
57 |
+
return x
|
58 |
+
|
59 |
+
|
60 |
+
class Downsample(nn.Module):
|
61 |
+
def __init__(self, in_channels, with_conv):
|
62 |
+
super().__init__()
|
63 |
+
self.with_conv = with_conv
|
64 |
+
if self.with_conv:
|
65 |
+
# no asymmetric padding in torch conv, must do it ourselves
|
66 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
67 |
+
in_channels,
|
68 |
+
kernel_size=3,
|
69 |
+
stride=2,
|
70 |
+
padding=0)
|
71 |
+
|
72 |
+
def forward(self, x):
|
73 |
+
if self.with_conv:
|
74 |
+
pad = (0,1,0,1)
|
75 |
+
x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
|
76 |
+
x = self.conv(x)
|
77 |
+
else:
|
78 |
+
x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
|
79 |
+
return x
|
80 |
+
|
81 |
+
|
82 |
+
class ResnetBlock(nn.Module):
|
83 |
+
def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
|
84 |
+
dropout, temb_channels=512):
|
85 |
+
super().__init__()
|
86 |
+
self.in_channels = in_channels
|
87 |
+
out_channels = in_channels if out_channels is None else out_channels
|
88 |
+
self.out_channels = out_channels
|
89 |
+
self.use_conv_shortcut = conv_shortcut
|
90 |
+
|
91 |
+
self.norm1 = Normalize(in_channels)
|
92 |
+
self.conv1 = torch.nn.Conv2d(in_channels,
|
93 |
+
out_channels,
|
94 |
+
kernel_size=3,
|
95 |
+
stride=1,
|
96 |
+
padding=1)
|
97 |
+
if temb_channels > 0:
|
98 |
+
self.temb_proj = torch.nn.Linear(temb_channels,
|
99 |
+
out_channels)
|
100 |
+
self.norm2 = Normalize(out_channels)
|
101 |
+
self.dropout = torch.nn.Dropout(dropout)
|
102 |
+
self.conv2 = torch.nn.Conv2d(out_channels,
|
103 |
+
out_channels,
|
104 |
+
kernel_size=3,
|
105 |
+
stride=1,
|
106 |
+
padding=1)
|
107 |
+
if self.in_channels != self.out_channels:
|
108 |
+
if self.use_conv_shortcut:
|
109 |
+
self.conv_shortcut = torch.nn.Conv2d(in_channels,
|
110 |
+
out_channels,
|
111 |
+
kernel_size=3,
|
112 |
+
stride=1,
|
113 |
+
padding=1)
|
114 |
+
else:
|
115 |
+
self.nin_shortcut = torch.nn.Conv2d(in_channels,
|
116 |
+
out_channels,
|
117 |
+
kernel_size=1,
|
118 |
+
stride=1,
|
119 |
+
padding=0)
|
120 |
+
|
121 |
+
def forward(self, x, temb):
|
122 |
+
h = x
|
123 |
+
h = self.norm1(h)
|
124 |
+
h = nonlinearity(h)
|
125 |
+
h = self.conv1(h)
|
126 |
+
|
127 |
+
if temb is not None:
|
128 |
+
h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None]
|
129 |
+
|
130 |
+
h = self.norm2(h)
|
131 |
+
h = nonlinearity(h)
|
132 |
+
h = self.dropout(h)
|
133 |
+
h = self.conv2(h)
|
134 |
+
|
135 |
+
if self.in_channels != self.out_channels:
|
136 |
+
if self.use_conv_shortcut:
|
137 |
+
x = self.conv_shortcut(x)
|
138 |
+
else:
|
139 |
+
x = self.nin_shortcut(x)
|
140 |
+
|
141 |
+
return x+h
|
142 |
+
|
143 |
+
|
144 |
+
class LinAttnBlock(LinearAttention):
|
145 |
+
"""to match AttnBlock usage"""
|
146 |
+
def __init__(self, in_channels):
|
147 |
+
super().__init__(dim=in_channels, heads=1, dim_head=in_channels)
|
148 |
+
|
149 |
+
|
150 |
+
class AttnBlock(nn.Module):
|
151 |
+
def __init__(self, in_channels):
|
152 |
+
super().__init__()
|
153 |
+
self.in_channels = in_channels
|
154 |
+
|
155 |
+
self.norm = Normalize(in_channels)
|
156 |
+
self.q = torch.nn.Conv2d(in_channels,
|
157 |
+
in_channels,
|
158 |
+
kernel_size=1,
|
159 |
+
stride=1,
|
160 |
+
padding=0)
|
161 |
+
self.k = torch.nn.Conv2d(in_channels,
|
162 |
+
in_channels,
|
163 |
+
kernel_size=1,
|
164 |
+
stride=1,
|
165 |
+
padding=0)
|
166 |
+
self.v = torch.nn.Conv2d(in_channels,
|
167 |
+
in_channels,
|
168 |
+
kernel_size=1,
|
169 |
+
stride=1,
|
170 |
+
padding=0)
|
171 |
+
self.proj_out = torch.nn.Conv2d(in_channels,
|
172 |
+
in_channels,
|
173 |
+
kernel_size=1,
|
174 |
+
stride=1,
|
175 |
+
padding=0)
|
176 |
+
|
177 |
+
|
178 |
+
def forward(self, x):
|
179 |
+
h_ = x
|
180 |
+
h_ = self.norm(h_)
|
181 |
+
q = self.q(h_)
|
182 |
+
k = self.k(h_)
|
183 |
+
v = self.v(h_)
|
184 |
+
|
185 |
+
# compute attention
|
186 |
+
b,c,h,w = q.shape
|
187 |
+
q = q.reshape(b,c,h*w)
|
188 |
+
q = q.permute(0,2,1) # b,hw,c
|
189 |
+
k = k.reshape(b,c,h*w) # b,c,hw
|
190 |
+
w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
|
191 |
+
w_ = w_ * (int(c)**(-0.5))
|
192 |
+
w_ = torch.nn.functional.softmax(w_, dim=2)
|
193 |
+
|
194 |
+
# attend to values
|
195 |
+
v = v.reshape(b,c,h*w)
|
196 |
+
w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q)
|
197 |
+
h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j]
|
198 |
+
h_ = h_.reshape(b,c,h,w)
|
199 |
+
|
200 |
+
h_ = self.proj_out(h_)
|
201 |
+
|
202 |
+
return x+h_
|
203 |
+
|
204 |
+
|
205 |
+
def make_attn(in_channels, attn_type="vanilla"):
|
206 |
+
assert attn_type in ["vanilla", "linear", "none"], f'attn_type {attn_type} unknown'
|
207 |
+
print(f"making attention of type '{attn_type}' with {in_channels} in_channels")
|
208 |
+
if attn_type == "vanilla":
|
209 |
+
return AttnBlock(in_channels)
|
210 |
+
elif attn_type == "none":
|
211 |
+
return nn.Identity(in_channels)
|
212 |
+
else:
|
213 |
+
return LinAttnBlock(in_channels)
|
214 |
+
|
215 |
+
|
216 |
+
class Model(nn.Module):
|
217 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
218 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
219 |
+
resolution, use_timestep=True, use_linear_attn=False, attn_type="vanilla"):
|
220 |
+
super().__init__()
|
221 |
+
if use_linear_attn: attn_type = "linear"
|
222 |
+
self.ch = ch
|
223 |
+
self.temb_ch = self.ch*4
|
224 |
+
self.num_resolutions = len(ch_mult)
|
225 |
+
self.num_res_blocks = num_res_blocks
|
226 |
+
self.resolution = resolution
|
227 |
+
self.in_channels = in_channels
|
228 |
+
|
229 |
+
self.use_timestep = use_timestep
|
230 |
+
if self.use_timestep:
|
231 |
+
# timestep embedding
|
232 |
+
self.temb = nn.Module()
|
233 |
+
self.temb.dense = nn.ModuleList([
|
234 |
+
torch.nn.Linear(self.ch,
|
235 |
+
self.temb_ch),
|
236 |
+
torch.nn.Linear(self.temb_ch,
|
237 |
+
self.temb_ch),
|
238 |
+
])
|
239 |
+
|
240 |
+
# downsampling
|
241 |
+
self.conv_in = torch.nn.Conv2d(in_channels,
|
242 |
+
self.ch,
|
243 |
+
kernel_size=3,
|
244 |
+
stride=1,
|
245 |
+
padding=1)
|
246 |
+
|
247 |
+
curr_res = resolution
|
248 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
249 |
+
self.down = nn.ModuleList()
|
250 |
+
for i_level in range(self.num_resolutions):
|
251 |
+
block = nn.ModuleList()
|
252 |
+
attn = nn.ModuleList()
|
253 |
+
block_in = ch*in_ch_mult[i_level]
|
254 |
+
block_out = ch*ch_mult[i_level]
|
255 |
+
for i_block in range(self.num_res_blocks):
|
256 |
+
block.append(ResnetBlock(in_channels=block_in,
|
257 |
+
out_channels=block_out,
|
258 |
+
temb_channels=self.temb_ch,
|
259 |
+
dropout=dropout))
|
260 |
+
block_in = block_out
|
261 |
+
if curr_res in attn_resolutions:
|
262 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
263 |
+
down = nn.Module()
|
264 |
+
down.block = block
|
265 |
+
down.attn = attn
|
266 |
+
if i_level != self.num_resolutions-1:
|
267 |
+
down.downsample = Downsample(block_in, resamp_with_conv)
|
268 |
+
curr_res = curr_res // 2
|
269 |
+
self.down.append(down)
|
270 |
+
|
271 |
+
# middle
|
272 |
+
self.mid = nn.Module()
|
273 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
274 |
+
out_channels=block_in,
|
275 |
+
temb_channels=self.temb_ch,
|
276 |
+
dropout=dropout)
|
277 |
+
self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
|
278 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
279 |
+
out_channels=block_in,
|
280 |
+
temb_channels=self.temb_ch,
|
281 |
+
dropout=dropout)
|
282 |
+
|
283 |
+
# upsampling
|
284 |
+
self.up = nn.ModuleList()
|
285 |
+
for i_level in reversed(range(self.num_resolutions)):
|
286 |
+
block = nn.ModuleList()
|
287 |
+
attn = nn.ModuleList()
|
288 |
+
block_out = ch*ch_mult[i_level]
|
289 |
+
skip_in = ch*ch_mult[i_level]
|
290 |
+
for i_block in range(self.num_res_blocks+1):
|
291 |
+
if i_block == self.num_res_blocks:
|
292 |
+
skip_in = ch*in_ch_mult[i_level]
|
293 |
+
block.append(ResnetBlock(in_channels=block_in+skip_in,
|
294 |
+
out_channels=block_out,
|
295 |
+
temb_channels=self.temb_ch,
|
296 |
+
dropout=dropout))
|
297 |
+
block_in = block_out
|
298 |
+
if curr_res in attn_resolutions:
|
299 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
300 |
+
up = nn.Module()
|
301 |
+
up.block = block
|
302 |
+
up.attn = attn
|
303 |
+
if i_level != 0:
|
304 |
+
up.upsample = Upsample(block_in, resamp_with_conv)
|
305 |
+
curr_res = curr_res * 2
|
306 |
+
self.up.insert(0, up) # prepend to get consistent order
|
307 |
+
|
308 |
+
# end
|
309 |
+
self.norm_out = Normalize(block_in)
|
310 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
311 |
+
out_ch,
|
312 |
+
kernel_size=3,
|
313 |
+
stride=1,
|
314 |
+
padding=1)
|
315 |
+
|
316 |
+
def forward(self, x, t=None, context=None):
|
317 |
+
#assert x.shape[2] == x.shape[3] == self.resolution
|
318 |
+
if context is not None:
|
319 |
+
# assume aligned context, cat along channel axis
|
320 |
+
x = torch.cat((x, context), dim=1)
|
321 |
+
if self.use_timestep:
|
322 |
+
# timestep embedding
|
323 |
+
assert t is not None
|
324 |
+
temb = get_timestep_embedding(t, self.ch)
|
325 |
+
temb = self.temb.dense[0](temb)
|
326 |
+
temb = nonlinearity(temb)
|
327 |
+
temb = self.temb.dense[1](temb)
|
328 |
+
else:
|
329 |
+
temb = None
|
330 |
+
|
331 |
+
# downsampling
|
332 |
+
hs = [self.conv_in(x)]
|
333 |
+
for i_level in range(self.num_resolutions):
|
334 |
+
for i_block in range(self.num_res_blocks):
|
335 |
+
h = self.down[i_level].block[i_block](hs[-1], temb)
|
336 |
+
if len(self.down[i_level].attn) > 0:
|
337 |
+
h = self.down[i_level].attn[i_block](h)
|
338 |
+
hs.append(h)
|
339 |
+
if i_level != self.num_resolutions-1:
|
340 |
+
hs.append(self.down[i_level].downsample(hs[-1]))
|
341 |
+
|
342 |
+
# middle
|
343 |
+
h = hs[-1]
|
344 |
+
h = self.mid.block_1(h, temb)
|
345 |
+
h = self.mid.attn_1(h)
|
346 |
+
h = self.mid.block_2(h, temb)
|
347 |
+
|
348 |
+
# upsampling
|
349 |
+
for i_level in reversed(range(self.num_resolutions)):
|
350 |
+
for i_block in range(self.num_res_blocks+1):
|
351 |
+
h = self.up[i_level].block[i_block](
|
352 |
+
torch.cat([h, hs.pop()], dim=1), temb)
|
353 |
+
if len(self.up[i_level].attn) > 0:
|
354 |
+
h = self.up[i_level].attn[i_block](h)
|
355 |
+
if i_level != 0:
|
356 |
+
h = self.up[i_level].upsample(h)
|
357 |
+
|
358 |
+
# end
|
359 |
+
h = self.norm_out(h)
|
360 |
+
h = nonlinearity(h)
|
361 |
+
h = self.conv_out(h)
|
362 |
+
return h
|
363 |
+
|
364 |
+
def get_last_layer(self):
|
365 |
+
return self.conv_out.weight
|
366 |
+
|
367 |
+
|
368 |
+
class Encoder(nn.Module):
|
369 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
370 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
371 |
+
resolution, z_channels, double_z=True, use_linear_attn=False, attn_type="vanilla",
|
372 |
+
**ignore_kwargs):
|
373 |
+
super().__init__()
|
374 |
+
if use_linear_attn: attn_type = "linear"
|
375 |
+
self.ch = ch
|
376 |
+
self.temb_ch = 0
|
377 |
+
self.num_resolutions = len(ch_mult)
|
378 |
+
self.num_res_blocks = num_res_blocks
|
379 |
+
self.resolution = resolution
|
380 |
+
self.in_channels = in_channels
|
381 |
+
|
382 |
+
# downsampling
|
383 |
+
self.conv_in = torch.nn.Conv2d(in_channels,
|
384 |
+
self.ch,
|
385 |
+
kernel_size=3,
|
386 |
+
stride=1,
|
387 |
+
padding=1)
|
388 |
+
|
389 |
+
curr_res = resolution
|
390 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
391 |
+
self.in_ch_mult = in_ch_mult
|
392 |
+
self.down = nn.ModuleList()
|
393 |
+
for i_level in range(self.num_resolutions):
|
394 |
+
block = nn.ModuleList()
|
395 |
+
attn = nn.ModuleList()
|
396 |
+
block_in = ch*in_ch_mult[i_level]
|
397 |
+
block_out = ch*ch_mult[i_level]
|
398 |
+
for i_block in range(self.num_res_blocks):
|
399 |
+
block.append(ResnetBlock(in_channels=block_in,
|
400 |
+
out_channels=block_out,
|
401 |
+
temb_channels=self.temb_ch,
|
402 |
+
dropout=dropout))
|
403 |
+
block_in = block_out
|
404 |
+
if curr_res in attn_resolutions:
|
405 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
406 |
+
down = nn.Module()
|
407 |
+
down.block = block
|
408 |
+
down.attn = attn
|
409 |
+
if i_level != self.num_resolutions-1:
|
410 |
+
down.downsample = Downsample(block_in, resamp_with_conv)
|
411 |
+
curr_res = curr_res // 2
|
412 |
+
self.down.append(down)
|
413 |
+
|
414 |
+
# middle
|
415 |
+
self.mid = nn.Module()
|
416 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
417 |
+
out_channels=block_in,
|
418 |
+
temb_channels=self.temb_ch,
|
419 |
+
dropout=dropout)
|
420 |
+
self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
|
421 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
422 |
+
out_channels=block_in,
|
423 |
+
temb_channels=self.temb_ch,
|
424 |
+
dropout=dropout)
|
425 |
+
|
426 |
+
# end
|
427 |
+
self.norm_out = Normalize(block_in)
|
428 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
429 |
+
2*z_channels if double_z else z_channels,
|
430 |
+
kernel_size=3,
|
431 |
+
stride=1,
|
432 |
+
padding=1)
|
433 |
+
|
434 |
+
def forward(self, x):
|
435 |
+
# timestep embedding
|
436 |
+
temb = None
|
437 |
+
|
438 |
+
# downsampling
|
439 |
+
hs = [self.conv_in(x)]
|
440 |
+
for i_level in range(self.num_resolutions):
|
441 |
+
for i_block in range(self.num_res_blocks):
|
442 |
+
h = self.down[i_level].block[i_block](hs[-1], temb)
|
443 |
+
if len(self.down[i_level].attn) > 0:
|
444 |
+
h = self.down[i_level].attn[i_block](h)
|
445 |
+
hs.append(h)
|
446 |
+
if i_level != self.num_resolutions-1:
|
447 |
+
hs.append(self.down[i_level].downsample(hs[-1]))
|
448 |
+
|
449 |
+
# middle
|
450 |
+
h = hs[-1]
|
451 |
+
h = self.mid.block_1(h, temb)
|
452 |
+
h = self.mid.attn_1(h)
|
453 |
+
h = self.mid.block_2(h, temb)
|
454 |
+
|
455 |
+
# end
|
456 |
+
h = self.norm_out(h)
|
457 |
+
h = nonlinearity(h)
|
458 |
+
h = self.conv_out(h)
|
459 |
+
return h
|
460 |
+
|
461 |
+
|
462 |
+
class Decoder(nn.Module):
|
463 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
464 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
465 |
+
resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False,
|
466 |
+
attn_type="vanilla", **ignorekwargs):
|
467 |
+
super().__init__()
|
468 |
+
if use_linear_attn: attn_type = "linear"
|
469 |
+
self.ch = ch
|
470 |
+
self.temb_ch = 0
|
471 |
+
self.num_resolutions = len(ch_mult)
|
472 |
+
self.num_res_blocks = num_res_blocks
|
473 |
+
self.resolution = resolution
|
474 |
+
self.in_channels = in_channels
|
475 |
+
self.give_pre_end = give_pre_end
|
476 |
+
self.tanh_out = tanh_out
|
477 |
+
|
478 |
+
# compute in_ch_mult, block_in and curr_res at lowest res
|
479 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
480 |
+
block_in = ch*ch_mult[self.num_resolutions-1]
|
481 |
+
curr_res = resolution // 2**(self.num_resolutions-1)
|
482 |
+
self.z_shape = (1,z_channels,curr_res,curr_res)
|
483 |
+
print("Working with z of shape {} = {} dimensions.".format(
|
484 |
+
self.z_shape, np.prod(self.z_shape)))
|
485 |
+
|
486 |
+
# z to block_in
|
487 |
+
self.conv_in = torch.nn.Conv2d(z_channels,
|
488 |
+
block_in,
|
489 |
+
kernel_size=3,
|
490 |
+
stride=1,
|
491 |
+
padding=1)
|
492 |
+
|
493 |
+
# middle
|
494 |
+
self.mid = nn.Module()
|
495 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
496 |
+
out_channels=block_in,
|
497 |
+
temb_channels=self.temb_ch,
|
498 |
+
dropout=dropout)
|
499 |
+
self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
|
500 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
501 |
+
out_channels=block_in,
|
502 |
+
temb_channels=self.temb_ch,
|
503 |
+
dropout=dropout)
|
504 |
+
|
505 |
+
# upsampling
|
506 |
+
self.up = nn.ModuleList()
|
507 |
+
for i_level in reversed(range(self.num_resolutions)):
|
508 |
+
block = nn.ModuleList()
|
509 |
+
attn = nn.ModuleList()
|
510 |
+
block_out = ch*ch_mult[i_level]
|
511 |
+
for i_block in range(self.num_res_blocks+1):
|
512 |
+
block.append(ResnetBlock(in_channels=block_in,
|
513 |
+
out_channels=block_out,
|
514 |
+
temb_channels=self.temb_ch,
|
515 |
+
dropout=dropout))
|
516 |
+
block_in = block_out
|
517 |
+
if curr_res in attn_resolutions:
|
518 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
519 |
+
up = nn.Module()
|
520 |
+
up.block = block
|
521 |
+
up.attn = attn
|
522 |
+
if i_level != 0:
|
523 |
+
up.upsample = Upsample(block_in, resamp_with_conv)
|
524 |
+
curr_res = curr_res * 2
|
525 |
+
self.up.insert(0, up) # prepend to get consistent order
|
526 |
+
|
527 |
+
# end
|
528 |
+
self.norm_out = Normalize(block_in)
|
529 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
530 |
+
out_ch,
|
531 |
+
kernel_size=3,
|
532 |
+
stride=1,
|
533 |
+
padding=1)
|
534 |
+
|
535 |
+
def forward(self, z):
|
536 |
+
#assert z.shape[1:] == self.z_shape[1:]
|
537 |
+
self.last_z_shape = z.shape
|
538 |
+
|
539 |
+
# timestep embedding
|
540 |
+
temb = None
|
541 |
+
|
542 |
+
# z to block_in
|
543 |
+
h = self.conv_in(z)
|
544 |
+
|
545 |
+
# middle
|
546 |
+
h = self.mid.block_1(h, temb)
|
547 |
+
h = self.mid.attn_1(h)
|
548 |
+
h = self.mid.block_2(h, temb)
|
549 |
+
|
550 |
+
# upsampling
|
551 |
+
for i_level in reversed(range(self.num_resolutions)):
|
552 |
+
for i_block in range(self.num_res_blocks+1):
|
553 |
+
h = self.up[i_level].block[i_block](h, temb)
|
554 |
+
if len(self.up[i_level].attn) > 0:
|
555 |
+
h = self.up[i_level].attn[i_block](h)
|
556 |
+
if i_level != 0:
|
557 |
+
h = self.up[i_level].upsample(h)
|
558 |
+
|
559 |
+
# end
|
560 |
+
if self.give_pre_end:
|
561 |
+
return h
|
562 |
+
|
563 |
+
h = self.norm_out(h)
|
564 |
+
h = nonlinearity(h)
|
565 |
+
h = self.conv_out(h)
|
566 |
+
if self.tanh_out:
|
567 |
+
h = torch.tanh(h)
|
568 |
+
return h
|
569 |
+
|
570 |
+
|
571 |
+
class SimpleDecoder(nn.Module):
|
572 |
+
def __init__(self, in_channels, out_channels, *args, **kwargs):
|
573 |
+
super().__init__()
|
574 |
+
self.model = nn.ModuleList([nn.Conv2d(in_channels, in_channels, 1),
|
575 |
+
ResnetBlock(in_channels=in_channels,
|
576 |
+
out_channels=2 * in_channels,
|
577 |
+
temb_channels=0, dropout=0.0),
|
578 |
+
ResnetBlock(in_channels=2 * in_channels,
|
579 |
+
out_channels=4 * in_channels,
|
580 |
+
temb_channels=0, dropout=0.0),
|
581 |
+
ResnetBlock(in_channels=4 * in_channels,
|
582 |
+
out_channels=2 * in_channels,
|
583 |
+
temb_channels=0, dropout=0.0),
|
584 |
+
nn.Conv2d(2*in_channels, in_channels, 1),
|
585 |
+
Upsample(in_channels, with_conv=True)])
|
586 |
+
# end
|
587 |
+
self.norm_out = Normalize(in_channels)
|
588 |
+
self.conv_out = torch.nn.Conv2d(in_channels,
|
589 |
+
out_channels,
|
590 |
+
kernel_size=3,
|
591 |
+
stride=1,
|
592 |
+
padding=1)
|
593 |
+
|
594 |
+
def forward(self, x):
|
595 |
+
for i, layer in enumerate(self.model):
|
596 |
+
if i in [1,2,3]:
|
597 |
+
x = layer(x, None)
|
598 |
+
else:
|
599 |
+
x = layer(x)
|
600 |
+
|
601 |
+
h = self.norm_out(x)
|
602 |
+
h = nonlinearity(h)
|
603 |
+
x = self.conv_out(h)
|
604 |
+
return x
|
605 |
+
|
606 |
+
|
607 |
+
class UpsampleDecoder(nn.Module):
|
608 |
+
def __init__(self, in_channels, out_channels, ch, num_res_blocks, resolution,
|
609 |
+
ch_mult=(2,2), dropout=0.0):
|
610 |
+
super().__init__()
|
611 |
+
# upsampling
|
612 |
+
self.temb_ch = 0
|
613 |
+
self.num_resolutions = len(ch_mult)
|
614 |
+
self.num_res_blocks = num_res_blocks
|
615 |
+
block_in = in_channels
|
616 |
+
curr_res = resolution // 2 ** (self.num_resolutions - 1)
|
617 |
+
self.res_blocks = nn.ModuleList()
|
618 |
+
self.upsample_blocks = nn.ModuleList()
|
619 |
+
for i_level in range(self.num_resolutions):
|
620 |
+
res_block = []
|
621 |
+
block_out = ch * ch_mult[i_level]
|
622 |
+
for i_block in range(self.num_res_blocks + 1):
|
623 |
+
res_block.append(ResnetBlock(in_channels=block_in,
|
624 |
+
out_channels=block_out,
|
625 |
+
temb_channels=self.temb_ch,
|
626 |
+
dropout=dropout))
|
627 |
+
block_in = block_out
|
628 |
+
self.res_blocks.append(nn.ModuleList(res_block))
|
629 |
+
if i_level != self.num_resolutions - 1:
|
630 |
+
self.upsample_blocks.append(Upsample(block_in, True))
|
631 |
+
curr_res = curr_res * 2
|
632 |
+
|
633 |
+
# end
|
634 |
+
self.norm_out = Normalize(block_in)
|
635 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
636 |
+
out_channels,
|
637 |
+
kernel_size=3,
|
638 |
+
stride=1,
|
639 |
+
padding=1)
|
640 |
+
|
641 |
+
def forward(self, x):
|
642 |
+
# upsampling
|
643 |
+
h = x
|
644 |
+
for k, i_level in enumerate(range(self.num_resolutions)):
|
645 |
+
for i_block in range(self.num_res_blocks + 1):
|
646 |
+
h = self.res_blocks[i_level][i_block](h, None)
|
647 |
+
if i_level != self.num_resolutions - 1:
|
648 |
+
h = self.upsample_blocks[k](h)
|
649 |
+
h = self.norm_out(h)
|
650 |
+
h = nonlinearity(h)
|
651 |
+
h = self.conv_out(h)
|
652 |
+
return h
|
653 |
+
|
654 |
+
|
655 |
+
class LatentRescaler(nn.Module):
|
656 |
+
def __init__(self, factor, in_channels, mid_channels, out_channels, depth=2):
|
657 |
+
super().__init__()
|
658 |
+
# residual block, interpolate, residual block
|
659 |
+
self.factor = factor
|
660 |
+
self.conv_in = nn.Conv2d(in_channels,
|
661 |
+
mid_channels,
|
662 |
+
kernel_size=3,
|
663 |
+
stride=1,
|
664 |
+
padding=1)
|
665 |
+
self.res_block1 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
|
666 |
+
out_channels=mid_channels,
|
667 |
+
temb_channels=0,
|
668 |
+
dropout=0.0) for _ in range(depth)])
|
669 |
+
self.attn = AttnBlock(mid_channels)
|
670 |
+
self.res_block2 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
|
671 |
+
out_channels=mid_channels,
|
672 |
+
temb_channels=0,
|
673 |
+
dropout=0.0) for _ in range(depth)])
|
674 |
+
|
675 |
+
self.conv_out = nn.Conv2d(mid_channels,
|
676 |
+
out_channels,
|
677 |
+
kernel_size=1,
|
678 |
+
)
|
679 |
+
|
680 |
+
def forward(self, x):
|
681 |
+
x = self.conv_in(x)
|
682 |
+
for block in self.res_block1:
|
683 |
+
x = block(x, None)
|
684 |
+
x = torch.nn.functional.interpolate(x, size=(int(round(x.shape[2]*self.factor)), int(round(x.shape[3]*self.factor))))
|
685 |
+
x = self.attn(x)
|
686 |
+
for block in self.res_block2:
|
687 |
+
x = block(x, None)
|
688 |
+
x = self.conv_out(x)
|
689 |
+
return x
|
690 |
+
|
691 |
+
|
692 |
+
class MergedRescaleEncoder(nn.Module):
|
693 |
+
def __init__(self, in_channels, ch, resolution, out_ch, num_res_blocks,
|
694 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True,
|
695 |
+
ch_mult=(1,2,4,8), rescale_factor=1.0, rescale_module_depth=1):
|
696 |
+
super().__init__()
|
697 |
+
intermediate_chn = ch * ch_mult[-1]
|
698 |
+
self.encoder = Encoder(in_channels=in_channels, num_res_blocks=num_res_blocks, ch=ch, ch_mult=ch_mult,
|
699 |
+
z_channels=intermediate_chn, double_z=False, resolution=resolution,
|
700 |
+
attn_resolutions=attn_resolutions, dropout=dropout, resamp_with_conv=resamp_with_conv,
|
701 |
+
out_ch=None)
|
702 |
+
self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=intermediate_chn,
|
703 |
+
mid_channels=intermediate_chn, out_channels=out_ch, depth=rescale_module_depth)
|
704 |
+
|
705 |
+
def forward(self, x):
|
706 |
+
x = self.encoder(x)
|
707 |
+
x = self.rescaler(x)
|
708 |
+
return x
|
709 |
+
|
710 |
+
|
711 |
+
class MergedRescaleDecoder(nn.Module):
|
712 |
+
def __init__(self, z_channels, out_ch, resolution, num_res_blocks, attn_resolutions, ch, ch_mult=(1,2,4,8),
|
713 |
+
dropout=0.0, resamp_with_conv=True, rescale_factor=1.0, rescale_module_depth=1):
|
714 |
+
super().__init__()
|
715 |
+
tmp_chn = z_channels*ch_mult[-1]
|
716 |
+
self.decoder = Decoder(out_ch=out_ch, z_channels=tmp_chn, attn_resolutions=attn_resolutions, dropout=dropout,
|
717 |
+
resamp_with_conv=resamp_with_conv, in_channels=None, num_res_blocks=num_res_blocks,
|
718 |
+
ch_mult=ch_mult, resolution=resolution, ch=ch)
|
719 |
+
self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=z_channels, mid_channels=tmp_chn,
|
720 |
+
out_channels=tmp_chn, depth=rescale_module_depth)
|
721 |
+
|
722 |
+
def forward(self, x):
|
723 |
+
x = self.rescaler(x)
|
724 |
+
x = self.decoder(x)
|
725 |
+
return x
|
726 |
+
|
727 |
+
|
728 |
+
class Upsampler(nn.Module):
|
729 |
+
def __init__(self, in_size, out_size, in_channels, out_channels, ch_mult=2):
|
730 |
+
super().__init__()
|
731 |
+
assert out_size >= in_size
|
732 |
+
num_blocks = int(np.log2(out_size//in_size))+1
|
733 |
+
factor_up = 1.+ (out_size % in_size)
|
734 |
+
print(f"Building {self.__class__.__name__} with in_size: {in_size} --> out_size {out_size} and factor {factor_up}")
|
735 |
+
self.rescaler = LatentRescaler(factor=factor_up, in_channels=in_channels, mid_channels=2*in_channels,
|
736 |
+
out_channels=in_channels)
|
737 |
+
self.decoder = Decoder(out_ch=out_channels, resolution=out_size, z_channels=in_channels, num_res_blocks=2,
|
738 |
+
attn_resolutions=[], in_channels=None, ch=in_channels,
|
739 |
+
ch_mult=[ch_mult for _ in range(num_blocks)])
|
740 |
+
|
741 |
+
def forward(self, x):
|
742 |
+
x = self.rescaler(x)
|
743 |
+
x = self.decoder(x)
|
744 |
+
return x
|
745 |
+
|
746 |
+
|
747 |
+
class Resize(nn.Module):
|
748 |
+
def __init__(self, in_channels=None, learned=False, mode="bilinear"):
|
749 |
+
super().__init__()
|
750 |
+
self.with_conv = learned
|
751 |
+
self.mode = mode
|
752 |
+
if self.with_conv:
|
753 |
+
print(f"Note: {self.__class__.__name} uses learned downsampling and will ignore the fixed {mode} mode")
|
754 |
+
raise NotImplementedError()
|
755 |
+
assert in_channels is not None
|
756 |
+
# no asymmetric padding in torch conv, must do it ourselves
|
757 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
758 |
+
in_channels,
|
759 |
+
kernel_size=4,
|
760 |
+
stride=2,
|
761 |
+
padding=1)
|
762 |
+
|
763 |
+
def forward(self, x, scale_factor=1.0):
|
764 |
+
if scale_factor==1.0:
|
765 |
+
return x
|
766 |
+
else:
|
767 |
+
x = torch.nn.functional.interpolate(x, mode=self.mode, align_corners=False, scale_factor=scale_factor)
|
768 |
+
return x
|
769 |
+
|
770 |
+
class FirstStagePostProcessor(nn.Module):
|
771 |
+
|
772 |
+
def __init__(self, ch_mult:list, in_channels,
|
773 |
+
pretrained_model:nn.Module=None,
|
774 |
+
reshape=False,
|
775 |
+
n_channels=None,
|
776 |
+
dropout=0.,
|
777 |
+
pretrained_config=None):
|
778 |
+
super().__init__()
|
779 |
+
if pretrained_config is None:
|
780 |
+
assert pretrained_model is not None, 'Either "pretrained_model" or "pretrained_config" must not be None'
|
781 |
+
self.pretrained_model = pretrained_model
|
782 |
+
else:
|
783 |
+
assert pretrained_config is not None, 'Either "pretrained_model" or "pretrained_config" must not be None'
|
784 |
+
self.instantiate_pretrained(pretrained_config)
|
785 |
+
|
786 |
+
self.do_reshape = reshape
|
787 |
+
|
788 |
+
if n_channels is None:
|
789 |
+
n_channels = self.pretrained_model.encoder.ch
|
790 |
+
|
791 |
+
self.proj_norm = Normalize(in_channels,num_groups=in_channels//2)
|
792 |
+
self.proj = nn.Conv2d(in_channels,n_channels,kernel_size=3,
|
793 |
+
stride=1,padding=1)
|
794 |
+
|
795 |
+
blocks = []
|
796 |
+
downs = []
|
797 |
+
ch_in = n_channels
|
798 |
+
for m in ch_mult:
|
799 |
+
blocks.append(ResnetBlock(in_channels=ch_in,out_channels=m*n_channels,dropout=dropout))
|
800 |
+
ch_in = m * n_channels
|
801 |
+
downs.append(Downsample(ch_in, with_conv=False))
|
802 |
+
|
803 |
+
self.model = nn.ModuleList(blocks)
|
804 |
+
self.downsampler = nn.ModuleList(downs)
|
805 |
+
|
806 |
+
|
807 |
+
def instantiate_pretrained(self, config):
|
808 |
+
model = instantiate_from_config(config)
|
809 |
+
self.pretrained_model = model.eval()
|
810 |
+
# self.pretrained_model.train = False
|
811 |
+
for param in self.pretrained_model.parameters():
|
812 |
+
param.requires_grad = False
|
813 |
+
|
814 |
+
|
815 |
+
@torch.no_grad()
|
816 |
+
def encode_with_pretrained(self,x):
|
817 |
+
c = self.pretrained_model.encode(x)
|
818 |
+
if isinstance(c, DiagonalGaussianDistribution):
|
819 |
+
c = c.mode()
|
820 |
+
return c
|
821 |
+
|
822 |
+
def forward(self,x):
|
823 |
+
z_fs = self.encode_with_pretrained(x)
|
824 |
+
z = self.proj_norm(z_fs)
|
825 |
+
z = self.proj(z)
|
826 |
+
z = nonlinearity(z)
|
827 |
+
|
828 |
+
for submodel, downmodel in zip(self.model,self.downsampler):
|
829 |
+
z = submodel(z,temb=None)
|
830 |
+
z = downmodel(z)
|
831 |
+
|
832 |
+
if self.do_reshape:
|
833 |
+
z = rearrange(z,'b c h w -> b (h w) c')
|
834 |
+
return z
|
835 |
+
|
models/ldm/modules/diffusionmodules/openaimodel.py
ADDED
@@ -0,0 +1,998 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from abc import abstractmethod
|
2 |
+
from functools import partial
|
3 |
+
import math
|
4 |
+
from typing import Iterable
|
5 |
+
|
6 |
+
import numpy as np
|
7 |
+
import torch as th
|
8 |
+
import torch.nn as nn
|
9 |
+
import torch.nn.functional as F
|
10 |
+
|
11 |
+
from ldm.modules.diffusionmodules.util import (
|
12 |
+
checkpoint,
|
13 |
+
conv_nd,
|
14 |
+
linear,
|
15 |
+
avg_pool_nd,
|
16 |
+
zero_module,
|
17 |
+
normalization,
|
18 |
+
timestep_embedding,
|
19 |
+
)
|
20 |
+
from ldm.modules.attention import SpatialTransformer
|
21 |
+
from ldm.util import exists
|
22 |
+
|
23 |
+
|
24 |
+
# dummy replace
|
25 |
+
def convert_module_to_f16(x):
|
26 |
+
pass
|
27 |
+
|
28 |
+
def convert_module_to_f32(x):
|
29 |
+
pass
|
30 |
+
|
31 |
+
|
32 |
+
## go
|
33 |
+
class AttentionPool2d(nn.Module):
|
34 |
+
"""
|
35 |
+
Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
|
36 |
+
"""
|
37 |
+
|
38 |
+
def __init__(
|
39 |
+
self,
|
40 |
+
spacial_dim: int,
|
41 |
+
embed_dim: int,
|
42 |
+
num_heads_channels: int,
|
43 |
+
output_dim: int = None,
|
44 |
+
):
|
45 |
+
super().__init__()
|
46 |
+
self.positional_embedding = nn.Parameter(th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5)
|
47 |
+
self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
|
48 |
+
self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
|
49 |
+
self.num_heads = embed_dim // num_heads_channels
|
50 |
+
self.attention = QKVAttention(self.num_heads)
|
51 |
+
|
52 |
+
def forward(self, x):
|
53 |
+
b, c, *_spatial = x.shape
|
54 |
+
x = x.reshape(b, c, -1) # NC(HW)
|
55 |
+
x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
|
56 |
+
x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
|
57 |
+
x = self.qkv_proj(x)
|
58 |
+
x = self.attention(x)
|
59 |
+
x = self.c_proj(x)
|
60 |
+
return x[:, :, 0]
|
61 |
+
|
62 |
+
|
63 |
+
class TimestepBlock(nn.Module):
|
64 |
+
"""
|
65 |
+
Any module where forward() takes timestep embeddings as a second argument.
|
66 |
+
"""
|
67 |
+
|
68 |
+
@abstractmethod
|
69 |
+
def forward(self, x, emb):
|
70 |
+
"""
|
71 |
+
Apply the module to `x` given `emb` timestep embeddings.
|
72 |
+
"""
|
73 |
+
|
74 |
+
|
75 |
+
class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
|
76 |
+
"""
|
77 |
+
A sequential module that passes timestep embeddings to the children that
|
78 |
+
support it as an extra input.
|
79 |
+
"""
|
80 |
+
|
81 |
+
def forward(self, x, emb, context=None):
|
82 |
+
for layer in self:
|
83 |
+
if isinstance(layer, TimestepBlock):
|
84 |
+
x = layer(x, emb)
|
85 |
+
elif isinstance(layer, SpatialTransformer):
|
86 |
+
x = layer(x, context)
|
87 |
+
else:
|
88 |
+
x = layer(x)
|
89 |
+
return x
|
90 |
+
|
91 |
+
|
92 |
+
class Upsample(nn.Module):
|
93 |
+
"""
|
94 |
+
An upsampling layer with an optional convolution.
|
95 |
+
:param channels: channels in the inputs and outputs.
|
96 |
+
:param use_conv: a bool determining if a convolution is applied.
|
97 |
+
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
|
98 |
+
upsampling occurs in the inner-two dimensions.
|
99 |
+
"""
|
100 |
+
|
101 |
+
def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1):
|
102 |
+
super().__init__()
|
103 |
+
self.channels = channels
|
104 |
+
self.out_channels = out_channels or channels
|
105 |
+
self.use_conv = use_conv
|
106 |
+
self.dims = dims
|
107 |
+
if use_conv:
|
108 |
+
self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding)
|
109 |
+
|
110 |
+
def forward(self, x):
|
111 |
+
assert x.shape[1] == self.channels
|
112 |
+
if self.dims == 3:
|
113 |
+
x = F.interpolate(
|
114 |
+
x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
|
115 |
+
)
|
116 |
+
else:
|
117 |
+
x = F.interpolate(x, scale_factor=2, mode="nearest")
|
118 |
+
if self.use_conv:
|
119 |
+
x = self.conv(x)
|
120 |
+
return x
|
121 |
+
|
122 |
+
class TransposedUpsample(nn.Module):
|
123 |
+
'Learned 2x upsampling without padding'
|
124 |
+
def __init__(self, channels, out_channels=None, ks=5):
|
125 |
+
super().__init__()
|
126 |
+
self.channels = channels
|
127 |
+
self.out_channels = out_channels or channels
|
128 |
+
|
129 |
+
self.up = nn.ConvTranspose2d(self.channels,self.out_channels,kernel_size=ks,stride=2)
|
130 |
+
|
131 |
+
def forward(self,x):
|
132 |
+
return self.up(x)
|
133 |
+
|
134 |
+
|
135 |
+
class Downsample(nn.Module):
|
136 |
+
"""
|
137 |
+
A downsampling layer with an optional convolution.
|
138 |
+
:param channels: channels in the inputs and outputs.
|
139 |
+
:param use_conv: a bool determining if a convolution is applied.
|
140 |
+
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
|
141 |
+
downsampling occurs in the inner-two dimensions.
|
142 |
+
"""
|
143 |
+
|
144 |
+
def __init__(self, channels, use_conv, dims=2, out_channels=None,padding=1):
|
145 |
+
super().__init__()
|
146 |
+
self.channels = channels
|
147 |
+
self.out_channels = out_channels or channels
|
148 |
+
self.use_conv = use_conv
|
149 |
+
self.dims = dims
|
150 |
+
stride = 2 if dims != 3 else (1, 2, 2)
|
151 |
+
if use_conv:
|
152 |
+
self.op = conv_nd(
|
153 |
+
dims, self.channels, self.out_channels, 3, stride=stride, padding=padding
|
154 |
+
)
|
155 |
+
else:
|
156 |
+
assert self.channels == self.out_channels
|
157 |
+
self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
|
158 |
+
|
159 |
+
def forward(self, x):
|
160 |
+
assert x.shape[1] == self.channels
|
161 |
+
return self.op(x)
|
162 |
+
|
163 |
+
|
164 |
+
class ResBlock(TimestepBlock):
|
165 |
+
"""
|
166 |
+
A residual block that can optionally change the number of channels.
|
167 |
+
:param channels: the number of input channels.
|
168 |
+
:param emb_channels: the number of timestep embedding channels.
|
169 |
+
:param dropout: the rate of dropout.
|
170 |
+
:param out_channels: if specified, the number of out channels.
|
171 |
+
:param use_conv: if True and out_channels is specified, use a spatial
|
172 |
+
convolution instead of a smaller 1x1 convolution to change the
|
173 |
+
channels in the skip connection.
|
174 |
+
:param dims: determines if the signal is 1D, 2D, or 3D.
|
175 |
+
:param use_checkpoint: if True, use gradient checkpointing on this module.
|
176 |
+
:param up: if True, use this block for upsampling.
|
177 |
+
:param down: if True, use this block for downsampling.
|
178 |
+
"""
|
179 |
+
|
180 |
+
def __init__(
|
181 |
+
self,
|
182 |
+
channels,
|
183 |
+
emb_channels,
|
184 |
+
dropout,
|
185 |
+
out_channels=None,
|
186 |
+
use_conv=False,
|
187 |
+
use_scale_shift_norm=False,
|
188 |
+
dims=2,
|
189 |
+
use_checkpoint=False,
|
190 |
+
up=False,
|
191 |
+
down=False,
|
192 |
+
):
|
193 |
+
super().__init__()
|
194 |
+
self.channels = channels
|
195 |
+
self.emb_channels = emb_channels
|
196 |
+
self.dropout = dropout
|
197 |
+
self.out_channels = out_channels or channels
|
198 |
+
self.use_conv = use_conv
|
199 |
+
self.use_checkpoint = use_checkpoint
|
200 |
+
self.use_scale_shift_norm = use_scale_shift_norm
|
201 |
+
|
202 |
+
self.in_layers = nn.Sequential(
|
203 |
+
normalization(channels),
|
204 |
+
nn.SiLU(),
|
205 |
+
conv_nd(dims, channels, self.out_channels, 3, padding=1),
|
206 |
+
)
|
207 |
+
|
208 |
+
self.updown = up or down
|
209 |
+
|
210 |
+
if up:
|
211 |
+
self.h_upd = Upsample(channels, False, dims)
|
212 |
+
self.x_upd = Upsample(channels, False, dims)
|
213 |
+
elif down:
|
214 |
+
self.h_upd = Downsample(channels, False, dims)
|
215 |
+
self.x_upd = Downsample(channels, False, dims)
|
216 |
+
else:
|
217 |
+
self.h_upd = self.x_upd = nn.Identity()
|
218 |
+
|
219 |
+
self.emb_layers = nn.Sequential(
|
220 |
+
nn.SiLU(),
|
221 |
+
linear(
|
222 |
+
emb_channels,
|
223 |
+
2 * self.out_channels if use_scale_shift_norm else self.out_channels,
|
224 |
+
),
|
225 |
+
)
|
226 |
+
self.out_layers = nn.Sequential(
|
227 |
+
normalization(self.out_channels),
|
228 |
+
nn.SiLU(),
|
229 |
+
nn.Dropout(p=dropout),
|
230 |
+
zero_module(
|
231 |
+
conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)
|
232 |
+
),
|
233 |
+
)
|
234 |
+
|
235 |
+
if self.out_channels == channels:
|
236 |
+
self.skip_connection = nn.Identity()
|
237 |
+
elif use_conv:
|
238 |
+
self.skip_connection = conv_nd(
|
239 |
+
dims, channels, self.out_channels, 3, padding=1
|
240 |
+
)
|
241 |
+
else:
|
242 |
+
self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
|
243 |
+
|
244 |
+
def forward(self, x, emb):
|
245 |
+
"""
|
246 |
+
Apply the block to a Tensor, conditioned on a timestep embedding.
|
247 |
+
:param x: an [N x C x ...] Tensor of features.
|
248 |
+
:param emb: an [N x emb_channels] Tensor of timestep embeddings.
|
249 |
+
:return: an [N x C x ...] Tensor of outputs.
|
250 |
+
"""
|
251 |
+
return checkpoint(
|
252 |
+
self._forward, (x, emb), self.parameters(), self.use_checkpoint
|
253 |
+
)
|
254 |
+
|
255 |
+
|
256 |
+
def _forward(self, x, emb):
|
257 |
+
if self.updown:
|
258 |
+
in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
|
259 |
+
h = in_rest(x)
|
260 |
+
h = self.h_upd(h)
|
261 |
+
x = self.x_upd(x)
|
262 |
+
h = in_conv(h)
|
263 |
+
else:
|
264 |
+
h = self.in_layers(x)
|
265 |
+
emb_out = self.emb_layers(emb).type(h.dtype)
|
266 |
+
while len(emb_out.shape) < len(h.shape):
|
267 |
+
emb_out = emb_out[..., None]
|
268 |
+
if self.use_scale_shift_norm:
|
269 |
+
out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
|
270 |
+
scale, shift = th.chunk(emb_out, 2, dim=1)
|
271 |
+
h = out_norm(h) * (1 + scale) + shift
|
272 |
+
h = out_rest(h)
|
273 |
+
else:
|
274 |
+
h = h + emb_out
|
275 |
+
h = self.out_layers(h)
|
276 |
+
return self.skip_connection(x) + h
|
277 |
+
|
278 |
+
|
279 |
+
class AttentionBlock(nn.Module):
|
280 |
+
"""
|
281 |
+
An attention block that allows spatial positions to attend to each other.
|
282 |
+
Originally ported from here, but adapted to the N-d case.
|
283 |
+
https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
|
284 |
+
"""
|
285 |
+
|
286 |
+
def __init__(
|
287 |
+
self,
|
288 |
+
channels,
|
289 |
+
num_heads=1,
|
290 |
+
num_head_channels=-1,
|
291 |
+
use_checkpoint=False,
|
292 |
+
use_new_attention_order=False,
|
293 |
+
):
|
294 |
+
super().__init__()
|
295 |
+
self.channels = channels
|
296 |
+
if num_head_channels == -1:
|
297 |
+
self.num_heads = num_heads
|
298 |
+
else:
|
299 |
+
assert (
|
300 |
+
channels % num_head_channels == 0
|
301 |
+
), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"
|
302 |
+
self.num_heads = channels // num_head_channels
|
303 |
+
self.use_checkpoint = use_checkpoint
|
304 |
+
self.norm = normalization(channels)
|
305 |
+
self.qkv = conv_nd(1, channels, channels * 3, 1)
|
306 |
+
if use_new_attention_order:
|
307 |
+
# split qkv before split heads
|
308 |
+
self.attention = QKVAttention(self.num_heads)
|
309 |
+
else:
|
310 |
+
# split heads before split qkv
|
311 |
+
self.attention = QKVAttentionLegacy(self.num_heads)
|
312 |
+
|
313 |
+
self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
|
314 |
+
|
315 |
+
def forward(self, x):
|
316 |
+
return checkpoint(self._forward, (x,), self.parameters(), True) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!!
|
317 |
+
#return pt_checkpoint(self._forward, x) # pytorch
|
318 |
+
|
319 |
+
def _forward(self, x):
|
320 |
+
b, c, *spatial = x.shape
|
321 |
+
x = x.reshape(b, c, -1)
|
322 |
+
qkv = self.qkv(self.norm(x))
|
323 |
+
h = self.attention(qkv)
|
324 |
+
h = self.proj_out(h)
|
325 |
+
return (x + h).reshape(b, c, *spatial)
|
326 |
+
|
327 |
+
|
328 |
+
def count_flops_attn(model, _x, y):
|
329 |
+
"""
|
330 |
+
A counter for the `thop` package to count the operations in an
|
331 |
+
attention operation.
|
332 |
+
Meant to be used like:
|
333 |
+
macs, params = thop.profile(
|
334 |
+
model,
|
335 |
+
inputs=(inputs, timestamps),
|
336 |
+
custom_ops={QKVAttention: QKVAttention.count_flops},
|
337 |
+
)
|
338 |
+
"""
|
339 |
+
b, c, *spatial = y[0].shape
|
340 |
+
num_spatial = int(np.prod(spatial))
|
341 |
+
# We perform two matmuls with the same number of ops.
|
342 |
+
# The first computes the weight matrix, the second computes
|
343 |
+
# the combination of the value vectors.
|
344 |
+
matmul_ops = 2 * b * (num_spatial ** 2) * c
|
345 |
+
model.total_ops += th.DoubleTensor([matmul_ops])
|
346 |
+
|
347 |
+
|
348 |
+
class QKVAttentionLegacy(nn.Module):
|
349 |
+
"""
|
350 |
+
A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
|
351 |
+
"""
|
352 |
+
|
353 |
+
def __init__(self, n_heads):
|
354 |
+
super().__init__()
|
355 |
+
self.n_heads = n_heads
|
356 |
+
|
357 |
+
def forward(self, qkv):
|
358 |
+
"""
|
359 |
+
Apply QKV attention.
|
360 |
+
:param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.
|
361 |
+
:return: an [N x (H * C) x T] tensor after attention.
|
362 |
+
"""
|
363 |
+
bs, width, length = qkv.shape
|
364 |
+
assert width % (3 * self.n_heads) == 0
|
365 |
+
ch = width // (3 * self.n_heads)
|
366 |
+
q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
|
367 |
+
scale = 1 / math.sqrt(math.sqrt(ch))
|
368 |
+
weight = th.einsum(
|
369 |
+
"bct,bcs->bts", q * scale, k * scale
|
370 |
+
) # More stable with f16 than dividing afterwards
|
371 |
+
weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
|
372 |
+
a = th.einsum("bts,bcs->bct", weight, v)
|
373 |
+
return a.reshape(bs, -1, length)
|
374 |
+
|
375 |
+
@staticmethod
|
376 |
+
def count_flops(model, _x, y):
|
377 |
+
return count_flops_attn(model, _x, y)
|
378 |
+
|
379 |
+
|
380 |
+
class QKVAttention(nn.Module):
|
381 |
+
"""
|
382 |
+
A module which performs QKV attention and splits in a different order.
|
383 |
+
"""
|
384 |
+
|
385 |
+
def __init__(self, n_heads):
|
386 |
+
super().__init__()
|
387 |
+
self.n_heads = n_heads
|
388 |
+
|
389 |
+
def forward(self, qkv):
|
390 |
+
"""
|
391 |
+
Apply QKV attention.
|
392 |
+
:param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
|
393 |
+
:return: an [N x (H * C) x T] tensor after attention.
|
394 |
+
"""
|
395 |
+
bs, width, length = qkv.shape
|
396 |
+
assert width % (3 * self.n_heads) == 0
|
397 |
+
ch = width // (3 * self.n_heads)
|
398 |
+
q, k, v = qkv.chunk(3, dim=1)
|
399 |
+
scale = 1 / math.sqrt(math.sqrt(ch))
|
400 |
+
weight = th.einsum(
|
401 |
+
"bct,bcs->bts",
|
402 |
+
(q * scale).view(bs * self.n_heads, ch, length),
|
403 |
+
(k * scale).view(bs * self.n_heads, ch, length),
|
404 |
+
) # More stable with f16 than dividing afterwards
|
405 |
+
weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
|
406 |
+
a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
|
407 |
+
return a.reshape(bs, -1, length)
|
408 |
+
|
409 |
+
@staticmethod
|
410 |
+
def count_flops(model, _x, y):
|
411 |
+
return count_flops_attn(model, _x, y)
|
412 |
+
|
413 |
+
|
414 |
+
class UNetModel(nn.Module):
|
415 |
+
"""
|
416 |
+
The full UNet model with attention and timestep embedding.
|
417 |
+
:param in_channels: channels in the input Tensor.
|
418 |
+
:param model_channels: base channel count for the model.
|
419 |
+
:param out_channels: channels in the output Tensor.
|
420 |
+
:param num_res_blocks: number of residual blocks per downsample.
|
421 |
+
:param attention_resolutions: a collection of downsample rates at which
|
422 |
+
attention will take place. May be a set, list, or tuple.
|
423 |
+
For example, if this contains 4, then at 4x downsampling, attention
|
424 |
+
will be used.
|
425 |
+
:param dropout: the dropout probability.
|
426 |
+
:param channel_mult: channel multiplier for each level of the UNet.
|
427 |
+
:param conv_resample: if True, use learned convolutions for upsampling and
|
428 |
+
downsampling.
|
429 |
+
:param dims: determines if the signal is 1D, 2D, or 3D.
|
430 |
+
:param num_classes: if specified (as an int), then this model will be
|
431 |
+
class-conditional with `num_classes` classes.
|
432 |
+
:param use_checkpoint: use gradient checkpointing to reduce memory usage.
|
433 |
+
:param num_heads: the number of attention heads in each attention layer.
|
434 |
+
:param num_heads_channels: if specified, ignore num_heads and instead use
|
435 |
+
a fixed channel width per attention head.
|
436 |
+
:param num_heads_upsample: works with num_heads to set a different number
|
437 |
+
of heads for upsampling. Deprecated.
|
438 |
+
:param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
|
439 |
+
:param resblock_updown: use residual blocks for up/downsampling.
|
440 |
+
:param use_new_attention_order: use a different attention pattern for potentially
|
441 |
+
increased efficiency.
|
442 |
+
"""
|
443 |
+
|
444 |
+
def __init__(
|
445 |
+
self,
|
446 |
+
image_size,
|
447 |
+
in_channels,
|
448 |
+
model_channels,
|
449 |
+
out_channels,
|
450 |
+
num_res_blocks,
|
451 |
+
attention_resolutions,
|
452 |
+
dropout=0,
|
453 |
+
channel_mult=(1, 2, 4, 8),
|
454 |
+
conv_resample=True,
|
455 |
+
dims=2,
|
456 |
+
num_classes=None,
|
457 |
+
use_checkpoint=False,
|
458 |
+
use_fp16=False,
|
459 |
+
num_heads=-1,
|
460 |
+
num_head_channels=-1,
|
461 |
+
num_heads_upsample=-1,
|
462 |
+
use_scale_shift_norm=False,
|
463 |
+
resblock_updown=False,
|
464 |
+
use_new_attention_order=False,
|
465 |
+
use_spatial_transformer=False, # custom transformer support
|
466 |
+
transformer_depth=1, # custom transformer support
|
467 |
+
context_dim=None, # custom transformer support
|
468 |
+
n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
|
469 |
+
legacy=True,
|
470 |
+
disable_self_attentions=None,
|
471 |
+
num_attention_blocks=None,
|
472 |
+
cross_domain_cfg=None
|
473 |
+
):
|
474 |
+
super().__init__()
|
475 |
+
if use_spatial_transformer:
|
476 |
+
assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
|
477 |
+
|
478 |
+
if context_dim is not None:
|
479 |
+
assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
|
480 |
+
from omegaconf.listconfig import ListConfig
|
481 |
+
if type(context_dim) == ListConfig:
|
482 |
+
context_dim = list(context_dim)
|
483 |
+
|
484 |
+
if num_heads_upsample == -1:
|
485 |
+
num_heads_upsample = num_heads
|
486 |
+
|
487 |
+
if num_heads == -1:
|
488 |
+
assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
|
489 |
+
|
490 |
+
if num_head_channels == -1:
|
491 |
+
assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
|
492 |
+
|
493 |
+
self.image_size = image_size
|
494 |
+
self.in_channels = in_channels
|
495 |
+
self.model_channels = model_channels
|
496 |
+
self.out_channels = out_channels
|
497 |
+
if isinstance(num_res_blocks, int):
|
498 |
+
self.num_res_blocks = len(channel_mult) * [num_res_blocks]
|
499 |
+
else:
|
500 |
+
if len(num_res_blocks) != len(channel_mult):
|
501 |
+
raise ValueError("provide num_res_blocks either as an int (globally constant) or "
|
502 |
+
"as a list/tuple (per-level) with the same length as channel_mult")
|
503 |
+
self.num_res_blocks = num_res_blocks
|
504 |
+
#self.num_res_blocks = num_res_blocks
|
505 |
+
if disable_self_attentions is not None:
|
506 |
+
# should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
|
507 |
+
assert len(disable_self_attentions) == len(channel_mult)
|
508 |
+
if num_attention_blocks is not None:
|
509 |
+
assert len(num_attention_blocks) == len(self.num_res_blocks)
|
510 |
+
assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
|
511 |
+
print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. "
|
512 |
+
f"This option has LESS priority than attention_resolutions {attention_resolutions}, "
|
513 |
+
f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, "
|
514 |
+
f"attention will still not be set.") # todo: convert to warning
|
515 |
+
|
516 |
+
self.attention_resolutions = attention_resolutions
|
517 |
+
self.dropout = dropout
|
518 |
+
self.channel_mult = channel_mult
|
519 |
+
self.conv_resample = conv_resample
|
520 |
+
self.num_classes = num_classes
|
521 |
+
self.use_checkpoint = use_checkpoint
|
522 |
+
self.dtype = th.float16 if use_fp16 else th.float32
|
523 |
+
self.num_heads = num_heads
|
524 |
+
self.num_head_channels = num_head_channels
|
525 |
+
self.num_heads_upsample = num_heads_upsample
|
526 |
+
self.predict_codebook_ids = n_embed is not None
|
527 |
+
|
528 |
+
time_embed_dim = model_channels * 4
|
529 |
+
self.time_embed = nn.Sequential(
|
530 |
+
linear(model_channels, time_embed_dim),
|
531 |
+
nn.SiLU(),
|
532 |
+
linear(time_embed_dim, time_embed_dim),
|
533 |
+
)
|
534 |
+
|
535 |
+
if self.num_classes is not None:
|
536 |
+
self.label_emb = nn.Embedding(num_classes, time_embed_dim)
|
537 |
+
|
538 |
+
self.input_blocks = nn.ModuleList(
|
539 |
+
[
|
540 |
+
TimestepEmbedSequential(
|
541 |
+
conv_nd(dims, in_channels, model_channels, 3, padding=1)
|
542 |
+
)
|
543 |
+
]
|
544 |
+
)
|
545 |
+
self._feature_size = model_channels
|
546 |
+
input_block_chans = [model_channels]
|
547 |
+
ch = model_channels
|
548 |
+
ds = 1
|
549 |
+
for level, mult in enumerate(channel_mult):
|
550 |
+
for nr in range(self.num_res_blocks[level]):
|
551 |
+
layers = [
|
552 |
+
ResBlock(
|
553 |
+
ch,
|
554 |
+
time_embed_dim,
|
555 |
+
dropout,
|
556 |
+
out_channels=mult * model_channels,
|
557 |
+
dims=dims,
|
558 |
+
use_checkpoint=use_checkpoint,
|
559 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
560 |
+
)
|
561 |
+
]
|
562 |
+
ch = mult * model_channels
|
563 |
+
if ds in attention_resolutions:
|
564 |
+
if num_head_channels == -1:
|
565 |
+
dim_head = ch // num_heads
|
566 |
+
else:
|
567 |
+
num_heads = ch // num_head_channels
|
568 |
+
dim_head = num_head_channels
|
569 |
+
if legacy:
|
570 |
+
#num_heads = 1
|
571 |
+
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
572 |
+
if exists(disable_self_attentions):
|
573 |
+
disabled_sa = disable_self_attentions[level]
|
574 |
+
else:
|
575 |
+
disabled_sa = False
|
576 |
+
|
577 |
+
if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
|
578 |
+
layers.append(
|
579 |
+
AttentionBlock(
|
580 |
+
ch,
|
581 |
+
use_checkpoint=use_checkpoint,
|
582 |
+
num_heads=num_heads,
|
583 |
+
num_head_channels=dim_head,
|
584 |
+
use_new_attention_order=use_new_attention_order,
|
585 |
+
) if not use_spatial_transformer else SpatialTransformer(
|
586 |
+
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
587 |
+
disable_self_attn=disabled_sa, cross_domain_cfg=cross_domain_cfg,
|
588 |
+
)
|
589 |
+
)
|
590 |
+
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
591 |
+
self._feature_size += ch
|
592 |
+
input_block_chans.append(ch)
|
593 |
+
if level != len(channel_mult) - 1:
|
594 |
+
out_ch = ch
|
595 |
+
self.input_blocks.append(
|
596 |
+
TimestepEmbedSequential(
|
597 |
+
ResBlock(
|
598 |
+
ch,
|
599 |
+
time_embed_dim,
|
600 |
+
dropout,
|
601 |
+
out_channels=out_ch,
|
602 |
+
dims=dims,
|
603 |
+
use_checkpoint=use_checkpoint,
|
604 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
605 |
+
down=True,
|
606 |
+
)
|
607 |
+
if resblock_updown
|
608 |
+
else Downsample(
|
609 |
+
ch, conv_resample, dims=dims, out_channels=out_ch
|
610 |
+
)
|
611 |
+
)
|
612 |
+
)
|
613 |
+
ch = out_ch
|
614 |
+
input_block_chans.append(ch)
|
615 |
+
ds *= 2
|
616 |
+
self._feature_size += ch
|
617 |
+
|
618 |
+
if num_head_channels == -1:
|
619 |
+
dim_head = ch // num_heads
|
620 |
+
else:
|
621 |
+
num_heads = ch // num_head_channels
|
622 |
+
dim_head = num_head_channels
|
623 |
+
if legacy:
|
624 |
+
#num_heads = 1
|
625 |
+
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
626 |
+
self.middle_block = TimestepEmbedSequential(
|
627 |
+
ResBlock(
|
628 |
+
ch,
|
629 |
+
time_embed_dim,
|
630 |
+
dropout,
|
631 |
+
dims=dims,
|
632 |
+
use_checkpoint=use_checkpoint,
|
633 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
634 |
+
),
|
635 |
+
AttentionBlock(
|
636 |
+
ch,
|
637 |
+
use_checkpoint=use_checkpoint,
|
638 |
+
num_heads=num_heads,
|
639 |
+
num_head_channels=dim_head,
|
640 |
+
use_new_attention_order=use_new_attention_order,
|
641 |
+
) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn
|
642 |
+
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
643 |
+
cross_domain_cfg=cross_domain_cfg,
|
644 |
+
),
|
645 |
+
ResBlock(
|
646 |
+
ch,
|
647 |
+
time_embed_dim,
|
648 |
+
dropout,
|
649 |
+
dims=dims,
|
650 |
+
use_checkpoint=use_checkpoint,
|
651 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
652 |
+
),
|
653 |
+
)
|
654 |
+
self._feature_size += ch
|
655 |
+
|
656 |
+
self.output_blocks = nn.ModuleList([])
|
657 |
+
for level, mult in list(enumerate(channel_mult))[::-1]:
|
658 |
+
for i in range(self.num_res_blocks[level] + 1):
|
659 |
+
ich = input_block_chans.pop()
|
660 |
+
layers = [
|
661 |
+
ResBlock(
|
662 |
+
ch + ich,
|
663 |
+
time_embed_dim,
|
664 |
+
dropout,
|
665 |
+
out_channels=model_channels * mult,
|
666 |
+
dims=dims,
|
667 |
+
use_checkpoint=use_checkpoint,
|
668 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
669 |
+
)
|
670 |
+
]
|
671 |
+
ch = model_channels * mult
|
672 |
+
if ds in attention_resolutions:
|
673 |
+
if num_head_channels == -1:
|
674 |
+
dim_head = ch // num_heads
|
675 |
+
else:
|
676 |
+
num_heads = ch // num_head_channels
|
677 |
+
dim_head = num_head_channels
|
678 |
+
if legacy:
|
679 |
+
#num_heads = 1
|
680 |
+
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
681 |
+
if exists(disable_self_attentions):
|
682 |
+
disabled_sa = disable_self_attentions[level]
|
683 |
+
else:
|
684 |
+
disabled_sa = False
|
685 |
+
|
686 |
+
if not exists(num_attention_blocks) or i < num_attention_blocks[level]:
|
687 |
+
layers.append(
|
688 |
+
AttentionBlock(
|
689 |
+
ch,
|
690 |
+
use_checkpoint=use_checkpoint,
|
691 |
+
num_heads=num_heads_upsample,
|
692 |
+
num_head_channels=dim_head,
|
693 |
+
use_new_attention_order=use_new_attention_order,
|
694 |
+
) if not use_spatial_transformer else SpatialTransformer(
|
695 |
+
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
696 |
+
disable_self_attn=disabled_sa, cross_domain_cfg=cross_domain_cfg,
|
697 |
+
)
|
698 |
+
)
|
699 |
+
if level and i == self.num_res_blocks[level]:
|
700 |
+
out_ch = ch
|
701 |
+
layers.append(
|
702 |
+
ResBlock(
|
703 |
+
ch,
|
704 |
+
time_embed_dim,
|
705 |
+
dropout,
|
706 |
+
out_channels=out_ch,
|
707 |
+
dims=dims,
|
708 |
+
use_checkpoint=use_checkpoint,
|
709 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
710 |
+
up=True,
|
711 |
+
)
|
712 |
+
if resblock_updown
|
713 |
+
else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
|
714 |
+
)
|
715 |
+
ds //= 2
|
716 |
+
self.output_blocks.append(TimestepEmbedSequential(*layers))
|
717 |
+
self._feature_size += ch
|
718 |
+
|
719 |
+
self.out = nn.Sequential(
|
720 |
+
normalization(ch),
|
721 |
+
nn.SiLU(),
|
722 |
+
zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)),
|
723 |
+
)
|
724 |
+
if self.predict_codebook_ids:
|
725 |
+
self.id_predictor = nn.Sequential(
|
726 |
+
normalization(ch),
|
727 |
+
conv_nd(dims, model_channels, n_embed, 1),
|
728 |
+
#nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
|
729 |
+
)
|
730 |
+
|
731 |
+
def convert_to_fp16(self):
|
732 |
+
"""
|
733 |
+
Convert the torso of the model to float16.
|
734 |
+
"""
|
735 |
+
self.input_blocks.apply(convert_module_to_f16)
|
736 |
+
self.middle_block.apply(convert_module_to_f16)
|
737 |
+
self.output_blocks.apply(convert_module_to_f16)
|
738 |
+
|
739 |
+
def convert_to_fp32(self):
|
740 |
+
"""
|
741 |
+
Convert the torso of the model to float32.
|
742 |
+
"""
|
743 |
+
self.input_blocks.apply(convert_module_to_f32)
|
744 |
+
self.middle_block.apply(convert_module_to_f32)
|
745 |
+
self.output_blocks.apply(convert_module_to_f32)
|
746 |
+
|
747 |
+
def forward(self, x, timesteps=None, context=None, y=None,**kwargs):
|
748 |
+
"""
|
749 |
+
Apply the model to an input batch.
|
750 |
+
:param x: an [N x C x ...] Tensor of inputs.
|
751 |
+
:param timesteps: a 1-D batch of timesteps.
|
752 |
+
:param context: conditioning plugged in via crossattn
|
753 |
+
:param y: an [N] Tensor of labels, if class-conditional.
|
754 |
+
:return: an [N x C x ...] Tensor of outputs.
|
755 |
+
"""
|
756 |
+
assert (y is not None) == (
|
757 |
+
self.num_classes is not None
|
758 |
+
), "must specify y if and only if the model is class-conditional"
|
759 |
+
hs = []
|
760 |
+
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
|
761 |
+
emb = self.time_embed(t_emb)
|
762 |
+
|
763 |
+
if self.num_classes is not None:
|
764 |
+
assert y.shape == (x.shape[0],)
|
765 |
+
emb = emb + self.label_emb(y)
|
766 |
+
|
767 |
+
h = x.type(self.dtype)
|
768 |
+
for module in self.input_blocks:
|
769 |
+
h = module(h, emb, context)
|
770 |
+
hs.append(h)
|
771 |
+
h = self.middle_block(h, emb, context)
|
772 |
+
for module in self.output_blocks:
|
773 |
+
h = th.cat([h, hs.pop()], dim=1)
|
774 |
+
h = module(h, emb, context)
|
775 |
+
h = h.type(x.dtype)
|
776 |
+
if self.predict_codebook_ids:
|
777 |
+
return self.id_predictor(h)
|
778 |
+
else:
|
779 |
+
return self.out(h)
|
780 |
+
|
781 |
+
|
782 |
+
class EncoderUNetModel(nn.Module):
|
783 |
+
"""
|
784 |
+
The half UNet model with attention and timestep embedding.
|
785 |
+
For usage, see UNet.
|
786 |
+
"""
|
787 |
+
|
788 |
+
def __init__(
|
789 |
+
self,
|
790 |
+
image_size,
|
791 |
+
in_channels,
|
792 |
+
model_channels,
|
793 |
+
out_channels,
|
794 |
+
num_res_blocks,
|
795 |
+
attention_resolutions,
|
796 |
+
dropout=0,
|
797 |
+
channel_mult=(1, 2, 4, 8),
|
798 |
+
conv_resample=True,
|
799 |
+
dims=2,
|
800 |
+
use_checkpoint=False,
|
801 |
+
use_fp16=False,
|
802 |
+
num_heads=1,
|
803 |
+
num_head_channels=-1,
|
804 |
+
num_heads_upsample=-1,
|
805 |
+
use_scale_shift_norm=False,
|
806 |
+
resblock_updown=False,
|
807 |
+
use_new_attention_order=False,
|
808 |
+
pool="adaptive",
|
809 |
+
*args,
|
810 |
+
**kwargs
|
811 |
+
):
|
812 |
+
super().__init__()
|
813 |
+
|
814 |
+
if num_heads_upsample == -1:
|
815 |
+
num_heads_upsample = num_heads
|
816 |
+
|
817 |
+
self.in_channels = in_channels
|
818 |
+
self.model_channels = model_channels
|
819 |
+
self.out_channels = out_channels
|
820 |
+
self.num_res_blocks = num_res_blocks
|
821 |
+
self.attention_resolutions = attention_resolutions
|
822 |
+
self.dropout = dropout
|
823 |
+
self.channel_mult = channel_mult
|
824 |
+
self.conv_resample = conv_resample
|
825 |
+
self.use_checkpoint = use_checkpoint
|
826 |
+
self.dtype = th.float16 if use_fp16 else th.float32
|
827 |
+
self.num_heads = num_heads
|
828 |
+
self.num_head_channels = num_head_channels
|
829 |
+
self.num_heads_upsample = num_heads_upsample
|
830 |
+
|
831 |
+
time_embed_dim = model_channels * 4
|
832 |
+
self.time_embed = nn.Sequential(
|
833 |
+
linear(model_channels, time_embed_dim),
|
834 |
+
nn.SiLU(),
|
835 |
+
linear(time_embed_dim, time_embed_dim),
|
836 |
+
)
|
837 |
+
|
838 |
+
self.input_blocks = nn.ModuleList(
|
839 |
+
[
|
840 |
+
TimestepEmbedSequential(
|
841 |
+
conv_nd(dims, in_channels, model_channels, 3, padding=1)
|
842 |
+
)
|
843 |
+
]
|
844 |
+
)
|
845 |
+
self._feature_size = model_channels
|
846 |
+
input_block_chans = [model_channels]
|
847 |
+
ch = model_channels
|
848 |
+
ds = 1
|
849 |
+
for level, mult in enumerate(channel_mult):
|
850 |
+
for _ in range(num_res_blocks):
|
851 |
+
layers = [
|
852 |
+
ResBlock(
|
853 |
+
ch,
|
854 |
+
time_embed_dim,
|
855 |
+
dropout,
|
856 |
+
out_channels=mult * model_channels,
|
857 |
+
dims=dims,
|
858 |
+
use_checkpoint=use_checkpoint,
|
859 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
860 |
+
)
|
861 |
+
]
|
862 |
+
ch = mult * model_channels
|
863 |
+
if ds in attention_resolutions:
|
864 |
+
layers.append(
|
865 |
+
AttentionBlock(
|
866 |
+
ch,
|
867 |
+
use_checkpoint=use_checkpoint,
|
868 |
+
num_heads=num_heads,
|
869 |
+
num_head_channels=num_head_channels,
|
870 |
+
use_new_attention_order=use_new_attention_order,
|
871 |
+
)
|
872 |
+
)
|
873 |
+
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
874 |
+
self._feature_size += ch
|
875 |
+
input_block_chans.append(ch)
|
876 |
+
if level != len(channel_mult) - 1:
|
877 |
+
out_ch = ch
|
878 |
+
self.input_blocks.append(
|
879 |
+
TimestepEmbedSequential(
|
880 |
+
ResBlock(
|
881 |
+
ch,
|
882 |
+
time_embed_dim,
|
883 |
+
dropout,
|
884 |
+
out_channels=out_ch,
|
885 |
+
dims=dims,
|
886 |
+
use_checkpoint=use_checkpoint,
|
887 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
888 |
+
down=True,
|
889 |
+
)
|
890 |
+
if resblock_updown
|
891 |
+
else Downsample(
|
892 |
+
ch, conv_resample, dims=dims, out_channels=out_ch
|
893 |
+
)
|
894 |
+
)
|
895 |
+
)
|
896 |
+
ch = out_ch
|
897 |
+
input_block_chans.append(ch)
|
898 |
+
ds *= 2
|
899 |
+
self._feature_size += ch
|
900 |
+
|
901 |
+
self.middle_block = TimestepEmbedSequential(
|
902 |
+
ResBlock(
|
903 |
+
ch,
|
904 |
+
time_embed_dim,
|
905 |
+
dropout,
|
906 |
+
dims=dims,
|
907 |
+
use_checkpoint=use_checkpoint,
|
908 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
909 |
+
),
|
910 |
+
AttentionBlock(
|
911 |
+
ch,
|
912 |
+
use_checkpoint=use_checkpoint,
|
913 |
+
num_heads=num_heads,
|
914 |
+
num_head_channels=num_head_channels,
|
915 |
+
use_new_attention_order=use_new_attention_order,
|
916 |
+
),
|
917 |
+
ResBlock(
|
918 |
+
ch,
|
919 |
+
time_embed_dim,
|
920 |
+
dropout,
|
921 |
+
dims=dims,
|
922 |
+
use_checkpoint=use_checkpoint,
|
923 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
924 |
+
),
|
925 |
+
)
|
926 |
+
self._feature_size += ch
|
927 |
+
self.pool = pool
|
928 |
+
if pool == "adaptive":
|
929 |
+
self.out = nn.Sequential(
|
930 |
+
normalization(ch),
|
931 |
+
nn.SiLU(),
|
932 |
+
nn.AdaptiveAvgPool2d((1, 1)),
|
933 |
+
zero_module(conv_nd(dims, ch, out_channels, 1)),
|
934 |
+
nn.Flatten(),
|
935 |
+
)
|
936 |
+
elif pool == "attention":
|
937 |
+
assert num_head_channels != -1
|
938 |
+
self.out = nn.Sequential(
|
939 |
+
normalization(ch),
|
940 |
+
nn.SiLU(),
|
941 |
+
AttentionPool2d(
|
942 |
+
(image_size // ds), ch, num_head_channels, out_channels
|
943 |
+
),
|
944 |
+
)
|
945 |
+
elif pool == "spatial":
|
946 |
+
self.out = nn.Sequential(
|
947 |
+
nn.Linear(self._feature_size, 2048),
|
948 |
+
nn.ReLU(),
|
949 |
+
nn.Linear(2048, self.out_channels),
|
950 |
+
)
|
951 |
+
elif pool == "spatial_v2":
|
952 |
+
self.out = nn.Sequential(
|
953 |
+
nn.Linear(self._feature_size, 2048),
|
954 |
+
normalization(2048),
|
955 |
+
nn.SiLU(),
|
956 |
+
nn.Linear(2048, self.out_channels),
|
957 |
+
)
|
958 |
+
else:
|
959 |
+
raise NotImplementedError(f"Unexpected {pool} pooling")
|
960 |
+
|
961 |
+
def convert_to_fp16(self):
|
962 |
+
"""
|
963 |
+
Convert the torso of the model to float16.
|
964 |
+
"""
|
965 |
+
self.input_blocks.apply(convert_module_to_f16)
|
966 |
+
self.middle_block.apply(convert_module_to_f16)
|
967 |
+
|
968 |
+
def convert_to_fp32(self):
|
969 |
+
"""
|
970 |
+
Convert the torso of the model to float32.
|
971 |
+
"""
|
972 |
+
self.input_blocks.apply(convert_module_to_f32)
|
973 |
+
self.middle_block.apply(convert_module_to_f32)
|
974 |
+
|
975 |
+
def forward(self, x, timesteps):
|
976 |
+
"""
|
977 |
+
Apply the model to an input batch.
|
978 |
+
:param x: an [N x C x ...] Tensor of inputs.
|
979 |
+
:param timesteps: a 1-D batch of timesteps.
|
980 |
+
:return: an [N x K] Tensor of outputs.
|
981 |
+
"""
|
982 |
+
emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
|
983 |
+
|
984 |
+
results = []
|
985 |
+
h = x.type(self.dtype)
|
986 |
+
for module in self.input_blocks:
|
987 |
+
h = module(h, emb)
|
988 |
+
if self.pool.startswith("spatial"):
|
989 |
+
results.append(h.type(x.dtype).mean(dim=(2, 3)))
|
990 |
+
h = self.middle_block(h, emb)
|
991 |
+
if self.pool.startswith("spatial"):
|
992 |
+
results.append(h.type(x.dtype).mean(dim=(2, 3)))
|
993 |
+
h = th.cat(results, axis=-1)
|
994 |
+
return self.out(h)
|
995 |
+
else:
|
996 |
+
h = h.type(x.dtype)
|
997 |
+
return self.out(h)
|
998 |
+
|
models/ldm/modules/diffusionmodules/util.py
ADDED
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# adopted from
|
2 |
+
# https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
|
3 |
+
# and
|
4 |
+
# https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
|
5 |
+
# and
|
6 |
+
# https://github.com/openai/guided-diffusion/blob/0ba878e517b276c45d1195eb29f6f5f72659a05b/guided_diffusion/nn.py
|
7 |
+
#
|
8 |
+
# thanks!
|
9 |
+
|
10 |
+
|
11 |
+
import os
|
12 |
+
import math
|
13 |
+
import torch
|
14 |
+
import torch.nn as nn
|
15 |
+
import numpy as np
|
16 |
+
from einops import repeat
|
17 |
+
|
18 |
+
from ldm.util import instantiate_from_config
|
19 |
+
|
20 |
+
|
21 |
+
def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
|
22 |
+
if schedule == "linear":
|
23 |
+
betas = (
|
24 |
+
torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2
|
25 |
+
)
|
26 |
+
|
27 |
+
elif schedule == "cosine":
|
28 |
+
timesteps = (
|
29 |
+
torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s
|
30 |
+
)
|
31 |
+
alphas = timesteps / (1 + cosine_s) * np.pi / 2
|
32 |
+
alphas = torch.cos(alphas).pow(2)
|
33 |
+
alphas = alphas / alphas[0]
|
34 |
+
betas = 1 - alphas[1:] / alphas[:-1]
|
35 |
+
betas = np.clip(betas, a_min=0, a_max=0.999)
|
36 |
+
|
37 |
+
elif schedule == "sqrt_linear":
|
38 |
+
betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64)
|
39 |
+
elif schedule == "sqrt":
|
40 |
+
betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5
|
41 |
+
else:
|
42 |
+
raise ValueError(f"schedule '{schedule}' unknown.")
|
43 |
+
return betas.numpy()
|
44 |
+
|
45 |
+
|
46 |
+
def make_ddim_timesteps(ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True):
|
47 |
+
if ddim_discr_method == 'uniform':
|
48 |
+
c = num_ddpm_timesteps // num_ddim_timesteps
|
49 |
+
ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c)))
|
50 |
+
elif ddim_discr_method == 'quad':
|
51 |
+
ddim_timesteps = ((np.linspace(0, np.sqrt(num_ddpm_timesteps * .8), num_ddim_timesteps)) ** 2).astype(int)
|
52 |
+
else:
|
53 |
+
raise NotImplementedError(f'There is no ddim discretization method called "{ddim_discr_method}"')
|
54 |
+
|
55 |
+
# assert ddim_timesteps.shape[0] == num_ddim_timesteps
|
56 |
+
# add one to get the final alpha values right (the ones from first scale to data during sampling)
|
57 |
+
steps_out = ddim_timesteps + 1
|
58 |
+
if verbose:
|
59 |
+
print(f'Selected timesteps for ddim sampler: {steps_out}')
|
60 |
+
return steps_out
|
61 |
+
|
62 |
+
|
63 |
+
def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):
|
64 |
+
# select alphas for computing the variance schedule
|
65 |
+
alphas = alphacums[ddim_timesteps]
|
66 |
+
alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist())
|
67 |
+
|
68 |
+
# according the the formula provided in https://arxiv.org/abs/2010.02502
|
69 |
+
sigmas = eta * np.sqrt((1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev))
|
70 |
+
if verbose:
|
71 |
+
print(f'Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}')
|
72 |
+
print(f'For the chosen value of eta, which is {eta}, '
|
73 |
+
f'this results in the following sigma_t schedule for ddim sampler {sigmas}')
|
74 |
+
return sigmas, alphas, alphas_prev
|
75 |
+
|
76 |
+
|
77 |
+
def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
|
78 |
+
"""
|
79 |
+
Create a beta schedule that discretizes the given alpha_t_bar function,
|
80 |
+
which defines the cumulative product of (1-beta) over time from t = [0,1].
|
81 |
+
:param num_diffusion_timesteps: the number of betas to produce.
|
82 |
+
:param alpha_bar: a lambda that takes an argument t from 0 to 1 and
|
83 |
+
produces the cumulative product of (1-beta) up to that
|
84 |
+
part of the diffusion process.
|
85 |
+
:param max_beta: the maximum beta to use; use values lower than 1 to
|
86 |
+
prevent singularities.
|
87 |
+
"""
|
88 |
+
betas = []
|
89 |
+
for i in range(num_diffusion_timesteps):
|
90 |
+
t1 = i / num_diffusion_timesteps
|
91 |
+
t2 = (i + 1) / num_diffusion_timesteps
|
92 |
+
betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
|
93 |
+
return np.array(betas)
|
94 |
+
|
95 |
+
|
96 |
+
def extract_into_tensor(a, t, x_shape):
|
97 |
+
b, *_ = t.shape
|
98 |
+
out = a.gather(-1, t)
|
99 |
+
return out.reshape(b, *((1,) * (len(x_shape) - 1)))
|
100 |
+
|
101 |
+
|
102 |
+
def checkpoint(func, inputs, params, flag):
|
103 |
+
"""
|
104 |
+
Evaluate a function without caching intermediate activations, allowing for
|
105 |
+
reduced memory at the expense of extra compute in the backward pass.
|
106 |
+
:param func: the function to evaluate.
|
107 |
+
:param inputs: the argument sequence to pass to `func`.
|
108 |
+
:param params: a sequence of parameters `func` depends on but does not
|
109 |
+
explicitly take as arguments.
|
110 |
+
:param flag: if False, disable gradient checkpointing.
|
111 |
+
"""
|
112 |
+
if flag:
|
113 |
+
args = tuple(inputs) + tuple(params)
|
114 |
+
return CheckpointFunction.apply(func, len(inputs), *args)
|
115 |
+
else:
|
116 |
+
return func(*inputs)
|
117 |
+
|
118 |
+
|
119 |
+
class CheckpointFunction(torch.autograd.Function):
|
120 |
+
@staticmethod
|
121 |
+
def forward(ctx, run_function, length, *args):
|
122 |
+
ctx.run_function = run_function
|
123 |
+
ctx.input_tensors = list(args[:length])
|
124 |
+
ctx.input_params = list(args[length:])
|
125 |
+
|
126 |
+
with torch.no_grad():
|
127 |
+
output_tensors = ctx.run_function(*ctx.input_tensors)
|
128 |
+
return output_tensors
|
129 |
+
|
130 |
+
@staticmethod
|
131 |
+
def backward(ctx, *output_grads):
|
132 |
+
ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
|
133 |
+
with torch.enable_grad():
|
134 |
+
# Fixes a bug where the first op in run_function modifies the
|
135 |
+
# Tensor storage in place, which is not allowed for detach()'d
|
136 |
+
# Tensors.
|
137 |
+
shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
|
138 |
+
output_tensors = ctx.run_function(*shallow_copies)
|
139 |
+
input_grads = torch.autograd.grad(
|
140 |
+
output_tensors,
|
141 |
+
ctx.input_tensors + ctx.input_params,
|
142 |
+
output_grads,
|
143 |
+
allow_unused=True,
|
144 |
+
)
|
145 |
+
del ctx.input_tensors
|
146 |
+
del ctx.input_params
|
147 |
+
del output_tensors
|
148 |
+
return (None, None) + input_grads
|
149 |
+
|
150 |
+
|
151 |
+
def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):
|
152 |
+
"""
|
153 |
+
Create sinusoidal timestep embeddings.
|
154 |
+
:param timesteps: a 1-D Tensor of N indices, one per batch element.
|
155 |
+
These may be fractional.
|
156 |
+
:param dim: the dimension of the output.
|
157 |
+
:param max_period: controls the minimum frequency of the embeddings.
|
158 |
+
:return: an [N x dim] Tensor of positional embeddings.
|
159 |
+
"""
|
160 |
+
if not repeat_only:
|
161 |
+
half = dim // 2
|
162 |
+
freqs = torch.exp(
|
163 |
+
-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
|
164 |
+
).to(device=timesteps.device)
|
165 |
+
args = timesteps[:, None].float() * freqs[None]
|
166 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
167 |
+
if dim % 2:
|
168 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
169 |
+
else:
|
170 |
+
embedding = repeat(timesteps, 'b -> b d', d=dim)
|
171 |
+
return embedding
|
172 |
+
|
173 |
+
|
174 |
+
def zero_module(module):
|
175 |
+
"""
|
176 |
+
Zero out the parameters of a module and return it.
|
177 |
+
"""
|
178 |
+
for p in module.parameters():
|
179 |
+
p.detach().zero_()
|
180 |
+
return module
|
181 |
+
|
182 |
+
|
183 |
+
def scale_module(module, scale):
|
184 |
+
"""
|
185 |
+
Scale the parameters of a module and return it.
|
186 |
+
"""
|
187 |
+
for p in module.parameters():
|
188 |
+
p.detach().mul_(scale)
|
189 |
+
return module
|
190 |
+
|
191 |
+
|
192 |
+
def mean_flat(tensor):
|
193 |
+
"""
|
194 |
+
Take the mean over all non-batch dimensions.
|
195 |
+
"""
|
196 |
+
return tensor.mean(dim=list(range(1, len(tensor.shape))))
|
197 |
+
|
198 |
+
|
199 |
+
def normalization(channels):
|
200 |
+
"""
|
201 |
+
Make a standard normalization layer.
|
202 |
+
:param channels: number of input channels.
|
203 |
+
:return: an nn.Module for normalization.
|
204 |
+
"""
|
205 |
+
return GroupNorm32(32, channels)
|
206 |
+
|
207 |
+
|
208 |
+
# PyTorch 1.7 has SiLU, but we support PyTorch 1.5.
|
209 |
+
class SiLU(nn.Module):
|
210 |
+
def forward(self, x):
|
211 |
+
return x * torch.sigmoid(x)
|
212 |
+
|
213 |
+
|
214 |
+
class GroupNorm32(nn.GroupNorm):
|
215 |
+
def forward(self, x):
|
216 |
+
return super().forward(x.float()).type(x.dtype)
|
217 |
+
|
218 |
+
def conv_nd(dims, *args, **kwargs):
|
219 |
+
"""
|
220 |
+
Create a 1D, 2D, or 3D convolution module.
|
221 |
+
"""
|
222 |
+
if dims == 1:
|
223 |
+
return nn.Conv1d(*args, **kwargs)
|
224 |
+
elif dims == 2:
|
225 |
+
return nn.Conv2d(*args, **kwargs)
|
226 |
+
elif dims == 3:
|
227 |
+
return nn.Conv3d(*args, **kwargs)
|
228 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
229 |
+
|
230 |
+
|
231 |
+
def linear(*args, **kwargs):
|
232 |
+
"""
|
233 |
+
Create a linear module.
|
234 |
+
"""
|
235 |
+
return nn.Linear(*args, **kwargs)
|
236 |
+
|
237 |
+
|
238 |
+
def avg_pool_nd(dims, *args, **kwargs):
|
239 |
+
"""
|
240 |
+
Create a 1D, 2D, or 3D average pooling module.
|
241 |
+
"""
|
242 |
+
if dims == 1:
|
243 |
+
return nn.AvgPool1d(*args, **kwargs)
|
244 |
+
elif dims == 2:
|
245 |
+
return nn.AvgPool2d(*args, **kwargs)
|
246 |
+
elif dims == 3:
|
247 |
+
return nn.AvgPool3d(*args, **kwargs)
|
248 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
249 |
+
|
250 |
+
|
251 |
+
class HybridConditioner(nn.Module):
|
252 |
+
|
253 |
+
def __init__(self, c_concat_config, c_crossattn_config):
|
254 |
+
super().__init__()
|
255 |
+
self.concat_conditioner = instantiate_from_config(c_concat_config)
|
256 |
+
self.crossattn_conditioner = instantiate_from_config(c_crossattn_config)
|
257 |
+
|
258 |
+
def forward(self, c_concat, c_crossattn):
|
259 |
+
c_concat = self.concat_conditioner(c_concat)
|
260 |
+
c_crossattn = self.crossattn_conditioner(c_crossattn)
|
261 |
+
return {'c_concat': [c_concat], 'c_crossattn': [c_crossattn]}
|
262 |
+
|
263 |
+
|
264 |
+
def noise_like(shape, device, repeat=False):
|
265 |
+
repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
|
266 |
+
noise = lambda: torch.randn(shape, device=device)
|
267 |
+
return repeat_noise() if repeat else noise()
|
models/ldm/modules/distributions/__init__.py
ADDED
File without changes
|