ddim.py 13 KB

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