ddpm_edit.py 66 KB

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