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