ddim_hacked.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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, device, schedule="linear", **kwargs):
  13. super().__init__()
  14. self.device = device
  15. self.model = model
  16. self.ddpm_num_timesteps = model.num_timesteps
  17. self.schedule = schedule
  18. def register_buffer(self, name, attr):
  19. if type(attr) == torch.Tensor:
  20. if attr.device != torch.device(self.device):
  21. attr = attr.to(torch.device(self.device))
  22. setattr(self, name, attr)
  23. def make_schedule(
  24. self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0.0, verbose=True
  25. ):
  26. self.ddim_timesteps = make_ddim_timesteps(
  27. ddim_discr_method=ddim_discretize,
  28. num_ddim_timesteps=ddim_num_steps,
  29. num_ddpm_timesteps=self.ddpm_num_timesteps,
  30. verbose=verbose,
  31. )
  32. alphas_cumprod = self.model.alphas_cumprod
  33. assert (
  34. alphas_cumprod.shape[0] == self.ddpm_num_timesteps
  35. ), "alphas have to be defined for each timestep"
  36. to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.device)
  37. self.register_buffer("betas", to_torch(self.model.betas))
  38. self.register_buffer("alphas_cumprod", to_torch(alphas_cumprod))
  39. self.register_buffer(
  40. "alphas_cumprod_prev", to_torch(self.model.alphas_cumprod_prev)
  41. )
  42. # calculations for diffusion q(x_t | x_{t-1}) and others
  43. self.register_buffer(
  44. "sqrt_alphas_cumprod", to_torch(np.sqrt(alphas_cumprod.cpu()))
  45. )
  46. self.register_buffer(
  47. "sqrt_one_minus_alphas_cumprod",
  48. to_torch(np.sqrt(1.0 - alphas_cumprod.cpu())),
  49. )
  50. self.register_buffer(
  51. "log_one_minus_alphas_cumprod", to_torch(np.log(1.0 - alphas_cumprod.cpu()))
  52. )
  53. self.register_buffer(
  54. "sqrt_recip_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod.cpu()))
  55. )
  56. self.register_buffer(
  57. "sqrt_recipm1_alphas_cumprod",
  58. to_torch(np.sqrt(1.0 / alphas_cumprod.cpu() - 1)),
  59. )
  60. # ddim sampling parameters
  61. ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(
  62. alphacums=alphas_cumprod.cpu(),
  63. ddim_timesteps=self.ddim_timesteps,
  64. eta=ddim_eta,
  65. verbose=verbose,
  66. )
  67. self.register_buffer("ddim_sigmas", ddim_sigmas)
  68. self.register_buffer("ddim_alphas", ddim_alphas)
  69. self.register_buffer("ddim_alphas_prev", ddim_alphas_prev)
  70. self.register_buffer("ddim_sqrt_one_minus_alphas", np.sqrt(1.0 - ddim_alphas))
  71. sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
  72. (1 - self.alphas_cumprod_prev)
  73. / (1 - self.alphas_cumprod)
  74. * (1 - self.alphas_cumprod / self.alphas_cumprod_prev)
  75. )
  76. self.register_buffer(
  77. "ddim_sigmas_for_original_num_steps", sigmas_for_original_sampling_steps
  78. )
  79. @torch.no_grad()
  80. def sample(
  81. self,
  82. S,
  83. batch_size,
  84. shape,
  85. conditioning=None,
  86. callback=None,
  87. normals_sequence=None,
  88. img_callback=None,
  89. quantize_x0=False,
  90. eta=0.0,
  91. mask=None,
  92. x0=None,
  93. temperature=1.0,
  94. noise_dropout=0.0,
  95. score_corrector=None,
  96. corrector_kwargs=None,
  97. verbose=True,
  98. x_T=None,
  99. log_every_t=100,
  100. unconditional_guidance_scale=1.0,
  101. unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
  102. dynamic_threshold=None,
  103. ucg_schedule=None,
  104. **kwargs,
  105. ):
  106. if conditioning is not None:
  107. if isinstance(conditioning, dict):
  108. ctmp = conditioning[list(conditioning.keys())[0]]
  109. while isinstance(ctmp, list):
  110. ctmp = ctmp[0]
  111. cbs = ctmp.shape[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]}
  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(None, i, None, None)
  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. return img, intermediates
  242. @torch.no_grad()
  243. def p_sample_ddim(
  244. self,
  245. x,
  246. c,
  247. t,
  248. index,
  249. repeat_noise=False,
  250. use_original_steps=False,
  251. quantize_denoised=False,
  252. temperature=1.0,
  253. noise_dropout=0.0,
  254. score_corrector=None,
  255. corrector_kwargs=None,
  256. unconditional_guidance_scale=1.0,
  257. unconditional_conditioning=None,
  258. dynamic_threshold=None,
  259. ):
  260. b, *_, device = *x.shape, x.device
  261. if unconditional_conditioning is None or unconditional_guidance_scale == 1.0:
  262. model_output = self.model.apply_model(x, t, c)
  263. else:
  264. model_t = self.model.apply_model(x, t, c)
  265. model_uncond = self.model.apply_model(x, t, unconditional_conditioning)
  266. model_output = model_uncond + unconditional_guidance_scale * (
  267. model_t - model_uncond
  268. )
  269. if self.model.parameterization == "v":
  270. e_t = self.model.predict_eps_from_z_and_v(x, t, model_output)
  271. else:
  272. e_t = model_output
  273. if score_corrector is not None:
  274. assert self.model.parameterization == "eps", "not implemented"
  275. e_t = score_corrector.modify_score(
  276. self.model, e_t, x, t, c, **corrector_kwargs
  277. )
  278. alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
  279. alphas_prev = (
  280. self.model.alphas_cumprod_prev
  281. if use_original_steps
  282. else self.ddim_alphas_prev
  283. )
  284. sqrt_one_minus_alphas = (
  285. self.model.sqrt_one_minus_alphas_cumprod
  286. if use_original_steps
  287. else self.ddim_sqrt_one_minus_alphas
  288. )
  289. sigmas = (
  290. self.model.ddim_sigmas_for_original_num_steps
  291. if use_original_steps
  292. else self.ddim_sigmas
  293. )
  294. # select parameters corresponding to the currently considered timestep
  295. a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
  296. a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
  297. sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
  298. sqrt_one_minus_at = torch.full(
  299. (b, 1, 1, 1), sqrt_one_minus_alphas[index], device=device
  300. )
  301. # current prediction for x_0
  302. if self.model.parameterization != "v":
  303. pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
  304. else:
  305. pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)
  306. if quantize_denoised:
  307. pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
  308. if dynamic_threshold is not None:
  309. raise NotImplementedError()
  310. # direction pointing to x_t
  311. dir_xt = (1.0 - a_prev - sigma_t**2).sqrt() * e_t
  312. noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
  313. if noise_dropout > 0.0:
  314. noise = torch.nn.functional.dropout(noise, p=noise_dropout)
  315. x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
  316. return x_prev, pred_x0
  317. @torch.no_grad()
  318. def encode(
  319. self,
  320. x0,
  321. c,
  322. t_enc,
  323. use_original_steps=False,
  324. return_intermediates=None,
  325. unconditional_guidance_scale=1.0,
  326. unconditional_conditioning=None,
  327. callback=None,
  328. ):
  329. timesteps = (
  330. np.arange(self.ddpm_num_timesteps)
  331. if use_original_steps
  332. else self.ddim_timesteps
  333. )
  334. num_reference_steps = timesteps.shape[0]
  335. assert t_enc <= num_reference_steps
  336. num_steps = t_enc
  337. if use_original_steps:
  338. alphas_next = self.alphas_cumprod[:num_steps]
  339. alphas = self.alphas_cumprod_prev[:num_steps]
  340. else:
  341. alphas_next = self.ddim_alphas[:num_steps]
  342. alphas = torch.tensor(self.ddim_alphas_prev[:num_steps])
  343. x_next = x0
  344. intermediates = []
  345. inter_steps = []
  346. for i in tqdm(range(num_steps), desc="Encoding Image"):
  347. t = torch.full(
  348. (x0.shape[0],), timesteps[i], device=self.model.device, dtype=torch.long
  349. )
  350. if unconditional_guidance_scale == 1.0:
  351. noise_pred = self.model.apply_model(x_next, t, c)
  352. else:
  353. assert unconditional_conditioning is not None
  354. e_t_uncond, noise_pred = torch.chunk(
  355. self.model.apply_model(
  356. torch.cat((x_next, x_next)),
  357. torch.cat((t, t)),
  358. torch.cat((unconditional_conditioning, c)),
  359. ),
  360. 2,
  361. )
  362. noise_pred = e_t_uncond + unconditional_guidance_scale * (
  363. noise_pred - e_t_uncond
  364. )
  365. xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next
  366. weighted_noise_pred = (
  367. alphas_next[i].sqrt()
  368. * ((1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt())
  369. * noise_pred
  370. )
  371. x_next = xt_weighted + weighted_noise_pred
  372. if (
  373. return_intermediates
  374. and i % (num_steps // return_intermediates) == 0
  375. and i < num_steps - 1
  376. ):
  377. intermediates.append(x_next)
  378. inter_steps.append(i)
  379. elif return_intermediates and i >= num_steps - 2:
  380. intermediates.append(x_next)
  381. inter_steps.append(i)
  382. if callback:
  383. callback(i)
  384. out = {"x_encoded": x_next, "intermediate_steps": inter_steps}
  385. if return_intermediates:
  386. out.update({"intermediates": intermediates})
  387. return x_next, out
  388. @torch.no_grad()
  389. def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):
  390. # fast, but does not allow for exact reconstruction
  391. # t serves as an index to gather the correct alphas
  392. if use_original_steps:
  393. sqrt_alphas_cumprod = self.sqrt_alphas_cumprod
  394. sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod
  395. else:
  396. sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)
  397. sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas
  398. if noise is None:
  399. noise = torch.randn_like(x0)
  400. return (
  401. extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0
  402. + extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise
  403. )
  404. @torch.no_grad()
  405. def decode(
  406. self,
  407. x_latent,
  408. cond,
  409. t_start,
  410. unconditional_guidance_scale=1.0,
  411. unconditional_conditioning=None,
  412. use_original_steps=False,
  413. callback=None,
  414. ):
  415. timesteps = (
  416. np.arange(self.ddpm_num_timesteps)
  417. if use_original_steps
  418. else self.ddim_timesteps
  419. )
  420. timesteps = timesteps[:t_start]
  421. time_range = np.flip(timesteps)
  422. total_steps = timesteps.shape[0]
  423. print(f"Running DDIM Sampling with {total_steps} timesteps")
  424. iterator = tqdm(time_range, desc="Decoding image", total=total_steps)
  425. x_dec = x_latent
  426. for i, step in enumerate(iterator):
  427. index = total_steps - i - 1
  428. ts = torch.full(
  429. (x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long
  430. )
  431. x_dec, _ = self.p_sample_ddim(
  432. x_dec,
  433. cond,
  434. ts,
  435. index=index,
  436. use_original_steps=use_original_steps,
  437. unconditional_guidance_scale=unconditional_guidance_scale,
  438. unconditional_conditioning=unconditional_conditioning,
  439. )
  440. if callback:
  441. callback(i)
  442. return x_dec