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