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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
wild mixture of
|
3 |
+
https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
|
4 |
+
https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py
|
5 |
+
https://github.com/CompVis/taming-transformers
|
6 |
+
-- merci
|
7 |
+
"""
|
8 |
+
|
9 |
+
import torch
|
10 |
+
import torch.nn as nn
|
11 |
+
import numpy as np
|
12 |
+
import pytorch_lightning as pl
|
13 |
+
from torch.optim.lr_scheduler import LambdaLR
|
14 |
+
from einops import rearrange, repeat
|
15 |
+
from contextlib import contextmanager
|
16 |
+
from functools import partial
|
17 |
+
from tqdm import tqdm
|
18 |
+
from torchvision.utils import make_grid
|
19 |
+
from pytorch_lightning.utilities.distributed import rank_zero_only
|
20 |
+
|
21 |
+
from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config
|
22 |
+
from ldm.modules.ema import LitEma
|
23 |
+
from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution
|
24 |
+
from ldm.models.autoencoder import VQModelInterface, IdentityFirstStage, AutoencoderKL
|
25 |
+
from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like
|
26 |
+
from ldm.models.diffusion.ddim import DDIMSampler
|
27 |
+
|
28 |
+
|
29 |
+
__conditioning_keys__ = {'concat': 'c_concat',
|
30 |
+
'crossattn': 'c_crossattn',
|
31 |
+
'adm': 'y'}
|
32 |
+
|
33 |
+
|
34 |
+
def disabled_train(self, mode=True):
|
35 |
+
"""Overwrite model.train with this function to make sure train/eval mode
|
36 |
+
does not change anymore."""
|
37 |
+
return self
|
38 |
+
|
39 |
+
|
40 |
+
def uniform_on_device(r1, r2, shape, device):
|
41 |
+
return (r1 - r2) * torch.rand(*shape, device=device) + r2
|
42 |
+
|
43 |
+
|
44 |
+
class DDPM(pl.LightningModule):
|
45 |
+
# classic DDPM with Gaussian diffusion, in image space
|
46 |
+
def __init__(self,
|
47 |
+
unet_config,
|
48 |
+
timesteps=1000,
|
49 |
+
beta_schedule="linear",
|
50 |
+
loss_type="l2",
|
51 |
+
ckpt_path=None,
|
52 |
+
ignore_keys=[],
|
53 |
+
load_only_unet=False,
|
54 |
+
monitor="val/loss",
|
55 |
+
use_ema=True,
|
56 |
+
first_stage_key="image",
|
57 |
+
image_size=256,
|
58 |
+
channels=3,
|
59 |
+
log_every_t=100,
|
60 |
+
clip_denoised=True,
|
61 |
+
linear_start=1e-4,
|
62 |
+
linear_end=2e-2,
|
63 |
+
cosine_s=8e-3,
|
64 |
+
given_betas=None,
|
65 |
+
original_elbo_weight=0.,
|
66 |
+
v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
|
67 |
+
l_simple_weight=1.,
|
68 |
+
conditioning_key=None,
|
69 |
+
parameterization="eps", # all assuming fixed variance schedules
|
70 |
+
scheduler_config=None,
|
71 |
+
use_positional_encodings=False,
|
72 |
+
learn_logvar=False,
|
73 |
+
logvar_init=0.,
|
74 |
+
):
|
75 |
+
super().__init__()
|
76 |
+
assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"'
|
77 |
+
self.parameterization = parameterization
|
78 |
+
print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
|
79 |
+
self.cond_stage_model = None
|
80 |
+
self.clip_denoised = clip_denoised
|
81 |
+
self.log_every_t = log_every_t
|
82 |
+
self.first_stage_key = first_stage_key
|
83 |
+
self.image_size = image_size # try conv?
|
84 |
+
self.channels = channels
|
85 |
+
self.use_positional_encodings = use_positional_encodings
|
86 |
+
self.model = DiffusionWrapper(unet_config, conditioning_key)
|
87 |
+
count_params(self.model, verbose=True)
|
88 |
+
self.use_ema = use_ema
|
89 |
+
if self.use_ema:
|
90 |
+
self.model_ema = LitEma(self.model)
|
91 |
+
print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
|
92 |
+
|
93 |
+
self.use_scheduler = scheduler_config is not None
|
94 |
+
if self.use_scheduler:
|
95 |
+
self.scheduler_config = scheduler_config
|
96 |
+
|
97 |
+
self.v_posterior = v_posterior
|
98 |
+
self.original_elbo_weight = original_elbo_weight
|
99 |
+
self.l_simple_weight = l_simple_weight
|
100 |
+
|
101 |
+
if monitor is not None:
|
102 |
+
self.monitor = monitor
|
103 |
+
if ckpt_path is not None:
|
104 |
+
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet)
|
105 |
+
|
106 |
+
self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
|
107 |
+
linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
|
108 |
+
|
109 |
+
self.loss_type = loss_type
|
110 |
+
|
111 |
+
self.learn_logvar = learn_logvar
|
112 |
+
self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
|
113 |
+
if self.learn_logvar:
|
114 |
+
self.logvar = nn.Parameter(self.logvar, requires_grad=True)
|
115 |
+
|
116 |
+
|
117 |
+
def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
|
118 |
+
linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
|
119 |
+
if exists(given_betas):
|
120 |
+
betas = given_betas
|
121 |
+
else:
|
122 |
+
betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
|
123 |
+
cosine_s=cosine_s)
|
124 |
+
alphas = 1. - betas
|
125 |
+
alphas_cumprod = np.cumprod(alphas, axis=0)
|
126 |
+
alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
|
127 |
+
|
128 |
+
timesteps, = betas.shape
|
129 |
+
self.num_timesteps = int(timesteps)
|
130 |
+
self.linear_start = linear_start
|
131 |
+
self.linear_end = linear_end
|
132 |
+
assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
|
133 |
+
|
134 |
+
to_torch = partial(torch.tensor, dtype=torch.float32)
|
135 |
+
|
136 |
+
self.register_buffer('betas', to_torch(betas))
|
137 |
+
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
|
138 |
+
self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
|
139 |
+
|
140 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
141 |
+
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
|
142 |
+
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
|
143 |
+
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
|
144 |
+
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
|
145 |
+
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
|
146 |
+
|
147 |
+
# calculations for posterior q(x_{t-1} | x_t, x_0)
|
148 |
+
posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / (
|
149 |
+
1. - alphas_cumprod) + self.v_posterior * betas
|
150 |
+
# above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
|
151 |
+
self.register_buffer('posterior_variance', to_torch(posterior_variance))
|
152 |
+
# below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
|
153 |
+
self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
|
154 |
+
self.register_buffer('posterior_mean_coef1', to_torch(
|
155 |
+
betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
|
156 |
+
self.register_buffer('posterior_mean_coef2', to_torch(
|
157 |
+
(1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
|
158 |
+
|
159 |
+
if self.parameterization == "eps":
|
160 |
+
lvlb_weights = self.betas ** 2 / (
|
161 |
+
2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))
|
162 |
+
elif self.parameterization == "x0":
|
163 |
+
lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod))
|
164 |
+
else:
|
165 |
+
raise NotImplementedError("mu not supported")
|
166 |
+
# TODO how to choose this term
|
167 |
+
lvlb_weights[0] = lvlb_weights[1]
|
168 |
+
self.register_buffer('lvlb_weights', lvlb_weights, persistent=False)
|
169 |
+
assert not torch.isnan(self.lvlb_weights).all()
|
170 |
+
|
171 |
+
@contextmanager
|
172 |
+
def ema_scope(self, context=None):
|
173 |
+
if self.use_ema:
|
174 |
+
self.model_ema.store(self.model.parameters())
|
175 |
+
self.model_ema.copy_to(self.model)
|
176 |
+
if context is not None:
|
177 |
+
print(f"{context}: Switched to EMA weights")
|
178 |
+
try:
|
179 |
+
yield None
|
180 |
+
finally:
|
181 |
+
if self.use_ema:
|
182 |
+
self.model_ema.restore(self.model.parameters())
|
183 |
+
if context is not None:
|
184 |
+
print(f"{context}: Restored training weights")
|
185 |
+
|
186 |
+
def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
|
187 |
+
sd = torch.load(path, map_location="cpu")
|
188 |
+
if "state_dict" in list(sd.keys()):
|
189 |
+
sd = sd["state_dict"]
|
190 |
+
keys = list(sd.keys())
|
191 |
+
for k in keys:
|
192 |
+
for ik in ignore_keys:
|
193 |
+
if k.startswith(ik):
|
194 |
+
print("Deleting key {} from state_dict.".format(k))
|
195 |
+
del sd[k]
|
196 |
+
missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
|
197 |
+
sd, strict=False)
|
198 |
+
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
199 |
+
if len(missing) > 0:
|
200 |
+
print(f"Missing Keys: {missing}")
|
201 |
+
if len(unexpected) > 0:
|
202 |
+
print(f"Unexpected Keys: {unexpected}")
|
203 |
+
|
204 |
+
def q_mean_variance(self, x_start, t):
|
205 |
+
"""
|
206 |
+
Get the distribution q(x_t | x_0).
|
207 |
+
:param x_start: the [N x C x ...] tensor of noiseless inputs.
|
208 |
+
:param t: the number of diffusion steps (minus 1). Here, 0 means one step.
|
209 |
+
:return: A tuple (mean, variance, log_variance), all of x_start's shape.
|
210 |
+
"""
|
211 |
+
mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
|
212 |
+
variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
|
213 |
+
log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
|
214 |
+
return mean, variance, log_variance
|
215 |
+
|
216 |
+
def predict_start_from_noise(self, x_t, t, noise):
|
217 |
+
return (
|
218 |
+
extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
|
219 |
+
extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
|
220 |
+
)
|
221 |
+
|
222 |
+
def q_posterior(self, x_start, x_t, t):
|
223 |
+
posterior_mean = (
|
224 |
+
extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start +
|
225 |
+
extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
|
226 |
+
)
|
227 |
+
posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape)
|
228 |
+
posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
|
229 |
+
return posterior_mean, posterior_variance, posterior_log_variance_clipped
|
230 |
+
|
231 |
+
def p_mean_variance(self, x, t, clip_denoised: bool):
|
232 |
+
model_out = self.model(x, t)
|
233 |
+
if self.parameterization == "eps":
|
234 |
+
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
|
235 |
+
elif self.parameterization == "x0":
|
236 |
+
x_recon = model_out
|
237 |
+
if clip_denoised:
|
238 |
+
x_recon.clamp_(-1., 1.)
|
239 |
+
|
240 |
+
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
|
241 |
+
return model_mean, posterior_variance, posterior_log_variance
|
242 |
+
|
243 |
+
@torch.no_grad()
|
244 |
+
def p_sample(self, x, t, clip_denoised=True, repeat_noise=False):
|
245 |
+
b, *_, device = *x.shape, x.device
|
246 |
+
model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
|
247 |
+
noise = noise_like(x.shape, device, repeat_noise)
|
248 |
+
# no noise when t == 0
|
249 |
+
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
|
250 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
|
251 |
+
|
252 |
+
@torch.no_grad()
|
253 |
+
def p_sample_loop(self, shape, return_intermediates=False):
|
254 |
+
device = self.betas.device
|
255 |
+
b = shape[0]
|
256 |
+
img = torch.randn(shape, device=device)
|
257 |
+
intermediates = [img]
|
258 |
+
for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps):
|
259 |
+
img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long),
|
260 |
+
clip_denoised=self.clip_denoised)
|
261 |
+
if i % self.log_every_t == 0 or i == self.num_timesteps - 1:
|
262 |
+
intermediates.append(img)
|
263 |
+
if return_intermediates:
|
264 |
+
return img, intermediates
|
265 |
+
return img
|
266 |
+
|
267 |
+
@torch.no_grad()
|
268 |
+
def sample(self, batch_size=16, return_intermediates=False):
|
269 |
+
image_size = self.image_size
|
270 |
+
channels = self.channels
|
271 |
+
return self.p_sample_loop((batch_size, channels, image_size, image_size),
|
272 |
+
return_intermediates=return_intermediates)
|
273 |
+
|
274 |
+
def q_sample(self, x_start, t, noise=None):
|
275 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
276 |
+
return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
|
277 |
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
|
278 |
+
|
279 |
+
def get_loss(self, pred, target, mean=True):
|
280 |
+
if self.loss_type == 'l1':
|
281 |
+
loss = (target - pred).abs()
|
282 |
+
if mean:
|
283 |
+
loss = loss.mean()
|
284 |
+
elif self.loss_type == 'l2':
|
285 |
+
if mean:
|
286 |
+
loss = torch.nn.functional.mse_loss(target, pred)
|
287 |
+
else:
|
288 |
+
loss = torch.nn.functional.mse_loss(target, pred, reduction='none')
|
289 |
+
else:
|
290 |
+
raise NotImplementedError("unknown loss type '{loss_type}'")
|
291 |
+
|
292 |
+
return loss
|
293 |
+
|
294 |
+
def p_losses(self, x_start, t, noise=None):
|
295 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
296 |
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
297 |
+
model_out = self.model(x_noisy, t)
|
298 |
+
|
299 |
+
loss_dict = {}
|
300 |
+
if self.parameterization == "eps":
|
301 |
+
target = noise
|
302 |
+
elif self.parameterization == "x0":
|
303 |
+
target = x_start
|
304 |
+
else:
|
305 |
+
raise NotImplementedError(f"Paramterization {self.parameterization} not yet supported")
|
306 |
+
|
307 |
+
loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3])
|
308 |
+
|
309 |
+
log_prefix = 'train' if self.training else 'val'
|
310 |
+
|
311 |
+
loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()})
|
312 |
+
loss_simple = loss.mean() * self.l_simple_weight
|
313 |
+
|
314 |
+
loss_vlb = (self.lvlb_weights[t] * loss).mean()
|
315 |
+
loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb})
|
316 |
+
|
317 |
+
loss = loss_simple + self.original_elbo_weight * loss_vlb
|
318 |
+
|
319 |
+
loss_dict.update({f'{log_prefix}/loss': loss})
|
320 |
+
|
321 |
+
return loss, loss_dict
|
322 |
+
|
323 |
+
def forward(self, x, *args, **kwargs):
|
324 |
+
# b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size
|
325 |
+
# assert h == img_size and w == img_size, f'height and width of image must be {img_size}'
|
326 |
+
t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
|
327 |
+
return self.p_losses(x, t, *args, **kwargs)
|
328 |
+
|
329 |
+
def get_input(self, batch, k):
|
330 |
+
x = batch[k]
|
331 |
+
if len(x.shape) == 3:
|
332 |
+
x = x[..., None]
|
333 |
+
x = rearrange(x, 'b h w c -> b c h w')
|
334 |
+
x = x.to(memory_format=torch.contiguous_format).float()
|
335 |
+
return x
|
336 |
+
|
337 |
+
def shared_step(self, batch):
|
338 |
+
x = self.get_input(batch, self.first_stage_key)
|
339 |
+
loss, loss_dict = self(x)
|
340 |
+
return loss, loss_dict
|
341 |
+
|
342 |
+
def training_step(self, batch, batch_idx):
|
343 |
+
loss, loss_dict = self.shared_step(batch)
|
344 |
+
|
345 |
+
self.log_dict(loss_dict, prog_bar=True,
|
346 |
+
logger=True, on_step=True, on_epoch=True)
|
347 |
+
|
348 |
+
self.log("global_step", self.global_step,
|
349 |
+
prog_bar=True, logger=True, on_step=True, on_epoch=False)
|
350 |
+
|
351 |
+
if self.use_scheduler:
|
352 |
+
lr = self.optimizers().param_groups[0]['lr']
|
353 |
+
self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False)
|
354 |
+
|
355 |
+
return loss
|
356 |
+
|
357 |
+
@torch.no_grad()
|
358 |
+
def validation_step(self, batch, batch_idx):
|
359 |
+
_, loss_dict_no_ema = self.shared_step(batch)
|
360 |
+
with self.ema_scope():
|
361 |
+
_, loss_dict_ema = self.shared_step(batch)
|
362 |
+
loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema}
|
363 |
+
self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
|
364 |
+
self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
|
365 |
+
|
366 |
+
def on_train_batch_end(self, *args, **kwargs):
|
367 |
+
if self.use_ema:
|
368 |
+
self.model_ema(self.model)
|
369 |
+
|
370 |
+
def _get_rows_from_list(self, samples):
|
371 |
+
n_imgs_per_row = len(samples)
|
372 |
+
denoise_grid = rearrange(samples, 'n b c h w -> b n c h w')
|
373 |
+
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
|
374 |
+
denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
|
375 |
+
return denoise_grid
|
376 |
+
|
377 |
+
@torch.no_grad()
|
378 |
+
def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
|
379 |
+
log = dict()
|
380 |
+
x = self.get_input(batch, self.first_stage_key)
|
381 |
+
N = min(x.shape[0], N)
|
382 |
+
n_row = min(x.shape[0], n_row)
|
383 |
+
x = x.to(self.device)[:N]
|
384 |
+
log["inputs"] = x
|
385 |
+
|
386 |
+
# get diffusion row
|
387 |
+
diffusion_row = list()
|
388 |
+
x_start = x[:n_row]
|
389 |
+
|
390 |
+
for t in range(self.num_timesteps):
|
391 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
392 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
393 |
+
t = t.to(self.device).long()
|
394 |
+
noise = torch.randn_like(x_start)
|
395 |
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
396 |
+
diffusion_row.append(x_noisy)
|
397 |
+
|
398 |
+
log["diffusion_row"] = self._get_rows_from_list(diffusion_row)
|
399 |
+
|
400 |
+
if sample:
|
401 |
+
# get denoise row
|
402 |
+
with self.ema_scope("Plotting"):
|
403 |
+
samples, denoise_row = self.sample(batch_size=N, return_intermediates=True)
|
404 |
+
|
405 |
+
log["samples"] = samples
|
406 |
+
log["denoise_row"] = self._get_rows_from_list(denoise_row)
|
407 |
+
|
408 |
+
if return_keys:
|
409 |
+
if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
|
410 |
+
return log
|
411 |
+
else:
|
412 |
+
return {key: log[key] for key in return_keys}
|
413 |
+
return log
|
414 |
+
|
415 |
+
def configure_optimizers(self):
|
416 |
+
lr = self.learning_rate
|
417 |
+
params = list(self.model.parameters())
|
418 |
+
if self.learn_logvar:
|
419 |
+
params = params + [self.logvar]
|
420 |
+
opt = torch.optim.AdamW(params, lr=lr)
|
421 |
+
return opt
|
422 |
+
|
423 |
+
|
424 |
+
class LatentDiffusion(DDPM):
|
425 |
+
"""main class"""
|
426 |
+
def __init__(self,
|
427 |
+
first_stage_config,
|
428 |
+
cond_stage_config,
|
429 |
+
num_timesteps_cond=None,
|
430 |
+
cond_stage_key="image",
|
431 |
+
cond_stage_trainable=False,
|
432 |
+
concat_mode=True,
|
433 |
+
cond_stage_forward=None,
|
434 |
+
conditioning_key=None,
|
435 |
+
scale_factor=1.0,
|
436 |
+
scale_by_std=False,
|
437 |
+
*args, **kwargs):
|
438 |
+
self.num_timesteps_cond = default(num_timesteps_cond, 1)
|
439 |
+
self.scale_by_std = scale_by_std
|
440 |
+
assert self.num_timesteps_cond <= kwargs['timesteps']
|
441 |
+
# for backwards compatibility after implementation of DiffusionWrapper
|
442 |
+
if conditioning_key is None:
|
443 |
+
conditioning_key = 'concat' if concat_mode else 'crossattn'
|
444 |
+
if cond_stage_config == '__is_unconditional__':
|
445 |
+
conditioning_key = None
|
446 |
+
ckpt_path = kwargs.pop("ckpt_path", None)
|
447 |
+
ignore_keys = kwargs.pop("ignore_keys", [])
|
448 |
+
super().__init__(conditioning_key=conditioning_key, *args, **kwargs)
|
449 |
+
self.concat_mode = concat_mode
|
450 |
+
self.cond_stage_trainable = cond_stage_trainable
|
451 |
+
self.cond_stage_key = cond_stage_key
|
452 |
+
try:
|
453 |
+
self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
|
454 |
+
except:
|
455 |
+
self.num_downs = 0
|
456 |
+
if not scale_by_std:
|
457 |
+
self.scale_factor = scale_factor
|
458 |
+
else:
|
459 |
+
self.register_buffer('scale_factor', torch.tensor(scale_factor))
|
460 |
+
self.instantiate_first_stage(first_stage_config)
|
461 |
+
self.instantiate_cond_stage(cond_stage_config)
|
462 |
+
self.cond_stage_forward = cond_stage_forward
|
463 |
+
self.clip_denoised = False
|
464 |
+
self.bbox_tokenizer = None
|
465 |
+
|
466 |
+
self.restarted_from_ckpt = False
|
467 |
+
if ckpt_path is not None:
|
468 |
+
self.init_from_ckpt(ckpt_path, ignore_keys)
|
469 |
+
self.restarted_from_ckpt = True
|
470 |
+
|
471 |
+
def make_cond_schedule(self, ):
|
472 |
+
self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)
|
473 |
+
ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()
|
474 |
+
self.cond_ids[:self.num_timesteps_cond] = ids
|
475 |
+
|
476 |
+
@rank_zero_only
|
477 |
+
@torch.no_grad()
|
478 |
+
def on_train_batch_start(self, batch, batch_idx, dataloader_idx):
|
479 |
+
# only for very first batch
|
480 |
+
if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt:
|
481 |
+
assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously'
|
482 |
+
# set rescale weight to 1./std of encodings
|
483 |
+
print("### USING STD-RESCALING ###")
|
484 |
+
x = super().get_input(batch, self.first_stage_key)
|
485 |
+
x = x.to(self.device)
|
486 |
+
encoder_posterior = self.encode_first_stage(x)
|
487 |
+
z = self.get_first_stage_encoding(encoder_posterior).detach()
|
488 |
+
del self.scale_factor
|
489 |
+
self.register_buffer('scale_factor', 1. / z.flatten().std())
|
490 |
+
print(f"setting self.scale_factor to {self.scale_factor}")
|
491 |
+
print("### USING STD-RESCALING ###")
|
492 |
+
|
493 |
+
def register_schedule(self,
|
494 |
+
given_betas=None, beta_schedule="linear", timesteps=1000,
|
495 |
+
linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
|
496 |
+
super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)
|
497 |
+
|
498 |
+
self.shorten_cond_schedule = self.num_timesteps_cond > 1
|
499 |
+
if self.shorten_cond_schedule:
|
500 |
+
self.make_cond_schedule()
|
501 |
+
|
502 |
+
def instantiate_first_stage(self, config):
|
503 |
+
model = instantiate_from_config(config)
|
504 |
+
self.first_stage_model = model.eval()
|
505 |
+
self.first_stage_model.train = disabled_train
|
506 |
+
for param in self.first_stage_model.parameters():
|
507 |
+
param.requires_grad = False
|
508 |
+
|
509 |
+
def instantiate_cond_stage(self, config):
|
510 |
+
if not self.cond_stage_trainable:
|
511 |
+
if config == "__is_first_stage__":
|
512 |
+
print("Using first stage also as cond stage.")
|
513 |
+
self.cond_stage_model = self.first_stage_model
|
514 |
+
elif config == "__is_unconditional__":
|
515 |
+
print(f"Training {self.__class__.__name__} as an unconditional model.")
|
516 |
+
self.cond_stage_model = None
|
517 |
+
# self.be_unconditional = True
|
518 |
+
else:
|
519 |
+
model = instantiate_from_config(config)
|
520 |
+
self.cond_stage_model = model.eval()
|
521 |
+
self.cond_stage_model.train = disabled_train
|
522 |
+
for param in self.cond_stage_model.parameters():
|
523 |
+
param.requires_grad = False
|
524 |
+
else:
|
525 |
+
assert config != '__is_first_stage__'
|
526 |
+
assert config != '__is_unconditional__'
|
527 |
+
model = instantiate_from_config(config)
|
528 |
+
self.cond_stage_model = model
|
529 |
+
|
530 |
+
def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False):
|
531 |
+
denoise_row = []
|
532 |
+
for zd in tqdm(samples, desc=desc):
|
533 |
+
denoise_row.append(self.decode_first_stage(zd.to(self.device),
|
534 |
+
force_not_quantize=force_no_decoder_quantization))
|
535 |
+
n_imgs_per_row = len(denoise_row)
|
536 |
+
denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W
|
537 |
+
denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')
|
538 |
+
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
|
539 |
+
denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
|
540 |
+
return denoise_grid
|
541 |
+
|
542 |
+
def get_first_stage_encoding(self, encoder_posterior):
|
543 |
+
if isinstance(encoder_posterior, DiagonalGaussianDistribution):
|
544 |
+
z = encoder_posterior.sample()
|
545 |
+
elif isinstance(encoder_posterior, torch.Tensor):
|
546 |
+
z = encoder_posterior
|
547 |
+
else:
|
548 |
+
raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented")
|
549 |
+
return self.scale_factor * z
|
550 |
+
|
551 |
+
def get_learned_conditioning(self, c):
|
552 |
+
if self.cond_stage_forward is None:
|
553 |
+
if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):
|
554 |
+
c = self.cond_stage_model.encode(c)
|
555 |
+
if isinstance(c, DiagonalGaussianDistribution):
|
556 |
+
c = c.mode()
|
557 |
+
else:
|
558 |
+
c = self.cond_stage_model(c)
|
559 |
+
else:
|
560 |
+
assert hasattr(self.cond_stage_model, self.cond_stage_forward)
|
561 |
+
c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)
|
562 |
+
return c
|
563 |
+
|
564 |
+
def meshgrid(self, h, w):
|
565 |
+
y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)
|
566 |
+
x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)
|
567 |
+
|
568 |
+
arr = torch.cat([y, x], dim=-1)
|
569 |
+
return arr
|
570 |
+
|
571 |
+
def delta_border(self, h, w):
|
572 |
+
"""
|
573 |
+
:param h: height
|
574 |
+
:param w: width
|
575 |
+
:return: normalized distance to image border,
|
576 |
+
wtith min distance = 0 at border and max dist = 0.5 at image center
|
577 |
+
"""
|
578 |
+
lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
|
579 |
+
arr = self.meshgrid(h, w) / lower_right_corner
|
580 |
+
dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]
|
581 |
+
dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]
|
582 |
+
edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0]
|
583 |
+
return edge_dist
|
584 |
+
|
585 |
+
def get_weighting(self, h, w, Ly, Lx, device):
|
586 |
+
weighting = self.delta_border(h, w)
|
587 |
+
weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"],
|
588 |
+
self.split_input_params["clip_max_weight"], )
|
589 |
+
weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)
|
590 |
+
|
591 |
+
if self.split_input_params["tie_braker"]:
|
592 |
+
L_weighting = self.delta_border(Ly, Lx)
|
593 |
+
L_weighting = torch.clip(L_weighting,
|
594 |
+
self.split_input_params["clip_min_tie_weight"],
|
595 |
+
self.split_input_params["clip_max_tie_weight"])
|
596 |
+
|
597 |
+
L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)
|
598 |
+
weighting = weighting * L_weighting
|
599 |
+
return weighting
|
600 |
+
|
601 |
+
def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code
|
602 |
+
"""
|
603 |
+
:param x: img of size (bs, c, h, w)
|
604 |
+
:return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])
|
605 |
+
"""
|
606 |
+
bs, nc, h, w = x.shape
|
607 |
+
|
608 |
+
# number of crops in image
|
609 |
+
Ly = (h - kernel_size[0]) // stride[0] + 1
|
610 |
+
Lx = (w - kernel_size[1]) // stride[1] + 1
|
611 |
+
|
612 |
+
if uf == 1 and df == 1:
|
613 |
+
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
|
614 |
+
unfold = torch.nn.Unfold(**fold_params)
|
615 |
+
|
616 |
+
fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)
|
617 |
+
|
618 |
+
weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype)
|
619 |
+
normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap
|
620 |
+
weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))
|
621 |
+
|
622 |
+
elif uf > 1 and df == 1:
|
623 |
+
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
|
624 |
+
unfold = torch.nn.Unfold(**fold_params)
|
625 |
+
|
626 |
+
fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),
|
627 |
+
dilation=1, padding=0,
|
628 |
+
stride=(stride[0] * uf, stride[1] * uf))
|
629 |
+
fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2)
|
630 |
+
|
631 |
+
weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype)
|
632 |
+
normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap
|
633 |
+
weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx))
|
634 |
+
|
635 |
+
elif df > 1 and uf == 1:
|
636 |
+
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
|
637 |
+
unfold = torch.nn.Unfold(**fold_params)
|
638 |
+
|
639 |
+
fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df),
|
640 |
+
dilation=1, padding=0,
|
641 |
+
stride=(stride[0] // df, stride[1] // df))
|
642 |
+
fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2)
|
643 |
+
|
644 |
+
weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype)
|
645 |
+
normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap
|
646 |
+
weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx))
|
647 |
+
|
648 |
+
else:
|
649 |
+
raise NotImplementedError
|
650 |
+
|
651 |
+
return fold, unfold, normalization, weighting
|
652 |
+
|
653 |
+
@torch.no_grad()
|
654 |
+
def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False,
|
655 |
+
cond_key=None, return_original_cond=False, bs=None):
|
656 |
+
x = super().get_input(batch, k)
|
657 |
+
if bs is not None:
|
658 |
+
x = x[:bs]
|
659 |
+
x = x.to(self.device)
|
660 |
+
encoder_posterior = self.encode_first_stage(x)
|
661 |
+
z = self.get_first_stage_encoding(encoder_posterior).detach()
|
662 |
+
|
663 |
+
if self.model.conditioning_key is not None:
|
664 |
+
if cond_key is None:
|
665 |
+
cond_key = self.cond_stage_key
|
666 |
+
if cond_key != self.first_stage_key:
|
667 |
+
if cond_key in ['caption', 'coordinates_bbox']:
|
668 |
+
xc = batch[cond_key]
|
669 |
+
elif cond_key == 'class_label':
|
670 |
+
xc = batch
|
671 |
+
else:
|
672 |
+
xc = super().get_input(batch, cond_key).to(self.device)
|
673 |
+
else:
|
674 |
+
xc = x
|
675 |
+
if not self.cond_stage_trainable or force_c_encode:
|
676 |
+
if isinstance(xc, dict) or isinstance(xc, list):
|
677 |
+
# import pudb; pudb.set_trace()
|
678 |
+
c = self.get_learned_conditioning(xc)
|
679 |
+
else:
|
680 |
+
c = self.get_learned_conditioning(xc.to(self.device))
|
681 |
+
else:
|
682 |
+
c = xc
|
683 |
+
if bs is not None:
|
684 |
+
c = c[:bs]
|
685 |
+
|
686 |
+
if self.use_positional_encodings:
|
687 |
+
pos_x, pos_y = self.compute_latent_shifts(batch)
|
688 |
+
ckey = __conditioning_keys__[self.model.conditioning_key]
|
689 |
+
c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y}
|
690 |
+
|
691 |
+
else:
|
692 |
+
c = None
|
693 |
+
xc = None
|
694 |
+
if self.use_positional_encodings:
|
695 |
+
pos_x, pos_y = self.compute_latent_shifts(batch)
|
696 |
+
c = {'pos_x': pos_x, 'pos_y': pos_y}
|
697 |
+
out = [z, c]
|
698 |
+
if return_first_stage_outputs:
|
699 |
+
xrec = self.decode_first_stage(z)
|
700 |
+
out.extend([x, xrec])
|
701 |
+
if return_original_cond:
|
702 |
+
out.append(xc)
|
703 |
+
return out
|
704 |
+
|
705 |
+
@torch.no_grad()
|
706 |
+
def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
|
707 |
+
if predict_cids:
|
708 |
+
if z.dim() == 4:
|
709 |
+
z = torch.argmax(z.exp(), dim=1).long()
|
710 |
+
z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
|
711 |
+
z = rearrange(z, 'b h w c -> b c h w').contiguous()
|
712 |
+
|
713 |
+
z = 1. / self.scale_factor * z
|
714 |
+
|
715 |
+
if hasattr(self, "split_input_params"):
|
716 |
+
if self.split_input_params["patch_distributed_vq"]:
|
717 |
+
ks = self.split_input_params["ks"] # eg. (128, 128)
|
718 |
+
stride = self.split_input_params["stride"] # eg. (64, 64)
|
719 |
+
uf = self.split_input_params["vqf"]
|
720 |
+
bs, nc, h, w = z.shape
|
721 |
+
if ks[0] > h or ks[1] > w:
|
722 |
+
ks = (min(ks[0], h), min(ks[1], w))
|
723 |
+
print("reducing Kernel")
|
724 |
+
|
725 |
+
if stride[0] > h or stride[1] > w:
|
726 |
+
stride = (min(stride[0], h), min(stride[1], w))
|
727 |
+
print("reducing stride")
|
728 |
+
|
729 |
+
fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf)
|
730 |
+
|
731 |
+
z = unfold(z) # (bn, nc * prod(**ks), L)
|
732 |
+
# 1. Reshape to img shape
|
733 |
+
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
|
734 |
+
|
735 |
+
# 2. apply model loop over last dim
|
736 |
+
if isinstance(self.first_stage_model, VQModelInterface):
|
737 |
+
output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
|
738 |
+
force_not_quantize=predict_cids or force_not_quantize)
|
739 |
+
for i in range(z.shape[-1])]
|
740 |
+
else:
|
741 |
+
|
742 |
+
output_list = [self.first_stage_model.decode(z[:, :, :, :, i])
|
743 |
+
for i in range(z.shape[-1])]
|
744 |
+
|
745 |
+
o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)
|
746 |
+
o = o * weighting
|
747 |
+
# Reverse 1. reshape to img shape
|
748 |
+
o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
|
749 |
+
# stitch crops together
|
750 |
+
decoded = fold(o)
|
751 |
+
decoded = decoded / normalization # norm is shape (1, 1, h, w)
|
752 |
+
return decoded
|
753 |
+
else:
|
754 |
+
if isinstance(self.first_stage_model, VQModelInterface):
|
755 |
+
return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
|
756 |
+
else:
|
757 |
+
return self.first_stage_model.decode(z)
|
758 |
+
|
759 |
+
else:
|
760 |
+
if isinstance(self.first_stage_model, VQModelInterface):
|
761 |
+
return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
|
762 |
+
else:
|
763 |
+
return self.first_stage_model.decode(z)
|
764 |
+
|
765 |
+
# same as above but without decorator
|
766 |
+
def differentiable_decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
|
767 |
+
if predict_cids:
|
768 |
+
if z.dim() == 4:
|
769 |
+
z = torch.argmax(z.exp(), dim=1).long()
|
770 |
+
z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
|
771 |
+
z = rearrange(z, 'b h w c -> b c h w').contiguous()
|
772 |
+
|
773 |
+
z = 1. / self.scale_factor * z
|
774 |
+
|
775 |
+
if hasattr(self, "split_input_params"):
|
776 |
+
if self.split_input_params["patch_distributed_vq"]:
|
777 |
+
ks = self.split_input_params["ks"] # eg. (128, 128)
|
778 |
+
stride = self.split_input_params["stride"] # eg. (64, 64)
|
779 |
+
uf = self.split_input_params["vqf"]
|
780 |
+
bs, nc, h, w = z.shape
|
781 |
+
if ks[0] > h or ks[1] > w:
|
782 |
+
ks = (min(ks[0], h), min(ks[1], w))
|
783 |
+
print("reducing Kernel")
|
784 |
+
|
785 |
+
if stride[0] > h or stride[1] > w:
|
786 |
+
stride = (min(stride[0], h), min(stride[1], w))
|
787 |
+
print("reducing stride")
|
788 |
+
|
789 |
+
fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf)
|
790 |
+
|
791 |
+
z = unfold(z) # (bn, nc * prod(**ks), L)
|
792 |
+
# 1. Reshape to img shape
|
793 |
+
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
|
794 |
+
|
795 |
+
# 2. apply model loop over last dim
|
796 |
+
if isinstance(self.first_stage_model, VQModelInterface):
|
797 |
+
output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
|
798 |
+
force_not_quantize=predict_cids or force_not_quantize)
|
799 |
+
for i in range(z.shape[-1])]
|
800 |
+
else:
|
801 |
+
|
802 |
+
output_list = [self.first_stage_model.decode(z[:, :, :, :, i])
|
803 |
+
for i in range(z.shape[-1])]
|
804 |
+
|
805 |
+
o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)
|
806 |
+
o = o * weighting
|
807 |
+
# Reverse 1. reshape to img shape
|
808 |
+
o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
|
809 |
+
# stitch crops together
|
810 |
+
decoded = fold(o)
|
811 |
+
decoded = decoded / normalization # norm is shape (1, 1, h, w)
|
812 |
+
return decoded
|
813 |
+
else:
|
814 |
+
if isinstance(self.first_stage_model, VQModelInterface):
|
815 |
+
return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
|
816 |
+
else:
|
817 |
+
return self.first_stage_model.decode(z)
|
818 |
+
|
819 |
+
else:
|
820 |
+
if isinstance(self.first_stage_model, VQModelInterface):
|
821 |
+
return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
|
822 |
+
else:
|
823 |
+
return self.first_stage_model.decode(z)
|
824 |
+
|
825 |
+
@torch.no_grad()
|
826 |
+
def encode_first_stage(self, x):
|
827 |
+
if hasattr(self, "split_input_params"):
|
828 |
+
if self.split_input_params["patch_distributed_vq"]:
|
829 |
+
ks = self.split_input_params["ks"] # eg. (128, 128)
|
830 |
+
stride = self.split_input_params["stride"] # eg. (64, 64)
|
831 |
+
df = self.split_input_params["vqf"]
|
832 |
+
self.split_input_params['original_image_size'] = x.shape[-2:]
|
833 |
+
bs, nc, h, w = x.shape
|
834 |
+
if ks[0] > h or ks[1] > w:
|
835 |
+
ks = (min(ks[0], h), min(ks[1], w))
|
836 |
+
print("reducing Kernel")
|
837 |
+
|
838 |
+
if stride[0] > h or stride[1] > w:
|
839 |
+
stride = (min(stride[0], h), min(stride[1], w))
|
840 |
+
print("reducing stride")
|
841 |
+
|
842 |
+
fold, unfold, normalization, weighting = self.get_fold_unfold(x, ks, stride, df=df)
|
843 |
+
z = unfold(x) # (bn, nc * prod(**ks), L)
|
844 |
+
# Reshape to img shape
|
845 |
+
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
|
846 |
+
|
847 |
+
output_list = [self.first_stage_model.encode(z[:, :, :, :, i])
|
848 |
+
for i in range(z.shape[-1])]
|
849 |
+
|
850 |
+
o = torch.stack(output_list, axis=-1)
|
851 |
+
o = o * weighting
|
852 |
+
|
853 |
+
# Reverse reshape to img shape
|
854 |
+
o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
|
855 |
+
# stitch crops together
|
856 |
+
decoded = fold(o)
|
857 |
+
decoded = decoded / normalization
|
858 |
+
return decoded
|
859 |
+
|
860 |
+
else:
|
861 |
+
return self.first_stage_model.encode(x)
|
862 |
+
else:
|
863 |
+
return self.first_stage_model.encode(x)
|
864 |
+
|
865 |
+
def shared_step(self, batch, **kwargs):
|
866 |
+
x, c = self.get_input(batch, self.first_stage_key)
|
867 |
+
loss = self(x, c)
|
868 |
+
return loss
|
869 |
+
|
870 |
+
def forward(self, x, c, *args, **kwargs):
|
871 |
+
t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
|
872 |
+
if self.model.conditioning_key is not None:
|
873 |
+
assert c is not None
|
874 |
+
if self.cond_stage_trainable:
|
875 |
+
c = self.get_learned_conditioning(c)
|
876 |
+
if self.shorten_cond_schedule: # TODO: drop this option
|
877 |
+
tc = self.cond_ids[t].to(self.device)
|
878 |
+
c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))
|
879 |
+
return self.p_losses(x, c, t, *args, **kwargs)
|
880 |
+
|
881 |
+
def _rescale_annotations(self, bboxes, crop_coordinates): # TODO: move to dataset
|
882 |
+
def rescale_bbox(bbox):
|
883 |
+
x0 = clamp((bbox[0] - crop_coordinates[0]) / crop_coordinates[2])
|
884 |
+
y0 = clamp((bbox[1] - crop_coordinates[1]) / crop_coordinates[3])
|
885 |
+
w = min(bbox[2] / crop_coordinates[2], 1 - x0)
|
886 |
+
h = min(bbox[3] / crop_coordinates[3], 1 - y0)
|
887 |
+
return x0, y0, w, h
|
888 |
+
|
889 |
+
return [rescale_bbox(b) for b in bboxes]
|
890 |
+
|
891 |
+
def apply_model(self, x_noisy, t, cond, return_ids=False):
|
892 |
+
|
893 |
+
if isinstance(cond, dict):
|
894 |
+
# hybrid case, cond is exptected to be a dict
|
895 |
+
pass
|
896 |
+
else:
|
897 |
+
if not isinstance(cond, list):
|
898 |
+
cond = [cond]
|
899 |
+
key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'
|
900 |
+
cond = {key: cond}
|
901 |
+
|
902 |
+
if hasattr(self, "split_input_params"):
|
903 |
+
assert len(cond) == 1 # todo can only deal with one conditioning atm
|
904 |
+
assert not return_ids
|
905 |
+
ks = self.split_input_params["ks"] # eg. (128, 128)
|
906 |
+
stride = self.split_input_params["stride"] # eg. (64, 64)
|
907 |
+
|
908 |
+
h, w = x_noisy.shape[-2:]
|
909 |
+
|
910 |
+
fold, unfold, normalization, weighting = self.get_fold_unfold(x_noisy, ks, stride)
|
911 |
+
|
912 |
+
z = unfold(x_noisy) # (bn, nc * prod(**ks), L)
|
913 |
+
# Reshape to img shape
|
914 |
+
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
|
915 |
+
z_list = [z[:, :, :, :, i] for i in range(z.shape[-1])]
|
916 |
+
|
917 |
+
if self.cond_stage_key in ["image", "LR_image", "segmentation",
|
918 |
+
'bbox_img'] and self.model.conditioning_key: # todo check for completeness
|
919 |
+
c_key = next(iter(cond.keys())) # get key
|
920 |
+
c = next(iter(cond.values())) # get value
|
921 |
+
assert (len(c) == 1) # todo extend to list with more than one elem
|
922 |
+
c = c[0] # get element
|
923 |
+
|
924 |
+
c = unfold(c)
|
925 |
+
c = c.view((c.shape[0], -1, ks[0], ks[1], c.shape[-1])) # (bn, nc, ks[0], ks[1], L )
|
926 |
+
|
927 |
+
cond_list = [{c_key: [c[:, :, :, :, i]]} for i in range(c.shape[-1])]
|
928 |
+
|
929 |
+
elif self.cond_stage_key == 'coordinates_bbox':
|
930 |
+
assert 'original_image_size' in self.split_input_params, 'BoudingBoxRescaling is missing original_image_size'
|
931 |
+
|
932 |
+
# assuming padding of unfold is always 0 and its dilation is always 1
|
933 |
+
n_patches_per_row = int((w - ks[0]) / stride[0] + 1)
|
934 |
+
full_img_h, full_img_w = self.split_input_params['original_image_size']
|
935 |
+
# as we are operating on latents, we need the factor from the original image size to the
|
936 |
+
# spatial latent size to properly rescale the crops for regenerating the bbox annotations
|
937 |
+
num_downs = self.first_stage_model.encoder.num_resolutions - 1
|
938 |
+
rescale_latent = 2 ** (num_downs)
|
939 |
+
|
940 |
+
# get top left postions of patches as conforming for the bbbox tokenizer, therefore we
|
941 |
+
# need to rescale the tl patch coordinates to be in between (0,1)
|
942 |
+
tl_patch_coordinates = [(rescale_latent * stride[0] * (patch_nr % n_patches_per_row) / full_img_w,
|
943 |
+
rescale_latent * stride[1] * (patch_nr // n_patches_per_row) / full_img_h)
|
944 |
+
for patch_nr in range(z.shape[-1])]
|
945 |
+
|
946 |
+
# patch_limits are tl_coord, width and height coordinates as (x_tl, y_tl, h, w)
|
947 |
+
patch_limits = [(x_tl, y_tl,
|
948 |
+
rescale_latent * ks[0] / full_img_w,
|
949 |
+
rescale_latent * ks[1] / full_img_h) for x_tl, y_tl in tl_patch_coordinates]
|
950 |
+
# patch_values = [(np.arange(x_tl,min(x_tl+ks, 1.)),np.arange(y_tl,min(y_tl+ks, 1.))) for x_tl, y_tl in tl_patch_coordinates]
|
951 |
+
|
952 |
+
# tokenize crop coordinates for the bounding boxes of the respective patches
|
953 |
+
patch_limits_tknzd = [torch.LongTensor(self.bbox_tokenizer._crop_encoder(bbox))[None].to(self.device)
|
954 |
+
for bbox in patch_limits] # list of length l with tensors of shape (1, 2)
|
955 |
+
print(patch_limits_tknzd[0].shape)
|
956 |
+
# cut tknzd crop position from conditioning
|
957 |
+
assert isinstance(cond, dict), 'cond must be dict to be fed into model'
|
958 |
+
cut_cond = cond['c_crossattn'][0][..., :-2].to(self.device)
|
959 |
+
print(cut_cond.shape)
|
960 |
+
|
961 |
+
adapted_cond = torch.stack([torch.cat([cut_cond, p], dim=1) for p in patch_limits_tknzd])
|
962 |
+
adapted_cond = rearrange(adapted_cond, 'l b n -> (l b) n')
|
963 |
+
print(adapted_cond.shape)
|
964 |
+
adapted_cond = self.get_learned_conditioning(adapted_cond)
|
965 |
+
print(adapted_cond.shape)
|
966 |
+
adapted_cond = rearrange(adapted_cond, '(l b) n d -> l b n d', l=z.shape[-1])
|
967 |
+
print(adapted_cond.shape)
|
968 |
+
|
969 |
+
cond_list = [{'c_crossattn': [e]} for e in adapted_cond]
|
970 |
+
|
971 |
+
else:
|
972 |
+
cond_list = [cond for i in range(z.shape[-1])] # Todo make this more efficient
|
973 |
+
|
974 |
+
# apply model by loop over crops
|
975 |
+
output_list = [self.model(z_list[i], t, **cond_list[i]) for i in range(z.shape[-1])]
|
976 |
+
assert not isinstance(output_list[0],
|
977 |
+
tuple) # todo cant deal with multiple model outputs check this never happens
|
978 |
+
|
979 |
+
o = torch.stack(output_list, axis=-1)
|
980 |
+
o = o * weighting
|
981 |
+
# Reverse reshape to img shape
|
982 |
+
o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
|
983 |
+
# stitch crops together
|
984 |
+
x_recon = fold(o) / normalization
|
985 |
+
|
986 |
+
else:
|
987 |
+
x_recon = self.model(x_noisy, t, **cond)
|
988 |
+
|
989 |
+
if isinstance(x_recon, tuple) and not return_ids:
|
990 |
+
return x_recon[0]
|
991 |
+
else:
|
992 |
+
return x_recon
|
993 |
+
|
994 |
+
def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
|
995 |
+
return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \
|
996 |
+
extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
|
997 |
+
|
998 |
+
def _prior_bpd(self, x_start):
|
999 |
+
"""
|
1000 |
+
Get the prior KL term for the variational lower-bound, measured in
|
1001 |
+
bits-per-dim.
|
1002 |
+
This term can't be optimized, as it only depends on the encoder.
|
1003 |
+
:param x_start: the [N x C x ...] tensor of inputs.
|
1004 |
+
:return: a batch of [N] KL values (in bits), one per batch element.
|
1005 |
+
"""
|
1006 |
+
batch_size = x_start.shape[0]
|
1007 |
+
t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
|
1008 |
+
qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
|
1009 |
+
kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
|
1010 |
+
return mean_flat(kl_prior) / np.log(2.0)
|
1011 |
+
|
1012 |
+
def p_losses(self, x_start, cond, t, noise=None):
|
1013 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
1014 |
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
1015 |
+
model_output = self.apply_model(x_noisy, t, cond)
|
1016 |
+
|
1017 |
+
loss_dict = {}
|
1018 |
+
prefix = 'train' if self.training else 'val'
|
1019 |
+
|
1020 |
+
if self.parameterization == "x0":
|
1021 |
+
target = x_start
|
1022 |
+
elif self.parameterization == "eps":
|
1023 |
+
target = noise
|
1024 |
+
else:
|
1025 |
+
raise NotImplementedError()
|
1026 |
+
|
1027 |
+
loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3])
|
1028 |
+
loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})
|
1029 |
+
|
1030 |
+
logvar_t = self.logvar[t].to(self.device)
|
1031 |
+
loss = loss_simple / torch.exp(logvar_t) + logvar_t
|
1032 |
+
# loss = loss_simple / torch.exp(self.logvar) + self.logvar
|
1033 |
+
if self.learn_logvar:
|
1034 |
+
loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})
|
1035 |
+
loss_dict.update({'logvar': self.logvar.data.mean()})
|
1036 |
+
|
1037 |
+
loss = self.l_simple_weight * loss.mean()
|
1038 |
+
|
1039 |
+
loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3))
|
1040 |
+
loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()
|
1041 |
+
loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})
|
1042 |
+
loss += (self.original_elbo_weight * loss_vlb)
|
1043 |
+
loss_dict.update({f'{prefix}/loss': loss})
|
1044 |
+
|
1045 |
+
return loss, loss_dict
|
1046 |
+
|
1047 |
+
def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False,
|
1048 |
+
return_x0=False, score_corrector=None, corrector_kwargs=None):
|
1049 |
+
t_in = t
|
1050 |
+
model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)
|
1051 |
+
|
1052 |
+
if score_corrector is not None:
|
1053 |
+
assert self.parameterization == "eps"
|
1054 |
+
model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)
|
1055 |
+
|
1056 |
+
if return_codebook_ids:
|
1057 |
+
model_out, logits = model_out
|
1058 |
+
|
1059 |
+
if self.parameterization == "eps":
|
1060 |
+
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
|
1061 |
+
elif self.parameterization == "x0":
|
1062 |
+
x_recon = model_out
|
1063 |
+
else:
|
1064 |
+
raise NotImplementedError()
|
1065 |
+
|
1066 |
+
if clip_denoised:
|
1067 |
+
x_recon.clamp_(-1., 1.)
|
1068 |
+
if quantize_denoised:
|
1069 |
+
x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)
|
1070 |
+
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
|
1071 |
+
if return_codebook_ids:
|
1072 |
+
return model_mean, posterior_variance, posterior_log_variance, logits
|
1073 |
+
elif return_x0:
|
1074 |
+
return model_mean, posterior_variance, posterior_log_variance, x_recon
|
1075 |
+
else:
|
1076 |
+
return model_mean, posterior_variance, posterior_log_variance
|
1077 |
+
|
1078 |
+
@torch.no_grad()
|
1079 |
+
def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False,
|
1080 |
+
return_codebook_ids=False, quantize_denoised=False, return_x0=False,
|
1081 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):
|
1082 |
+
b, *_, device = *x.shape, x.device
|
1083 |
+
outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised,
|
1084 |
+
return_codebook_ids=return_codebook_ids,
|
1085 |
+
quantize_denoised=quantize_denoised,
|
1086 |
+
return_x0=return_x0,
|
1087 |
+
score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
|
1088 |
+
if return_codebook_ids:
|
1089 |
+
raise DeprecationWarning("Support dropped.")
|
1090 |
+
model_mean, _, model_log_variance, logits = outputs
|
1091 |
+
elif return_x0:
|
1092 |
+
model_mean, _, model_log_variance, x0 = outputs
|
1093 |
+
else:
|
1094 |
+
model_mean, _, model_log_variance = outputs
|
1095 |
+
|
1096 |
+
noise = noise_like(x.shape, device, repeat_noise) * temperature
|
1097 |
+
if noise_dropout > 0.:
|
1098 |
+
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
|
1099 |
+
# no noise when t == 0
|
1100 |
+
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
|
1101 |
+
|
1102 |
+
if return_codebook_ids:
|
1103 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1)
|
1104 |
+
if return_x0:
|
1105 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0
|
1106 |
+
else:
|
1107 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
|
1108 |
+
|
1109 |
+
@torch.no_grad()
|
1110 |
+
def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False,
|
1111 |
+
img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0.,
|
1112 |
+
score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None,
|
1113 |
+
log_every_t=None):
|
1114 |
+
if not log_every_t:
|
1115 |
+
log_every_t = self.log_every_t
|
1116 |
+
timesteps = self.num_timesteps
|
1117 |
+
if batch_size is not None:
|
1118 |
+
b = batch_size if batch_size is not None else shape[0]
|
1119 |
+
shape = [batch_size] + list(shape)
|
1120 |
+
else:
|
1121 |
+
b = batch_size = shape[0]
|
1122 |
+
if x_T is None:
|
1123 |
+
img = torch.randn(shape, device=self.device)
|
1124 |
+
else:
|
1125 |
+
img = x_T
|
1126 |
+
intermediates = []
|
1127 |
+
if cond is not None:
|
1128 |
+
if isinstance(cond, dict):
|
1129 |
+
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
|
1130 |
+
list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
|
1131 |
+
else:
|
1132 |
+
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
|
1133 |
+
|
1134 |
+
if start_T is not None:
|
1135 |
+
timesteps = min(timesteps, start_T)
|
1136 |
+
iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation',
|
1137 |
+
total=timesteps) if verbose else reversed(
|
1138 |
+
range(0, timesteps))
|
1139 |
+
if type(temperature) == float:
|
1140 |
+
temperature = [temperature] * timesteps
|
1141 |
+
|
1142 |
+
for i in iterator:
|
1143 |
+
ts = torch.full((b,), i, device=self.device, dtype=torch.long)
|
1144 |
+
if self.shorten_cond_schedule:
|
1145 |
+
assert self.model.conditioning_key != 'hybrid'
|
1146 |
+
tc = self.cond_ids[ts].to(cond.device)
|
1147 |
+
cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
|
1148 |
+
|
1149 |
+
img, x0_partial = self.p_sample(img, cond, ts,
|
1150 |
+
clip_denoised=self.clip_denoised,
|
1151 |
+
quantize_denoised=quantize_denoised, return_x0=True,
|
1152 |
+
temperature=temperature[i], noise_dropout=noise_dropout,
|
1153 |
+
score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
|
1154 |
+
if mask is not None:
|
1155 |
+
assert x0 is not None
|
1156 |
+
img_orig = self.q_sample(x0, ts)
|
1157 |
+
img = img_orig * mask + (1. - mask) * img
|
1158 |
+
|
1159 |
+
if i % log_every_t == 0 or i == timesteps - 1:
|
1160 |
+
intermediates.append(x0_partial)
|
1161 |
+
if callback: callback(i)
|
1162 |
+
if img_callback: img_callback(img, i)
|
1163 |
+
return img, intermediates
|
1164 |
+
|
1165 |
+
@torch.no_grad()
|
1166 |
+
def p_sample_loop(self, cond, shape, return_intermediates=False,
|
1167 |
+
x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False,
|
1168 |
+
mask=None, x0=None, img_callback=None, start_T=None,
|
1169 |
+
log_every_t=None):
|
1170 |
+
|
1171 |
+
if not log_every_t:
|
1172 |
+
log_every_t = self.log_every_t
|
1173 |
+
device = self.betas.device
|
1174 |
+
b = shape[0]
|
1175 |
+
if x_T is None:
|
1176 |
+
img = torch.randn(shape, device=device)
|
1177 |
+
else:
|
1178 |
+
img = x_T
|
1179 |
+
|
1180 |
+
intermediates = [img]
|
1181 |
+
if timesteps is None:
|
1182 |
+
timesteps = self.num_timesteps
|
1183 |
+
|
1184 |
+
if start_T is not None:
|
1185 |
+
timesteps = min(timesteps, start_T)
|
1186 |
+
iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(
|
1187 |
+
range(0, timesteps))
|
1188 |
+
|
1189 |
+
if mask is not None:
|
1190 |
+
assert x0 is not None
|
1191 |
+
assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match
|
1192 |
+
|
1193 |
+
for i in iterator:
|
1194 |
+
ts = torch.full((b,), i, device=device, dtype=torch.long)
|
1195 |
+
if self.shorten_cond_schedule:
|
1196 |
+
assert self.model.conditioning_key != 'hybrid'
|
1197 |
+
tc = self.cond_ids[ts].to(cond.device)
|
1198 |
+
cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
|
1199 |
+
|
1200 |
+
img = self.p_sample(img, cond, ts,
|
1201 |
+
clip_denoised=self.clip_denoised,
|
1202 |
+
quantize_denoised=quantize_denoised)
|
1203 |
+
if mask is not None:
|
1204 |
+
img_orig = self.q_sample(x0, ts)
|
1205 |
+
img = img_orig * mask + (1. - mask) * img
|
1206 |
+
|
1207 |
+
if i % log_every_t == 0 or i == timesteps - 1:
|
1208 |
+
intermediates.append(img)
|
1209 |
+
if callback: callback(i)
|
1210 |
+
if img_callback: img_callback(img, i)
|
1211 |
+
|
1212 |
+
if return_intermediates:
|
1213 |
+
return img, intermediates
|
1214 |
+
return img
|
1215 |
+
|
1216 |
+
@torch.no_grad()
|
1217 |
+
def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None,
|
1218 |
+
verbose=True, timesteps=None, quantize_denoised=False,
|
1219 |
+
mask=None, x0=None, shape=None,**kwargs):
|
1220 |
+
if shape is None:
|
1221 |
+
shape = (batch_size, self.channels, self.image_size, self.image_size)
|
1222 |
+
if cond is not None:
|
1223 |
+
if isinstance(cond, dict):
|
1224 |
+
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
|
1225 |
+
list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
|
1226 |
+
else:
|
1227 |
+
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
|
1228 |
+
return self.p_sample_loop(cond,
|
1229 |
+
shape,
|
1230 |
+
return_intermediates=return_intermediates, x_T=x_T,
|
1231 |
+
verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised,
|
1232 |
+
mask=mask, x0=x0)
|
1233 |
+
|
1234 |
+
@torch.no_grad()
|
1235 |
+
def sample_log(self,cond,batch_size,ddim, ddim_steps,**kwargs):
|
1236 |
+
|
1237 |
+
if ddim:
|
1238 |
+
ddim_sampler = DDIMSampler(self)
|
1239 |
+
shape = (self.channels, self.image_size, self.image_size)
|
1240 |
+
samples, intermediates =ddim_sampler.sample(ddim_steps,batch_size,
|
1241 |
+
shape,cond,verbose=False,**kwargs)
|
1242 |
+
|
1243 |
+
else:
|
1244 |
+
samples, intermediates = self.sample(cond=cond, batch_size=batch_size,
|
1245 |
+
return_intermediates=True,**kwargs)
|
1246 |
+
|
1247 |
+
return samples, intermediates
|
1248 |
+
|
1249 |
+
|
1250 |
+
@torch.no_grad()
|
1251 |
+
def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
|
1252 |
+
quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
|
1253 |
+
plot_diffusion_rows=True, **kwargs):
|
1254 |
+
|
1255 |
+
use_ddim = ddim_steps is not None
|
1256 |
+
|
1257 |
+
log = dict()
|
1258 |
+
z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,
|
1259 |
+
return_first_stage_outputs=True,
|
1260 |
+
force_c_encode=True,
|
1261 |
+
return_original_cond=True,
|
1262 |
+
bs=N)
|
1263 |
+
N = min(x.shape[0], N)
|
1264 |
+
n_row = min(x.shape[0], n_row)
|
1265 |
+
log["inputs"] = x
|
1266 |
+
log["reconstruction"] = xrec
|
1267 |
+
if self.model.conditioning_key is not None:
|
1268 |
+
if hasattr(self.cond_stage_model, "decode"):
|
1269 |
+
xc = self.cond_stage_model.decode(c)
|
1270 |
+
log["conditioning"] = xc
|
1271 |
+
elif self.cond_stage_key in ["caption"]:
|
1272 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["caption"])
|
1273 |
+
log["conditioning"] = xc
|
1274 |
+
elif self.cond_stage_key == 'class_label':
|
1275 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"])
|
1276 |
+
log['conditioning'] = xc
|
1277 |
+
elif isimage(xc):
|
1278 |
+
log["conditioning"] = xc
|
1279 |
+
if ismap(xc):
|
1280 |
+
log["original_conditioning"] = self.to_rgb(xc)
|
1281 |
+
|
1282 |
+
if plot_diffusion_rows:
|
1283 |
+
# get diffusion row
|
1284 |
+
diffusion_row = list()
|
1285 |
+
z_start = z[:n_row]
|
1286 |
+
for t in range(self.num_timesteps):
|
1287 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
1288 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
1289 |
+
t = t.to(self.device).long()
|
1290 |
+
noise = torch.randn_like(z_start)
|
1291 |
+
z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
|
1292 |
+
diffusion_row.append(self.decode_first_stage(z_noisy))
|
1293 |
+
|
1294 |
+
diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
|
1295 |
+
diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
|
1296 |
+
diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
|
1297 |
+
diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
|
1298 |
+
log["diffusion_row"] = diffusion_grid
|
1299 |
+
|
1300 |
+
if sample:
|
1301 |
+
# get denoise row
|
1302 |
+
with self.ema_scope("Plotting"):
|
1303 |
+
samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim,
|
1304 |
+
ddim_steps=ddim_steps,eta=ddim_eta)
|
1305 |
+
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
|
1306 |
+
x_samples = self.decode_first_stage(samples)
|
1307 |
+
log["samples"] = x_samples
|
1308 |
+
if plot_denoise_rows:
|
1309 |
+
denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
|
1310 |
+
log["denoise_row"] = denoise_grid
|
1311 |
+
|
1312 |
+
if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(
|
1313 |
+
self.first_stage_model, IdentityFirstStage):
|
1314 |
+
# also display when quantizing x0 while sampling
|
1315 |
+
with self.ema_scope("Plotting Quantized Denoised"):
|
1316 |
+
samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim,
|
1317 |
+
ddim_steps=ddim_steps,eta=ddim_eta,
|
1318 |
+
quantize_denoised=True)
|
1319 |
+
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,
|
1320 |
+
# quantize_denoised=True)
|
1321 |
+
x_samples = self.decode_first_stage(samples.to(self.device))
|
1322 |
+
log["samples_x0_quantized"] = x_samples
|
1323 |
+
|
1324 |
+
if inpaint:
|
1325 |
+
# make a simple center square
|
1326 |
+
b, h, w = z.shape[0], z.shape[2], z.shape[3]
|
1327 |
+
mask = torch.ones(N, h, w).to(self.device)
|
1328 |
+
# zeros will be filled in
|
1329 |
+
mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.
|
1330 |
+
mask = mask[:, None, ...]
|
1331 |
+
with self.ema_scope("Plotting Inpaint"):
|
1332 |
+
|
1333 |
+
samples, _ = self.sample_log(cond=c,batch_size=N,ddim=use_ddim, eta=ddim_eta,
|
1334 |
+
ddim_steps=ddim_steps, x0=z[:N], mask=mask)
|
1335 |
+
x_samples = self.decode_first_stage(samples.to(self.device))
|
1336 |
+
log["samples_inpainting"] = x_samples
|
1337 |
+
log["mask"] = mask
|
1338 |
+
|
1339 |
+
# outpaint
|
1340 |
+
with self.ema_scope("Plotting Outpaint"):
|
1341 |
+
samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,eta=ddim_eta,
|
1342 |
+
ddim_steps=ddim_steps, x0=z[:N], mask=mask)
|
1343 |
+
x_samples = self.decode_first_stage(samples.to(self.device))
|
1344 |
+
log["samples_outpainting"] = x_samples
|
1345 |
+
|
1346 |
+
if plot_progressive_rows:
|
1347 |
+
with self.ema_scope("Plotting Progressives"):
|
1348 |
+
img, progressives = self.progressive_denoising(c,
|
1349 |
+
shape=(self.channels, self.image_size, self.image_size),
|
1350 |
+
batch_size=N)
|
1351 |
+
prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
|
1352 |
+
log["progressive_row"] = prog_row
|
1353 |
+
|
1354 |
+
if return_keys:
|
1355 |
+
if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
|
1356 |
+
return log
|
1357 |
+
else:
|
1358 |
+
return {key: log[key] for key in return_keys}
|
1359 |
+
return log
|
1360 |
+
|
1361 |
+
def configure_optimizers(self):
|
1362 |
+
lr = self.learning_rate
|
1363 |
+
params = list(self.model.parameters())
|
1364 |
+
if self.cond_stage_trainable:
|
1365 |
+
print(f"{self.__class__.__name__}: Also optimizing conditioner params!")
|
1366 |
+
params = params + list(self.cond_stage_model.parameters())
|
1367 |
+
if self.learn_logvar:
|
1368 |
+
print('Diffusion model optimizing logvar')
|
1369 |
+
params.append(self.logvar)
|
1370 |
+
opt = torch.optim.AdamW(params, lr=lr)
|
1371 |
+
if self.use_scheduler:
|
1372 |
+
assert 'target' in self.scheduler_config
|
1373 |
+
scheduler = instantiate_from_config(self.scheduler_config)
|
1374 |
+
|
1375 |
+
print("Setting up LambdaLR scheduler...")
|
1376 |
+
scheduler = [
|
1377 |
+
{
|
1378 |
+
'scheduler': LambdaLR(opt, lr_lambda=scheduler.schedule),
|
1379 |
+
'interval': 'step',
|
1380 |
+
'frequency': 1
|
1381 |
+
}]
|
1382 |
+
return [opt], scheduler
|
1383 |
+
return opt
|
1384 |
+
|
1385 |
+
@torch.no_grad()
|
1386 |
+
def to_rgb(self, x):
|
1387 |
+
x = x.float()
|
1388 |
+
if not hasattr(self, "colorize"):
|
1389 |
+
self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)
|
1390 |
+
x = nn.functional.conv2d(x, weight=self.colorize)
|
1391 |
+
x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.
|
1392 |
+
return x
|
1393 |
+
|
1394 |
+
|
1395 |
+
class DiffusionWrapper(pl.LightningModule):
|
1396 |
+
def __init__(self, diff_model_config, conditioning_key):
|
1397 |
+
super().__init__()
|
1398 |
+
self.diffusion_model = instantiate_from_config(diff_model_config)
|
1399 |
+
self.conditioning_key = conditioning_key
|
1400 |
+
assert self.conditioning_key in [None, 'concat', 'crossattn', 'hybrid', 'adm']
|
1401 |
+
|
1402 |
+
def forward(self, x, t, c_concat: list = None, c_crossattn: list = None):
|
1403 |
+
if self.conditioning_key is None:
|
1404 |
+
out = self.diffusion_model(x, t)
|
1405 |
+
elif self.conditioning_key == 'concat':
|
1406 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1407 |
+
out = self.diffusion_model(xc, t)
|
1408 |
+
elif self.conditioning_key == 'crossattn':
|
1409 |
+
cc = torch.cat(c_crossattn, 1)
|
1410 |
+
out = self.diffusion_model(x, t, context=cc)
|
1411 |
+
elif self.conditioning_key == 'hybrid':
|
1412 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1413 |
+
cc = torch.cat(c_crossattn, 1)
|
1414 |
+
out = self.diffusion_model(xc, t, context=cc)
|
1415 |
+
elif self.conditioning_key == 'adm':
|
1416 |
+
cc = c_crossattn[0]
|
1417 |
+
out = self.diffusion_model(x, t, y=cc)
|
1418 |
+
else:
|
1419 |
+
raise NotImplementedError()
|
1420 |
+
|
1421 |
+
return out
|
1422 |
+
|
1423 |
+
|
1424 |
+
class Layout2ImgDiffusion(LatentDiffusion):
|
1425 |
+
# TODO: move all layout-specific hacks to this class
|
1426 |
+
def __init__(self, cond_stage_key, *args, **kwargs):
|
1427 |
+
assert cond_stage_key == 'coordinates_bbox', 'Layout2ImgDiffusion only for cond_stage_key="coordinates_bbox"'
|
1428 |
+
super().__init__(cond_stage_key=cond_stage_key, *args, **kwargs)
|
1429 |
+
|
1430 |
+
def log_images(self, batch, N=8, *args, **kwargs):
|
1431 |
+
logs = super().log_images(batch=batch, N=N, *args, **kwargs)
|
1432 |
+
|
1433 |
+
key = 'train' if self.training else 'validation'
|
1434 |
+
dset = self.trainer.datamodule.datasets[key]
|
1435 |
+
mapper = dset.conditional_builders[self.cond_stage_key]
|
1436 |
+
|
1437 |
+
bbox_imgs = []
|
1438 |
+
map_fn = lambda catno: dset.get_textual_label(dset.get_category_id(catno))
|
1439 |
+
for tknzd_bbox in batch[self.cond_stage_key][:N]:
|
1440 |
+
bboximg = mapper.plot(tknzd_bbox.detach().cpu(), map_fn, (256, 256))
|
1441 |
+
bbox_imgs.append(bboximg)
|
1442 |
+
|
1443 |
+
cond_img = torch.stack(bbox_imgs, dim=0)
|
1444 |
+
logs['bbox_image'] = cond_img
|
1445 |
+
return logs
|