plms.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. """SAMPLING ONLY."""
  2. from functools import partial
  3. import numpy as np
  4. import torch
  5. from tqdm import tqdm
  6. from sorawm.iopaint.model.anytext.ldm.models.diffusion.sampling_util import (
  7. norm_thresholding,
  8. )
  9. from sorawm.iopaint.model.anytext.ldm.modules.diffusionmodules.util import (
  10. make_ddim_sampling_parameters,
  11. make_ddim_timesteps,
  12. noise_like,
  13. )
  14. class PLMSSampler(object):
  15. def __init__(self, model, schedule="linear", **kwargs):
  16. super().__init__()
  17. self.model = model
  18. self.ddpm_num_timesteps = model.num_timesteps
  19. self.schedule = schedule
  20. def register_buffer(self, name, attr):
  21. if type(attr) == torch.Tensor:
  22. if attr.device != torch.device("cuda"):
  23. attr = attr.to(torch.device("cuda"))
  24. setattr(self, name, attr)
  25. def make_schedule(
  26. self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0.0, verbose=True
  27. ):
  28. if ddim_eta != 0:
  29. raise ValueError("ddim_eta must be 0 for PLMS")
  30. self.ddim_timesteps = make_ddim_timesteps(
  31. ddim_discr_method=ddim_discretize,
  32. num_ddim_timesteps=ddim_num_steps,
  33. num_ddpm_timesteps=self.ddpm_num_timesteps,
  34. verbose=verbose,
  35. )
  36. alphas_cumprod = self.model.alphas_cumprod
  37. assert (
  38. alphas_cumprod.shape[0] == self.ddpm_num_timesteps
  39. ), "alphas have to be defined for each timestep"
  40. to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
  41. self.register_buffer("betas", to_torch(self.model.betas))
  42. self.register_buffer("alphas_cumprod", to_torch(alphas_cumprod))
  43. self.register_buffer(
  44. "alphas_cumprod_prev", to_torch(self.model.alphas_cumprod_prev)
  45. )
  46. # calculations for diffusion q(x_t | x_{t-1}) and others
  47. self.register_buffer(
  48. "sqrt_alphas_cumprod", to_torch(np.sqrt(alphas_cumprod.cpu()))
  49. )
  50. self.register_buffer(
  51. "sqrt_one_minus_alphas_cumprod",
  52. to_torch(np.sqrt(1.0 - alphas_cumprod.cpu())),
  53. )
  54. self.register_buffer(
  55. "log_one_minus_alphas_cumprod", to_torch(np.log(1.0 - alphas_cumprod.cpu()))
  56. )
  57. self.register_buffer(
  58. "sqrt_recip_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod.cpu()))
  59. )
  60. self.register_buffer(
  61. "sqrt_recipm1_alphas_cumprod",
  62. to_torch(np.sqrt(1.0 / alphas_cumprod.cpu() - 1)),
  63. )
  64. # ddim sampling parameters
  65. ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(
  66. alphacums=alphas_cumprod.cpu(),
  67. ddim_timesteps=self.ddim_timesteps,
  68. eta=ddim_eta,
  69. verbose=verbose,
  70. )
  71. self.register_buffer("ddim_sigmas", ddim_sigmas)
  72. self.register_buffer("ddim_alphas", ddim_alphas)
  73. self.register_buffer("ddim_alphas_prev", ddim_alphas_prev)
  74. self.register_buffer("ddim_sqrt_one_minus_alphas", np.sqrt(1.0 - ddim_alphas))
  75. sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
  76. (1 - self.alphas_cumprod_prev)
  77. / (1 - self.alphas_cumprod)
  78. * (1 - self.alphas_cumprod / self.alphas_cumprod_prev)
  79. )
  80. self.register_buffer(
  81. "ddim_sigmas_for_original_num_steps", sigmas_for_original_sampling_steps
  82. )
  83. @torch.no_grad()
  84. def sample(
  85. self,
  86. S,
  87. batch_size,
  88. shape,
  89. conditioning=None,
  90. callback=None,
  91. normals_sequence=None,
  92. img_callback=None,
  93. quantize_x0=False,
  94. eta=0.0,
  95. mask=None,
  96. x0=None,
  97. temperature=1.0,
  98. noise_dropout=0.0,
  99. score_corrector=None,
  100. corrector_kwargs=None,
  101. verbose=True,
  102. x_T=None,
  103. log_every_t=100,
  104. unconditional_guidance_scale=1.0,
  105. unconditional_conditioning=None,
  106. # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
  107. dynamic_threshold=None,
  108. **kwargs,
  109. ):
  110. if conditioning is not None:
  111. if isinstance(conditioning, dict):
  112. cbs = conditioning[list(conditioning.keys())[0]].shape[0]
  113. if cbs != batch_size:
  114. print(
  115. f"Warning: Got {cbs} conditionings but batch-size is {batch_size}"
  116. )
  117. else:
  118. if conditioning.shape[0] != batch_size:
  119. print(
  120. f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}"
  121. )
  122. self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
  123. # sampling
  124. C, H, W = shape
  125. size = (batch_size, C, H, W)
  126. print(f"Data shape for PLMS sampling is {size}")
  127. samples, intermediates = self.plms_sampling(
  128. conditioning,
  129. size,
  130. callback=callback,
  131. img_callback=img_callback,
  132. quantize_denoised=quantize_x0,
  133. mask=mask,
  134. x0=x0,
  135. ddim_use_original_steps=False,
  136. noise_dropout=noise_dropout,
  137. temperature=temperature,
  138. score_corrector=score_corrector,
  139. corrector_kwargs=corrector_kwargs,
  140. x_T=x_T,
  141. log_every_t=log_every_t,
  142. unconditional_guidance_scale=unconditional_guidance_scale,
  143. unconditional_conditioning=unconditional_conditioning,
  144. dynamic_threshold=dynamic_threshold,
  145. )
  146. return samples, intermediates
  147. @torch.no_grad()
  148. def plms_sampling(
  149. self,
  150. cond,
  151. shape,
  152. x_T=None,
  153. ddim_use_original_steps=False,
  154. callback=None,
  155. timesteps=None,
  156. quantize_denoised=False,
  157. mask=None,
  158. x0=None,
  159. img_callback=None,
  160. log_every_t=100,
  161. temperature=1.0,
  162. noise_dropout=0.0,
  163. score_corrector=None,
  164. corrector_kwargs=None,
  165. unconditional_guidance_scale=1.0,
  166. unconditional_conditioning=None,
  167. dynamic_threshold=None,
  168. ):
  169. device = self.model.betas.device
  170. b = shape[0]
  171. if x_T is None:
  172. img = torch.randn(shape, device=device)
  173. else:
  174. img = x_T
  175. if timesteps is None:
  176. timesteps = (
  177. self.ddpm_num_timesteps
  178. if ddim_use_original_steps
  179. else self.ddim_timesteps
  180. )
  181. elif timesteps is not None and not ddim_use_original_steps:
  182. subset_end = (
  183. int(
  184. min(timesteps / self.ddim_timesteps.shape[0], 1)
  185. * self.ddim_timesteps.shape[0]
  186. )
  187. - 1
  188. )
  189. timesteps = self.ddim_timesteps[:subset_end]
  190. intermediates = {"x_inter": [img], "pred_x0": [img]}
  191. time_range = (
  192. list(reversed(range(0, timesteps)))
  193. if ddim_use_original_steps
  194. else np.flip(timesteps)
  195. )
  196. total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
  197. print(f"Running PLMS Sampling with {total_steps} timesteps")
  198. iterator = tqdm(time_range, desc="PLMS Sampler", total=total_steps)
  199. old_eps = []
  200. for i, step in enumerate(iterator):
  201. index = total_steps - i - 1
  202. ts = torch.full((b,), step, device=device, dtype=torch.long)
  203. ts_next = torch.full(
  204. (b,),
  205. time_range[min(i + 1, len(time_range) - 1)],
  206. device=device,
  207. dtype=torch.long,
  208. )
  209. if mask is not None:
  210. assert x0 is not None
  211. img_orig = self.model.q_sample(
  212. x0, ts
  213. ) # TODO: deterministic forward pass?
  214. img = img_orig * mask + (1.0 - mask) * img
  215. outs = self.p_sample_plms(
  216. img,
  217. cond,
  218. ts,
  219. index=index,
  220. use_original_steps=ddim_use_original_steps,
  221. quantize_denoised=quantize_denoised,
  222. temperature=temperature,
  223. noise_dropout=noise_dropout,
  224. score_corrector=score_corrector,
  225. corrector_kwargs=corrector_kwargs,
  226. unconditional_guidance_scale=unconditional_guidance_scale,
  227. unconditional_conditioning=unconditional_conditioning,
  228. old_eps=old_eps,
  229. t_next=ts_next,
  230. dynamic_threshold=dynamic_threshold,
  231. )
  232. img, pred_x0, e_t = outs
  233. old_eps.append(e_t)
  234. if len(old_eps) >= 4:
  235. old_eps.pop(0)
  236. if callback:
  237. callback(i)
  238. if img_callback:
  239. img_callback(pred_x0, i)
  240. if index % log_every_t == 0 or index == total_steps - 1:
  241. intermediates["x_inter"].append(img)
  242. intermediates["pred_x0"].append(pred_x0)
  243. return img, intermediates
  244. @torch.no_grad()
  245. def p_sample_plms(
  246. self,
  247. x,
  248. c,
  249. t,
  250. index,
  251. repeat_noise=False,
  252. use_original_steps=False,
  253. quantize_denoised=False,
  254. temperature=1.0,
  255. noise_dropout=0.0,
  256. score_corrector=None,
  257. corrector_kwargs=None,
  258. unconditional_guidance_scale=1.0,
  259. unconditional_conditioning=None,
  260. old_eps=None,
  261. t_next=None,
  262. dynamic_threshold=None,
  263. ):
  264. b, *_, device = *x.shape, x.device
  265. def get_model_output(x, t):
  266. if (
  267. unconditional_conditioning is None
  268. or unconditional_guidance_scale == 1.0
  269. ):
  270. e_t = self.model.apply_model(x, t, c)
  271. else:
  272. x_in = torch.cat([x] * 2)
  273. t_in = torch.cat([t] * 2)
  274. c_in = torch.cat([unconditional_conditioning, c])
  275. e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)
  276. e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)
  277. if score_corrector is not None:
  278. assert self.model.parameterization == "eps"
  279. e_t = score_corrector.modify_score(
  280. self.model, e_t, x, t, c, **corrector_kwargs
  281. )
  282. return e_t
  283. alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
  284. alphas_prev = (
  285. self.model.alphas_cumprod_prev
  286. if use_original_steps
  287. else self.ddim_alphas_prev
  288. )
  289. sqrt_one_minus_alphas = (
  290. self.model.sqrt_one_minus_alphas_cumprod
  291. if use_original_steps
  292. else self.ddim_sqrt_one_minus_alphas
  293. )
  294. sigmas = (
  295. self.model.ddim_sigmas_for_original_num_steps
  296. if use_original_steps
  297. else self.ddim_sigmas
  298. )
  299. def get_x_prev_and_pred_x0(e_t, index):
  300. # select parameters corresponding to the currently considered timestep
  301. a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
  302. a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
  303. sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
  304. sqrt_one_minus_at = torch.full(
  305. (b, 1, 1, 1), sqrt_one_minus_alphas[index], device=device
  306. )
  307. # current prediction for x_0
  308. pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
  309. if quantize_denoised:
  310. pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
  311. if dynamic_threshold is not None:
  312. pred_x0 = norm_thresholding(pred_x0, dynamic_threshold)
  313. # direction pointing to x_t
  314. dir_xt = (1.0 - a_prev - sigma_t**2).sqrt() * e_t
  315. noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
  316. if noise_dropout > 0.0:
  317. noise = torch.nn.functional.dropout(noise, p=noise_dropout)
  318. x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
  319. return x_prev, pred_x0
  320. e_t = get_model_output(x, t)
  321. if len(old_eps) == 0:
  322. # Pseudo Improved Euler (2nd order)
  323. x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t, index)
  324. e_t_next = get_model_output(x_prev, t_next)
  325. e_t_prime = (e_t + e_t_next) / 2
  326. elif len(old_eps) == 1:
  327. # 2nd order Pseudo Linear Multistep (Adams-Bashforth)
  328. e_t_prime = (3 * e_t - old_eps[-1]) / 2
  329. elif len(old_eps) == 2:
  330. # 3nd order Pseudo Linear Multistep (Adams-Bashforth)
  331. e_t_prime = (23 * e_t - 16 * old_eps[-1] + 5 * old_eps[-2]) / 12
  332. elif len(old_eps) >= 3:
  333. # 4nd order Pseudo Linear Multistep (Adams-Bashforth)
  334. e_t_prime = (
  335. 55 * e_t - 59 * old_eps[-1] + 37 * old_eps[-2] - 9 * old_eps[-3]
  336. ) / 24
  337. x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t_prime, index)
  338. return x_prev, pred_x0, e_t