autoencoder.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. from contextlib import contextmanager
  2. import torch
  3. import torch.nn.functional as F
  4. from sorawm.iopaint.model.anytext.ldm.modules.diffusionmodules.model import (
  5. Decoder,
  6. Encoder,
  7. )
  8. from sorawm.iopaint.model.anytext.ldm.modules.distributions.distributions import (
  9. DiagonalGaussianDistribution,
  10. )
  11. from sorawm.iopaint.model.anytext.ldm.modules.ema import LitEma
  12. from sorawm.iopaint.model.anytext.ldm.util import instantiate_from_config
  13. class AutoencoderKL(torch.nn.Module):
  14. def __init__(
  15. self,
  16. ddconfig,
  17. lossconfig,
  18. embed_dim,
  19. ckpt_path=None,
  20. ignore_keys=[],
  21. image_key="image",
  22. colorize_nlabels=None,
  23. monitor=None,
  24. ema_decay=None,
  25. learn_logvar=False,
  26. ):
  27. super().__init__()
  28. self.learn_logvar = learn_logvar
  29. self.image_key = image_key
  30. self.encoder = Encoder(**ddconfig)
  31. self.decoder = Decoder(**ddconfig)
  32. self.loss = instantiate_from_config(lossconfig)
  33. assert ddconfig["double_z"]
  34. self.quant_conv = torch.nn.Conv2d(2 * ddconfig["z_channels"], 2 * embed_dim, 1)
  35. self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
  36. self.embed_dim = embed_dim
  37. if colorize_nlabels is not None:
  38. assert type(colorize_nlabels) == int
  39. self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
  40. if monitor is not None:
  41. self.monitor = monitor
  42. self.use_ema = ema_decay is not None
  43. if self.use_ema:
  44. self.ema_decay = ema_decay
  45. assert 0.0 < ema_decay < 1.0
  46. self.model_ema = LitEma(self, decay=ema_decay)
  47. print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
  48. if ckpt_path is not None:
  49. self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
  50. def init_from_ckpt(self, path, ignore_keys=list()):
  51. sd = torch.load(path, map_location="cpu")["state_dict"]
  52. keys = list(sd.keys())
  53. for k in keys:
  54. for ik in ignore_keys:
  55. if k.startswith(ik):
  56. print("Deleting key {} from state_dict.".format(k))
  57. del sd[k]
  58. self.load_state_dict(sd, strict=False)
  59. print(f"Restored from {path}")
  60. @contextmanager
  61. def ema_scope(self, context=None):
  62. if self.use_ema:
  63. self.model_ema.store(self.parameters())
  64. self.model_ema.copy_to(self)
  65. if context is not None:
  66. print(f"{context}: Switched to EMA weights")
  67. try:
  68. yield None
  69. finally:
  70. if self.use_ema:
  71. self.model_ema.restore(self.parameters())
  72. if context is not None:
  73. print(f"{context}: Restored training weights")
  74. def on_train_batch_end(self, *args, **kwargs):
  75. if self.use_ema:
  76. self.model_ema(self)
  77. def encode(self, x):
  78. h = self.encoder(x)
  79. moments = self.quant_conv(h)
  80. posterior = DiagonalGaussianDistribution(moments)
  81. return posterior
  82. def decode(self, z):
  83. z = self.post_quant_conv(z)
  84. dec = self.decoder(z)
  85. return dec
  86. def forward(self, input, sample_posterior=True):
  87. posterior = self.encode(input)
  88. if sample_posterior:
  89. z = posterior.sample()
  90. else:
  91. z = posterior.mode()
  92. dec = self.decode(z)
  93. return dec, posterior
  94. def get_input(self, batch, k):
  95. x = batch[k]
  96. if len(x.shape) == 3:
  97. x = x[..., None]
  98. x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
  99. return x
  100. def training_step(self, batch, batch_idx, optimizer_idx):
  101. inputs = self.get_input(batch, self.image_key)
  102. reconstructions, posterior = self(inputs)
  103. if optimizer_idx == 0:
  104. # train encoder+decoder+logvar
  105. aeloss, log_dict_ae = self.loss(
  106. inputs,
  107. reconstructions,
  108. posterior,
  109. optimizer_idx,
  110. self.global_step,
  111. last_layer=self.get_last_layer(),
  112. split="train",
  113. )
  114. self.log(
  115. "aeloss",
  116. aeloss,
  117. prog_bar=True,
  118. logger=True,
  119. on_step=True,
  120. on_epoch=True,
  121. )
  122. self.log_dict(
  123. log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False
  124. )
  125. return aeloss
  126. if optimizer_idx == 1:
  127. # train the discriminator
  128. discloss, log_dict_disc = self.loss(
  129. inputs,
  130. reconstructions,
  131. posterior,
  132. optimizer_idx,
  133. self.global_step,
  134. last_layer=self.get_last_layer(),
  135. split="train",
  136. )
  137. self.log(
  138. "discloss",
  139. discloss,
  140. prog_bar=True,
  141. logger=True,
  142. on_step=True,
  143. on_epoch=True,
  144. )
  145. self.log_dict(
  146. log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False
  147. )
  148. return discloss
  149. def validation_step(self, batch, batch_idx):
  150. log_dict = self._validation_step(batch, batch_idx)
  151. with self.ema_scope():
  152. log_dict_ema = self._validation_step(batch, batch_idx, postfix="_ema")
  153. return log_dict
  154. def _validation_step(self, batch, batch_idx, postfix=""):
  155. inputs = self.get_input(batch, self.image_key)
  156. reconstructions, posterior = self(inputs)
  157. aeloss, log_dict_ae = self.loss(
  158. inputs,
  159. reconstructions,
  160. posterior,
  161. 0,
  162. self.global_step,
  163. last_layer=self.get_last_layer(),
  164. split="val" + postfix,
  165. )
  166. discloss, log_dict_disc = self.loss(
  167. inputs,
  168. reconstructions,
  169. posterior,
  170. 1,
  171. self.global_step,
  172. last_layer=self.get_last_layer(),
  173. split="val" + postfix,
  174. )
  175. self.log(f"val{postfix}/rec_loss", log_dict_ae[f"val{postfix}/rec_loss"])
  176. self.log_dict(log_dict_ae)
  177. self.log_dict(log_dict_disc)
  178. return self.log_dict
  179. def configure_optimizers(self):
  180. lr = self.learning_rate
  181. ae_params_list = (
  182. list(self.encoder.parameters())
  183. + list(self.decoder.parameters())
  184. + list(self.quant_conv.parameters())
  185. + list(self.post_quant_conv.parameters())
  186. )
  187. if self.learn_logvar:
  188. print(f"{self.__class__.__name__}: Learning logvar")
  189. ae_params_list.append(self.loss.logvar)
  190. opt_ae = torch.optim.Adam(ae_params_list, lr=lr, betas=(0.5, 0.9))
  191. opt_disc = torch.optim.Adam(
  192. self.loss.discriminator.parameters(), lr=lr, betas=(0.5, 0.9)
  193. )
  194. return [opt_ae, opt_disc], []
  195. def get_last_layer(self):
  196. return self.decoder.conv_out.weight
  197. @torch.no_grad()
  198. def log_images(self, batch, only_inputs=False, log_ema=False, **kwargs):
  199. log = dict()
  200. x = self.get_input(batch, self.image_key)
  201. x = x.to(self.device)
  202. if not only_inputs:
  203. xrec, posterior = self(x)
  204. if x.shape[1] > 3:
  205. # colorize with random projection
  206. assert xrec.shape[1] > 3
  207. x = self.to_rgb(x)
  208. xrec = self.to_rgb(xrec)
  209. log["samples"] = self.decode(torch.randn_like(posterior.sample()))
  210. log["reconstructions"] = xrec
  211. if log_ema or self.use_ema:
  212. with self.ema_scope():
  213. xrec_ema, posterior_ema = self(x)
  214. if x.shape[1] > 3:
  215. # colorize with random projection
  216. assert xrec_ema.shape[1] > 3
  217. xrec_ema = self.to_rgb(xrec_ema)
  218. log["samples_ema"] = self.decode(
  219. torch.randn_like(posterior_ema.sample())
  220. )
  221. log["reconstructions_ema"] = xrec_ema
  222. log["inputs"] = x
  223. return log
  224. def to_rgb(self, x):
  225. assert self.image_key == "segmentation"
  226. if not hasattr(self, "colorize"):
  227. self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
  228. x = F.conv2d(x, weight=self.colorize)
  229. x = 2.0 * (x - x.min()) / (x.max() - x.min()) - 1.0
  230. return x
  231. class IdentityFirstStage(torch.nn.Module):
  232. def __init__(self, *args, vq_interface=False, **kwargs):
  233. self.vq_interface = vq_interface
  234. super().__init__()
  235. def encode(self, x, *args, **kwargs):
  236. return x
  237. def decode(self, x, *args, **kwargs):
  238. return x
  239. def quantize(self, x, *args, **kwargs):
  240. if self.vq_interface:
  241. return x, None, [None, None, None]
  242. return x
  243. def forward(self, x, *args, **kwargs):
  244. return x