Repository navigation
Expand file tree
/
Copy pathdcdm.py
More file actions
279 lines (215 loc) · 8.58 KB
/
Copy pathdcdm.py
File metadata and controls
279 lines (215 loc) · 8.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import copy
import glob
import math
import os
import random
from collections import namedtuple
from functools import partial
from multiprocessing import cpu_count
from pathlib import Path
import torchvision.transforms as transforms
import cv2
import numpy as np
import torch
import torch.nn.functional as F
import torchvision.transforms.functional as TF
from accelerate import Accelerator
from einops import rearrange, reduce
from einops.layers.torch import Rearrange
from ema_pytorch import EMA
from PIL import Image
import time
from torch import einsum, nn
from torch.optim import Adam, RAdam
from torch.utils.data import DataLoader
from torchvision import transforms as T
from torchvision import utils
from tqdm.auto import tqdm
import copy
from typing import Union, List, Tuple, Dict
import lpips
# import importlib
ModelResPrediction = namedtuple(
'ModelResPrediction', ['pred_v','pred_x']) # v for velocity, a for acceleration
# helpers functions
# metric_module = importlib.import_module('metrics')
def set_seed(SEED):
# initialize random seed
torch.manual_seed(SEED)
torch.cuda.manual_seed_all(SEED)
np.random.seed(SEED)
random.seed(SEED)
def exists(x):
return x is not None
def default(val, d):
if exists(val):
return val
return d() if callable(d) else d
def identity(t, *args, **kwargs):
return t
def cycle(dl):
while True:
for data in dl:
yield data
def has_int_squareroot(num):
return (math.sqrt(num) ** 2) == num
def num_to_groups(num, divisor):
groups = num // divisor
remainder = num % divisor
arr = [divisor] * groups
if remainder > 0:
arr.append(remainder)
return arr
def normalize_to_neg_one_to_one(img):
if isinstance(img, list):
return [img[k] * 2 - 1 for k in range(len(img))]
else:
return img * 2 - 1
def unnormalize_to_zero_to_one(img):
if isinstance(img, list):
return [(img[k] + 1) * 0.5 for k in range(len(img))]
else:
return (img + 1) * 0.5
def extract(a, t, x_shape):
b, *_ = t.shape
out = a.gather(-1, t)
return out.reshape(b, *((1,) * (len(x_shape) - 1)))
def betas_for_alpha_bar(num_diffusion_timesteps, max_beta=0.999) -> torch.Tensor:
def alpha_bar(time_step):
return math.cos((time_step + 0.008) / 1.008 * math.pi / 2) ** 2
betas = []
for i in range(num_diffusion_timesteps):
t1 = i / num_diffusion_timesteps
t2 = (i + 1) / num_diffusion_timesteps
betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
return torch.tensor(betas, dtype=torch.float32)
class MDDM(nn.Module):
def __init__(self, model, timesteps=100,):
super().__init__()
self.model = model
self.T = timesteps
self.gamma_max = 1
self.loss_fn = nn.MSELoss()
self.lpip_fn = lpips.LPIPS(net='alex')
for p in self.lpip_fn.parameters():
p.requires_grad = False
self.lpip_fn.eval()
def generate_random_timesteps(self, batch):
timesteps = torch.randint(
0, int(1.2*(self.T + 1)), (batch, 1)).long().clamp(0,self.T)
return timesteps
def _generate_alpha(self, t):
return t.float() / self.T
def _generate_gamma(self,t):
return t.float() / self.T * self.gamma_max + 0.001
def _sinkhorn_solve(self, x_ts, x_hq, gamma_t=0.1, n_iters=50):
B, N, C, H, W = x_ts.shape
device = x_ts.device
mu_flat = x_ts.view(B, N, -1)
x0_flat = x_hq.view(B, 1, -1)
C = ((mu_flat - x0_flat) ** 2).sum(dim=-1, keepdim=True)
r = torch.ones(B, N, 1, device=device) / N
c = torch.ones(B, 1, 1, device=device)
K = torch.exp(-C / gamma_t)
u = torch.ones(B, N, 1, device=device) / N
v = torch.ones(B, 1, 1, device=device)
for _ in range(n_iters):
u = r / (K * v)
v = c / ((K.transpose(1, 2) @ u))
P = u * K * v
omega_t = P.squeeze(-1)
omega_t = omega_t / omega_t.sum(dim=-1, keepdim=True)
return omega_t
def _fast_solve(self, x_ts, x_hq, gamma_t=0.1, n_iters=None):
B, N, C, H, W = x_ts.shape
device = x_ts.device
dtype = x_ts.dtype
if x_hq.dim() == 5:
x_hq = x_hq.squeeze(1)
mu_flat = x_ts.reshape(B, N, -1)
x0_flat = x_hq.reshape(B, 1, -1)
dist = ((mu_flat - x0_flat) ** 2).mean(dim=-1)
if not torch.is_tensor(gamma_t):
gamma_t = torch.tensor(gamma_t, device=device, dtype=dtype)
else:
gamma_t = gamma_t.to(device=device, dtype=dtype)
if gamma_t.dim() == 0:
gamma_t = gamma_t.view(1, 1).expand(B, 1)
elif gamma_t.dim() == 1:
gamma_t = gamma_t.view(B, 1)
elif gamma_t.dim() == 2:
gamma_t = gamma_t.view(B, 1)
else:
raise ValueError(f"Unsupported gamma_t shape: {gamma_t.shape}")
gamma_t = gamma_t.view(B, 1).clamp_min(1e-8)
logits = -dist / gamma_t
omega_t = torch.softmax(logits, dim=1)
return omega_t
def _dynamic_center(self, x_lqs, x_hq, t):
B, N, C, H, W = x_lqs.shape
alpha_t = self._generate_alpha(t)
gamma_t = self._generate_gamma(t)
x_hq_expand = x_hq.view(B, 1, C, H, W).expand(B, N, C, H, W)
t_u = alpha_t.view(-1, 1, 1, 1, 1).expand_as(x_lqs)
x_ts = (1 - t_u) * x_hq_expand + t_u * x_lqs
# omega_t = self._sinkhorn_solve(x_ts, x_hq, gamma_t, n_iters=50)
omega_t = self._fast_solve(x_ts, x_hq, gamma_t)
omega_t_expand = omega_t.view(B, N, 1, 1, 1)
mu_phi = (omega_t_expand * x_lqs).sum(dim=1) # [B,C,H,W]
mu_t = (omega_t_expand * x_ts).sum(dim=1) # [B,C,H,W]
t_v = alpha_t.view(-1, 1, 1, 1).expand_as(x_hq)
x_t = (1 - t_v) * x_hq + t_v * mu_phi
return x_t, mu_t, mu_phi, omega_t, alpha_t.view(B, 1)
def forward(self, x_lqs, x_hq):
device = x_hq.device
b, c, h, w = x_hq.shape
t = self.generate_random_timesteps(b).to(device)
x_t, mu_t, mu_phi, omega_t, _ = self._dynamic_center(x_lqs, x_hq, t)
f_pred = self.model(x_t.to(device),x_lqs.to(device), t.to(device))
loss = self.loss_fn(f_pred, x_hq)
return loss
@torch.no_grad()
def sample(self, x_lqs, num_steps=50, schedule="linear",power=2.0, clamp=True,):
B, N, C, H, W = x_lqs.shape
device = x_lqs.device
dtype = x_lqs.dtype
if num_steps is None:
num_steps = self.T
num_steps = min(num_steps, self.T)
if schedule == "linear":
timesteps = torch.linspace(self.T, 0, steps=num_steps + 1, device=device,).round().long()
elif schedule == "quadratic":
u = torch.linspace(1.0, 0.0,steps=num_steps + 1, device=device, dtype=dtype, )
timesteps = (u ** power * self.T).round().long()
else:
raise ValueError(f"Unknown schedule: {schedule}")
timesteps = torch.unique_consecutive(timesteps)
# Ensure start/end
if timesteps[0].item() != self.T:
timesteps = torch.cat([torch.tensor([self.T], device=device, dtype=torch.long), timesteps, ])
if timesteps[-1].item() != 0:
timesteps = torch.cat([timesteps,torch.tensor([0], device=device, dtype=torch.long),])
x = x_lqs.mean(dim=1) # [B, C, H, W]
if clamp:
x = x.clamp(0.0, 1.0)
for i in range(len(timesteps) - 1):
t_val = timesteps[i].item()
s_val = timesteps[i + 1].item()
t = torch.full((B, 1), t_val, device=device, dtype=torch.long,)
s = torch.full((B, 1), s_val, device=device, dtype=torch.long,)
alpha_t = self._generate_alpha(t).view(B, 1, 1, 1)
alpha_s = self._generate_alpha(s).view(B, 1, 1, 1)
x0_hat = self.model(x_lqs, t )
if clamp:
x0_hat = x0_hat.clamp(0.0, 1.0)
_, mu_t, mu_phi_t, omega_t, _ = self._dynamic_center(x_lqs=x_lqs, x_hq=x0_hat, t=t)
_, mu_s, mu_phi_s, omega_s, _ = self._dynamic_center(x_lqs=x_lqs, x_hq=x0_hat, t=s)
f_t = x0_hat - mu_phi_t
g_t_to_s = mu_phi_s - mu_phi_t
x = x + (alpha_t - alpha_s) * f_t + alpha_s * g_t_to_s
if clamp:
x = x.clamp(0.0, 1.0)
return x
if __name__ == '__main__':
print('Hello World')
print('Finished')