plms.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. """SAMPLING ONLY."""
  2. import torch
  3. import numpy as np
  4. from tqdm import tqdm
  5. from functools import partial
  6. from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like
  7. class PLMSSampler(object):
  8. def __init__(self, model, schedule="linear", **kwargs):
  9. super().__init__()
  10. self.model = model
  11. self.ddpm_num_timesteps = model.num_timesteps
  12. self.schedule = schedule
  13. def register_buffer(self, name, attr):
  14. if type(attr) == torch.Tensor:
  15. if attr.device != torch.device("cuda"):
  16. attr = attr.to(torch.device("cuda"))
  17. setattr(self, name, attr)
  18. def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
  19. if ddim_eta != 0:
  20. raise ValueError('ddim_eta must be 0 for PLMS')
  21. self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
  22. num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
  23. alphas_cumprod = self.model.alphas_cumprod
  24. assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
  25. to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
  26. self.register_buffer('betas', to_torch(self.model.betas))
  27. self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
  28. self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
  29. # calculations for diffusion q(x_t | x_{t-1}) and others
  30. self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
  31. self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
  32. self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
  33. self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
  34. self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
  35. # ddim sampling parameters
  36. ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
  37. ddim_timesteps=self.ddim_timesteps,
  38. eta=ddim_eta,verbose=verbose)
  39. self.register_buffer('ddim_sigmas', ddim_sigmas)
  40. self.register_buffer('ddim_alphas', ddim_alphas)
  41. self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
  42. self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
  43. sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
  44. (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
  45. 1 - self.alphas_cumprod / self.alphas_cumprod_prev))
  46. self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
  47. @torch.no_grad()
  48. def sample(self,
  49. S,
  50. batch_size,
  51. shape,
  52. conditioning=None,
  53. callback=None,
  54. normals_sequence=None,
  55. img_callback=None,
  56. quantize_x0=False,
  57. eta=0.,
  58. mask=None,
  59. x0=None,
  60. temperature=1.,
  61. noise_dropout=0.,
  62. score_corrector=None,
  63. corrector_kwargs=None,
  64. verbose=True,
  65. x_T=None,
  66. log_every_t=100,
  67. unconditional_guidance_scale=1.,
  68. unconditional_conditioning=None,
  69. # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
  70. **kwargs
  71. ):
  72. if conditioning is not None:
  73. if isinstance(conditioning, dict):
  74. cbs = conditioning[list(conditioning.keys())[0]].shape[0]
  75. if cbs != batch_size:
  76. print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
  77. else:
  78. if conditioning.shape[0] != batch_size:
  79. print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
  80. self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
  81. # sampling
  82. C, H, W = shape
  83. size = (batch_size, C, H, W)
  84. print(f'Data shape for PLMS sampling is {size}')
  85. samples, intermediates = self.plms_sampling(conditioning, size,
  86. callback=callback,
  87. img_callback=img_callback,
  88. quantize_denoised=quantize_x0,
  89. mask=mask, x0=x0,
  90. ddim_use_original_steps=False,
  91. noise_dropout=noise_dropout,
  92. temperature=temperature,
  93. score_corrector=score_corrector,
  94. corrector_kwargs=corrector_kwargs,
  95. x_T=x_T,
  96. log_every_t=log_every_t,
  97. unconditional_guidance_scale=unconditional_guidance_scale,
  98. unconditional_conditioning=unconditional_conditioning,
  99. )
  100. return samples, intermediates
  101. @torch.no_grad()
  102. def plms_sampling(self, cond, shape,
  103. x_T=None, ddim_use_original_steps=False,
  104. callback=None, timesteps=None, quantize_denoised=False,
  105. mask=None, x0=None, img_callback=None, log_every_t=100,
  106. temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
  107. unconditional_guidance_scale=1., unconditional_conditioning=None,):
  108. device = self.model.betas.device
  109. b = shape[0]
  110. if x_T is None:
  111. img = torch.randn(shape, device=device)
  112. else:
  113. img = x_T
  114. if timesteps is None:
  115. timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
  116. elif timesteps is not None and not ddim_use_original_steps:
  117. subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
  118. timesteps = self.ddim_timesteps[:subset_end]
  119. intermediates = {'x_inter': [img], 'pred_x0': [img]}
  120. time_range = list(reversed(range(0,timesteps))) if ddim_use_original_steps else np.flip(timesteps)
  121. total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
  122. print(f"Running PLMS Sampling with {total_steps} timesteps")
  123. iterator = tqdm(time_range, desc='PLMS Sampler', total=total_steps)
  124. old_eps = []
  125. for i, step in enumerate(iterator):
  126. index = total_steps - i - 1
  127. ts = torch.full((b,), step, device=device, dtype=torch.long)
  128. ts_next = torch.full((b,), time_range[min(i + 1, len(time_range) - 1)], device=device, dtype=torch.long)
  129. if mask is not None:
  130. assert x0 is not None
  131. img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
  132. img = img_orig * mask + (1. - mask) * img
  133. outs = self.p_sample_plms(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
  134. quantize_denoised=quantize_denoised, temperature=temperature,
  135. noise_dropout=noise_dropout, score_corrector=score_corrector,
  136. corrector_kwargs=corrector_kwargs,
  137. unconditional_guidance_scale=unconditional_guidance_scale,
  138. unconditional_conditioning=unconditional_conditioning,
  139. old_eps=old_eps, t_next=ts_next)
  140. img, pred_x0, e_t = outs
  141. old_eps.append(e_t)
  142. if len(old_eps) >= 4:
  143. old_eps.pop(0)
  144. if callback: callback(i)
  145. if img_callback: img_callback(pred_x0, i)
  146. if index % log_every_t == 0 or index == total_steps - 1:
  147. intermediates['x_inter'].append(img)
  148. intermediates['pred_x0'].append(pred_x0)
  149. return img, intermediates
  150. @torch.no_grad()
  151. def p_sample_plms(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
  152. temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
  153. unconditional_guidance_scale=1., unconditional_conditioning=None, old_eps=None, t_next=None):
  154. b, *_, device = *x.shape, x.device
  155. def get_model_output(x, t):
  156. if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
  157. e_t = self.model.apply_model(x, t, c)
  158. else:
  159. x_in = torch.cat([x] * 2)
  160. t_in = torch.cat([t] * 2)
  161. c_in = torch.cat([unconditional_conditioning, c])
  162. e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)
  163. e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)
  164. if score_corrector is not None:
  165. assert self.model.parameterization == "eps"
  166. e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
  167. return e_t
  168. alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
  169. alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
  170. sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
  171. sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
  172. def get_x_prev_and_pred_x0(e_t, index):
  173. # select parameters corresponding to the currently considered timestep
  174. a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
  175. a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
  176. sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
  177. sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
  178. # current prediction for x_0
  179. pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
  180. if quantize_denoised:
  181. pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
  182. # direction pointing to x_t
  183. dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
  184. noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
  185. if noise_dropout > 0.:
  186. noise = torch.nn.functional.dropout(noise, p=noise_dropout)
  187. x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
  188. return x_prev, pred_x0
  189. e_t = get_model_output(x, t)
  190. if len(old_eps) == 0:
  191. # Pseudo Improved Euler (2nd order)
  192. x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t, index)
  193. e_t_next = get_model_output(x_prev, t_next)
  194. e_t_prime = (e_t + e_t_next) / 2
  195. elif len(old_eps) == 1:
  196. # 2nd order Pseudo Linear Multistep (Adams-Bashforth)
  197. e_t_prime = (3 * e_t - old_eps[-1]) / 2
  198. elif len(old_eps) == 2:
  199. # 3nd order Pseudo Linear Multistep (Adams-Bashforth)
  200. e_t_prime = (23 * e_t - 16 * old_eps[-1] + 5 * old_eps[-2]) / 12
  201. elif len(old_eps) >= 3:
  202. # 4nd order Pseudo Linear Multistep (Adams-Bashforth)
  203. e_t_prime = (55 * e_t - 59 * old_eps[-1] + 37 * old_eps[-2] - 9 * old_eps[-3]) / 24
  204. x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t_prime, index)
  205. return x_prev, pred_x0, e_t