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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
"""
|
3 |
+
wild mixture of
|
4 |
+
https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
|
5 |
+
https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py
|
6 |
+
https://github.com/CompVis/taming-transformers
|
7 |
+
-- merci
|
8 |
+
"""
|
9 |
+
|
10 |
+
import torch
|
11 |
+
import torch.nn as nn
|
12 |
+
import numpy as np
|
13 |
+
import pytorch_lightning as pl
|
14 |
+
from torch.optim.lr_scheduler import LambdaLR
|
15 |
+
from einops import rearrange, repeat
|
16 |
+
from contextlib import contextmanager, nullcontext
|
17 |
+
from functools import partial
|
18 |
+
import itertools
|
19 |
+
from tqdm import tqdm
|
20 |
+
from torchvision.utils import make_grid
|
21 |
+
from pytorch_lightning.utilities.rank_zero import rank_zero_only
|
22 |
+
from omegaconf import ListConfig
|
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 |
+
|
32 |
+
__conditioning_keys__ = {'concat': 'c_concat',
|
33 |
+
'crossattn': 'c_crossattn',
|
34 |
+
'adm': 'y'}
|
35 |
+
|
36 |
+
|
37 |
+
def disabled_train(self, mode=True):
|
38 |
+
"""Overwrite model.train with this function to make sure train/eval mode
|
39 |
+
does not change anymore."""
|
40 |
+
return self
|
41 |
+
|
42 |
+
|
43 |
+
def uniform_on_device(r1, r2, shape, device):
|
44 |
+
return (r1 - r2) * torch.rand(*shape, device=device) + r2
|
45 |
+
|
46 |
+
|
47 |
+
class DDPM(pl.LightningModule):
|
48 |
+
# classic DDPM with Gaussian diffusion, in image space
|
49 |
+
def __init__(self,
|
50 |
+
unet_config,
|
51 |
+
timesteps=1000,
|
52 |
+
beta_schedule="linear",
|
53 |
+
loss_type="l2",
|
54 |
+
ckpt_path=None,
|
55 |
+
ignore_keys=[],
|
56 |
+
load_only_unet=False,
|
57 |
+
monitor="val/loss",
|
58 |
+
use_ema=True,
|
59 |
+
first_stage_key="image",
|
60 |
+
image_size=256,
|
61 |
+
channels=3,
|
62 |
+
log_every_t=100,
|
63 |
+
clip_denoised=True,
|
64 |
+
linear_start=1e-4,
|
65 |
+
linear_end=2e-2,
|
66 |
+
cosine_s=8e-3,
|
67 |
+
given_betas=None,
|
68 |
+
original_elbo_weight=0.,
|
69 |
+
v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
|
70 |
+
l_simple_weight=1.,
|
71 |
+
conditioning_key=None,
|
72 |
+
parameterization="eps", # all assuming fixed variance schedules
|
73 |
+
scheduler_config=None,
|
74 |
+
use_positional_encodings=False,
|
75 |
+
learn_logvar=False,
|
76 |
+
logvar_init=0.,
|
77 |
+
make_it_fit=False,
|
78 |
+
ucg_training=None,
|
79 |
+
reset_ema=False,
|
80 |
+
reset_num_ema_updates=False,
|
81 |
+
):
|
82 |
+
super().__init__()
|
83 |
+
assert parameterization in ["eps", "x0", "v"], 'currently only supporting "eps" and "x0" and "v"'
|
84 |
+
self.parameterization = parameterization
|
85 |
+
print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
|
86 |
+
self.cond_stage_model = None
|
87 |
+
self.clip_denoised = clip_denoised
|
88 |
+
self.log_every_t = log_every_t
|
89 |
+
self.first_stage_key = first_stage_key
|
90 |
+
self.image_size = image_size # try conv?
|
91 |
+
self.channels = channels
|
92 |
+
self.use_positional_encodings = use_positional_encodings
|
93 |
+
self.model = DiffusionWrapper(unet_config, conditioning_key)
|
94 |
+
count_params(self.model, verbose=True)
|
95 |
+
self.use_ema = use_ema
|
96 |
+
if self.use_ema:
|
97 |
+
self.model_ema = LitEma(self.model)
|
98 |
+
print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
|
99 |
+
|
100 |
+
self.use_scheduler = scheduler_config is not None
|
101 |
+
if self.use_scheduler:
|
102 |
+
self.scheduler_config = scheduler_config
|
103 |
+
|
104 |
+
self.v_posterior = v_posterior
|
105 |
+
self.original_elbo_weight = original_elbo_weight
|
106 |
+
self.l_simple_weight = l_simple_weight
|
107 |
+
|
108 |
+
if monitor is not None:
|
109 |
+
self.monitor = monitor
|
110 |
+
self.make_it_fit = make_it_fit
|
111 |
+
if reset_ema: assert exists(ckpt_path)
|
112 |
+
if ckpt_path is not None:
|
113 |
+
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet)
|
114 |
+
if reset_ema:
|
115 |
+
assert self.use_ema
|
116 |
+
print(f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.")
|
117 |
+
self.model_ema = LitEma(self.model)
|
118 |
+
if reset_num_ema_updates:
|
119 |
+
print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ")
|
120 |
+
assert self.use_ema
|
121 |
+
self.model_ema.reset_num_updates()
|
122 |
+
|
123 |
+
self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
|
124 |
+
linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
|
125 |
+
|
126 |
+
self.loss_type = loss_type
|
127 |
+
|
128 |
+
self.learn_logvar = learn_logvar
|
129 |
+
self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
|
130 |
+
if self.learn_logvar:
|
131 |
+
self.logvar = nn.Parameter(self.logvar, requires_grad=True)
|
132 |
+
|
133 |
+
self.ucg_training = ucg_training or dict()
|
134 |
+
if self.ucg_training:
|
135 |
+
self.ucg_prng = np.random.RandomState()
|
136 |
+
|
137 |
+
def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
|
138 |
+
linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
|
139 |
+
if exists(given_betas):
|
140 |
+
betas = given_betas
|
141 |
+
else:
|
142 |
+
betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
|
143 |
+
cosine_s=cosine_s)
|
144 |
+
alphas = 1. - betas
|
145 |
+
alphas_cumprod = np.cumprod(alphas, axis=0)
|
146 |
+
alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
|
147 |
+
|
148 |
+
timesteps, = betas.shape
|
149 |
+
self.num_timesteps = int(timesteps)
|
150 |
+
self.linear_start = linear_start
|
151 |
+
self.linear_end = linear_end
|
152 |
+
assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
|
153 |
+
|
154 |
+
to_torch = partial(torch.tensor, dtype=torch.float32)
|
155 |
+
|
156 |
+
self.register_buffer('betas', to_torch(betas))
|
157 |
+
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
|
158 |
+
self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
|
159 |
+
|
160 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
161 |
+
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
|
162 |
+
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
|
163 |
+
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
|
164 |
+
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
|
165 |
+
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
|
166 |
+
|
167 |
+
# calculations for posterior q(x_{t-1} | x_t, x_0)
|
168 |
+
posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / (
|
169 |
+
1. - alphas_cumprod) + self.v_posterior * betas
|
170 |
+
# above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
|
171 |
+
self.register_buffer('posterior_variance', to_torch(posterior_variance))
|
172 |
+
# below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
|
173 |
+
self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
|
174 |
+
self.register_buffer('posterior_mean_coef1', to_torch(
|
175 |
+
betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
|
176 |
+
self.register_buffer('posterior_mean_coef2', to_torch(
|
177 |
+
(1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
|
178 |
+
|
179 |
+
if self.parameterization == "eps":
|
180 |
+
lvlb_weights = self.betas ** 2 / (
|
181 |
+
2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))
|
182 |
+
elif self.parameterization == "x0":
|
183 |
+
lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod))
|
184 |
+
elif self.parameterization == "v":
|
185 |
+
lvlb_weights = torch.ones_like(self.betas ** 2 / (
|
186 |
+
2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod)))
|
187 |
+
else:
|
188 |
+
raise NotImplementedError("mu not supported")
|
189 |
+
lvlb_weights[0] = lvlb_weights[1]
|
190 |
+
self.register_buffer('lvlb_weights', lvlb_weights, persistent=False)
|
191 |
+
assert not torch.isnan(self.lvlb_weights).all()
|
192 |
+
|
193 |
+
@contextmanager
|
194 |
+
def ema_scope(self, context=None):
|
195 |
+
if self.use_ema:
|
196 |
+
self.model_ema.store(self.model.parameters())
|
197 |
+
self.model_ema.copy_to(self.model)
|
198 |
+
if context is not None:
|
199 |
+
print(f"{context}: Switched to EMA weights")
|
200 |
+
try:
|
201 |
+
yield None
|
202 |
+
finally:
|
203 |
+
if self.use_ema:
|
204 |
+
self.model_ema.restore(self.model.parameters())
|
205 |
+
if context is not None:
|
206 |
+
print(f"{context}: Restored training weights")
|
207 |
+
|
208 |
+
@torch.no_grad()
|
209 |
+
def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
|
210 |
+
sd = torch.load(path, map_location="cpu")
|
211 |
+
if "state_dict" in list(sd.keys()):
|
212 |
+
sd = sd["state_dict"]
|
213 |
+
keys = list(sd.keys())
|
214 |
+
for k in keys:
|
215 |
+
for ik in ignore_keys:
|
216 |
+
if k.startswith(ik):
|
217 |
+
print("Deleting key {} from state_dict.".format(k))
|
218 |
+
del sd[k]
|
219 |
+
if self.make_it_fit:
|
220 |
+
n_params = len([name for name, _ in
|
221 |
+
itertools.chain(self.named_parameters(),
|
222 |
+
self.named_buffers())])
|
223 |
+
for name, param in tqdm(
|
224 |
+
itertools.chain(self.named_parameters(),
|
225 |
+
self.named_buffers()),
|
226 |
+
desc="Fitting old weights to new weights",
|
227 |
+
total=n_params
|
228 |
+
):
|
229 |
+
if not name in sd:
|
230 |
+
continue
|
231 |
+
old_shape = sd[name].shape
|
232 |
+
new_shape = param.shape
|
233 |
+
assert len(old_shape) == len(new_shape)
|
234 |
+
if len(new_shape) > 2:
|
235 |
+
# we only modify first two axes
|
236 |
+
assert new_shape[2:] == old_shape[2:]
|
237 |
+
# assumes first axis corresponds to output dim
|
238 |
+
if not new_shape == old_shape:
|
239 |
+
new_param = param.clone()
|
240 |
+
old_param = sd[name]
|
241 |
+
if len(new_shape) == 1:
|
242 |
+
for i in range(new_param.shape[0]):
|
243 |
+
new_param[i] = old_param[i % old_shape[0]]
|
244 |
+
elif len(new_shape) >= 2:
|
245 |
+
for i in range(new_param.shape[0]):
|
246 |
+
for j in range(new_param.shape[1]):
|
247 |
+
new_param[i, j] = old_param[i % old_shape[0], j % old_shape[1]]
|
248 |
+
|
249 |
+
n_used_old = torch.ones(old_shape[1])
|
250 |
+
for j in range(new_param.shape[1]):
|
251 |
+
n_used_old[j % old_shape[1]] += 1
|
252 |
+
n_used_new = torch.zeros(new_shape[1])
|
253 |
+
for j in range(new_param.shape[1]):
|
254 |
+
n_used_new[j] = n_used_old[j % old_shape[1]]
|
255 |
+
|
256 |
+
n_used_new = n_used_new[None, :]
|
257 |
+
while len(n_used_new.shape) < len(new_shape):
|
258 |
+
n_used_new = n_used_new.unsqueeze(-1)
|
259 |
+
new_param /= n_used_new
|
260 |
+
|
261 |
+
sd[name] = new_param
|
262 |
+
|
263 |
+
missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
|
264 |
+
sd, strict=False)
|
265 |
+
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
266 |
+
if len(missing) > 0:
|
267 |
+
print(f"Missing Keys:\n {missing}")
|
268 |
+
if len(unexpected) > 0:
|
269 |
+
print(f"\nUnexpected Keys:\n {unexpected}")
|
270 |
+
|
271 |
+
def q_mean_variance(self, x_start, t):
|
272 |
+
"""
|
273 |
+
Get the distribution q(x_t | x_0).
|
274 |
+
:param x_start: the [N x C x ...] tensor of noiseless inputs.
|
275 |
+
:param t: the number of diffusion steps (minus 1). Here, 0 means one step.
|
276 |
+
:return: A tuple (mean, variance, log_variance), all of x_start's shape.
|
277 |
+
"""
|
278 |
+
mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
|
279 |
+
variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
|
280 |
+
log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
|
281 |
+
return mean, variance, log_variance
|
282 |
+
|
283 |
+
def predict_start_from_noise(self, x_t, t, noise):
|
284 |
+
return (
|
285 |
+
extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
|
286 |
+
extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
|
287 |
+
)
|
288 |
+
|
289 |
+
def predict_start_from_z_and_v(self, x_t, t, v):
|
290 |
+
# self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
|
291 |
+
# self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
|
292 |
+
return (
|
293 |
+
extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * x_t -
|
294 |
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * v
|
295 |
+
)
|
296 |
+
|
297 |
+
def predict_eps_from_z_and_v(self, x_t, t, v):
|
298 |
+
return (
|
299 |
+
extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * v +
|
300 |
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * x_t
|
301 |
+
)
|
302 |
+
|
303 |
+
def q_posterior(self, x_start, x_t, t):
|
304 |
+
posterior_mean = (
|
305 |
+
extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start +
|
306 |
+
extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
|
307 |
+
)
|
308 |
+
posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape)
|
309 |
+
posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
|
310 |
+
return posterior_mean, posterior_variance, posterior_log_variance_clipped
|
311 |
+
|
312 |
+
def p_mean_variance(self, x, t, clip_denoised: bool):
|
313 |
+
model_out = self.model(x, t)
|
314 |
+
if self.parameterization == "eps":
|
315 |
+
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
|
316 |
+
elif self.parameterization == "x0":
|
317 |
+
x_recon = model_out
|
318 |
+
if clip_denoised:
|
319 |
+
x_recon.clamp_(-1., 1.)
|
320 |
+
|
321 |
+
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
|
322 |
+
return model_mean, posterior_variance, posterior_log_variance
|
323 |
+
|
324 |
+
@torch.no_grad()
|
325 |
+
def p_sample(self, x, t, clip_denoised=True, repeat_noise=False):
|
326 |
+
b, *_, device = *x.shape, x.device
|
327 |
+
model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
|
328 |
+
noise = noise_like(x.shape, device, repeat_noise)
|
329 |
+
# no noise when t == 0
|
330 |
+
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
|
331 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
|
332 |
+
|
333 |
+
@torch.no_grad()
|
334 |
+
def p_sample_loop(self, shape, return_intermediates=False):
|
335 |
+
device = self.betas.device
|
336 |
+
b = shape[0]
|
337 |
+
img = torch.randn(shape, device=device)
|
338 |
+
intermediates = [img]
|
339 |
+
for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps):
|
340 |
+
img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long),
|
341 |
+
clip_denoised=self.clip_denoised)
|
342 |
+
if i % self.log_every_t == 0 or i == self.num_timesteps - 1:
|
343 |
+
intermediates.append(img)
|
344 |
+
if return_intermediates:
|
345 |
+
return img, intermediates
|
346 |
+
return img
|
347 |
+
|
348 |
+
@torch.no_grad()
|
349 |
+
def sample(self, batch_size=16, return_intermediates=False):
|
350 |
+
image_size = self.image_size
|
351 |
+
channels = self.channels
|
352 |
+
return self.p_sample_loop((batch_size, channels, image_size, image_size),
|
353 |
+
return_intermediates=return_intermediates)
|
354 |
+
|
355 |
+
def q_sample(self, x_start, t, noise=None):
|
356 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
357 |
+
return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
|
358 |
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
|
359 |
+
|
360 |
+
def get_v(self, x, noise, t):
|
361 |
+
return (
|
362 |
+
extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * noise -
|
363 |
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * x
|
364 |
+
)
|
365 |
+
|
366 |
+
def get_loss(self, pred, target, mean=True):
|
367 |
+
if self.loss_type == 'l1':
|
368 |
+
loss = (target - pred).abs()
|
369 |
+
if mean:
|
370 |
+
loss = loss.mean()
|
371 |
+
elif self.loss_type == 'l2':
|
372 |
+
if mean:
|
373 |
+
loss = torch.nn.functional.mse_loss(target, pred)
|
374 |
+
else:
|
375 |
+
loss = torch.nn.functional.mse_loss(target, pred, reduction='none')
|
376 |
+
else:
|
377 |
+
raise NotImplementedError("unknown loss type '{loss_type}'")
|
378 |
+
|
379 |
+
return loss
|
380 |
+
|
381 |
+
def p_losses(self, x_start, t, noise=None):
|
382 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
383 |
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
384 |
+
model_out = self.model(x_noisy, t)
|
385 |
+
|
386 |
+
loss_dict = {}
|
387 |
+
if self.parameterization == "eps":
|
388 |
+
target = noise
|
389 |
+
elif self.parameterization == "x0":
|
390 |
+
target = x_start
|
391 |
+
elif self.parameterization == "v":
|
392 |
+
target = self.get_v(x_start, noise, t)
|
393 |
+
else:
|
394 |
+
raise NotImplementedError(f"Parameterization {self.parameterization} not yet supported")
|
395 |
+
|
396 |
+
loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3])
|
397 |
+
|
398 |
+
log_prefix = 'train' if self.training else 'val'
|
399 |
+
|
400 |
+
loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()})
|
401 |
+
loss_simple = loss.mean() * self.l_simple_weight
|
402 |
+
|
403 |
+
loss_vlb = (self.lvlb_weights[t] * loss).mean()
|
404 |
+
loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb})
|
405 |
+
|
406 |
+
loss = loss_simple + self.original_elbo_weight * loss_vlb
|
407 |
+
|
408 |
+
loss_dict.update({f'{log_prefix}/loss': loss})
|
409 |
+
|
410 |
+
return loss, loss_dict
|
411 |
+
|
412 |
+
def forward(self, x, *args, **kwargs):
|
413 |
+
# b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size
|
414 |
+
# assert h == img_size and w == img_size, f'height and width of image must be {img_size}'
|
415 |
+
t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
|
416 |
+
return self.p_losses(x, t, *args, **kwargs)
|
417 |
+
|
418 |
+
def get_input(self, batch, k):
|
419 |
+
x = batch[k]
|
420 |
+
if len(x.shape) == 3:
|
421 |
+
x = x[..., None]
|
422 |
+
x = rearrange(x, 'b h w c -> b c h w')
|
423 |
+
x = x.to(memory_format=torch.contiguous_format).float()
|
424 |
+
return x
|
425 |
+
|
426 |
+
def shared_step(self, batch):
|
427 |
+
x = self.get_input(batch, self.first_stage_key)
|
428 |
+
loss, loss_dict = self(x)
|
429 |
+
return loss, loss_dict
|
430 |
+
|
431 |
+
def training_step(self, batch, batch_idx):
|
432 |
+
for k in self.ucg_training:
|
433 |
+
p = self.ucg_training[k]["p"]
|
434 |
+
val = self.ucg_training[k]["val"]
|
435 |
+
if val is None:
|
436 |
+
val = ""
|
437 |
+
for i in range(len(batch[k])):
|
438 |
+
if self.ucg_prng.choice(2, p=[1 - p, p]):
|
439 |
+
batch[k][i] = val
|
440 |
+
|
441 |
+
loss, loss_dict = self.shared_step(batch)
|
442 |
+
|
443 |
+
self.log_dict(loss_dict, prog_bar=True,
|
444 |
+
logger=True, on_step=True, on_epoch=True)
|
445 |
+
|
446 |
+
self.log("global_step", self.global_step,
|
447 |
+
prog_bar=True, logger=True, on_step=True, on_epoch=False)
|
448 |
+
|
449 |
+
if self.use_scheduler:
|
450 |
+
lr = self.optimizers().param_groups[0]['lr']
|
451 |
+
self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False)
|
452 |
+
|
453 |
+
return loss
|
454 |
+
|
455 |
+
@torch.no_grad()
|
456 |
+
def validation_step(self, batch, batch_idx):
|
457 |
+
_, loss_dict_no_ema = self.shared_step(batch)
|
458 |
+
with self.ema_scope():
|
459 |
+
_, loss_dict_ema = self.shared_step(batch)
|
460 |
+
loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema}
|
461 |
+
self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
|
462 |
+
self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
|
463 |
+
|
464 |
+
def on_train_batch_end(self, *args, **kwargs):
|
465 |
+
if self.use_ema:
|
466 |
+
self.model_ema(self.model)
|
467 |
+
|
468 |
+
def _get_rows_from_list(self, samples):
|
469 |
+
n_imgs_per_row = len(samples)
|
470 |
+
denoise_grid = rearrange(samples, 'n b c h w -> b n c h w')
|
471 |
+
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
|
472 |
+
denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
|
473 |
+
return denoise_grid
|
474 |
+
|
475 |
+
@torch.no_grad()
|
476 |
+
def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
|
477 |
+
log = dict()
|
478 |
+
x = self.get_input(batch, self.first_stage_key)
|
479 |
+
N = min(x.shape[0], N)
|
480 |
+
n_row = min(x.shape[0], n_row)
|
481 |
+
x = x.to(self.device)[:N]
|
482 |
+
log["inputs"] = x
|
483 |
+
|
484 |
+
# get diffusion row
|
485 |
+
diffusion_row = list()
|
486 |
+
x_start = x[:n_row]
|
487 |
+
|
488 |
+
for t in range(self.num_timesteps):
|
489 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
490 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
491 |
+
t = t.to(self.device).long()
|
492 |
+
noise = torch.randn_like(x_start)
|
493 |
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
494 |
+
diffusion_row.append(x_noisy)
|
495 |
+
|
496 |
+
log["diffusion_row"] = self._get_rows_from_list(diffusion_row)
|
497 |
+
|
498 |
+
if sample:
|
499 |
+
# get denoise row
|
500 |
+
with self.ema_scope("Plotting"):
|
501 |
+
samples, denoise_row = self.sample(batch_size=N, return_intermediates=True)
|
502 |
+
|
503 |
+
log["samples"] = samples
|
504 |
+
log["denoise_row"] = self._get_rows_from_list(denoise_row)
|
505 |
+
|
506 |
+
if return_keys:
|
507 |
+
if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
|
508 |
+
return log
|
509 |
+
else:
|
510 |
+
return {key: log[key] for key in return_keys}
|
511 |
+
return log
|
512 |
+
|
513 |
+
def configure_optimizers(self):
|
514 |
+
lr = self.learning_rate
|
515 |
+
params = list(self.model.parameters())
|
516 |
+
if self.learn_logvar:
|
517 |
+
params = params + [self.logvar]
|
518 |
+
opt = torch.optim.AdamW(params, lr=lr)
|
519 |
+
return opt
|
520 |
+
|
521 |
+
|
522 |
+
class LatentDiffusion(DDPM):
|
523 |
+
"""main class"""
|
524 |
+
|
525 |
+
def __init__(self,
|
526 |
+
first_stage_config,
|
527 |
+
cond_stage_config,
|
528 |
+
num_timesteps_cond=None,
|
529 |
+
cond_stage_key="image",
|
530 |
+
cond_stage_trainable=False,
|
531 |
+
concat_mode=True,
|
532 |
+
cond_stage_forward=None,
|
533 |
+
conditioning_key=None,
|
534 |
+
scale_factor=1.0,
|
535 |
+
scale_by_std=False,
|
536 |
+
force_null_conditioning=False,
|
537 |
+
*args, **kwargs):
|
538 |
+
self.force_null_conditioning = force_null_conditioning
|
539 |
+
self.num_timesteps_cond = default(num_timesteps_cond, 1)
|
540 |
+
self.scale_by_std = scale_by_std
|
541 |
+
assert self.num_timesteps_cond <= kwargs['timesteps']
|
542 |
+
# for backwards compatibility after implementation of DiffusionWrapper
|
543 |
+
if conditioning_key is None:
|
544 |
+
conditioning_key = 'concat' if concat_mode else 'crossattn'
|
545 |
+
if cond_stage_config == '__is_unconditional__' and not self.force_null_conditioning:
|
546 |
+
conditioning_key = None
|
547 |
+
ckpt_path = kwargs.pop("ckpt_path", None)
|
548 |
+
reset_ema = kwargs.pop("reset_ema", False)
|
549 |
+
reset_num_ema_updates = kwargs.pop("reset_num_ema_updates", False)
|
550 |
+
ignore_keys = kwargs.pop("ignore_keys", [])
|
551 |
+
super().__init__(conditioning_key=conditioning_key, *args, **kwargs)
|
552 |
+
self.concat_mode = concat_mode
|
553 |
+
self.cond_stage_trainable = cond_stage_trainable
|
554 |
+
self.cond_stage_key = cond_stage_key
|
555 |
+
try:
|
556 |
+
self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
|
557 |
+
except:
|
558 |
+
self.num_downs = 0
|
559 |
+
if not scale_by_std:
|
560 |
+
self.scale_factor = scale_factor
|
561 |
+
else:
|
562 |
+
self.register_buffer('scale_factor', torch.tensor(scale_factor))
|
563 |
+
self.instantiate_first_stage(first_stage_config)
|
564 |
+
self.instantiate_cond_stage(cond_stage_config)
|
565 |
+
self.cond_stage_forward = cond_stage_forward
|
566 |
+
self.clip_denoised = False
|
567 |
+
self.bbox_tokenizer = None
|
568 |
+
|
569 |
+
self.restarted_from_ckpt = False
|
570 |
+
if ckpt_path is not None:
|
571 |
+
self.init_from_ckpt(ckpt_path, ignore_keys)
|
572 |
+
self.restarted_from_ckpt = True
|
573 |
+
if reset_ema:
|
574 |
+
assert self.use_ema
|
575 |
+
print(
|
576 |
+
f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.")
|
577 |
+
self.model_ema = LitEma(self.model)
|
578 |
+
if reset_num_ema_updates:
|
579 |
+
print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ")
|
580 |
+
assert self.use_ema
|
581 |
+
self.model_ema.reset_num_updates()
|
582 |
+
|
583 |
+
def make_cond_schedule(self, ):
|
584 |
+
self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)
|
585 |
+
ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()
|
586 |
+
self.cond_ids[:self.num_timesteps_cond] = ids
|
587 |
+
|
588 |
+
@rank_zero_only
|
589 |
+
@torch.no_grad()
|
590 |
+
def on_train_batch_start(self, batch, batch_idx, dataloader_idx):
|
591 |
+
# only for very first batch
|
592 |
+
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:
|
593 |
+
assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously'
|
594 |
+
# set rescale weight to 1./std of encodings
|
595 |
+
print("### USING STD-RESCALING ###")
|
596 |
+
x = super().get_input(batch, self.first_stage_key)
|
597 |
+
x = x.to(self.device)
|
598 |
+
encoder_posterior = self.encode_first_stage(x)
|
599 |
+
z = self.get_first_stage_encoding(encoder_posterior).detach()
|
600 |
+
del self.scale_factor
|
601 |
+
self.register_buffer('scale_factor', 1. / z.flatten().std())
|
602 |
+
print(f"setting self.scale_factor to {self.scale_factor}")
|
603 |
+
print("### USING STD-RESCALING ###")
|
604 |
+
|
605 |
+
def register_schedule(self,
|
606 |
+
given_betas=None, beta_schedule="linear", timesteps=1000,
|
607 |
+
linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
|
608 |
+
super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)
|
609 |
+
|
610 |
+
self.shorten_cond_schedule = self.num_timesteps_cond > 1
|
611 |
+
if self.shorten_cond_schedule:
|
612 |
+
self.make_cond_schedule()
|
613 |
+
|
614 |
+
def instantiate_first_stage(self, config):
|
615 |
+
model = instantiate_from_config(config)
|
616 |
+
self.first_stage_model = model.eval()
|
617 |
+
self.first_stage_model.train = disabled_train
|
618 |
+
for param in self.first_stage_model.parameters():
|
619 |
+
param.requires_grad = False
|
620 |
+
|
621 |
+
def instantiate_cond_stage(self, config):
|
622 |
+
if not self.cond_stage_trainable:
|
623 |
+
if config == "__is_first_stage__":
|
624 |
+
print("Using first stage also as cond stage.")
|
625 |
+
self.cond_stage_model = self.first_stage_model
|
626 |
+
elif config == "__is_unconditional__":
|
627 |
+
print(f"Training {self.__class__.__name__} as an unconditional model.")
|
628 |
+
self.cond_stage_model = None
|
629 |
+
# self.be_unconditional = True
|
630 |
+
else:
|
631 |
+
model = instantiate_from_config(config)
|
632 |
+
self.cond_stage_model = model.eval()
|
633 |
+
self.cond_stage_model.train = disabled_train
|
634 |
+
for param in self.cond_stage_model.parameters():
|
635 |
+
param.requires_grad = False
|
636 |
+
else:
|
637 |
+
assert config != '__is_first_stage__'
|
638 |
+
assert config != '__is_unconditional__'
|
639 |
+
model = instantiate_from_config(config)
|
640 |
+
self.cond_stage_model = model
|
641 |
+
|
642 |
+
def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False):
|
643 |
+
denoise_row = []
|
644 |
+
for zd in tqdm(samples, desc=desc):
|
645 |
+
denoise_row.append(self.decode_first_stage(zd.to(self.device),
|
646 |
+
force_not_quantize=force_no_decoder_quantization))
|
647 |
+
n_imgs_per_row = len(denoise_row)
|
648 |
+
denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W
|
649 |
+
denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')
|
650 |
+
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
|
651 |
+
denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
|
652 |
+
return denoise_grid
|
653 |
+
|
654 |
+
def get_first_stage_encoding(self, encoder_posterior):
|
655 |
+
if isinstance(encoder_posterior, DiagonalGaussianDistribution):
|
656 |
+
z = encoder_posterior.sample()
|
657 |
+
elif isinstance(encoder_posterior, torch.Tensor):
|
658 |
+
z = encoder_posterior
|
659 |
+
else:
|
660 |
+
raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented")
|
661 |
+
return self.scale_factor * z
|
662 |
+
|
663 |
+
def get_learned_conditioning(self, c):
|
664 |
+
if self.cond_stage_forward is None:
|
665 |
+
if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):
|
666 |
+
c = self.cond_stage_model.encode(c)
|
667 |
+
if isinstance(c, DiagonalGaussianDistribution):
|
668 |
+
c = c.mode()
|
669 |
+
else:
|
670 |
+
c = self.cond_stage_model(c)
|
671 |
+
else:
|
672 |
+
assert hasattr(self.cond_stage_model, self.cond_stage_forward)
|
673 |
+
c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)
|
674 |
+
return c
|
675 |
+
|
676 |
+
def meshgrid(self, h, w):
|
677 |
+
y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)
|
678 |
+
x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)
|
679 |
+
|
680 |
+
arr = torch.cat([y, x], dim=-1)
|
681 |
+
return arr
|
682 |
+
|
683 |
+
def delta_border(self, h, w):
|
684 |
+
"""
|
685 |
+
:param h: height
|
686 |
+
:param w: width
|
687 |
+
:return: normalized distance to image border,
|
688 |
+
wtith min distance = 0 at border and max dist = 0.5 at image center
|
689 |
+
"""
|
690 |
+
lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
|
691 |
+
arr = self.meshgrid(h, w) / lower_right_corner
|
692 |
+
dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]
|
693 |
+
dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]
|
694 |
+
edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0]
|
695 |
+
return edge_dist
|
696 |
+
|
697 |
+
def get_weighting(self, h, w, Ly, Lx, device):
|
698 |
+
weighting = self.delta_border(h, w)
|
699 |
+
weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"],
|
700 |
+
self.split_input_params["clip_max_weight"], )
|
701 |
+
weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)
|
702 |
+
|
703 |
+
if self.split_input_params["tie_braker"]:
|
704 |
+
L_weighting = self.delta_border(Ly, Lx)
|
705 |
+
L_weighting = torch.clip(L_weighting,
|
706 |
+
self.split_input_params["clip_min_tie_weight"],
|
707 |
+
self.split_input_params["clip_max_tie_weight"])
|
708 |
+
|
709 |
+
L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)
|
710 |
+
weighting = weighting * L_weighting
|
711 |
+
return weighting
|
712 |
+
|
713 |
+
def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code
|
714 |
+
"""
|
715 |
+
:param x: img of size (bs, c, h, w)
|
716 |
+
:return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])
|
717 |
+
"""
|
718 |
+
bs, nc, h, w = x.shape
|
719 |
+
|
720 |
+
# number of crops in image
|
721 |
+
Ly = (h - kernel_size[0]) // stride[0] + 1
|
722 |
+
Lx = (w - kernel_size[1]) // stride[1] + 1
|
723 |
+
|
724 |
+
if uf == 1 and df == 1:
|
725 |
+
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
|
726 |
+
unfold = torch.nn.Unfold(**fold_params)
|
727 |
+
|
728 |
+
fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)
|
729 |
+
|
730 |
+
weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype)
|
731 |
+
normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap
|
732 |
+
weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))
|
733 |
+
|
734 |
+
elif uf > 1 and df == 1:
|
735 |
+
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
|
736 |
+
unfold = torch.nn.Unfold(**fold_params)
|
737 |
+
|
738 |
+
fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),
|
739 |
+
dilation=1, padding=0,
|
740 |
+
stride=(stride[0] * uf, stride[1] * uf))
|
741 |
+
fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2)
|
742 |
+
|
743 |
+
weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype)
|
744 |
+
normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap
|
745 |
+
weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx))
|
746 |
+
|
747 |
+
elif df > 1 and uf == 1:
|
748 |
+
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
|
749 |
+
unfold = torch.nn.Unfold(**fold_params)
|
750 |
+
|
751 |
+
fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df),
|
752 |
+
dilation=1, padding=0,
|
753 |
+
stride=(stride[0] // df, stride[1] // df))
|
754 |
+
fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2)
|
755 |
+
|
756 |
+
weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype)
|
757 |
+
normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap
|
758 |
+
weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx))
|
759 |
+
|
760 |
+
else:
|
761 |
+
raise NotImplementedError
|
762 |
+
|
763 |
+
return fold, unfold, normalization, weighting
|
764 |
+
|
765 |
+
@torch.no_grad()
|
766 |
+
def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False,
|
767 |
+
cond_key=None, return_original_cond=False, bs=None, return_x=False):
|
768 |
+
x = super().get_input(batch, k)
|
769 |
+
if bs is not None:
|
770 |
+
x = x[:bs]
|
771 |
+
x = x.to(self.device)
|
772 |
+
encoder_posterior = self.encode_first_stage(x)
|
773 |
+
z = self.get_first_stage_encoding(encoder_posterior).detach()
|
774 |
+
|
775 |
+
if self.model.conditioning_key is not None and not self.force_null_conditioning:
|
776 |
+
if cond_key is None:
|
777 |
+
cond_key = self.cond_stage_key
|
778 |
+
if cond_key != self.first_stage_key:
|
779 |
+
if cond_key in ['caption', 'coordinates_bbox', "txt"]:
|
780 |
+
xc = batch[cond_key]
|
781 |
+
elif cond_key in ['class_label', 'cls']:
|
782 |
+
xc = batch
|
783 |
+
else:
|
784 |
+
xc = super().get_input(batch, cond_key).to(self.device)
|
785 |
+
else:
|
786 |
+
xc = x
|
787 |
+
if not self.cond_stage_trainable or force_c_encode:
|
788 |
+
if isinstance(xc, dict) or isinstance(xc, list):
|
789 |
+
c = self.get_learned_conditioning(xc)
|
790 |
+
else:
|
791 |
+
c = self.get_learned_conditioning(xc.to(self.device))
|
792 |
+
else:
|
793 |
+
c = xc
|
794 |
+
if bs is not None:
|
795 |
+
c = c[:bs]
|
796 |
+
|
797 |
+
if self.use_positional_encodings:
|
798 |
+
pos_x, pos_y = self.compute_latent_shifts(batch)
|
799 |
+
ckey = __conditioning_keys__[self.model.conditioning_key]
|
800 |
+
c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y}
|
801 |
+
|
802 |
+
else:
|
803 |
+
c = None
|
804 |
+
xc = None
|
805 |
+
if self.use_positional_encodings:
|
806 |
+
pos_x, pos_y = self.compute_latent_shifts(batch)
|
807 |
+
c = {'pos_x': pos_x, 'pos_y': pos_y}
|
808 |
+
out = [z, c]
|
809 |
+
if return_first_stage_outputs:
|
810 |
+
xrec = self.decode_first_stage(z)
|
811 |
+
out.extend([x, xrec])
|
812 |
+
if return_x:
|
813 |
+
out.extend([x])
|
814 |
+
if return_original_cond:
|
815 |
+
out.append(xc)
|
816 |
+
return out
|
817 |
+
|
818 |
+
@torch.no_grad()
|
819 |
+
def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
|
820 |
+
if predict_cids:
|
821 |
+
if z.dim() == 4:
|
822 |
+
z = torch.argmax(z.exp(), dim=1).long()
|
823 |
+
z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
|
824 |
+
z = rearrange(z, 'b h w c -> b c h w').contiguous()
|
825 |
+
|
826 |
+
z = 1. / self.scale_factor * z
|
827 |
+
return self.first_stage_model.decode(z)
|
828 |
+
|
829 |
+
@torch.no_grad()
|
830 |
+
def encode_first_stage(self, x):
|
831 |
+
return self.first_stage_model.encode(x)
|
832 |
+
|
833 |
+
def shared_step(self, batch, **kwargs):
|
834 |
+
x, c = self.get_input(batch, self.first_stage_key)
|
835 |
+
loss = self(x, c)
|
836 |
+
return loss
|
837 |
+
|
838 |
+
def forward(self, x, c, *args, **kwargs):
|
839 |
+
t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
|
840 |
+
if self.model.conditioning_key is not None:
|
841 |
+
assert c is not None
|
842 |
+
if self.cond_stage_trainable:
|
843 |
+
c = self.get_learned_conditioning(c)
|
844 |
+
if self.shorten_cond_schedule: # TODO: drop this option
|
845 |
+
tc = self.cond_ids[t].to(self.device)
|
846 |
+
c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))
|
847 |
+
return self.p_losses(x, c, t, *args, **kwargs)
|
848 |
+
|
849 |
+
def apply_model(self, x_noisy, t, cond, return_ids=False):
|
850 |
+
if isinstance(cond, dict):
|
851 |
+
# hybrid case, cond is expected to be a dict
|
852 |
+
pass
|
853 |
+
else:
|
854 |
+
if not isinstance(cond, list):
|
855 |
+
cond = [cond]
|
856 |
+
key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'
|
857 |
+
cond = {key: cond}
|
858 |
+
|
859 |
+
x_recon = self.model(x_noisy, t, **cond)
|
860 |
+
|
861 |
+
if isinstance(x_recon, tuple) and not return_ids:
|
862 |
+
return x_recon[0]
|
863 |
+
else:
|
864 |
+
return x_recon
|
865 |
+
|
866 |
+
def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
|
867 |
+
return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \
|
868 |
+
extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
|
869 |
+
|
870 |
+
def _prior_bpd(self, x_start):
|
871 |
+
"""
|
872 |
+
Get the prior KL term for the variational lower-bound, measured in
|
873 |
+
bits-per-dim.
|
874 |
+
This term can't be optimized, as it only depends on the encoder.
|
875 |
+
:param x_start: the [N x C x ...] tensor of inputs.
|
876 |
+
:return: a batch of [N] KL values (in bits), one per batch element.
|
877 |
+
"""
|
878 |
+
batch_size = x_start.shape[0]
|
879 |
+
t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
|
880 |
+
qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
|
881 |
+
kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
|
882 |
+
return mean_flat(kl_prior) / np.log(2.0)
|
883 |
+
|
884 |
+
def p_losses(self, x_start, cond, t, noise=None):
|
885 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
886 |
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
887 |
+
model_output = self.apply_model(x_noisy, t, cond)
|
888 |
+
|
889 |
+
loss_dict = {}
|
890 |
+
prefix = 'train' if self.training else 'val'
|
891 |
+
|
892 |
+
if self.parameterization == "x0":
|
893 |
+
target = x_start
|
894 |
+
elif self.parameterization == "eps":
|
895 |
+
target = noise
|
896 |
+
elif self.parameterization == "v":
|
897 |
+
target = self.get_v(x_start, noise, t)
|
898 |
+
else:
|
899 |
+
raise NotImplementedError()
|
900 |
+
|
901 |
+
loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3])
|
902 |
+
loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})
|
903 |
+
|
904 |
+
logvar_t = self.logvar[t].to(self.device)
|
905 |
+
loss = loss_simple / torch.exp(logvar_t) + logvar_t
|
906 |
+
# loss = loss_simple / torch.exp(self.logvar) + self.logvar
|
907 |
+
if self.learn_logvar:
|
908 |
+
loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})
|
909 |
+
loss_dict.update({'logvar': self.logvar.data.mean()})
|
910 |
+
|
911 |
+
loss = self.l_simple_weight * loss.mean()
|
912 |
+
|
913 |
+
loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3))
|
914 |
+
loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()
|
915 |
+
loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})
|
916 |
+
loss += (self.original_elbo_weight * loss_vlb)
|
917 |
+
loss_dict.update({f'{prefix}/loss': loss})
|
918 |
+
|
919 |
+
return loss, loss_dict
|
920 |
+
|
921 |
+
def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False,
|
922 |
+
return_x0=False, score_corrector=None, corrector_kwargs=None):
|
923 |
+
t_in = t
|
924 |
+
model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)
|
925 |
+
|
926 |
+
if score_corrector is not None:
|
927 |
+
assert self.parameterization == "eps"
|
928 |
+
model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)
|
929 |
+
|
930 |
+
if return_codebook_ids:
|
931 |
+
model_out, logits = model_out
|
932 |
+
|
933 |
+
if self.parameterization == "eps":
|
934 |
+
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
|
935 |
+
elif self.parameterization == "x0":
|
936 |
+
x_recon = model_out
|
937 |
+
else:
|
938 |
+
raise NotImplementedError()
|
939 |
+
|
940 |
+
if clip_denoised:
|
941 |
+
x_recon.clamp_(-1., 1.)
|
942 |
+
if quantize_denoised:
|
943 |
+
x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)
|
944 |
+
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
|
945 |
+
if return_codebook_ids:
|
946 |
+
return model_mean, posterior_variance, posterior_log_variance, logits
|
947 |
+
elif return_x0:
|
948 |
+
return model_mean, posterior_variance, posterior_log_variance, x_recon
|
949 |
+
else:
|
950 |
+
return model_mean, posterior_variance, posterior_log_variance
|
951 |
+
|
952 |
+
@torch.no_grad()
|
953 |
+
def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False,
|
954 |
+
return_codebook_ids=False, quantize_denoised=False, return_x0=False,
|
955 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):
|
956 |
+
b, *_, device = *x.shape, x.device
|
957 |
+
outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised,
|
958 |
+
return_codebook_ids=return_codebook_ids,
|
959 |
+
quantize_denoised=quantize_denoised,
|
960 |
+
return_x0=return_x0,
|
961 |
+
score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
|
962 |
+
if return_codebook_ids:
|
963 |
+
raise DeprecationWarning("Support dropped.")
|
964 |
+
model_mean, _, model_log_variance, logits = outputs
|
965 |
+
elif return_x0:
|
966 |
+
model_mean, _, model_log_variance, x0 = outputs
|
967 |
+
else:
|
968 |
+
model_mean, _, model_log_variance = outputs
|
969 |
+
|
970 |
+
noise = noise_like(x.shape, device, repeat_noise) * temperature
|
971 |
+
if noise_dropout > 0.:
|
972 |
+
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
|
973 |
+
# no noise when t == 0
|
974 |
+
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
|
975 |
+
|
976 |
+
if return_codebook_ids:
|
977 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1)
|
978 |
+
if return_x0:
|
979 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0
|
980 |
+
else:
|
981 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
|
982 |
+
|
983 |
+
@torch.no_grad()
|
984 |
+
def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False,
|
985 |
+
img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0.,
|
986 |
+
score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None,
|
987 |
+
log_every_t=None):
|
988 |
+
if not log_every_t:
|
989 |
+
log_every_t = self.log_every_t
|
990 |
+
timesteps = self.num_timesteps
|
991 |
+
if batch_size is not None:
|
992 |
+
b = batch_size if batch_size is not None else shape[0]
|
993 |
+
shape = [batch_size] + list(shape)
|
994 |
+
else:
|
995 |
+
b = batch_size = shape[0]
|
996 |
+
if x_T is None:
|
997 |
+
img = torch.randn(shape, device=self.device)
|
998 |
+
else:
|
999 |
+
img = x_T
|
1000 |
+
intermediates = []
|
1001 |
+
if cond is not None:
|
1002 |
+
if isinstance(cond, dict):
|
1003 |
+
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
|
1004 |
+
list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
|
1005 |
+
else:
|
1006 |
+
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
|
1007 |
+
|
1008 |
+
if start_T is not None:
|
1009 |
+
timesteps = min(timesteps, start_T)
|
1010 |
+
iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation',
|
1011 |
+
total=timesteps) if verbose else reversed(
|
1012 |
+
range(0, timesteps))
|
1013 |
+
if type(temperature) == float:
|
1014 |
+
temperature = [temperature] * timesteps
|
1015 |
+
|
1016 |
+
for i in iterator:
|
1017 |
+
ts = torch.full((b,), i, device=self.device, dtype=torch.long)
|
1018 |
+
if self.shorten_cond_schedule:
|
1019 |
+
assert self.model.conditioning_key != 'hybrid'
|
1020 |
+
tc = self.cond_ids[ts].to(cond.device)
|
1021 |
+
cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
|
1022 |
+
|
1023 |
+
img, x0_partial = self.p_sample(img, cond, ts,
|
1024 |
+
clip_denoised=self.clip_denoised,
|
1025 |
+
quantize_denoised=quantize_denoised, return_x0=True,
|
1026 |
+
temperature=temperature[i], noise_dropout=noise_dropout,
|
1027 |
+
score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
|
1028 |
+
if mask is not None:
|
1029 |
+
assert x0 is not None
|
1030 |
+
img_orig = self.q_sample(x0, ts)
|
1031 |
+
img = img_orig * mask + (1. - mask) * img
|
1032 |
+
|
1033 |
+
if i % log_every_t == 0 or i == timesteps - 1:
|
1034 |
+
intermediates.append(x0_partial)
|
1035 |
+
if callback: callback(i)
|
1036 |
+
if img_callback: img_callback(img, i)
|
1037 |
+
return img, intermediates
|
1038 |
+
|
1039 |
+
@torch.no_grad()
|
1040 |
+
def p_sample_loop(self, cond, shape, return_intermediates=False,
|
1041 |
+
x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False,
|
1042 |
+
mask=None, x0=None, img_callback=None, start_T=None,
|
1043 |
+
log_every_t=None):
|
1044 |
+
|
1045 |
+
if not log_every_t:
|
1046 |
+
log_every_t = self.log_every_t
|
1047 |
+
device = self.betas.device
|
1048 |
+
b = shape[0]
|
1049 |
+
if x_T is None:
|
1050 |
+
img = torch.randn(shape, device=device)
|
1051 |
+
else:
|
1052 |
+
img = x_T
|
1053 |
+
|
1054 |
+
intermediates = [img]
|
1055 |
+
if timesteps is None:
|
1056 |
+
timesteps = self.num_timesteps
|
1057 |
+
|
1058 |
+
if start_T is not None:
|
1059 |
+
timesteps = min(timesteps, start_T)
|
1060 |
+
iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(
|
1061 |
+
range(0, timesteps))
|
1062 |
+
|
1063 |
+
if mask is not None:
|
1064 |
+
assert x0 is not None
|
1065 |
+
assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match
|
1066 |
+
|
1067 |
+
for i in iterator:
|
1068 |
+
ts = torch.full((b,), i, device=device, dtype=torch.long)
|
1069 |
+
if self.shorten_cond_schedule:
|
1070 |
+
assert self.model.conditioning_key != 'hybrid'
|
1071 |
+
tc = self.cond_ids[ts].to(cond.device)
|
1072 |
+
cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
|
1073 |
+
|
1074 |
+
img = self.p_sample(img, cond, ts,
|
1075 |
+
clip_denoised=self.clip_denoised,
|
1076 |
+
quantize_denoised=quantize_denoised)
|
1077 |
+
if mask is not None:
|
1078 |
+
img_orig = self.q_sample(x0, ts)
|
1079 |
+
img = img_orig * mask + (1. - mask) * img
|
1080 |
+
|
1081 |
+
if i % log_every_t == 0 or i == timesteps - 1:
|
1082 |
+
intermediates.append(img)
|
1083 |
+
if callback: callback(i)
|
1084 |
+
if img_callback: img_callback(img, i)
|
1085 |
+
|
1086 |
+
if return_intermediates:
|
1087 |
+
return img, intermediates
|
1088 |
+
return img
|
1089 |
+
|
1090 |
+
@torch.no_grad()
|
1091 |
+
def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None,
|
1092 |
+
verbose=True, timesteps=None, quantize_denoised=False,
|
1093 |
+
mask=None, x0=None, shape=None, **kwargs):
|
1094 |
+
if shape is None:
|
1095 |
+
shape = (batch_size, self.channels, self.image_size, self.image_size)
|
1096 |
+
if cond is not None:
|
1097 |
+
if isinstance(cond, dict):
|
1098 |
+
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
|
1099 |
+
list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
|
1100 |
+
else:
|
1101 |
+
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
|
1102 |
+
return self.p_sample_loop(cond,
|
1103 |
+
shape,
|
1104 |
+
return_intermediates=return_intermediates, x_T=x_T,
|
1105 |
+
verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised,
|
1106 |
+
mask=mask, x0=x0)
|
1107 |
+
|
1108 |
+
@torch.no_grad()
|
1109 |
+
def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs):
|
1110 |
+
if ddim:
|
1111 |
+
ddim_sampler = DDIMSampler(self)
|
1112 |
+
shape = (self.channels, self.image_size, self.image_size)
|
1113 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size,
|
1114 |
+
shape, cond, verbose=False, **kwargs)
|
1115 |
+
|
1116 |
+
else:
|
1117 |
+
samples, intermediates = self.sample(cond=cond, batch_size=batch_size,
|
1118 |
+
return_intermediates=True, **kwargs)
|
1119 |
+
|
1120 |
+
return samples, intermediates
|
1121 |
+
|
1122 |
+
@torch.no_grad()
|
1123 |
+
def get_unconditional_conditioning(self, batch_size, null_label=None):
|
1124 |
+
if null_label is not None:
|
1125 |
+
xc = null_label
|
1126 |
+
if isinstance(xc, ListConfig):
|
1127 |
+
xc = list(xc)
|
1128 |
+
if isinstance(xc, dict) or isinstance(xc, list):
|
1129 |
+
c = self.get_learned_conditioning(xc)
|
1130 |
+
else:
|
1131 |
+
if hasattr(xc, "to"):
|
1132 |
+
xc = xc.to(self.device)
|
1133 |
+
c = self.get_learned_conditioning(xc)
|
1134 |
+
else:
|
1135 |
+
if self.cond_stage_key in ["class_label", "cls"]:
|
1136 |
+
xc = self.cond_stage_model.get_unconditional_conditioning(batch_size, device=self.device)
|
1137 |
+
return self.get_learned_conditioning(xc)
|
1138 |
+
else:
|
1139 |
+
raise NotImplementedError("todo")
|
1140 |
+
if isinstance(c, list): # in case the encoder gives us a list
|
1141 |
+
for i in range(len(c)):
|
1142 |
+
c[i] = repeat(c[i], '1 ... -> b ...', b=batch_size).to(self.device)
|
1143 |
+
else:
|
1144 |
+
c = repeat(c, '1 ... -> b ...', b=batch_size).to(self.device)
|
1145 |
+
return c
|
1146 |
+
|
1147 |
+
@torch.no_grad()
|
1148 |
+
def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=50, ddim_eta=0., return_keys=None,
|
1149 |
+
quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
|
1150 |
+
plot_diffusion_rows=True, unconditional_guidance_scale=1., unconditional_guidance_label=None,
|
1151 |
+
use_ema_scope=True,
|
1152 |
+
**kwargs):
|
1153 |
+
ema_scope = self.ema_scope if use_ema_scope else nullcontext
|
1154 |
+
use_ddim = ddim_steps is not None
|
1155 |
+
|
1156 |
+
log = dict()
|
1157 |
+
z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,
|
1158 |
+
return_first_stage_outputs=True,
|
1159 |
+
force_c_encode=True,
|
1160 |
+
return_original_cond=True,
|
1161 |
+
bs=N)
|
1162 |
+
N = min(x.shape[0], N)
|
1163 |
+
n_row = min(x.shape[0], n_row)
|
1164 |
+
log["inputs"] = x
|
1165 |
+
log["reconstruction"] = xrec
|
1166 |
+
if self.model.conditioning_key is not None:
|
1167 |
+
if hasattr(self.cond_stage_model, "decode"):
|
1168 |
+
xc = self.cond_stage_model.decode(c)
|
1169 |
+
log["conditioning"] = xc
|
1170 |
+
elif self.cond_stage_key in ["caption", "txt"]:
|
1171 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25)
|
1172 |
+
log["conditioning"] = xc
|
1173 |
+
elif self.cond_stage_key in ['class_label', "cls"]:
|
1174 |
+
try:
|
1175 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2] // 25)
|
1176 |
+
log['conditioning'] = xc
|
1177 |
+
except KeyError:
|
1178 |
+
# probably no "human_label" in batch
|
1179 |
+
pass
|
1180 |
+
elif isimage(xc):
|
1181 |
+
log["conditioning"] = xc
|
1182 |
+
if ismap(xc):
|
1183 |
+
log["original_conditioning"] = self.to_rgb(xc)
|
1184 |
+
|
1185 |
+
if plot_diffusion_rows:
|
1186 |
+
# get diffusion row
|
1187 |
+
diffusion_row = list()
|
1188 |
+
z_start = z[:n_row]
|
1189 |
+
for t in range(self.num_timesteps):
|
1190 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
1191 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
1192 |
+
t = t.to(self.device).long()
|
1193 |
+
noise = torch.randn_like(z_start)
|
1194 |
+
z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
|
1195 |
+
diffusion_row.append(self.decode_first_stage(z_noisy))
|
1196 |
+
|
1197 |
+
diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
|
1198 |
+
diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
|
1199 |
+
diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
|
1200 |
+
diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
|
1201 |
+
log["diffusion_row"] = diffusion_grid
|
1202 |
+
|
1203 |
+
if sample:
|
1204 |
+
# get denoise row
|
1205 |
+
with ema_scope("Sampling"):
|
1206 |
+
samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
1207 |
+
ddim_steps=ddim_steps, eta=ddim_eta)
|
1208 |
+
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
|
1209 |
+
x_samples = self.decode_first_stage(samples)
|
1210 |
+
log["samples"] = x_samples
|
1211 |
+
if plot_denoise_rows:
|
1212 |
+
denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
|
1213 |
+
log["denoise_row"] = denoise_grid
|
1214 |
+
|
1215 |
+
if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(
|
1216 |
+
self.first_stage_model, IdentityFirstStage):
|
1217 |
+
# also display when quantizing x0 while sampling
|
1218 |
+
with ema_scope("Plotting Quantized Denoised"):
|
1219 |
+
samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
1220 |
+
ddim_steps=ddim_steps, eta=ddim_eta,
|
1221 |
+
quantize_denoised=True)
|
1222 |
+
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,
|
1223 |
+
# quantize_denoised=True)
|
1224 |
+
x_samples = self.decode_first_stage(samples.to(self.device))
|
1225 |
+
log["samples_x0_quantized"] = x_samples
|
1226 |
+
|
1227 |
+
if unconditional_guidance_scale > 1.0:
|
1228 |
+
uc = self.get_unconditional_conditioning(N, unconditional_guidance_label)
|
1229 |
+
if self.model.conditioning_key == "crossattn-adm":
|
1230 |
+
uc = {"c_crossattn": [uc], "c_adm": c["c_adm"]}
|
1231 |
+
with ema_scope("Sampling with classifier-free guidance"):
|
1232 |
+
samples_cfg, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
1233 |
+
ddim_steps=ddim_steps, eta=ddim_eta,
|
1234 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
1235 |
+
unconditional_conditioning=uc,
|
1236 |
+
)
|
1237 |
+
x_samples_cfg = self.decode_first_stage(samples_cfg)
|
1238 |
+
log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
|
1239 |
+
|
1240 |
+
if inpaint:
|
1241 |
+
# make a simple center square
|
1242 |
+
b, h, w = z.shape[0], z.shape[2], z.shape[3]
|
1243 |
+
mask = torch.ones(N, h, w).to(self.device)
|
1244 |
+
# zeros will be filled in
|
1245 |
+
mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.
|
1246 |
+
mask = mask[:, None, ...]
|
1247 |
+
with ema_scope("Plotting Inpaint"):
|
1248 |
+
samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta,
|
1249 |
+
ddim_steps=ddim_steps, x0=z[:N], mask=mask)
|
1250 |
+
x_samples = self.decode_first_stage(samples.to(self.device))
|
1251 |
+
log["samples_inpainting"] = x_samples
|
1252 |
+
log["mask"] = mask
|
1253 |
+
|
1254 |
+
# outpaint
|
1255 |
+
mask = 1. - mask
|
1256 |
+
with ema_scope("Plotting Outpaint"):
|
1257 |
+
samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta,
|
1258 |
+
ddim_steps=ddim_steps, x0=z[:N], mask=mask)
|
1259 |
+
x_samples = self.decode_first_stage(samples.to(self.device))
|
1260 |
+
log["samples_outpainting"] = x_samples
|
1261 |
+
|
1262 |
+
if plot_progressive_rows:
|
1263 |
+
with ema_scope("Plotting Progressives"):
|
1264 |
+
img, progressives = self.progressive_denoising(c,
|
1265 |
+
shape=(self.channels, self.image_size, self.image_size),
|
1266 |
+
batch_size=N)
|
1267 |
+
prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
|
1268 |
+
log["progressive_row"] = prog_row
|
1269 |
+
|
1270 |
+
if return_keys:
|
1271 |
+
if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
|
1272 |
+
return log
|
1273 |
+
else:
|
1274 |
+
return {key: log[key] for key in return_keys}
|
1275 |
+
return log
|
1276 |
+
|
1277 |
+
def configure_optimizers(self):
|
1278 |
+
lr = self.learning_rate
|
1279 |
+
params = list(self.model.parameters())
|
1280 |
+
if self.cond_stage_trainable:
|
1281 |
+
print(f"{self.__class__.__name__}: Also optimizing conditioner params!")
|
1282 |
+
params = params + list(self.cond_stage_model.parameters())
|
1283 |
+
if self.learn_logvar:
|
1284 |
+
print('Diffusion model optimizing logvar')
|
1285 |
+
params.append(self.logvar)
|
1286 |
+
opt = torch.optim.AdamW(params, lr=lr)
|
1287 |
+
if self.use_scheduler:
|
1288 |
+
assert 'target' in self.scheduler_config
|
1289 |
+
scheduler = instantiate_from_config(self.scheduler_config)
|
1290 |
+
|
1291 |
+
print("Setting up LambdaLR scheduler...")
|
1292 |
+
scheduler = [
|
1293 |
+
{
|
1294 |
+
'scheduler': LambdaLR(opt, lr_lambda=scheduler.schedule),
|
1295 |
+
'interval': 'step',
|
1296 |
+
'frequency': 1
|
1297 |
+
}]
|
1298 |
+
return [opt], scheduler
|
1299 |
+
return opt
|
1300 |
+
|
1301 |
+
@torch.no_grad()
|
1302 |
+
def to_rgb(self, x):
|
1303 |
+
x = x.float()
|
1304 |
+
if not hasattr(self, "colorize"):
|
1305 |
+
self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)
|
1306 |
+
x = nn.functional.conv2d(x, weight=self.colorize)
|
1307 |
+
x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.
|
1308 |
+
return x
|
1309 |
+
|
1310 |
+
|
1311 |
+
class DiffusionWrapper(pl.LightningModule):
|
1312 |
+
def __init__(self, diff_model_config, conditioning_key):
|
1313 |
+
super().__init__()
|
1314 |
+
self.sequential_cross_attn = diff_model_config.pop("sequential_crossattn", False)
|
1315 |
+
self.diffusion_model = instantiate_from_config(diff_model_config)
|
1316 |
+
self.conditioning_key = conditioning_key
|
1317 |
+
assert self.conditioning_key in [None, 'concat', 'crossattn', 'hybrid', 'adm', 'hybrid-adm', 'crossattn-adm']
|
1318 |
+
|
1319 |
+
def forward(self, x, t, c_concat: list = None, c_crossattn: list = None, c_adm=None):
|
1320 |
+
if self.conditioning_key is None:
|
1321 |
+
out = self.diffusion_model(x, t)
|
1322 |
+
elif self.conditioning_key == 'concat':
|
1323 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1324 |
+
out = self.diffusion_model(xc, t)
|
1325 |
+
elif self.conditioning_key == 'crossattn':
|
1326 |
+
if not self.sequential_cross_attn:
|
1327 |
+
cc = torch.cat(c_crossattn, 1)
|
1328 |
+
else:
|
1329 |
+
cc = c_crossattn
|
1330 |
+
if hasattr(self, "scripted_diffusion_model"):
|
1331 |
+
# TorchScript changes names of the arguments
|
1332 |
+
# with argument cc defined as context=cc scripted model will produce
|
1333 |
+
# an error: RuntimeError: forward() is missing value for argument 'argument_3'.
|
1334 |
+
out = self.scripted_diffusion_model(x, t, cc)
|
1335 |
+
else:
|
1336 |
+
out = self.diffusion_model(x, t, context=cc)
|
1337 |
+
elif self.conditioning_key == 'hybrid':
|
1338 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1339 |
+
cc = torch.cat(c_crossattn, 1)
|
1340 |
+
out = self.diffusion_model(xc, t, context=cc)
|
1341 |
+
elif self.conditioning_key == 'hybrid-adm':
|
1342 |
+
assert c_adm is not None
|
1343 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1344 |
+
cc = torch.cat(c_crossattn, 1)
|
1345 |
+
out = self.diffusion_model(xc, t, context=cc, y=c_adm)
|
1346 |
+
elif self.conditioning_key == 'crossattn-adm':
|
1347 |
+
assert c_adm is not None
|
1348 |
+
cc = torch.cat(c_crossattn, 1)
|
1349 |
+
out = self.diffusion_model(x, t, context=cc, y=c_adm)
|
1350 |
+
elif self.conditioning_key == 'adm':
|
1351 |
+
cc = c_crossattn[0]
|
1352 |
+
out = self.diffusion_model(x, t, y=cc)
|
1353 |
+
else:
|
1354 |
+
raise NotImplementedError()
|
1355 |
+
|
1356 |
+
return out
|
1357 |
+
|
1358 |
+
|
1359 |
+
class LatentUpscaleDiffusion(LatentDiffusion):
|
1360 |
+
def __init__(self, *args, low_scale_config, low_scale_key="LR", noise_level_key=None, **kwargs):
|
1361 |
+
super().__init__(*args, **kwargs)
|
1362 |
+
# assumes that neither the cond_stage nor the low_scale_model contain trainable params
|
1363 |
+
assert not self.cond_stage_trainable
|
1364 |
+
self.instantiate_low_stage(low_scale_config)
|
1365 |
+
self.low_scale_key = low_scale_key
|
1366 |
+
self.noise_level_key = noise_level_key
|
1367 |
+
|
1368 |
+
def instantiate_low_stage(self, config):
|
1369 |
+
model = instantiate_from_config(config)
|
1370 |
+
self.low_scale_model = model.eval()
|
1371 |
+
self.low_scale_model.train = disabled_train
|
1372 |
+
for param in self.low_scale_model.parameters():
|
1373 |
+
param.requires_grad = False
|
1374 |
+
|
1375 |
+
@torch.no_grad()
|
1376 |
+
def get_input(self, batch, k, cond_key=None, bs=None, log_mode=False):
|
1377 |
+
if not log_mode:
|
1378 |
+
z, c = super().get_input(batch, k, force_c_encode=True, bs=bs)
|
1379 |
+
else:
|
1380 |
+
z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
|
1381 |
+
force_c_encode=True, return_original_cond=True, bs=bs)
|
1382 |
+
x_low = batch[self.low_scale_key][:bs]
|
1383 |
+
x_low = rearrange(x_low, 'b h w c -> b c h w')
|
1384 |
+
x_low = x_low.to(memory_format=torch.contiguous_format).float()
|
1385 |
+
zx, noise_level = self.low_scale_model(x_low)
|
1386 |
+
if self.noise_level_key is not None:
|
1387 |
+
# get noise level from batch instead, e.g. when extracting a custom noise level for bsr
|
1388 |
+
raise NotImplementedError('TODO')
|
1389 |
+
|
1390 |
+
all_conds = {"c_concat": [zx], "c_crossattn": [c], "c_adm": noise_level}
|
1391 |
+
if log_mode:
|
1392 |
+
# TODO: maybe disable if too expensive
|
1393 |
+
x_low_rec = self.low_scale_model.decode(zx)
|
1394 |
+
return z, all_conds, x, xrec, xc, x_low, x_low_rec, noise_level
|
1395 |
+
return z, all_conds
|
1396 |
+
|
1397 |
+
@torch.no_grad()
|
1398 |
+
def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
|
1399 |
+
plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=True,
|
1400 |
+
unconditional_guidance_scale=1., unconditional_guidance_label=None, use_ema_scope=True,
|
1401 |
+
**kwargs):
|
1402 |
+
ema_scope = self.ema_scope if use_ema_scope else nullcontext
|
1403 |
+
use_ddim = ddim_steps is not None
|
1404 |
+
|
1405 |
+
log = dict()
|
1406 |
+
z, c, x, xrec, xc, x_low, x_low_rec, noise_level = self.get_input(batch, self.first_stage_key, bs=N,
|
1407 |
+
log_mode=True)
|
1408 |
+
N = min(x.shape[0], N)
|
1409 |
+
n_row = min(x.shape[0], n_row)
|
1410 |
+
log["inputs"] = x
|
1411 |
+
log["reconstruction"] = xrec
|
1412 |
+
log["x_lr"] = x_low
|
1413 |
+
log[f"x_lr_rec_@noise_levels{'-'.join(map(lambda x: str(x), list(noise_level.cpu().numpy())))}"] = x_low_rec
|
1414 |
+
if self.model.conditioning_key is not None:
|
1415 |
+
if hasattr(self.cond_stage_model, "decode"):
|
1416 |
+
xc = self.cond_stage_model.decode(c)
|
1417 |
+
log["conditioning"] = xc
|
1418 |
+
elif self.cond_stage_key in ["caption", "txt"]:
|
1419 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25)
|
1420 |
+
log["conditioning"] = xc
|
1421 |
+
elif self.cond_stage_key in ['class_label', 'cls']:
|
1422 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2] // 25)
|
1423 |
+
log['conditioning'] = xc
|
1424 |
+
elif isimage(xc):
|
1425 |
+
log["conditioning"] = xc
|
1426 |
+
if ismap(xc):
|
1427 |
+
log["original_conditioning"] = self.to_rgb(xc)
|
1428 |
+
|
1429 |
+
if plot_diffusion_rows:
|
1430 |
+
# get diffusion row
|
1431 |
+
diffusion_row = list()
|
1432 |
+
z_start = z[:n_row]
|
1433 |
+
for t in range(self.num_timesteps):
|
1434 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
1435 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
1436 |
+
t = t.to(self.device).long()
|
1437 |
+
noise = torch.randn_like(z_start)
|
1438 |
+
z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
|
1439 |
+
diffusion_row.append(self.decode_first_stage(z_noisy))
|
1440 |
+
|
1441 |
+
diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
|
1442 |
+
diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
|
1443 |
+
diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
|
1444 |
+
diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
|
1445 |
+
log["diffusion_row"] = diffusion_grid
|
1446 |
+
|
1447 |
+
if sample:
|
1448 |
+
# get denoise row
|
1449 |
+
with ema_scope("Sampling"):
|
1450 |
+
samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
1451 |
+
ddim_steps=ddim_steps, eta=ddim_eta)
|
1452 |
+
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
|
1453 |
+
x_samples = self.decode_first_stage(samples)
|
1454 |
+
log["samples"] = x_samples
|
1455 |
+
if plot_denoise_rows:
|
1456 |
+
denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
|
1457 |
+
log["denoise_row"] = denoise_grid
|
1458 |
+
|
1459 |
+
if unconditional_guidance_scale > 1.0:
|
1460 |
+
uc_tmp = self.get_unconditional_conditioning(N, unconditional_guidance_label)
|
1461 |
+
# TODO explore better "unconditional" choices for the other keys
|
1462 |
+
# maybe guide away from empty text label and highest noise level and maximally degraded zx?
|
1463 |
+
uc = dict()
|
1464 |
+
for k in c:
|
1465 |
+
if k == "c_crossattn":
|
1466 |
+
assert isinstance(c[k], list) and len(c[k]) == 1
|
1467 |
+
uc[k] = [uc_tmp]
|
1468 |
+
elif k == "c_adm": # todo: only run with text-based guidance?
|
1469 |
+
assert isinstance(c[k], torch.Tensor)
|
1470 |
+
#uc[k] = torch.ones_like(c[k]) * self.low_scale_model.max_noise_level
|
1471 |
+
uc[k] = c[k]
|
1472 |
+
elif isinstance(c[k], list):
|
1473 |
+
uc[k] = [c[k][i] for i in range(len(c[k]))]
|
1474 |
+
else:
|
1475 |
+
uc[k] = c[k]
|
1476 |
+
|
1477 |
+
with ema_scope("Sampling with classifier-free guidance"):
|
1478 |
+
samples_cfg, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
1479 |
+
ddim_steps=ddim_steps, eta=ddim_eta,
|
1480 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
1481 |
+
unconditional_conditioning=uc,
|
1482 |
+
)
|
1483 |
+
x_samples_cfg = self.decode_first_stage(samples_cfg)
|
1484 |
+
log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
|
1485 |
+
|
1486 |
+
if plot_progressive_rows:
|
1487 |
+
with ema_scope("Plotting Progressives"):
|
1488 |
+
img, progressives = self.progressive_denoising(c,
|
1489 |
+
shape=(self.channels, self.image_size, self.image_size),
|
1490 |
+
batch_size=N)
|
1491 |
+
prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
|
1492 |
+
log["progressive_row"] = prog_row
|
1493 |
+
|
1494 |
+
return log
|
1495 |
+
|
1496 |
+
|
1497 |
+
class LatentFinetuneDiffusion(LatentDiffusion):
|
1498 |
+
"""
|
1499 |
+
Basis for different finetunas, such as inpainting or depth2image
|
1500 |
+
To disable finetuning mode, set finetune_keys to None
|
1501 |
+
"""
|
1502 |
+
|
1503 |
+
def __init__(self,
|
1504 |
+
concat_keys: tuple,
|
1505 |
+
finetune_keys=("model.diffusion_model.input_blocks.0.0.weight",
|
1506 |
+
"model_ema.diffusion_modelinput_blocks00weight"
|
1507 |
+
),
|
1508 |
+
keep_finetune_dims=4,
|
1509 |
+
# if model was trained without concat mode before and we would like to keep these channels
|
1510 |
+
c_concat_log_start=None, # to log reconstruction of c_concat codes
|
1511 |
+
c_concat_log_end=None,
|
1512 |
+
*args, **kwargs
|
1513 |
+
):
|
1514 |
+
ckpt_path = kwargs.pop("ckpt_path", None)
|
1515 |
+
ignore_keys = kwargs.pop("ignore_keys", list())
|
1516 |
+
super().__init__(*args, **kwargs)
|
1517 |
+
self.finetune_keys = finetune_keys
|
1518 |
+
self.concat_keys = concat_keys
|
1519 |
+
self.keep_dims = keep_finetune_dims
|
1520 |
+
self.c_concat_log_start = c_concat_log_start
|
1521 |
+
self.c_concat_log_end = c_concat_log_end
|
1522 |
+
if exists(self.finetune_keys): assert exists(ckpt_path), 'can only finetune from a given checkpoint'
|
1523 |
+
if exists(ckpt_path):
|
1524 |
+
self.init_from_ckpt(ckpt_path, ignore_keys)
|
1525 |
+
|
1526 |
+
def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
|
1527 |
+
sd = torch.load(path, map_location="cpu")
|
1528 |
+
if "state_dict" in list(sd.keys()):
|
1529 |
+
sd = sd["state_dict"]
|
1530 |
+
keys = list(sd.keys())
|
1531 |
+
for k in keys:
|
1532 |
+
for ik in ignore_keys:
|
1533 |
+
if k.startswith(ik):
|
1534 |
+
print("Deleting key {} from state_dict.".format(k))
|
1535 |
+
del sd[k]
|
1536 |
+
|
1537 |
+
# make it explicit, finetune by including extra input channels
|
1538 |
+
if exists(self.finetune_keys) and k in self.finetune_keys:
|
1539 |
+
new_entry = None
|
1540 |
+
for name, param in self.named_parameters():
|
1541 |
+
if name in self.finetune_keys:
|
1542 |
+
print(
|
1543 |
+
f"modifying key '{name}' and keeping its original {self.keep_dims} (channels) dimensions only")
|
1544 |
+
new_entry = torch.zeros_like(param) # zero init
|
1545 |
+
assert exists(new_entry), 'did not find matching parameter to modify'
|
1546 |
+
new_entry[:, :self.keep_dims, ...] = sd[k]
|
1547 |
+
sd[k] = new_entry
|
1548 |
+
|
1549 |
+
missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
|
1550 |
+
sd, strict=False)
|
1551 |
+
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
1552 |
+
if len(missing) > 0:
|
1553 |
+
print(f"Missing Keys: {missing}")
|
1554 |
+
if len(unexpected) > 0:
|
1555 |
+
print(f"Unexpected Keys: {unexpected}")
|
1556 |
+
|
1557 |
+
@torch.no_grad()
|
1558 |
+
def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
|
1559 |
+
quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
|
1560 |
+
plot_diffusion_rows=True, unconditional_guidance_scale=1., unconditional_guidance_label=None,
|
1561 |
+
use_ema_scope=True,
|
1562 |
+
**kwargs):
|
1563 |
+
ema_scope = self.ema_scope if use_ema_scope else nullcontext
|
1564 |
+
use_ddim = ddim_steps is not None
|
1565 |
+
|
1566 |
+
log = dict()
|
1567 |
+
z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key, bs=N, return_first_stage_outputs=True)
|
1568 |
+
c_cat, c = c["c_concat"][0], c["c_crossattn"][0]
|
1569 |
+
N = min(x.shape[0], N)
|
1570 |
+
n_row = min(x.shape[0], n_row)
|
1571 |
+
log["inputs"] = x
|
1572 |
+
log["reconstruction"] = xrec
|
1573 |
+
if self.model.conditioning_key is not None:
|
1574 |
+
if hasattr(self.cond_stage_model, "decode"):
|
1575 |
+
xc = self.cond_stage_model.decode(c)
|
1576 |
+
log["conditioning"] = xc
|
1577 |
+
elif self.cond_stage_key in ["caption", "txt"]:
|
1578 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25)
|
1579 |
+
log["conditioning"] = xc
|
1580 |
+
elif self.cond_stage_key in ['class_label', 'cls']:
|
1581 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2] // 25)
|
1582 |
+
log['conditioning'] = xc
|
1583 |
+
elif isimage(xc):
|
1584 |
+
log["conditioning"] = xc
|
1585 |
+
if ismap(xc):
|
1586 |
+
log["original_conditioning"] = self.to_rgb(xc)
|
1587 |
+
|
1588 |
+
if not (self.c_concat_log_start is None and self.c_concat_log_end is None):
|
1589 |
+
log["c_concat_decoded"] = self.decode_first_stage(c_cat[:, self.c_concat_log_start:self.c_concat_log_end])
|
1590 |
+
|
1591 |
+
if plot_diffusion_rows:
|
1592 |
+
# get diffusion row
|
1593 |
+
diffusion_row = list()
|
1594 |
+
z_start = z[:n_row]
|
1595 |
+
for t in range(self.num_timesteps):
|
1596 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
1597 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
1598 |
+
t = t.to(self.device).long()
|
1599 |
+
noise = torch.randn_like(z_start)
|
1600 |
+
z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
|
1601 |
+
diffusion_row.append(self.decode_first_stage(z_noisy))
|
1602 |
+
|
1603 |
+
diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
|
1604 |
+
diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
|
1605 |
+
diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
|
1606 |
+
diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
|
1607 |
+
log["diffusion_row"] = diffusion_grid
|
1608 |
+
|
1609 |
+
if sample:
|
1610 |
+
# get denoise row
|
1611 |
+
with ema_scope("Sampling"):
|
1612 |
+
samples, z_denoise_row = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},
|
1613 |
+
batch_size=N, ddim=use_ddim,
|
1614 |
+
ddim_steps=ddim_steps, eta=ddim_eta)
|
1615 |
+
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
|
1616 |
+
x_samples = self.decode_first_stage(samples)
|
1617 |
+
log["samples"] = x_samples
|
1618 |
+
if plot_denoise_rows:
|
1619 |
+
denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
|
1620 |
+
log["denoise_row"] = denoise_grid
|
1621 |
+
|
1622 |
+
if unconditional_guidance_scale > 1.0:
|
1623 |
+
uc_cross = self.get_unconditional_conditioning(N, unconditional_guidance_label)
|
1624 |
+
uc_cat = c_cat
|
1625 |
+
uc_full = {"c_concat": [uc_cat], "c_crossattn": [uc_cross]}
|
1626 |
+
with ema_scope("Sampling with classifier-free guidance"):
|
1627 |
+
samples_cfg, _ = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},
|
1628 |
+
batch_size=N, ddim=use_ddim,
|
1629 |
+
ddim_steps=ddim_steps, eta=ddim_eta,
|
1630 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
1631 |
+
unconditional_conditioning=uc_full,
|
1632 |
+
)
|
1633 |
+
x_samples_cfg = self.decode_first_stage(samples_cfg)
|
1634 |
+
log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
|
1635 |
+
|
1636 |
+
return log
|
1637 |
+
|
1638 |
+
|
1639 |
+
class LatentInpaintDiffusion(LatentFinetuneDiffusion):
|
1640 |
+
"""
|
1641 |
+
can either run as pure inpainting model (only concat mode) or with mixed conditionings,
|
1642 |
+
e.g. mask as concat and text via cross-attn.
|
1643 |
+
To disable finetuning mode, set finetune_keys to None
|
1644 |
+
"""
|
1645 |
+
|
1646 |
+
def __init__(self,
|
1647 |
+
concat_keys=("mask", "masked_image"),
|
1648 |
+
masked_image_key="masked_image",
|
1649 |
+
*args, **kwargs
|
1650 |
+
):
|
1651 |
+
super().__init__(concat_keys, *args, **kwargs)
|
1652 |
+
self.masked_image_key = masked_image_key
|
1653 |
+
assert self.masked_image_key in concat_keys
|
1654 |
+
|
1655 |
+
@torch.no_grad()
|
1656 |
+
def get_input(self, batch, k, cond_key=None, bs=None, return_first_stage_outputs=False):
|
1657 |
+
# note: restricted to non-trainable encoders currently
|
1658 |
+
assert not self.cond_stage_trainable, 'trainable cond stages not yet supported for inpainting'
|
1659 |
+
z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
|
1660 |
+
force_c_encode=True, return_original_cond=True, bs=bs)
|
1661 |
+
|
1662 |
+
assert exists(self.concat_keys)
|
1663 |
+
c_cat = list()
|
1664 |
+
for ck in self.concat_keys:
|
1665 |
+
cc = rearrange(batch[ck], 'b h w c -> b c h w').to(memory_format=torch.contiguous_format).float()
|
1666 |
+
if bs is not None:
|
1667 |
+
cc = cc[:bs]
|
1668 |
+
cc = cc.to(self.device)
|
1669 |
+
bchw = z.shape
|
1670 |
+
if ck != self.masked_image_key:
|
1671 |
+
cc = torch.nn.functional.interpolate(cc, size=bchw[-2:])
|
1672 |
+
else:
|
1673 |
+
cc = self.get_first_stage_encoding(self.encode_first_stage(cc))
|
1674 |
+
c_cat.append(cc)
|
1675 |
+
c_cat = torch.cat(c_cat, dim=1)
|
1676 |
+
all_conds = {"c_concat": [c_cat], "c_crossattn": [c]}
|
1677 |
+
if return_first_stage_outputs:
|
1678 |
+
return z, all_conds, x, xrec, xc
|
1679 |
+
return z, all_conds
|
1680 |
+
|
1681 |
+
@torch.no_grad()
|
1682 |
+
def log_images(self, *args, **kwargs):
|
1683 |
+
log = super(LatentInpaintDiffusion, self).log_images(*args, **kwargs)
|
1684 |
+
log["masked_image"] = rearrange(args[0]["masked_image"],
|
1685 |
+
'b h w c -> b c h w').to(memory_format=torch.contiguous_format).float()
|
1686 |
+
return log
|
1687 |
+
|
1688 |
+
|
1689 |
+
class LatentDepth2ImageDiffusion(LatentFinetuneDiffusion):
|
1690 |
+
"""
|
1691 |
+
condition on monocular depth estimation
|
1692 |
+
"""
|
1693 |
+
|
1694 |
+
def __init__(self, depth_stage_config, concat_keys=("midas_in",), *args, **kwargs):
|
1695 |
+
super().__init__(concat_keys=concat_keys, *args, **kwargs)
|
1696 |
+
self.depth_model = instantiate_from_config(depth_stage_config)
|
1697 |
+
self.depth_stage_key = concat_keys[0]
|
1698 |
+
|
1699 |
+
@torch.no_grad()
|
1700 |
+
def get_input(self, batch, k, cond_key=None, bs=None, return_first_stage_outputs=False):
|
1701 |
+
# note: restricted to non-trainable encoders currently
|
1702 |
+
assert not self.cond_stage_trainable, 'trainable cond stages not yet supported for depth2img'
|
1703 |
+
z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
|
1704 |
+
force_c_encode=True, return_original_cond=True, bs=bs)
|
1705 |
+
|
1706 |
+
assert exists(self.concat_keys)
|
1707 |
+
assert len(self.concat_keys) == 1
|
1708 |
+
c_cat = list()
|
1709 |
+
for ck in self.concat_keys:
|
1710 |
+
cc = batch[ck]
|
1711 |
+
if bs is not None:
|
1712 |
+
cc = cc[:bs]
|
1713 |
+
cc = cc.to(self.device)
|
1714 |
+
cc = self.depth_model(cc)
|
1715 |
+
cc = torch.nn.functional.interpolate(
|
1716 |
+
cc,
|
1717 |
+
size=z.shape[2:],
|
1718 |
+
mode="bicubic",
|
1719 |
+
align_corners=False,
|
1720 |
+
)
|
1721 |
+
|
1722 |
+
depth_min, depth_max = torch.amin(cc, dim=[1, 2, 3], keepdim=True), torch.amax(cc, dim=[1, 2, 3],
|
1723 |
+
keepdim=True)
|
1724 |
+
cc = 2. * (cc - depth_min) / (depth_max - depth_min + 0.001) - 1.
|
1725 |
+
c_cat.append(cc)
|
1726 |
+
c_cat = torch.cat(c_cat, dim=1)
|
1727 |
+
all_conds = {"c_concat": [c_cat], "c_crossattn": [c]}
|
1728 |
+
if return_first_stage_outputs:
|
1729 |
+
return z, all_conds, x, xrec, xc
|
1730 |
+
return z, all_conds
|
1731 |
+
|
1732 |
+
@torch.no_grad()
|
1733 |
+
def log_images(self, *args, **kwargs):
|
1734 |
+
log = super().log_images(*args, **kwargs)
|
1735 |
+
depth = self.depth_model(args[0][self.depth_stage_key])
|
1736 |
+
depth_min, depth_max = torch.amin(depth, dim=[1, 2, 3], keepdim=True), \
|
1737 |
+
torch.amax(depth, dim=[1, 2, 3], keepdim=True)
|
1738 |
+
log["depth"] = 2. * (depth - depth_min) / (depth_max - depth_min) - 1.
|
1739 |
+
return log
|
1740 |
+
|
1741 |
+
|
1742 |
+
class LatentUpscaleFinetuneDiffusion(LatentFinetuneDiffusion):
|
1743 |
+
"""
|
1744 |
+
condition on low-res image (and optionally on some spatial noise augmentation)
|
1745 |
+
"""
|
1746 |
+
def __init__(self, concat_keys=("lr",), reshuffle_patch_size=None,
|
1747 |
+
low_scale_config=None, low_scale_key=None, *args, **kwargs):
|
1748 |
+
super().__init__(concat_keys=concat_keys, *args, **kwargs)
|
1749 |
+
self.reshuffle_patch_size = reshuffle_patch_size
|
1750 |
+
self.low_scale_model = None
|
1751 |
+
if low_scale_config is not None:
|
1752 |
+
print("Initializing a low-scale model")
|
1753 |
+
assert exists(low_scale_key)
|
1754 |
+
self.instantiate_low_stage(low_scale_config)
|
1755 |
+
self.low_scale_key = low_scale_key
|
1756 |
+
|
1757 |
+
def instantiate_low_stage(self, config):
|
1758 |
+
model = instantiate_from_config(config)
|
1759 |
+
self.low_scale_model = model.eval()
|
1760 |
+
self.low_scale_model.train = disabled_train
|
1761 |
+
for param in self.low_scale_model.parameters():
|
1762 |
+
param.requires_grad = False
|
1763 |
+
|
1764 |
+
@torch.no_grad()
|
1765 |
+
def get_input(self, batch, k, cond_key=None, bs=None, return_first_stage_outputs=False):
|
1766 |
+
# note: restricted to non-trainable encoders currently
|
1767 |
+
assert not self.cond_stage_trainable, 'trainable cond stages not yet supported for upscaling-ft'
|
1768 |
+
z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,
|
1769 |
+
force_c_encode=True, return_original_cond=True, bs=bs)
|
1770 |
+
|
1771 |
+
assert exists(self.concat_keys)
|
1772 |
+
assert len(self.concat_keys) == 1
|
1773 |
+
# optionally make spatial noise_level here
|
1774 |
+
c_cat = list()
|
1775 |
+
noise_level = None
|
1776 |
+
for ck in self.concat_keys:
|
1777 |
+
cc = batch[ck]
|
1778 |
+
cc = rearrange(cc, 'b h w c -> b c h w')
|
1779 |
+
if exists(self.reshuffle_patch_size):
|
1780 |
+
assert isinstance(self.reshuffle_patch_size, int)
|
1781 |
+
cc = rearrange(cc, 'b c (p1 h) (p2 w) -> b (p1 p2 c) h w',
|
1782 |
+
p1=self.reshuffle_patch_size, p2=self.reshuffle_patch_size)
|
1783 |
+
if bs is not None:
|
1784 |
+
cc = cc[:bs]
|
1785 |
+
cc = cc.to(self.device)
|
1786 |
+
if exists(self.low_scale_model) and ck == self.low_scale_key:
|
1787 |
+
cc, noise_level = self.low_scale_model(cc)
|
1788 |
+
c_cat.append(cc)
|
1789 |
+
c_cat = torch.cat(c_cat, dim=1)
|
1790 |
+
if exists(noise_level):
|
1791 |
+
all_conds = {"c_concat": [c_cat], "c_crossattn": [c], "c_adm": noise_level}
|
1792 |
+
else:
|
1793 |
+
all_conds = {"c_concat": [c_cat], "c_crossattn": [c]}
|
1794 |
+
if return_first_stage_outputs:
|
1795 |
+
return z, all_conds, x, xrec, xc
|
1796 |
+
return z, all_conds
|
1797 |
+
|
1798 |
+
@torch.no_grad()
|
1799 |
+
def log_images(self, *args, **kwargs):
|
1800 |
+
log = super().log_images(*args, **kwargs)
|
1801 |
+
log["lr"] = rearrange(args[0]["lr"], 'b h w c -> b c h w')
|
1802 |
+
return log
|
1803 |
+
|
1804 |
+
|
1805 |
+
class ImageEmbeddingConditionedLatentDiffusion(LatentDiffusion):
|
1806 |
+
def __init__(self, embedder_config, embedding_key="jpg", embedding_dropout=0.5,
|
1807 |
+
freeze_embedder=True, noise_aug_config=None, *args, **kwargs):
|
1808 |
+
super().__init__(*args, **kwargs)
|
1809 |
+
self.embed_key = embedding_key
|
1810 |
+
self.embedding_dropout = embedding_dropout
|
1811 |
+
self._init_embedder(embedder_config, freeze_embedder)
|
1812 |
+
self._init_noise_aug(noise_aug_config)
|
1813 |
+
|
1814 |
+
def _init_embedder(self, config, freeze=True):
|
1815 |
+
embedder = instantiate_from_config(config)
|
1816 |
+
if freeze:
|
1817 |
+
self.embedder = embedder.eval()
|
1818 |
+
self.embedder.train = disabled_train
|
1819 |
+
for param in self.embedder.parameters():
|
1820 |
+
param.requires_grad = False
|
1821 |
+
|
1822 |
+
def _init_noise_aug(self, config):
|
1823 |
+
if config is not None:
|
1824 |
+
# use the KARLO schedule for noise augmentation on CLIP image embeddings
|
1825 |
+
noise_augmentor = instantiate_from_config(config)
|
1826 |
+
assert isinstance(noise_augmentor, nn.Module)
|
1827 |
+
noise_augmentor = noise_augmentor.eval()
|
1828 |
+
noise_augmentor.train = disabled_train
|
1829 |
+
self.noise_augmentor = noise_augmentor
|
1830 |
+
else:
|
1831 |
+
self.noise_augmentor = None
|
1832 |
+
|
1833 |
+
def get_input(self, batch, k, cond_key=None, bs=None, **kwargs):
|
1834 |
+
outputs = LatentDiffusion.get_input(self, batch, k, bs=bs, **kwargs)
|
1835 |
+
z, c = outputs[0], outputs[1]
|
1836 |
+
img = batch[self.embed_key][:bs]
|
1837 |
+
img = rearrange(img, 'b h w c -> b c h w')
|
1838 |
+
c_adm = self.embedder(img)
|
1839 |
+
if self.noise_augmentor is not None:
|
1840 |
+
c_adm, noise_level_emb = self.noise_augmentor(c_adm)
|
1841 |
+
# assume this gives embeddings of noise levels
|
1842 |
+
c_adm = torch.cat((c_adm, noise_level_emb), 1)
|
1843 |
+
if self.training:
|
1844 |
+
c_adm = torch.bernoulli((1. - self.embedding_dropout) * torch.ones(c_adm.shape[0],
|
1845 |
+
device=c_adm.device)[:, None]) * c_adm
|
1846 |
+
all_conds = {"c_crossattn": [c], "c_adm": c_adm}
|
1847 |
+
noutputs = [z, all_conds]
|
1848 |
+
noutputs.extend(outputs[2:])
|
1849 |
+
return noutputs
|
1850 |
+
|
1851 |
+
@torch.no_grad()
|
1852 |
+
def log_images(self, batch, N=8, n_row=4, **kwargs):
|
1853 |
+
log = dict()
|
1854 |
+
z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key, bs=N, return_first_stage_outputs=True,
|
1855 |
+
return_original_cond=True)
|
1856 |
+
log["inputs"] = x
|
1857 |
+
log["reconstruction"] = xrec
|
1858 |
+
assert self.model.conditioning_key is not None
|
1859 |
+
assert self.cond_stage_key in ["caption", "txt"]
|
1860 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25)
|
1861 |
+
log["conditioning"] = xc
|
1862 |
+
uc = self.get_unconditional_conditioning(N, kwargs.get('unconditional_guidance_label', ''))
|
1863 |
+
unconditional_guidance_scale = kwargs.get('unconditional_guidance_scale', 5.)
|
1864 |
+
|
1865 |
+
uc_ = {"c_crossattn": [uc], "c_adm": c["c_adm"]}
|
1866 |
+
ema_scope = self.ema_scope if kwargs.get('use_ema_scope', True) else nullcontext
|
1867 |
+
with ema_scope(f"Sampling"):
|
1868 |
+
samples_cfg, _ = self.sample_log(cond=c, batch_size=N, ddim=True,
|
1869 |
+
ddim_steps=kwargs.get('ddim_steps', 50), eta=kwargs.get('ddim_eta', 0.),
|
1870 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
1871 |
+
unconditional_conditioning=uc_, )
|
1872 |
+
x_samples_cfg = self.decode_first_stage(samples_cfg)
|
1873 |
+
log[f"samplescfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
|
1874 |
+
return log
|