Spaces:
Runtime error
Runtime error
add codes
Browse files- .DS_Store +0 -0
- README.md +3 -3
- app.py +92 -0
- diffusion.py +185 -0
- diffusion_arch.py +1208 -0
- examples/lssd2025.jpg +0 -0
- examples/web-shadow0243.jpg +0 -0
- examples/web-shadow0248.jpg +0 -0
- header.html +18 -0
- net_g_400000.pth +3 -0
.DS_Store
ADDED
Binary file (6.15 kB). View file
|
|
README.md
CHANGED
@@ -1,10 +1,10 @@
|
|
1 |
---
|
2 |
title: InstanceShadow
|
3 |
-
emoji:
|
4 |
-
colorFrom:
|
5 |
colorTo: gray
|
6 |
sdk: gradio
|
7 |
-
sdk_version:
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
license: cc-by-4.0
|
|
|
1 |
---
|
2 |
title: InstanceShadow
|
3 |
+
emoji: ๐ฅ
|
4 |
+
colorFrom: red
|
5 |
colorTo: gray
|
6 |
sdk: gradio
|
7 |
+
sdk_version: 3.50.2
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
license: cc-by-4.0
|
app.py
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
|
3 |
+
from PIL import Image
|
4 |
+
|
5 |
+
import torch
|
6 |
+
from diffusion import DiffusionPipeline
|
7 |
+
|
8 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
9 |
+
|
10 |
+
pipe = DiffusionPipeline(device)
|
11 |
+
|
12 |
+
def read_content(file_path: str) -> str:
|
13 |
+
"""read the content of target file
|
14 |
+
"""
|
15 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
16 |
+
content = f.read()
|
17 |
+
|
18 |
+
return content
|
19 |
+
|
20 |
+
def predict(input, dkernel, diffusion_step, q=False):
|
21 |
+
lq = input["image"].convert("RGB")
|
22 |
+
mask = input["mask"].convert("RGB")
|
23 |
+
mask = mask.resize(lq.size, resample=Image.NEAREST)
|
24 |
+
output = pipe(lq=lq, mask=mask, dkernel=dkernel, diffusion_step=diffusion_step)
|
25 |
+
return output
|
26 |
+
|
27 |
+
def qpredict(input, dkernel, diffusion_step, q=False):
|
28 |
+
lq = input["image"].convert("RGB")
|
29 |
+
mask = input["mask"].convert("RGB")
|
30 |
+
mask = mask.resize(lq.size, resample=Image.NEAREST)
|
31 |
+
for output in pipe.quick_solve(lq=lq, mask=mask, dkernel=dkernel, diffusion_step=diffusion_step):
|
32 |
+
yield output
|
33 |
+
|
34 |
+
|
35 |
+
css = '''
|
36 |
+
.container {max-width: 1150px;margin: auto;padding-top: 1.5rem}
|
37 |
+
#image_upload{min-height:400px}
|
38 |
+
#image_upload [data-testid="image"], #image_upload [data-testid="image"] > div{min-height: 400px}
|
39 |
+
#mask_radio .gr-form{background:transparent; border: none}
|
40 |
+
#word_mask{margin-top: .75em !important}
|
41 |
+
#word_mask textarea:disabled{opacity: 0.3}
|
42 |
+
.footer {margin-bottom: 45px;margin-top: 35px;text-align: center;border-bottom: 1px solid #e5e5e5}
|
43 |
+
.footer>p {font-size: .8rem; display: inline-block; padding: 0 10px;transform: translateY(10px);background: white}
|
44 |
+
.dark .footer {border-color: #303030}
|
45 |
+
.dark .footer>p {background: #0b0f19}
|
46 |
+
.acknowledgments h4{margin: 1.25em 0 .25em 0;font-weight: bold;font-size: 115%}
|
47 |
+
#image_upload .touch-none{display: flex}
|
48 |
+
@keyframes spin {
|
49 |
+
from {
|
50 |
+
transform: rotate(0deg);
|
51 |
+
}
|
52 |
+
to {
|
53 |
+
transform: rotate(360deg);
|
54 |
+
}
|
55 |
+
}
|
56 |
+
'''
|
57 |
+
|
58 |
+
image_blocks = gr.Blocks(css=css)
|
59 |
+
with image_blocks as demo:
|
60 |
+
gr.HTML(read_content("header.html"))
|
61 |
+
with gr.Group():
|
62 |
+
with gr.Box():
|
63 |
+
with gr.Row():
|
64 |
+
with gr.Column():
|
65 |
+
image = gr.Image(source='upload', tool='sketch', elem_id="image_upload", type="pil", label="Shadow Image").style(height=400)
|
66 |
+
dkernel = gr.Slider(minimum=11, maximum=55, step=2, value=25, label="Dilation Kernel Size")
|
67 |
+
diffusion_step = gr.Slider(minimum=10, maximum=200, step=5, value=50, label="Diffusion Time Step")
|
68 |
+
with gr.Row(elem_id="prompt-container").style(mobile_collapse=False, equal_height=True):
|
69 |
+
with gr.Column():
|
70 |
+
btn = gr.Button("Removal").style(
|
71 |
+
margin=False,
|
72 |
+
full_width=True,
|
73 |
+
)
|
74 |
+
with gr.Column():
|
75 |
+
qbtn = gr.Button("Quick Removal").style(
|
76 |
+
margin=False,
|
77 |
+
full_width=True,
|
78 |
+
)
|
79 |
+
|
80 |
+
with gr.Column():
|
81 |
+
image_out = gr.Image(label="Removal Result", elem_id="output-img").style(height=400)
|
82 |
+
with gr.Row():
|
83 |
+
gr.Examples(examples=[
|
84 |
+
'examples/web-shadow0243.jpg',
|
85 |
+
'examples/web-shadow0248.jpg',
|
86 |
+
'examples/lssd2025.jpg'
|
87 |
+
], inputs=[image])
|
88 |
+
|
89 |
+
btn.click(fn=predict, inputs=[image, dkernel, diffusion_step], outputs=[image_out])
|
90 |
+
qbtn.click(fn=qpredict, inputs=[image, dkernel, diffusion_step], outputs=[image_out])
|
91 |
+
|
92 |
+
image_blocks.launch(enable_queue=True, share=False, debug=False, server_port=10011)
|
diffusion.py
ADDED
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import inspect
|
2 |
+
from tkinter import Image
|
3 |
+
from typing import List, Optional, Union
|
4 |
+
|
5 |
+
import numpy as np
|
6 |
+
import torch
|
7 |
+
|
8 |
+
import PIL
|
9 |
+
from PIL import Image
|
10 |
+
from tqdm.auto import tqdm
|
11 |
+
|
12 |
+
from diffusion_arch import DensePosteriorConditionalUNet
|
13 |
+
from guided_diffusion.script_util import create_gaussian_diffusion
|
14 |
+
|
15 |
+
import torch.nn.functional as F
|
16 |
+
import torchvision.transforms.functional as TF
|
17 |
+
|
18 |
+
from einops import rearrange
|
19 |
+
from kornia.morphology import dilation
|
20 |
+
|
21 |
+
from tqdm import tqdm
|
22 |
+
|
23 |
+
def preprocess_image(image):
|
24 |
+
w, h = image.size
|
25 |
+
w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
|
26 |
+
image = image.resize((w, h), resample=PIL.Image.LANCZOS)
|
27 |
+
image = np.array(image).astype(np.float32) / 255.0
|
28 |
+
image = torch.from_numpy(image.transpose(2,0,1)).unsqueeze(0)
|
29 |
+
return 2.0 * image - 1.0
|
30 |
+
|
31 |
+
def preprocess_mask(mask):
|
32 |
+
mask = mask.convert("L")
|
33 |
+
w, h = mask.size
|
34 |
+
w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
|
35 |
+
mask = mask.resize((w, h), resample=PIL.Image.NEAREST)
|
36 |
+
mask = np.array(mask).astype(np.float32) / 255.0
|
37 |
+
mask = torch.from_numpy(np.repeat(mask[None, ...], 3, axis=0)).unsqueeze(0)
|
38 |
+
mask[mask > 0] = 1
|
39 |
+
return mask
|
40 |
+
|
41 |
+
|
42 |
+
class DiffusionPipeline():
|
43 |
+
def __init__(self, device):
|
44 |
+
super().__init__()
|
45 |
+
self.device = device
|
46 |
+
self.model = DensePosteriorConditionalUNet(
|
47 |
+
in_channels=9,
|
48 |
+
model_channels=256,
|
49 |
+
out_channels=6,
|
50 |
+
num_res_blocks=2,
|
51 |
+
attention_resolutions=[8, 16, 32],
|
52 |
+
dropout=0.0,
|
53 |
+
channel_mult=(1, 1, 2, 2, 4, 4),
|
54 |
+
num_classes=None,
|
55 |
+
use_checkpoint=False,
|
56 |
+
use_fp16=False,
|
57 |
+
num_heads=4,
|
58 |
+
num_head_channels=64,
|
59 |
+
num_heads_upsample=-1,
|
60 |
+
use_scale_shift_norm=True,
|
61 |
+
resblock_updown=True,
|
62 |
+
use_new_attention_order=True
|
63 |
+
)
|
64 |
+
self.model.eval()
|
65 |
+
self.model.to(self.device)
|
66 |
+
self.model.load_state_dict(torch.load('net_g_400000.pth', map_location='cpu')["params_ema"], strict=True)
|
67 |
+
|
68 |
+
|
69 |
+
@torch.no_grad()
|
70 |
+
def __call__(self, lq, mask, dkernel, diffusion_step):
|
71 |
+
self.eval_gaussian_diffusion = create_gaussian_diffusion(
|
72 |
+
steps=1000,
|
73 |
+
learn_sigma=True,
|
74 |
+
noise_schedule='linear',
|
75 |
+
use_kl=False,
|
76 |
+
timestep_respacing="ddim" + str(diffusion_step),
|
77 |
+
predict_xstart=False,
|
78 |
+
rescale_timesteps=False,
|
79 |
+
rescale_learned_sigmas=False,
|
80 |
+
p2_gamma=1,
|
81 |
+
p2_k=1,
|
82 |
+
)
|
83 |
+
|
84 |
+
ow, oh = lq.size
|
85 |
+
|
86 |
+
# preprocess image
|
87 |
+
lq = preprocess_image(lq).to(self.device)
|
88 |
+
|
89 |
+
# preprocess mask
|
90 |
+
mask = preprocess_mask(mask).to(self.device)
|
91 |
+
mask = dilation(mask, torch.ones(dkernel, dkernel, device=self.device))
|
92 |
+
|
93 |
+
# return Image.fromarray(np.uint8(torch.cat(((lq / 2 + 0.5).clamp(0, 1), mask), dim=2).cpu().permute(0, 2, 3, 1).numpy()[0] * 255.))
|
94 |
+
|
95 |
+
#======== PADDING FORWARDING ============
|
96 |
+
stride = 64
|
97 |
+
kernel_size = 256
|
98 |
+
|
99 |
+
_, _, h, w = mask.shape
|
100 |
+
mask = F.unfold(mask, kernel_size=kernel_size, stride=stride)
|
101 |
+
lq = F.unfold(lq, kernel_size=kernel_size, stride=stride)
|
102 |
+
|
103 |
+
n, c, l = mask.shape
|
104 |
+
mask = rearrange(mask, 'n (c3 h w) l -> (n l) c3 h w', h=kernel_size, w=kernel_size)
|
105 |
+
lq = rearrange(lq, 'n (c3 h w) l -> (n l) c3 h w', h=kernel_size, w=kernel_size)
|
106 |
+
|
107 |
+
#======== PADDING END ============
|
108 |
+
|
109 |
+
#======== FORWARDING ============
|
110 |
+
sub_imgs = []
|
111 |
+
for (sub_lq, sub_mask) in zip(lq.unsqueeze(1), mask.unsqueeze(1)):
|
112 |
+
if torch.sum(sub_mask) > 1:
|
113 |
+
img = torch.randn_like(sub_lq, device=self.device)
|
114 |
+
indices = list(range(self.eval_gaussian_diffusion.num_timesteps))[::-1]
|
115 |
+
for i in indices:
|
116 |
+
t = torch.tensor([i] * img.size(0), device=self.device)
|
117 |
+
img = img * sub_mask + self.eval_gaussian_diffusion.q_sample(sub_lq, t) * (1 - sub_mask)
|
118 |
+
out = self.eval_gaussian_diffusion.p_mean_variance(self.model, img.contiguous(), t, model_kwargs={'latent': torch.cat((sub_lq, sub_mask), dim=1)})
|
119 |
+
nonzero_mask = (
|
120 |
+
(t != 0).float().view(-1, *([1] * (len(img.shape) - 1)))
|
121 |
+
) # no noise when t == 0
|
122 |
+
img = out["mean"] + nonzero_mask * torch.exp(0.5 * out["log_variance"]) * torch.randn_like(img, device=self.device)
|
123 |
+
sub_imgs.append(img)
|
124 |
+
else:
|
125 |
+
sub_imgs.append(sub_lq)
|
126 |
+
img = torch.cat(sub_imgs, dim=0)
|
127 |
+
|
128 |
+
#======== PADDING BACKWARDING ============
|
129 |
+
img = rearrange(img, '(n l) c3 h w -> n (c3 h w) l', h=kernel_size, w=kernel_size, l=l)
|
130 |
+
img = F.fold(img, (h, w), kernel_size=kernel_size, stride=stride)
|
131 |
+
norm_map = F.fold(F.unfold(torch.ones_like(img), kernel_size, stride=stride), (h, w), kernel_size, stride=stride)
|
132 |
+
img /= norm_map
|
133 |
+
|
134 |
+
img = (img / 2 + 0.5).clamp(0, 1)
|
135 |
+
img = img.cpu().permute(0, 2, 3, 1).numpy()[0]
|
136 |
+
img = Image.fromarray(np.uint8(img * 255.))
|
137 |
+
img = img.resize((ow, oh), resample=PIL.Image.LANCZOS)
|
138 |
+
|
139 |
+
return img
|
140 |
+
|
141 |
+
|
142 |
+
|
143 |
+
@torch.no_grad()
|
144 |
+
def quick_solve(self, lq, mask, dkernel, diffusion_step):
|
145 |
+
self.eval_gaussian_diffusion = create_gaussian_diffusion(
|
146 |
+
steps=1000,
|
147 |
+
learn_sigma=True,
|
148 |
+
noise_schedule='linear',
|
149 |
+
use_kl=False,
|
150 |
+
timestep_respacing="ddim" + str(diffusion_step),
|
151 |
+
predict_xstart=False,
|
152 |
+
rescale_timesteps=False,
|
153 |
+
rescale_learned_sigmas=False,
|
154 |
+
p2_gamma=1,
|
155 |
+
p2_k=1,
|
156 |
+
)
|
157 |
+
|
158 |
+
ow, oh = lq.size
|
159 |
+
|
160 |
+
lq = lq.resize((512, 512), resample=Image.LANCZOS)
|
161 |
+
mask = mask.resize((512, 512), resample=Image.NEAREST)
|
162 |
+
|
163 |
+
# preprocess image
|
164 |
+
lq = preprocess_image(lq).to(self.device)
|
165 |
+
|
166 |
+
# preprocess mask
|
167 |
+
mask = preprocess_mask(mask).to(self.device)
|
168 |
+
mask = dilation(mask, torch.ones(dkernel, dkernel, device=self.device))
|
169 |
+
|
170 |
+
# return Image.fromarray(np.uint8(torch.cat(((lq / 2 + 0.5).clamp(0, 1), mask), dim=2).cpu().permute(0, 2, 3, 1).numpy()[0] * 255.))
|
171 |
+
|
172 |
+
img = torch.randn_like(lq, device=self.device)
|
173 |
+
indices = list(range(self.eval_gaussian_diffusion.num_timesteps))[::-1]
|
174 |
+
for i in indices:
|
175 |
+
t = torch.tensor([i] * img.size(0), device=self.device)
|
176 |
+
img = img * mask + self.eval_gaussian_diffusion.q_sample(lq, t) * (1 - mask)
|
177 |
+
out = self.eval_gaussian_diffusion.p_mean_variance(self.model, img.contiguous(), t, model_kwargs={'latent': torch.cat((lq, mask), dim=1)})
|
178 |
+
nonzero_mask = (
|
179 |
+
(t != 0).float().view(-1, *([1] * (len(img.shape) - 1)))
|
180 |
+
) # no noise when t == 0
|
181 |
+
img = out["mean"] + nonzero_mask * torch.exp(0.5 * out["log_variance"]) * torch.randn_like(img, device=self.device)
|
182 |
+
|
183 |
+
yield Image.fromarray(np.uint8((out["pred_xstart"] / 2 + 0.5).clamp(0, 1).cpu().permute(0, 2, 3, 1).numpy()[0] * 255.)).resize((ow, oh), resample=Image.LANCZOS)
|
184 |
+
|
185 |
+
yield Image.fromarray(np.uint8((img / 2 + 0.5).clamp(0, 1).cpu().permute(0, 2, 3, 1).numpy()[0] * 255.)).resize((ow, oh), resample=Image.LANCZOS)
|
diffusion_arch.py
ADDED
@@ -0,0 +1,1208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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torch.nn as nn
|
7 |
+
import torch.nn.functional as F
|
8 |
+
|
9 |
+
import torchvision
|
10 |
+
import torchvision.transforms.functional as TF
|
11 |
+
|
12 |
+
import numpy as np
|
13 |
+
|
14 |
+
from guided_diffusion.fp16_util import convert_module_to_f16, convert_module_to_f32
|
15 |
+
from guided_diffusion.nn import (
|
16 |
+
checkpoint,
|
17 |
+
conv_nd,
|
18 |
+
linear,
|
19 |
+
avg_pool_nd,
|
20 |
+
zero_module,
|
21 |
+
normalization,
|
22 |
+
timestep_embedding,
|
23 |
+
)
|
24 |
+
|
25 |
+
class AttentionPool2d(nn.Module):
|
26 |
+
"""
|
27 |
+
Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
|
28 |
+
"""
|
29 |
+
|
30 |
+
def __init__(
|
31 |
+
self,
|
32 |
+
spacial_dim: int,
|
33 |
+
embed_dim: int,
|
34 |
+
num_heads_channels: int,
|
35 |
+
output_dim: int = None,
|
36 |
+
):
|
37 |
+
super().__init__()
|
38 |
+
self.positional_embedding = nn.Parameter(
|
39 |
+
torch.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5
|
40 |
+
)
|
41 |
+
self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
|
42 |
+
self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
|
43 |
+
self.num_heads = embed_dim // num_heads_channels
|
44 |
+
self.attention = QKVAttention(self.num_heads)
|
45 |
+
|
46 |
+
def forward(self, x):
|
47 |
+
b, c, *_spatial = x.shape
|
48 |
+
x = x.reshape(b, c, -1) # NC(HW)
|
49 |
+
x = torch.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
|
50 |
+
x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
|
51 |
+
x = self.qkv_proj(x)
|
52 |
+
x = self.attention(x)
|
53 |
+
x = self.c_proj(x)
|
54 |
+
return x[:, :, 0]
|
55 |
+
|
56 |
+
|
57 |
+
class TimestepBlock(nn.Module):
|
58 |
+
"""
|
59 |
+
Any module where forward() takes timestep embeddings as a second argument.
|
60 |
+
"""
|
61 |
+
|
62 |
+
@abstractmethod
|
63 |
+
def forward(self, x, emb):
|
64 |
+
"""
|
65 |
+
Apply the module to `x` given `emb` timestep embeddings.
|
66 |
+
"""
|
67 |
+
|
68 |
+
|
69 |
+
class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
|
70 |
+
"""
|
71 |
+
A sequential module that passes timestep embeddings to the children that
|
72 |
+
support it as an extra input.
|
73 |
+
"""
|
74 |
+
|
75 |
+
def forward(self, x, emb):
|
76 |
+
for layer in self:
|
77 |
+
if isinstance(layer, TimestepBlock):
|
78 |
+
x = layer(x, emb)
|
79 |
+
else:
|
80 |
+
x = layer(x)
|
81 |
+
return x
|
82 |
+
|
83 |
+
class Upsample(nn.Module):
|
84 |
+
"""
|
85 |
+
An upsampling layer with an optional convolution.
|
86 |
+
|
87 |
+
:param channels: channels in the inputs and outputs.
|
88 |
+
:param use_conv: a bool determining if a convolution is applied.
|
89 |
+
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
|
90 |
+
upsampling occurs in the inner-two dimensions.
|
91 |
+
"""
|
92 |
+
|
93 |
+
def __init__(self, channels, use_conv, dims=2, out_channels=None):
|
94 |
+
super().__init__()
|
95 |
+
self.channels = channels
|
96 |
+
self.out_channels = out_channels or channels
|
97 |
+
self.use_conv = use_conv
|
98 |
+
self.dims = dims
|
99 |
+
if use_conv:
|
100 |
+
self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=1)
|
101 |
+
|
102 |
+
def forward(self, x):
|
103 |
+
assert x.shape[1] == self.channels
|
104 |
+
if self.dims == 3:
|
105 |
+
x = F.interpolate(
|
106 |
+
x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
|
107 |
+
)
|
108 |
+
else:
|
109 |
+
x = F.interpolate(x, scale_factor=2, mode="nearest")
|
110 |
+
if self.use_conv:
|
111 |
+
x = self.conv(x)
|
112 |
+
return x
|
113 |
+
|
114 |
+
|
115 |
+
class Downsample(nn.Module):
|
116 |
+
"""
|
117 |
+
A downsampling layer with an optional convolution.
|
118 |
+
|
119 |
+
:param channels: channels in the inputs and outputs.
|
120 |
+
:param use_conv: a bool determining if a convolution is applied.
|
121 |
+
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
|
122 |
+
downsampling occurs in the inner-two dimensions.
|
123 |
+
"""
|
124 |
+
|
125 |
+
def __init__(self, channels, use_conv, dims=2, out_channels=None):
|
126 |
+
super().__init__()
|
127 |
+
self.channels = channels
|
128 |
+
self.out_channels = out_channels or channels
|
129 |
+
self.use_conv = use_conv
|
130 |
+
self.dims = dims
|
131 |
+
stride = 2 if dims != 3 else (1, 2, 2)
|
132 |
+
if use_conv:
|
133 |
+
self.op = conv_nd(
|
134 |
+
dims, self.channels, self.out_channels, 3, stride=stride, padding=1
|
135 |
+
)
|
136 |
+
else:
|
137 |
+
assert self.channels == self.out_channels
|
138 |
+
self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
|
139 |
+
|
140 |
+
def forward(self, x):
|
141 |
+
assert x.shape[1] == self.channels
|
142 |
+
return self.op(x)
|
143 |
+
|
144 |
+
|
145 |
+
class ResBlock(TimestepBlock):
|
146 |
+
"""
|
147 |
+
A residual block that can optionally change the number of channels.
|
148 |
+
|
149 |
+
:param channels: the number of input channels.
|
150 |
+
:param emb_channels: the number of timestep embedding channels.
|
151 |
+
:param dropout: the rate of dropout.
|
152 |
+
:param out_channels: if specified, the number of out channels.
|
153 |
+
:param use_conv: if True and out_channels is specified, use a spatial
|
154 |
+
convolution instead of a smaller 1x1 convolution to change the
|
155 |
+
channels in the skip connection.
|
156 |
+
:param dims: determines if the signal is 1D, 2D, or 3D.
|
157 |
+
:param use_checkpoint: if True, use gradient checkpointing on this module.
|
158 |
+
:param up: if True, use this block for upsampling.
|
159 |
+
:param down: if True, use this block for downsampling.
|
160 |
+
"""
|
161 |
+
|
162 |
+
def __init__(
|
163 |
+
self,
|
164 |
+
channels,
|
165 |
+
emb_channels,
|
166 |
+
dropout,
|
167 |
+
out_channels=None,
|
168 |
+
use_conv=False,
|
169 |
+
use_scale_shift_norm=False,
|
170 |
+
dims=2,
|
171 |
+
use_checkpoint=False,
|
172 |
+
up=False,
|
173 |
+
down=False,
|
174 |
+
):
|
175 |
+
super().__init__()
|
176 |
+
self.channels = channels
|
177 |
+
self.emb_channels = emb_channels
|
178 |
+
self.dropout = dropout
|
179 |
+
self.out_channels = out_channels or channels
|
180 |
+
self.use_conv = use_conv
|
181 |
+
self.use_checkpoint = use_checkpoint
|
182 |
+
self.use_scale_shift_norm = use_scale_shift_norm
|
183 |
+
|
184 |
+
self.in_layers = nn.Sequential(
|
185 |
+
normalization(channels),
|
186 |
+
nn.SiLU(),
|
187 |
+
conv_nd(dims, channels, self.out_channels, 3, padding=1),
|
188 |
+
)
|
189 |
+
|
190 |
+
self.updown = up or down
|
191 |
+
|
192 |
+
if up:
|
193 |
+
self.h_upd = Upsample(channels, False, dims)
|
194 |
+
self.x_upd = Upsample(channels, False, dims)
|
195 |
+
elif down:
|
196 |
+
self.h_upd = Downsample(channels, False, dims)
|
197 |
+
self.x_upd = Downsample(channels, False, dims)
|
198 |
+
else:
|
199 |
+
self.h_upd = self.x_upd = nn.Identity()
|
200 |
+
|
201 |
+
self.emb_layers = nn.Sequential(
|
202 |
+
nn.SiLU(),
|
203 |
+
linear(
|
204 |
+
emb_channels,
|
205 |
+
2 * self.out_channels if use_scale_shift_norm else self.out_channels,
|
206 |
+
),
|
207 |
+
)
|
208 |
+
self.out_layers = nn.Sequential(
|
209 |
+
normalization(self.out_channels),
|
210 |
+
nn.SiLU(),
|
211 |
+
nn.Dropout(p=dropout),
|
212 |
+
zero_module(
|
213 |
+
conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)
|
214 |
+
),
|
215 |
+
)
|
216 |
+
|
217 |
+
if self.out_channels == channels:
|
218 |
+
self.skip_connection = nn.Identity()
|
219 |
+
elif use_conv:
|
220 |
+
self.skip_connection = conv_nd(
|
221 |
+
dims, channels, self.out_channels, 3, padding=1
|
222 |
+
)
|
223 |
+
else:
|
224 |
+
self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
|
225 |
+
|
226 |
+
def forward(self, x, emb):
|
227 |
+
"""
|
228 |
+
Apply the block to a Tensor, conditioned on a timestep embedding.
|
229 |
+
|
230 |
+
:param x: an [N x C x ...] Tensor of features.
|
231 |
+
:param emb: an [N x emb_channels] Tensor of timestep embeddings.
|
232 |
+
:return: an [N x C x ...] Tensor of outputs.
|
233 |
+
"""
|
234 |
+
return checkpoint(
|
235 |
+
self._forward, (x, emb), self.parameters(), self.use_checkpoint
|
236 |
+
)
|
237 |
+
|
238 |
+
def _forward(self, x, emb):
|
239 |
+
if self.updown:
|
240 |
+
in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
|
241 |
+
h = in_rest(x)
|
242 |
+
h = self.h_upd(h)
|
243 |
+
x = self.x_upd(x)
|
244 |
+
h = in_conv(h)
|
245 |
+
else:
|
246 |
+
h = self.in_layers(x)
|
247 |
+
emb_out = self.emb_layers(emb).type(h.dtype)
|
248 |
+
while len(emb_out.shape) < len(h.shape):
|
249 |
+
emb_out = emb_out[..., None]
|
250 |
+
if self.use_scale_shift_norm:
|
251 |
+
out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
|
252 |
+
scale, shift = torch.chunk(emb_out, 2, dim=1)
|
253 |
+
h = out_norm(h) * (1 + scale) + shift
|
254 |
+
h = out_rest(h)
|
255 |
+
else:
|
256 |
+
h = h + emb_out
|
257 |
+
h = self.out_layers(h)
|
258 |
+
return self.skip_connection(x) + h
|
259 |
+
|
260 |
+
|
261 |
+
class AttentionBlock(nn.Module):
|
262 |
+
"""
|
263 |
+
An attention block that allows spatial positions to attend to each other.
|
264 |
+
|
265 |
+
Originally ported from here, but adapted to the N-d case.
|
266 |
+
https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
|
267 |
+
"""
|
268 |
+
|
269 |
+
def __init__(
|
270 |
+
self,
|
271 |
+
channels,
|
272 |
+
num_heads=1,
|
273 |
+
num_head_channels=-1,
|
274 |
+
use_checkpoint=False,
|
275 |
+
use_new_attention_order=False,
|
276 |
+
):
|
277 |
+
super().__init__()
|
278 |
+
self.channels = channels
|
279 |
+
if num_head_channels == -1:
|
280 |
+
self.num_heads = num_heads
|
281 |
+
else:
|
282 |
+
assert (
|
283 |
+
channels % num_head_channels == 0
|
284 |
+
), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"
|
285 |
+
self.num_heads = channels // num_head_channels
|
286 |
+
self.use_checkpoint = use_checkpoint
|
287 |
+
self.norm = normalization(channels)
|
288 |
+
self.qkv = conv_nd(1, channels, channels * 3, 1)
|
289 |
+
if use_new_attention_order:
|
290 |
+
# split qkv before split heads
|
291 |
+
self.attention = QKVAttention(self.num_heads)
|
292 |
+
else:
|
293 |
+
# split heads before split qkv
|
294 |
+
self.attention = QKVAttentionLegacy(self.num_heads)
|
295 |
+
|
296 |
+
self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
|
297 |
+
|
298 |
+
def forward(self, x):
|
299 |
+
return checkpoint(self._forward, (x,), self.parameters(), True)
|
300 |
+
|
301 |
+
def _forward(self, x):
|
302 |
+
b, c, *spatial = x.shape
|
303 |
+
x = x.reshape(b, c, -1)
|
304 |
+
qkv = self.qkv(self.norm(x))
|
305 |
+
h = self.attention(qkv)
|
306 |
+
h = self.proj_out(h)
|
307 |
+
return (x + h).reshape(b, c, *spatial)
|
308 |
+
|
309 |
+
|
310 |
+
def count_flops_attn(model, _x, y):
|
311 |
+
"""
|
312 |
+
A counter for the `thop` package to count the operations in an
|
313 |
+
attention operation.
|
314 |
+
Meant to be used like:
|
315 |
+
macs, params = thop.profile(
|
316 |
+
model,
|
317 |
+
inputs=(inputs, timestamps),
|
318 |
+
custom_ops={QKVAttention: QKVAttention.count_flops},
|
319 |
+
)
|
320 |
+
"""
|
321 |
+
b, c, *spatial = y[0].shape
|
322 |
+
num_spatial = int(np.prod(spatial))
|
323 |
+
# We perform two matmuls with the same number of ops.
|
324 |
+
# The first computes the weight matrix, the second computes
|
325 |
+
# the combination of the value vectors.
|
326 |
+
matmul_ops = 2 * b * (num_spatial ** 2) * c
|
327 |
+
model.total_ops += torch.DoubleTensor([matmul_ops])
|
328 |
+
|
329 |
+
|
330 |
+
class QKVAttentionLegacy(nn.Module):
|
331 |
+
"""
|
332 |
+
A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
|
333 |
+
"""
|
334 |
+
|
335 |
+
def __init__(self, n_heads):
|
336 |
+
super().__init__()
|
337 |
+
self.n_heads = n_heads
|
338 |
+
|
339 |
+
def forward(self, qkv):
|
340 |
+
"""
|
341 |
+
Apply QKV attention.
|
342 |
+
|
343 |
+
:param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.
|
344 |
+
:return: an [N x (H * C) x T] tensor after attention.
|
345 |
+
"""
|
346 |
+
bs, width, length = qkv.shape
|
347 |
+
assert width % (3 * self.n_heads) == 0
|
348 |
+
ch = width // (3 * self.n_heads)
|
349 |
+
q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
|
350 |
+
scale = 1 / math.sqrt(math.sqrt(ch))
|
351 |
+
weight = torch.einsum(
|
352 |
+
"bct,bcs->bts", q * scale, k * scale
|
353 |
+
) # More stable with f16 than dividing afterwards
|
354 |
+
weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
|
355 |
+
a = torch.einsum("bts,bcs->bct", weight, v)
|
356 |
+
return a.reshape(bs, -1, length)
|
357 |
+
|
358 |
+
@staticmethod
|
359 |
+
def count_flops(model, _x, y):
|
360 |
+
return count_flops_attn(model, _x, y)
|
361 |
+
|
362 |
+
|
363 |
+
class QKVAttention(nn.Module):
|
364 |
+
"""
|
365 |
+
A module which performs QKV attention and splits in a different order.
|
366 |
+
"""
|
367 |
+
|
368 |
+
def __init__(self, n_heads):
|
369 |
+
super().__init__()
|
370 |
+
self.n_heads = n_heads
|
371 |
+
|
372 |
+
def forward(self, qkv):
|
373 |
+
"""
|
374 |
+
Apply QKV attention.
|
375 |
+
|
376 |
+
:param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
|
377 |
+
:return: an [N x (H * C) x T] tensor after attention.
|
378 |
+
"""
|
379 |
+
bs, width, length = qkv.shape
|
380 |
+
assert width % (3 * self.n_heads) == 0
|
381 |
+
ch = width // (3 * self.n_heads)
|
382 |
+
q, k, v = qkv.chunk(3, dim=1)
|
383 |
+
scale = 1 / math.sqrt(math.sqrt(ch))
|
384 |
+
weight = torch.einsum(
|
385 |
+
"bct,bcs->bts",
|
386 |
+
(q * scale).view(bs * self.n_heads, ch, length),
|
387 |
+
(k * scale).view(bs * self.n_heads, ch, length),
|
388 |
+
) # More stable with f16 than dividing afterwards
|
389 |
+
weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
|
390 |
+
a = torch.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
|
391 |
+
return a.reshape(bs, -1, length)
|
392 |
+
|
393 |
+
@staticmethod
|
394 |
+
def count_flops(model, _x, y):
|
395 |
+
return count_flops_attn(model, _x, y)
|
396 |
+
|
397 |
+
class UNetModel(nn.Module):
|
398 |
+
"""
|
399 |
+
The full UNet model with attention and timestep embedding.
|
400 |
+
|
401 |
+
:param in_channels: channels in the input Tensor.
|
402 |
+
:param model_channels: base channel count for the model.
|
403 |
+
:param out_channels: channels in the output Tensor.
|
404 |
+
:param num_res_blocks: number of residual blocks per downsample.
|
405 |
+
:param attention_resolutions: a collection of downsample rates at which
|
406 |
+
attention will take place. May be a set, list, or tuple.
|
407 |
+
For example, if this contains 4, then at 4x downsampling, attention
|
408 |
+
will be used.
|
409 |
+
:param dropout: the dropout probability.
|
410 |
+
:param channel_mult: channel multiplier for each level of the UNet.
|
411 |
+
:param conv_resample: if True, use learned convolutions for upsampling and
|
412 |
+
downsampling.
|
413 |
+
:param dims: determines if the signal is 1D, 2D, or 3D.
|
414 |
+
:param num_classes: if specified (as an int), then this model will be
|
415 |
+
class-conditional with `num_classes` classes.
|
416 |
+
:param use_checkpoint: use gradient checkpointing to reduce memory usage.
|
417 |
+
:param num_heads: the number of attention heads in each attention layer.
|
418 |
+
:param num_heads_channels: if specified, ignore num_heads and instead use
|
419 |
+
a fixed channel width per attention head.
|
420 |
+
:param num_heads_upsample: works with num_heads to set a different number
|
421 |
+
of heads for upsampling. Deprecated.
|
422 |
+
:param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
|
423 |
+
:param resblock_updown: use residual blocks for up/downsampling.
|
424 |
+
:param use_new_attention_order: use a different attention pattern for potentially
|
425 |
+
increased efficiency.
|
426 |
+
"""
|
427 |
+
|
428 |
+
def __init__(
|
429 |
+
self,
|
430 |
+
in_channels,
|
431 |
+
out_channels,
|
432 |
+
model_channels,
|
433 |
+
num_res_blocks,
|
434 |
+
attention_resolutions,
|
435 |
+
dropout=0,
|
436 |
+
channel_mult=(1, 2, 4, 8),
|
437 |
+
conv_resample=True,
|
438 |
+
dims=2,
|
439 |
+
num_classes=None,
|
440 |
+
use_checkpoint=False,
|
441 |
+
use_fp16=False,
|
442 |
+
num_heads=1,
|
443 |
+
num_head_channels=-1,
|
444 |
+
num_heads_upsample=-1,
|
445 |
+
use_scale_shift_norm=False,
|
446 |
+
resblock_updown=False,
|
447 |
+
use_new_attention_order=False,
|
448 |
+
):
|
449 |
+
super().__init__()
|
450 |
+
|
451 |
+
if num_heads_upsample == -1:
|
452 |
+
num_heads_upsample = num_heads
|
453 |
+
|
454 |
+
self.in_channels = in_channels
|
455 |
+
self.model_channels = model_channels
|
456 |
+
self.out_channels = out_channels
|
457 |
+
self.num_res_blocks = num_res_blocks
|
458 |
+
self.attention_resolutions = attention_resolutions
|
459 |
+
self.dropout = dropout
|
460 |
+
self.channel_mult = channel_mult
|
461 |
+
self.conv_resample = conv_resample
|
462 |
+
self.num_classes = num_classes
|
463 |
+
self.use_checkpoint = use_checkpoint
|
464 |
+
self.dtype = torch.float16 if use_fp16 else torch.float32
|
465 |
+
self.num_heads = num_heads
|
466 |
+
self.num_head_channels = num_head_channels
|
467 |
+
self.num_heads_upsample = num_heads_upsample
|
468 |
+
|
469 |
+
time_embed_dim = model_channels * 4
|
470 |
+
self.dt_embed = nn.Sequential(
|
471 |
+
linear(model_channels, time_embed_dim),
|
472 |
+
nn.SiLU(),
|
473 |
+
linear(time_embed_dim, time_embed_dim),
|
474 |
+
)
|
475 |
+
|
476 |
+
if self.num_classes is not None:
|
477 |
+
self.label_emb = nn.Embedding(num_classes, time_embed_dim)
|
478 |
+
|
479 |
+
ch = input_ch = int(channel_mult[0] * model_channels)
|
480 |
+
self.input_blocks = nn.ModuleList(
|
481 |
+
[TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))]
|
482 |
+
)
|
483 |
+
self._feature_size = ch
|
484 |
+
input_block_chans = [ch]
|
485 |
+
ds = 1
|
486 |
+
for level, mult in enumerate(channel_mult):
|
487 |
+
for _ in range(num_res_blocks):
|
488 |
+
layers = [
|
489 |
+
ResBlock(
|
490 |
+
ch,
|
491 |
+
time_embed_dim,
|
492 |
+
dropout,
|
493 |
+
out_channels=int(mult * model_channels),
|
494 |
+
dims=dims,
|
495 |
+
use_checkpoint=use_checkpoint,
|
496 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
497 |
+
)
|
498 |
+
]
|
499 |
+
ch = int(mult * model_channels)
|
500 |
+
if ds in attention_resolutions:
|
501 |
+
layers.append(
|
502 |
+
AttentionBlock(
|
503 |
+
ch,
|
504 |
+
use_checkpoint=use_checkpoint,
|
505 |
+
num_heads=num_heads,
|
506 |
+
num_head_channels=num_head_channels,
|
507 |
+
use_new_attention_order=use_new_attention_order,
|
508 |
+
)
|
509 |
+
)
|
510 |
+
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
511 |
+
self._feature_size += ch
|
512 |
+
input_block_chans.append(ch)
|
513 |
+
if level != len(channel_mult) - 1:
|
514 |
+
out_ch = ch
|
515 |
+
self.input_blocks.append(
|
516 |
+
TimestepEmbedSequential(
|
517 |
+
ResBlock(
|
518 |
+
ch,
|
519 |
+
time_embed_dim,
|
520 |
+
dropout,
|
521 |
+
out_channels=out_ch,
|
522 |
+
dims=dims,
|
523 |
+
use_checkpoint=use_checkpoint,
|
524 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
525 |
+
down=True,
|
526 |
+
)
|
527 |
+
if resblock_updown
|
528 |
+
else Downsample(
|
529 |
+
ch, conv_resample, dims=dims, out_channels=out_ch
|
530 |
+
)
|
531 |
+
)
|
532 |
+
)
|
533 |
+
ch = out_ch
|
534 |
+
input_block_chans.append(ch)
|
535 |
+
ds *= 2
|
536 |
+
self._feature_size += ch
|
537 |
+
|
538 |
+
self.middle_block = TimestepEmbedSequential(
|
539 |
+
ResBlock(
|
540 |
+
ch,
|
541 |
+
time_embed_dim,
|
542 |
+
dropout,
|
543 |
+
dims=dims,
|
544 |
+
use_checkpoint=use_checkpoint,
|
545 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
546 |
+
),
|
547 |
+
AttentionBlock(
|
548 |
+
ch,
|
549 |
+
use_checkpoint=use_checkpoint,
|
550 |
+
num_heads=num_heads,
|
551 |
+
num_head_channels=num_head_channels,
|
552 |
+
use_new_attention_order=use_new_attention_order,
|
553 |
+
),
|
554 |
+
ResBlock(
|
555 |
+
ch,
|
556 |
+
time_embed_dim,
|
557 |
+
dropout,
|
558 |
+
dims=dims,
|
559 |
+
use_checkpoint=use_checkpoint,
|
560 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
561 |
+
),
|
562 |
+
)
|
563 |
+
self._feature_size += ch
|
564 |
+
|
565 |
+
self.output_blocks = nn.ModuleList([])
|
566 |
+
for level, mult in list(enumerate(channel_mult))[::-1]:
|
567 |
+
for i in range(num_res_blocks + 1):
|
568 |
+
ich = input_block_chans.pop()
|
569 |
+
layers = [
|
570 |
+
ResBlock(
|
571 |
+
ch + ich,
|
572 |
+
time_embed_dim,
|
573 |
+
dropout,
|
574 |
+
out_channels=int(model_channels * mult),
|
575 |
+
dims=dims,
|
576 |
+
use_checkpoint=use_checkpoint,
|
577 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
578 |
+
)
|
579 |
+
]
|
580 |
+
ch = int(model_channels * mult)
|
581 |
+
if ds in attention_resolutions:
|
582 |
+
layers.append(
|
583 |
+
AttentionBlock(
|
584 |
+
ch,
|
585 |
+
use_checkpoint=use_checkpoint,
|
586 |
+
num_heads=num_heads_upsample,
|
587 |
+
num_head_channels=num_head_channels,
|
588 |
+
use_new_attention_order=use_new_attention_order,
|
589 |
+
)
|
590 |
+
)
|
591 |
+
if level and i == num_res_blocks:
|
592 |
+
out_ch = ch
|
593 |
+
layers.append(
|
594 |
+
ResBlock(
|
595 |
+
ch,
|
596 |
+
time_embed_dim,
|
597 |
+
dropout,
|
598 |
+
out_channels=out_ch,
|
599 |
+
dims=dims,
|
600 |
+
use_checkpoint=use_checkpoint,
|
601 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
602 |
+
up=True,
|
603 |
+
)
|
604 |
+
if resblock_updown
|
605 |
+
else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
|
606 |
+
)
|
607 |
+
ds //= 2
|
608 |
+
self.output_blocks.append(TimestepEmbedSequential(*layers))
|
609 |
+
self._feature_size += ch
|
610 |
+
|
611 |
+
self.out = nn.Sequential(
|
612 |
+
normalization(ch),
|
613 |
+
nn.SiLU(),
|
614 |
+
zero_module(conv_nd(dims, input_ch, out_channels, 3, padding=1)),
|
615 |
+
)
|
616 |
+
|
617 |
+
def convert_to_fp16(self):
|
618 |
+
"""
|
619 |
+
Convert the torso of the model to float16.
|
620 |
+
"""
|
621 |
+
self.input_blocks.apply(convert_module_to_f16)
|
622 |
+
self.middle_block.apply(convert_module_to_f16)
|
623 |
+
self.output_blocks.apply(convert_module_to_f16)
|
624 |
+
|
625 |
+
def convert_to_fp32(self):
|
626 |
+
"""
|
627 |
+
Convert the torso of the model to float32.
|
628 |
+
"""
|
629 |
+
self.input_blocks.apply(convert_module_to_f32)
|
630 |
+
self.middle_block.apply(convert_module_to_f32)
|
631 |
+
self.output_blocks.apply(convert_module_to_f32)
|
632 |
+
|
633 |
+
def forward(self, x, dt, y=None):
|
634 |
+
"""
|
635 |
+
Apply the model to an input batch.
|
636 |
+
|
637 |
+
:param x: an [N x C x ...] Tensor of inputs.
|
638 |
+
:param timesteps: a 1-D batch of timesteps.
|
639 |
+
:param y: an [N] Tensor of labels, if class-conditional.
|
640 |
+
:return: an [N x C x ...] Tensor of outputs.
|
641 |
+
"""
|
642 |
+
assert (y is not None) == (
|
643 |
+
self.num_classes is not None
|
644 |
+
), "must specify y if and only if the model is class-conditional"
|
645 |
+
|
646 |
+
hs = []
|
647 |
+
emb = self.dt_embed(timestep_embedding(dt, self.model_channels))
|
648 |
+
|
649 |
+
if self.num_classes is not None:
|
650 |
+
assert y.shape == (x.shape[0],)
|
651 |
+
emb = emb + self.label_emb(y)
|
652 |
+
|
653 |
+
h = x.type(self.dtype)
|
654 |
+
for module in self.input_blocks:
|
655 |
+
h = module(h, emb)
|
656 |
+
hs.append(h)
|
657 |
+
h = self.middle_block(h, emb)
|
658 |
+
for module in self.output_blocks:
|
659 |
+
h = torch.cat([h, hs.pop()], dim=1)
|
660 |
+
h = module(h, emb)
|
661 |
+
h = h.type(x.dtype)
|
662 |
+
return self.out(h)
|
663 |
+
|
664 |
+
|
665 |
+
|
666 |
+
class SkippedUNetModel(nn.Module):
|
667 |
+
"""
|
668 |
+
The full UNet model with attention and timestep embedding.
|
669 |
+
|
670 |
+
:param in_channels: channels in the input Tensor.
|
671 |
+
:param model_channels: base channel count for the model.
|
672 |
+
:param out_channels: channels in the output Tensor.
|
673 |
+
:param num_res_blocks: number of residual blocks per downsample.
|
674 |
+
:param attention_resolutions: a collection of downsample rates at which
|
675 |
+
attention will take place. May be a set, list, or tuple.
|
676 |
+
For example, if this contains 4, then at 4x downsampling, attention
|
677 |
+
will be used.
|
678 |
+
:param dropout: the dropout probability.
|
679 |
+
:param channel_mult: channel multiplier for each level of the UNet.
|
680 |
+
:param conv_resample: if True, use learned convolutions for upsampling and
|
681 |
+
downsampling.
|
682 |
+
:param dims: determines if the signal is 1D, 2D, or 3D.
|
683 |
+
:param num_classes: if specified (as an int), then this model will be
|
684 |
+
class-conditional with `num_classes` classes.
|
685 |
+
:param use_checkpoint: use gradient checkpointing to reduce memory usage.
|
686 |
+
:param num_heads: the number of attention heads in each attention layer.
|
687 |
+
:param num_heads_channels: if specified, ignore num_heads and instead use
|
688 |
+
a fixed channel width per attention head.
|
689 |
+
:param num_heads_upsample: works with num_heads to set a different number
|
690 |
+
of heads for upsampling. Deprecated.
|
691 |
+
:param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
|
692 |
+
:param resblock_updown: use residual blocks for up/downsampling.
|
693 |
+
:param use_new_attention_order: use a different attention pattern for potentially
|
694 |
+
increased efficiency.
|
695 |
+
"""
|
696 |
+
|
697 |
+
def __init__(
|
698 |
+
self,
|
699 |
+
in_channels,
|
700 |
+
out_channels,
|
701 |
+
model_channels,
|
702 |
+
num_res_blocks,
|
703 |
+
attention_resolutions,
|
704 |
+
dropout=0,
|
705 |
+
channel_mult=(1, 2, 4, 8),
|
706 |
+
conv_resample=True,
|
707 |
+
dims=2,
|
708 |
+
num_classes=None,
|
709 |
+
use_checkpoint=False,
|
710 |
+
use_fp16=False,
|
711 |
+
num_heads=1,
|
712 |
+
num_head_channels=-1,
|
713 |
+
num_heads_upsample=-1,
|
714 |
+
use_scale_shift_norm=False,
|
715 |
+
resblock_updown=False,
|
716 |
+
use_new_attention_order=False,
|
717 |
+
):
|
718 |
+
super().__init__()
|
719 |
+
|
720 |
+
if num_heads_upsample == -1:
|
721 |
+
num_heads_upsample = num_heads
|
722 |
+
|
723 |
+
self.in_channels = in_channels
|
724 |
+
self.model_channels = model_channels
|
725 |
+
self.out_channels = out_channels
|
726 |
+
self.num_res_blocks = num_res_blocks
|
727 |
+
self.attention_resolutions = attention_resolutions
|
728 |
+
self.dropout = dropout
|
729 |
+
self.channel_mult = channel_mult
|
730 |
+
self.conv_resample = conv_resample
|
731 |
+
self.num_classes = num_classes
|
732 |
+
self.use_checkpoint = use_checkpoint
|
733 |
+
self.dtype = torch.float16 if use_fp16 else torch.float32
|
734 |
+
self.num_heads = num_heads
|
735 |
+
self.num_head_channels = num_head_channels
|
736 |
+
self.num_heads_upsample = num_heads_upsample
|
737 |
+
|
738 |
+
time_embed_dim = model_channels * 4
|
739 |
+
self.dt_embed = nn.Sequential(
|
740 |
+
linear(model_channels, time_embed_dim),
|
741 |
+
nn.SiLU(),
|
742 |
+
linear(time_embed_dim, time_embed_dim),
|
743 |
+
)
|
744 |
+
|
745 |
+
if self.num_classes is not None:
|
746 |
+
self.label_emb = nn.Embedding(num_classes, time_embed_dim)
|
747 |
+
|
748 |
+
ch = input_ch = int(channel_mult[0] * model_channels)
|
749 |
+
self.input_blocks = nn.ModuleList(
|
750 |
+
[TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))]
|
751 |
+
)
|
752 |
+
self._feature_size = ch
|
753 |
+
input_block_chans = [ch]
|
754 |
+
ds = 1
|
755 |
+
for level, mult in enumerate(channel_mult):
|
756 |
+
for _ in range(num_res_blocks):
|
757 |
+
layers = [
|
758 |
+
ResBlock(
|
759 |
+
ch,
|
760 |
+
time_embed_dim,
|
761 |
+
dropout,
|
762 |
+
out_channels=int(mult * model_channels),
|
763 |
+
dims=dims,
|
764 |
+
use_checkpoint=use_checkpoint,
|
765 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
766 |
+
)
|
767 |
+
]
|
768 |
+
ch = int(mult * model_channels)
|
769 |
+
if ds in attention_resolutions:
|
770 |
+
layers.append(
|
771 |
+
AttentionBlock(
|
772 |
+
ch,
|
773 |
+
use_checkpoint=use_checkpoint,
|
774 |
+
num_heads=num_heads,
|
775 |
+
num_head_channels=num_head_channels,
|
776 |
+
use_new_attention_order=use_new_attention_order,
|
777 |
+
)
|
778 |
+
)
|
779 |
+
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
780 |
+
self._feature_size += ch
|
781 |
+
input_block_chans.append(ch)
|
782 |
+
if level != len(channel_mult) - 1:
|
783 |
+
out_ch = ch
|
784 |
+
self.input_blocks.append(
|
785 |
+
TimestepEmbedSequential(
|
786 |
+
ResBlock(
|
787 |
+
ch,
|
788 |
+
time_embed_dim,
|
789 |
+
dropout,
|
790 |
+
out_channels=out_ch,
|
791 |
+
dims=dims,
|
792 |
+
use_checkpoint=use_checkpoint,
|
793 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
794 |
+
down=True,
|
795 |
+
)
|
796 |
+
if resblock_updown
|
797 |
+
else Downsample(
|
798 |
+
ch, conv_resample, dims=dims, out_channels=out_ch
|
799 |
+
)
|
800 |
+
)
|
801 |
+
)
|
802 |
+
ch = out_ch
|
803 |
+
input_block_chans.append(ch)
|
804 |
+
ds *= 2
|
805 |
+
self._feature_size += ch
|
806 |
+
|
807 |
+
self.middle_block = TimestepEmbedSequential(
|
808 |
+
ResBlock(
|
809 |
+
ch,
|
810 |
+
time_embed_dim,
|
811 |
+
dropout,
|
812 |
+
dims=dims,
|
813 |
+
use_checkpoint=use_checkpoint,
|
814 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
815 |
+
),
|
816 |
+
AttentionBlock(
|
817 |
+
ch,
|
818 |
+
use_checkpoint=use_checkpoint,
|
819 |
+
num_heads=num_heads,
|
820 |
+
num_head_channels=num_head_channels,
|
821 |
+
use_new_attention_order=use_new_attention_order,
|
822 |
+
),
|
823 |
+
ResBlock(
|
824 |
+
ch,
|
825 |
+
time_embed_dim,
|
826 |
+
dropout,
|
827 |
+
dims=dims,
|
828 |
+
use_checkpoint=use_checkpoint,
|
829 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
830 |
+
),
|
831 |
+
)
|
832 |
+
self._feature_size += ch
|
833 |
+
|
834 |
+
self.output_blocks = nn.ModuleList([])
|
835 |
+
for level, mult in list(enumerate(channel_mult))[::-1]:
|
836 |
+
for i in range(num_res_blocks + 1):
|
837 |
+
ich = input_block_chans.pop()
|
838 |
+
layers = [
|
839 |
+
ResBlock(
|
840 |
+
ch + ich,
|
841 |
+
time_embed_dim,
|
842 |
+
dropout,
|
843 |
+
out_channels=int(model_channels * mult),
|
844 |
+
dims=dims,
|
845 |
+
use_checkpoint=use_checkpoint,
|
846 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
847 |
+
)
|
848 |
+
]
|
849 |
+
ch = int(model_channels * mult)
|
850 |
+
if ds in attention_resolutions:
|
851 |
+
layers.append(
|
852 |
+
AttentionBlock(
|
853 |
+
ch,
|
854 |
+
use_checkpoint=use_checkpoint,
|
855 |
+
num_heads=num_heads_upsample,
|
856 |
+
num_head_channels=num_head_channels,
|
857 |
+
use_new_attention_order=use_new_attention_order,
|
858 |
+
)
|
859 |
+
)
|
860 |
+
if level and i == num_res_blocks:
|
861 |
+
out_ch = ch
|
862 |
+
layers.append(
|
863 |
+
ResBlock(
|
864 |
+
ch,
|
865 |
+
time_embed_dim,
|
866 |
+
dropout,
|
867 |
+
out_channels=out_ch,
|
868 |
+
dims=dims,
|
869 |
+
use_checkpoint=use_checkpoint,
|
870 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
871 |
+
up=True,
|
872 |
+
)
|
873 |
+
if resblock_updown
|
874 |
+
else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
|
875 |
+
)
|
876 |
+
ds //= 2
|
877 |
+
self.output_blocks.append(TimestepEmbedSequential(*layers))
|
878 |
+
self._feature_size += ch
|
879 |
+
|
880 |
+
self.out = nn.Sequential(
|
881 |
+
normalization(ch),
|
882 |
+
nn.SiLU(),
|
883 |
+
zero_module(conv_nd(dims, input_ch, out_channels, 3, padding=1)),
|
884 |
+
)
|
885 |
+
|
886 |
+
self.emb_h_layer = nn.Sequential(
|
887 |
+
linear(64 * 64 * 3, time_embed_dim),
|
888 |
+
nn.SiLU(),
|
889 |
+
linear(time_embed_dim, time_embed_dim),
|
890 |
+
)
|
891 |
+
|
892 |
+
def convert_to_fp16(self):
|
893 |
+
"""
|
894 |
+
Convert the torso of the model to float16.
|
895 |
+
"""
|
896 |
+
self.input_blocks.apply(convert_module_to_f16)
|
897 |
+
self.middle_block.apply(convert_module_to_f16)
|
898 |
+
self.output_blocks.apply(convert_module_to_f16)
|
899 |
+
|
900 |
+
def convert_to_fp32(self):
|
901 |
+
"""
|
902 |
+
Convert the torso of the model to float32.
|
903 |
+
"""
|
904 |
+
self.input_blocks.apply(convert_module_to_f32)
|
905 |
+
self.middle_block.apply(convert_module_to_f32)
|
906 |
+
self.output_blocks.apply(convert_module_to_f32)
|
907 |
+
|
908 |
+
def forward(self, x, dt, shadow=None, **kwargs):
|
909 |
+
"""
|
910 |
+
Apply the model to an input batch.
|
911 |
+
|
912 |
+
:param x: an [N x C x ...] Tensor of inputs.
|
913 |
+
:param timesteps: a 1-D batch of timesteps.
|
914 |
+
:param y: an [N] Tensor of labels, if class-conditional.
|
915 |
+
:return: an [N x C x ...] Tensor of outputs.
|
916 |
+
"""
|
917 |
+
|
918 |
+
hs = []
|
919 |
+
emb = self.dt_embed(timestep_embedding(dt, self.model_channels))
|
920 |
+
emb_h = F.adaptive_avg_pool2d(x, (64, 64)).view(x.shape[0], -1)
|
921 |
+
emb_h = self.emb_h_layer(emb_h)
|
922 |
+
emb = emb + emb_h
|
923 |
+
|
924 |
+
x = torch.cat([x, shadow], dim=1)
|
925 |
+
|
926 |
+
h = x.type(self.dtype)
|
927 |
+
for module in self.input_blocks:
|
928 |
+
h = module(h, emb)
|
929 |
+
hs.append(h)
|
930 |
+
h = self.middle_block(h, emb)
|
931 |
+
for module in self.output_blocks:
|
932 |
+
h = torch.cat([h, hs.pop()], dim=1)
|
933 |
+
h = module(h, emb)
|
934 |
+
h = h.type(x.dtype)
|
935 |
+
return self.out(h)
|
936 |
+
|
937 |
+
|
938 |
+
class ConditionalUNetModel(UNetModel):
|
939 |
+
def __init__(self, in_channels, *args, **kwargs):
|
940 |
+
super().__init__(in_channels * 2, *args, **kwargs)
|
941 |
+
|
942 |
+
def forward(self, x, timesteps, shadow=None, **kwargs):
|
943 |
+
x = torch.cat([x, shadow], dim=1)
|
944 |
+
return super().forward(x, timesteps, **kwargs)
|
945 |
+
|
946 |
+
|
947 |
+
class ConditionalMaskUNetModel(UNetModel):
|
948 |
+
def __init__(self, in_channels, out_channels, *args, **kwargs):
|
949 |
+
super().__init__(in_channels * 3, out_channels, *args, **kwargs)
|
950 |
+
|
951 |
+
def forward(self, x, timesteps, shadow=None, mask=None, **kwargs):
|
952 |
+
x = torch.cat([x, shadow, mask], dim=1)
|
953 |
+
x = super().forward(x, timesteps, **kwargs)
|
954 |
+
return x
|
955 |
+
|
956 |
+
|
957 |
+
class ConditionalLatentUNetModel(UNetModel):
|
958 |
+
def __init__(self, in_channels, out_channels, *args, **kwargs):
|
959 |
+
super().__init__(in_channels, out_channels, *args, **kwargs)
|
960 |
+
|
961 |
+
def forward(self, x, timesteps, latent=None, **kwargs):
|
962 |
+
x = torch.cat([x, latent], dim=1)
|
963 |
+
x = super().forward(x, timesteps, **kwargs)
|
964 |
+
return x
|
965 |
+
|
966 |
+
|
967 |
+
|
968 |
+
class DensePosteriorConditionalUNet(nn.Module):
|
969 |
+
def __init__(
|
970 |
+
self,
|
971 |
+
in_channels,
|
972 |
+
out_channels,
|
973 |
+
model_channels,
|
974 |
+
num_res_blocks,
|
975 |
+
attention_resolutions,
|
976 |
+
dropout=0,
|
977 |
+
channel_mult=(1, 2, 4, 8),
|
978 |
+
conv_resample=True,
|
979 |
+
dims=2,
|
980 |
+
num_classes=None,
|
981 |
+
use_checkpoint=False,
|
982 |
+
use_fp16=False,
|
983 |
+
num_heads=1,
|
984 |
+
num_head_channels=-1,
|
985 |
+
num_heads_upsample=-1,
|
986 |
+
use_scale_shift_norm=False,
|
987 |
+
resblock_updown=False,
|
988 |
+
use_new_attention_order=False,
|
989 |
+
):
|
990 |
+
super().__init__()
|
991 |
+
|
992 |
+
if num_heads_upsample == -1:
|
993 |
+
num_heads_upsample = num_heads
|
994 |
+
|
995 |
+
self.in_channels = in_channels
|
996 |
+
self.model_channels = model_channels
|
997 |
+
self.out_channels = out_channels
|
998 |
+
self.num_res_blocks = num_res_blocks
|
999 |
+
self.attention_resolutions = attention_resolutions
|
1000 |
+
self.dropout = dropout
|
1001 |
+
self.channel_mult = channel_mult
|
1002 |
+
self.conv_resample = conv_resample
|
1003 |
+
self.num_classes = num_classes
|
1004 |
+
self.use_checkpoint = use_checkpoint
|
1005 |
+
self.dtype = torch.float16 if use_fp16 else torch.float32
|
1006 |
+
self.num_heads = num_heads
|
1007 |
+
self.num_head_channels = num_head_channels
|
1008 |
+
self.num_heads_upsample = num_heads_upsample
|
1009 |
+
|
1010 |
+
time_embed_dim = model_channels * 4
|
1011 |
+
self.dt_embed = nn.Sequential(
|
1012 |
+
linear(model_channels, time_embed_dim),
|
1013 |
+
nn.SiLU(),
|
1014 |
+
linear(time_embed_dim, time_embed_dim),
|
1015 |
+
)
|
1016 |
+
|
1017 |
+
if self.num_classes is not None:
|
1018 |
+
self.label_emb = nn.Embedding(num_classes, time_embed_dim)
|
1019 |
+
|
1020 |
+
ch = input_ch = int(channel_mult[0] * model_channels)
|
1021 |
+
self.input_blocks = nn.ModuleList(
|
1022 |
+
[TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))]
|
1023 |
+
)
|
1024 |
+
self._feature_size = ch
|
1025 |
+
input_block_chans = [ch]
|
1026 |
+
ds = 1
|
1027 |
+
for level, mult in enumerate(channel_mult):
|
1028 |
+
for _ in range(num_res_blocks):
|
1029 |
+
layers = [
|
1030 |
+
ResBlock(
|
1031 |
+
ch,
|
1032 |
+
time_embed_dim,
|
1033 |
+
dropout,
|
1034 |
+
out_channels=int(mult * model_channels),
|
1035 |
+
dims=dims,
|
1036 |
+
use_checkpoint=use_checkpoint,
|
1037 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
1038 |
+
)
|
1039 |
+
]
|
1040 |
+
ch = int(mult * model_channels)
|
1041 |
+
if ds in attention_resolutions:
|
1042 |
+
layers.append(
|
1043 |
+
AttentionBlock(
|
1044 |
+
ch,
|
1045 |
+
use_checkpoint=use_checkpoint,
|
1046 |
+
num_heads=num_heads,
|
1047 |
+
num_head_channels=num_head_channels,
|
1048 |
+
use_new_attention_order=use_new_attention_order,
|
1049 |
+
)
|
1050 |
+
)
|
1051 |
+
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
1052 |
+
self._feature_size += ch
|
1053 |
+
input_block_chans.append(ch)
|
1054 |
+
if level != len(channel_mult) - 1:
|
1055 |
+
out_ch = ch
|
1056 |
+
self.input_blocks.append(
|
1057 |
+
TimestepEmbedSequential(
|
1058 |
+
ResBlock(
|
1059 |
+
ch,
|
1060 |
+
time_embed_dim,
|
1061 |
+
dropout,
|
1062 |
+
out_channels=out_ch,
|
1063 |
+
dims=dims,
|
1064 |
+
use_checkpoint=use_checkpoint,
|
1065 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
1066 |
+
down=True,
|
1067 |
+
)
|
1068 |
+
if resblock_updown
|
1069 |
+
else Downsample(
|
1070 |
+
ch, conv_resample, dims=dims, out_channels=out_ch
|
1071 |
+
)
|
1072 |
+
)
|
1073 |
+
)
|
1074 |
+
ch = out_ch
|
1075 |
+
input_block_chans.append(ch)
|
1076 |
+
ds *= 2
|
1077 |
+
self._feature_size += ch
|
1078 |
+
|
1079 |
+
self.middle_block = TimestepEmbedSequential(
|
1080 |
+
ResBlock(
|
1081 |
+
ch,
|
1082 |
+
time_embed_dim,
|
1083 |
+
dropout,
|
1084 |
+
dims=dims,
|
1085 |
+
use_checkpoint=use_checkpoint,
|
1086 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
1087 |
+
),
|
1088 |
+
AttentionBlock(
|
1089 |
+
ch,
|
1090 |
+
use_checkpoint=use_checkpoint,
|
1091 |
+
num_heads=num_heads,
|
1092 |
+
num_head_channels=num_head_channels,
|
1093 |
+
use_new_attention_order=use_new_attention_order,
|
1094 |
+
),
|
1095 |
+
ResBlock(
|
1096 |
+
ch,
|
1097 |
+
time_embed_dim,
|
1098 |
+
dropout,
|
1099 |
+
dims=dims,
|
1100 |
+
use_checkpoint=use_checkpoint,
|
1101 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
1102 |
+
),
|
1103 |
+
)
|
1104 |
+
self._feature_size += ch
|
1105 |
+
|
1106 |
+
self.output_blocks = nn.ModuleList([])
|
1107 |
+
for level, mult in list(enumerate(channel_mult))[::-1]:
|
1108 |
+
for i in range(num_res_blocks + 1):
|
1109 |
+
ich = input_block_chans.pop()
|
1110 |
+
layers = [
|
1111 |
+
ResBlock(
|
1112 |
+
ch + ich,
|
1113 |
+
time_embed_dim,
|
1114 |
+
dropout,
|
1115 |
+
out_channels=int(model_channels * mult),
|
1116 |
+
dims=dims,
|
1117 |
+
use_checkpoint=use_checkpoint,
|
1118 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
1119 |
+
)
|
1120 |
+
]
|
1121 |
+
ch = int(model_channels * mult)
|
1122 |
+
if ds in attention_resolutions:
|
1123 |
+
layers.append(
|
1124 |
+
AttentionBlock(
|
1125 |
+
ch,
|
1126 |
+
use_checkpoint=use_checkpoint,
|
1127 |
+
num_heads=num_heads_upsample,
|
1128 |
+
num_head_channels=num_head_channels,
|
1129 |
+
use_new_attention_order=use_new_attention_order,
|
1130 |
+
)
|
1131 |
+
)
|
1132 |
+
if level and i == num_res_blocks:
|
1133 |
+
out_ch = ch
|
1134 |
+
layers.append(
|
1135 |
+
ResBlock(
|
1136 |
+
ch,
|
1137 |
+
time_embed_dim,
|
1138 |
+
dropout,
|
1139 |
+
out_channels=out_ch,
|
1140 |
+
dims=dims,
|
1141 |
+
use_checkpoint=use_checkpoint,
|
1142 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
1143 |
+
up=True,
|
1144 |
+
)
|
1145 |
+
if resblock_updown
|
1146 |
+
else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
|
1147 |
+
)
|
1148 |
+
ds //= 2
|
1149 |
+
self.output_blocks.append(TimestepEmbedSequential(*layers))
|
1150 |
+
self._feature_size += ch
|
1151 |
+
|
1152 |
+
self.out = nn.Sequential(
|
1153 |
+
normalization(ch),
|
1154 |
+
nn.SiLU(),
|
1155 |
+
zero_module(conv_nd(dims, input_ch, out_channels, 3, padding=1)),
|
1156 |
+
)
|
1157 |
+
|
1158 |
+
self.emb_h_layer = nn.Sequential(
|
1159 |
+
linear(64 * 64 * 3, time_embed_dim),
|
1160 |
+
nn.SiLU(),
|
1161 |
+
linear(time_embed_dim, time_embed_dim),
|
1162 |
+
)
|
1163 |
+
|
1164 |
+
def convert_to_fp16(self):
|
1165 |
+
"""
|
1166 |
+
Convert the torso of the model to float16.
|
1167 |
+
"""
|
1168 |
+
self.input_blocks.apply(convert_module_to_f16)
|
1169 |
+
self.middle_block.apply(convert_module_to_f16)
|
1170 |
+
self.output_blocks.apply(convert_module_to_f16)
|
1171 |
+
|
1172 |
+
def convert_to_fp32(self):
|
1173 |
+
"""
|
1174 |
+
Convert the torso of the model to float32.
|
1175 |
+
"""
|
1176 |
+
self.input_blocks.apply(convert_module_to_f32)
|
1177 |
+
self.middle_block.apply(convert_module_to_f32)
|
1178 |
+
self.output_blocks.apply(convert_module_to_f32)
|
1179 |
+
|
1180 |
+
def forward(self, x, dt, latent, **kwargs):
|
1181 |
+
"""
|
1182 |
+
Apply the model to an input batch.
|
1183 |
+
|
1184 |
+
:param x: an [N x C x ...] Tensor of inputs.
|
1185 |
+
:param timesteps: a 1-D batch of timesteps.
|
1186 |
+
:param y: an [N] Tensor of labels, if class-conditional.
|
1187 |
+
:return: an [N x C x ...] Tensor of outputs.
|
1188 |
+
"""
|
1189 |
+
|
1190 |
+
|
1191 |
+
hs = []
|
1192 |
+
emb = self.dt_embed(timestep_embedding(dt, self.model_channels))
|
1193 |
+
emb_h = F.adaptive_avg_pool2d(x, (64, 64)).view(x.shape[0], -1)
|
1194 |
+
emb_h = self.emb_h_layer(emb_h)
|
1195 |
+
emb = emb + emb_h
|
1196 |
+
|
1197 |
+
x = torch.cat([x, latent], dim=1)
|
1198 |
+
|
1199 |
+
h = x.type(self.dtype)
|
1200 |
+
for module in self.input_blocks:
|
1201 |
+
h = module(h, emb)
|
1202 |
+
hs.append(h)
|
1203 |
+
h = self.middle_block(h, emb)
|
1204 |
+
for module in self.output_blocks:
|
1205 |
+
h = torch.cat([h, hs.pop()], dim=1)
|
1206 |
+
h = module(h, emb)
|
1207 |
+
h = h.type(x.dtype)
|
1208 |
+
return self.out(h)
|
examples/lssd2025.jpg
ADDED
examples/web-shadow0243.jpg
ADDED
examples/web-shadow0248.jpg
ADDED
header.html
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<div style="text-align: center; max-width: 650px; margin: 0 auto;">
|
2 |
+
<div style="
|
3 |
+
display: inline-flex;
|
4 |
+
gap: 0.8rem;
|
5 |
+
font-size: 1.75rem;
|
6 |
+
justify-content: center;
|
7 |
+
margin-bottom: 10px;
|
8 |
+
">
|
9 |
+
<h1 style="font-weight: 900; align-items: center; margin-bottom: 7px; margin-top: 20px;">
|
10 |
+
Instance Shadow Removal
|
11 |
+
</h1>
|
12 |
+
</div>
|
13 |
+
<div>
|
14 |
+
<p style="align-items: center; margin-bottom: 7px;">
|
15 |
+
The new sota shadow removal model even for instnace case. <br> Add a mask for what shadow want to removal. Please draw as accurate as possible.
|
16 |
+
</p>
|
17 |
+
</div>
|
18 |
+
</div>
|
net_g_400000.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d9eb122113d07cfb5321ea20f34884a739171e74c4d9cb54d8ee69ed485b8e3f
|
3 |
+
size 4532130337
|