ddim.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. """SAMPLING ONLY."""
  2. import numpy as np
  3. import torch
  4. from tqdm import tqdm
  5. from sorawm.iopaint.model.anytext.ldm.modules.diffusionmodules.util import (
  6. extract_into_tensor,
  7. make_ddim_sampling_parameters,
  8. make_ddim_timesteps,
  9. noise_like,
  10. )
  11. class DDIMSampler(object):
  12. def __init__(self, model, schedule="linear", **kwargs):
  13. super().__init__()
  14. self.model = model
  15. self.ddpm_num_timesteps = model.num_timesteps
  16. self.schedule = schedule
  17. def register_buffer(self, name, attr):
  18. if type(attr) == torch.Tensor:
  19. if attr.device != torch.device("cuda"):
  20. attr = attr.to(torch.device("cuda"))
  21. setattr(self, name, attr)
  22. def make_schedule(
  23. self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0.0, verbose=True
  24. ):
  25. self.ddim_timesteps = make_ddim_timesteps(
  26. ddim_discr_method=ddim_discretize,
  27. num_ddim_timesteps=ddim_num_steps,
  28. num_ddpm_timesteps=self.ddpm_num_timesteps,
  29. verbose=verbose,
  30. )
  31. alphas_cumprod = self.model.alphas_cumprod
  32. assert (
  33. alphas_cumprod.shape[0] == self.ddpm_num_timesteps
  34. ), "alphas have to be defined for each timestep"
  35. to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
  36. self.register_buffer("betas", to_torch(self.model.betas))
  37. self.register_buffer("alphas_cumprod", to_torch(alphas_cumprod))
  38. self.register_buffer(
  39. "alphas_cumprod_prev", to_torch(self.model.alphas_cumprod_prev)
  40. )
  41. # calculations for diffusion q(x_t | x_{t-1}) and others
  42. self.register_buffer(
  43. "sqrt_alphas_cumprod", to_torch(np.sqrt(alphas_cumprod.cpu()))
  44. )
  45. self.register_buffer(
  46. "sqrt_one_minus_alphas_cumprod",
  47. to_torch(np.sqrt(1.0 - alphas_cumprod.cpu())),
  48. )
  49. self.register_buffer(
  50. "log_one_minus_alphas_cumprod", to_torch(np.log(1.0 - alphas_cumprod.cpu()))
  51. )
  52. self.register_buffer(
  53. "sqrt_recip_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod.cpu()))
  54. )
  55. self.register_buffer(
  56. "sqrt_recipm1_alphas_cumprod",
  57. to_torch(np.sqrt(1.0 / alphas_cumprod.cpu() - 1)),
  58. )
  59. # ddim sampling parameters
  60. ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(
  61. alphacums=alphas_cumprod.cpu(),
  62. ddim_timesteps=self.ddim_timesteps,
  63. eta=ddim_eta,
  64. verbose=verbose,
  65. )
  66. self.register_buffer("ddim_sigmas", ddim_sigmas)
  67. self.register_buffer("ddim_alphas", ddim_alphas)
  68. self.register_buffer("ddim_alphas_prev", ddim_alphas_prev)
  69. self.register_buffer("ddim_sqrt_one_minus_alphas", np.sqrt(1.0 - ddim_alphas))
  70. sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
  71. (1 - self.alphas_cumprod_prev)
  72. / (1 - self.alphas_cumprod)
  73. * (1 - self.alphas_cumprod / self.alphas_cumprod_prev)
  74. )
  75. self.register_buffer(
  76. "ddim_sigmas_for_original_num_steps", sigmas_for_original_sampling_steps
  77. )
  78. @torch.no_grad()
  79. def sample(
  80. self,
  81. S,
  82. batch_size,
  83. shape,
  84. conditioning=None,
  85. callback=None,
  86. normals_sequence=None,
  87. img_callback=None,
  88. quantize_x0=False,
  89. eta=0.0,
  90. mask=None,
  91. x0=None,
  92. temperature=1.0,
  93. noise_dropout=0.0,
  94. score_corrector=None,
  95. corrector_kwargs=None,
  96. verbose=True,
  97. x_T=None,
  98. log_every_t=100,
  99. unconditional_guidance_scale=1.0,
  100. unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
  101. dynamic_threshold=None,
  102. ucg_schedule=None,
  103. **kwargs,
  104. ):
  105. if conditioning is not None:
  106. if isinstance(conditioning, dict):
  107. ctmp = conditioning[list(conditioning.keys())[0]]
  108. while isinstance(ctmp, list):
  109. ctmp = ctmp[0]
  110. cbs = ctmp.shape[0]
  111. # cbs = len(ctmp[0])
  112. if cbs != batch_size:
  113. print(
  114. f"Warning: Got {cbs} conditionings but batch-size is {batch_size}"
  115. )
  116. elif isinstance(conditioning, list):
  117. for ctmp in conditioning:
  118. if ctmp.shape[0] != batch_size:
  119. print(
  120. f"Warning: Got {cbs} conditionings but batch-size is {batch_size}"
  121. )
  122. else:
  123. if conditioning.shape[0] != batch_size:
  124. print(
  125. f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}"
  126. )
  127. self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
  128. # sampling
  129. C, H, W = shape
  130. size = (batch_size, C, H, W)
  131. print(f"Data shape for DDIM sampling is {size}, eta {eta}")
  132. samples, intermediates = self.ddim_sampling(
  133. conditioning,
  134. size,
  135. callback=callback,
  136. img_callback=img_callback,
  137. quantize_denoised=quantize_x0,
  138. mask=mask,
  139. x0=x0,
  140. ddim_use_original_steps=False,
  141. noise_dropout=noise_dropout,
  142. temperature=temperature,
  143. score_corrector=score_corrector,
  144. corrector_kwargs=corrector_kwargs,
  145. x_T=x_T,
  146. log_every_t=log_every_t,
  147. unconditional_guidance_scale=unconditional_guidance_scale,
  148. unconditional_conditioning=unconditional_conditioning,
  149. dynamic_threshold=dynamic_threshold,
  150. ucg_schedule=ucg_schedule,
  151. )
  152. return samples, intermediates
  153. @torch.no_grad()
  154. def ddim_sampling(
  155. self,
  156. cond,
  157. shape,
  158. x_T=None,
  159. ddim_use_original_steps=False,
  160. callback=None,
  161. timesteps=None,
  162. quantize_denoised=False,
  163. mask=None,
  164. x0=None,
  165. img_callback=None,
  166. log_every_t=100,
  167. temperature=1.0,
  168. noise_dropout=0.0,
  169. score_corrector=None,
  170. corrector_kwargs=None,
  171. unconditional_guidance_scale=1.0,
  172. unconditional_conditioning=None,
  173. dynamic_threshold=None,
  174. ucg_schedule=None,
  175. ):
  176. device = self.model.betas.device
  177. b = shape[0]
  178. if x_T is None:
  179. img = torch.randn(shape, device=device)
  180. else:
  181. img = x_T
  182. if timesteps is None:
  183. timesteps = (
  184. self.ddpm_num_timesteps
  185. if ddim_use_original_steps
  186. else self.ddim_timesteps
  187. )
  188. elif timesteps is not None and not ddim_use_original_steps:
  189. subset_end = (
  190. int(
  191. min(timesteps / self.ddim_timesteps.shape[0], 1)
  192. * self.ddim_timesteps.shape[0]
  193. )
  194. - 1
  195. )
  196. timesteps = self.ddim_timesteps[:subset_end]
  197. intermediates = {"x_inter": [img], "pred_x0": [img], "index": [10000]}
  198. time_range = (
  199. reversed(range(0, timesteps))
  200. if ddim_use_original_steps
  201. else np.flip(timesteps)
  202. )
  203. total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
  204. print(f"Running DDIM Sampling with {total_steps} timesteps")
  205. iterator = tqdm(time_range, desc="DDIM Sampler", total=total_steps)
  206. for i, step in enumerate(iterator):
  207. index = total_steps - i - 1
  208. ts = torch.full((b,), step, device=device, dtype=torch.long)
  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. if ucg_schedule is not None:
  216. assert len(ucg_schedule) == len(time_range)
  217. unconditional_guidance_scale = ucg_schedule[i]
  218. outs = self.p_sample_ddim(
  219. img,
  220. cond,
  221. ts,
  222. index=index,
  223. use_original_steps=ddim_use_original_steps,
  224. quantize_denoised=quantize_denoised,
  225. temperature=temperature,
  226. noise_dropout=noise_dropout,
  227. score_corrector=score_corrector,
  228. corrector_kwargs=corrector_kwargs,
  229. unconditional_guidance_scale=unconditional_guidance_scale,
  230. unconditional_conditioning=unconditional_conditioning,
  231. dynamic_threshold=dynamic_threshold,
  232. )
  233. img, pred_x0 = outs
  234. if callback:
  235. callback(i)
  236. if img_callback:
  237. img_callback(pred_x0, i)
  238. if index % log_every_t == 0 or index == total_steps - 1:
  239. intermediates["x_inter"].append(img)
  240. intermediates["pred_x0"].append(pred_x0)
  241. intermediates["index"].append(index)
  242. return img, intermediates
  243. @torch.no_grad()
  244. def p_sample_ddim(
  245. self,
  246. x,
  247. c,
  248. t,
  249. index,
  250. repeat_noise=False,
  251. use_original_steps=False,
  252. quantize_denoised=False,
  253. temperature=1.0,
  254. noise_dropout=0.0,
  255. score_corrector=None,
  256. corrector_kwargs=None,
  257. unconditional_guidance_scale=1.0,
  258. unconditional_conditioning=None,
  259. dynamic_threshold=None,
  260. ):
  261. b, *_, device = *x.shape, x.device
  262. if unconditional_conditioning is None or unconditional_guidance_scale == 1.0:
  263. model_output = self.model.apply_model(x, t, c)
  264. else:
  265. x_in = torch.cat([x] * 2)
  266. t_in = torch.cat([t] * 2)
  267. if isinstance(c, dict):
  268. assert isinstance(unconditional_conditioning, dict)
  269. c_in = dict()
  270. for k in c:
  271. if isinstance(c[k], list):
  272. c_in[k] = [
  273. torch.cat([unconditional_conditioning[k][i], c[k][i]])
  274. for i in range(len(c[k]))
  275. ]
  276. elif isinstance(c[k], dict):
  277. c_in[k] = dict()
  278. for key in c[k]:
  279. if isinstance(c[k][key], list):
  280. if not isinstance(c[k][key][0], torch.Tensor):
  281. continue
  282. c_in[k][key] = [
  283. torch.cat(
  284. [
  285. unconditional_conditioning[k][key][i],
  286. c[k][key][i],
  287. ]
  288. )
  289. for i in range(len(c[k][key]))
  290. ]
  291. else:
  292. c_in[k][key] = torch.cat(
  293. [unconditional_conditioning[k][key], c[k][key]]
  294. )
  295. else:
  296. c_in[k] = torch.cat([unconditional_conditioning[k], c[k]])
  297. elif isinstance(c, list):
  298. c_in = list()
  299. assert isinstance(unconditional_conditioning, list)
  300. for i in range(len(c)):
  301. c_in.append(torch.cat([unconditional_conditioning[i], c[i]]))
  302. else:
  303. c_in = torch.cat([unconditional_conditioning, c])
  304. model_uncond, model_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)
  305. model_output = model_uncond + unconditional_guidance_scale * (
  306. model_t - model_uncond
  307. )
  308. if self.model.parameterization == "v":
  309. e_t = self.model.predict_eps_from_z_and_v(x, t, model_output)
  310. else:
  311. e_t = model_output
  312. if score_corrector is not None:
  313. assert self.model.parameterization == "eps", "not implemented"
  314. e_t = score_corrector.modify_score(
  315. self.model, e_t, x, t, c, **corrector_kwargs
  316. )
  317. alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
  318. alphas_prev = (
  319. self.model.alphas_cumprod_prev
  320. if use_original_steps
  321. else self.ddim_alphas_prev
  322. )
  323. sqrt_one_minus_alphas = (
  324. self.model.sqrt_one_minus_alphas_cumprod
  325. if use_original_steps
  326. else self.ddim_sqrt_one_minus_alphas
  327. )
  328. sigmas = (
  329. self.model.ddim_sigmas_for_original_num_steps
  330. if use_original_steps
  331. else self.ddim_sigmas
  332. )
  333. # select parameters corresponding to the currently considered timestep
  334. a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
  335. a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
  336. sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
  337. sqrt_one_minus_at = torch.full(
  338. (b, 1, 1, 1), sqrt_one_minus_alphas[index], device=device
  339. )
  340. # current prediction for x_0
  341. if self.model.parameterization != "v":
  342. pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
  343. else:
  344. pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)
  345. if quantize_denoised:
  346. pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
  347. if dynamic_threshold is not None:
  348. raise NotImplementedError()
  349. # direction pointing to x_t
  350. dir_xt = (1.0 - a_prev - sigma_t**2).sqrt() * e_t
  351. noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
  352. if noise_dropout > 0.0:
  353. noise = torch.nn.functional.dropout(noise, p=noise_dropout)
  354. x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
  355. return x_prev, pred_x0
  356. @torch.no_grad()
  357. def encode(
  358. self,
  359. x0,
  360. c,
  361. t_enc,
  362. use_original_steps=False,
  363. return_intermediates=None,
  364. unconditional_guidance_scale=1.0,
  365. unconditional_conditioning=None,
  366. callback=None,
  367. ):
  368. num_reference_steps = (
  369. self.ddpm_num_timesteps
  370. if use_original_steps
  371. else self.ddim_timesteps.shape[0]
  372. )
  373. assert t_enc <= num_reference_steps
  374. num_steps = t_enc
  375. if use_original_steps:
  376. alphas_next = self.alphas_cumprod[:num_steps]
  377. alphas = self.alphas_cumprod_prev[:num_steps]
  378. else:
  379. alphas_next = self.ddim_alphas[:num_steps]
  380. alphas = torch.tensor(self.ddim_alphas_prev[:num_steps])
  381. x_next = x0
  382. intermediates = []
  383. inter_steps = []
  384. for i in tqdm(range(num_steps), desc="Encoding Image"):
  385. t = torch.full(
  386. (x0.shape[0],), i, device=self.model.device, dtype=torch.long
  387. )
  388. if unconditional_guidance_scale == 1.0:
  389. noise_pred = self.model.apply_model(x_next, t, c)
  390. else:
  391. assert unconditional_conditioning is not None
  392. e_t_uncond, noise_pred = torch.chunk(
  393. self.model.apply_model(
  394. torch.cat((x_next, x_next)),
  395. torch.cat((t, t)),
  396. torch.cat((unconditional_conditioning, c)),
  397. ),
  398. 2,
  399. )
  400. noise_pred = e_t_uncond + unconditional_guidance_scale * (
  401. noise_pred - e_t_uncond
  402. )
  403. xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next
  404. weighted_noise_pred = (
  405. alphas_next[i].sqrt()
  406. * ((1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt())
  407. * noise_pred
  408. )
  409. x_next = xt_weighted + weighted_noise_pred
  410. if (
  411. return_intermediates
  412. and i % (num_steps // return_intermediates) == 0
  413. and i < num_steps - 1
  414. ):
  415. intermediates.append(x_next)
  416. inter_steps.append(i)
  417. elif return_intermediates and i >= num_steps - 2:
  418. intermediates.append(x_next)
  419. inter_steps.append(i)
  420. if callback:
  421. callback(i)
  422. out = {"x_encoded": x_next, "intermediate_steps": inter_steps}
  423. if return_intermediates:
  424. out.update({"intermediates": intermediates})
  425. return x_next, out
  426. @torch.no_grad()
  427. def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):
  428. # fast, but does not allow for exact reconstruction
  429. # t serves as an index to gather the correct alphas
  430. if use_original_steps:
  431. sqrt_alphas_cumprod = self.sqrt_alphas_cumprod
  432. sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod
  433. else:
  434. sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)
  435. sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas
  436. if noise is None:
  437. noise = torch.randn_like(x0)
  438. return (
  439. extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0
  440. + extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise
  441. )
  442. @torch.no_grad()
  443. def decode(
  444. self,
  445. x_latent,
  446. cond,
  447. t_start,
  448. unconditional_guidance_scale=1.0,
  449. unconditional_conditioning=None,
  450. use_original_steps=False,
  451. callback=None,
  452. ):
  453. timesteps = (
  454. np.arange(self.ddpm_num_timesteps)
  455. if use_original_steps
  456. else self.ddim_timesteps
  457. )
  458. timesteps = timesteps[:t_start]
  459. time_range = np.flip(timesteps)
  460. total_steps = timesteps.shape[0]
  461. print(f"Running DDIM Sampling with {total_steps} timesteps")
  462. iterator = tqdm(time_range, desc="Decoding image", total=total_steps)
  463. x_dec = x_latent
  464. for i, step in enumerate(iterator):
  465. index = total_steps - i - 1
  466. ts = torch.full(
  467. (x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long
  468. )
  469. x_dec, _ = self.p_sample_ddim(
  470. x_dec,
  471. cond,
  472. ts,
  473. index=index,
  474. use_original_steps=use_original_steps,
  475. unconditional_guidance_scale=unconditional_guidance_scale,
  476. unconditional_conditioning=unconditional_conditioning,
  477. )
  478. if callback:
  479. callback(i)
  480. return x_dec