ddpm.py 66 KB

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