vqgan_arch.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. # this file is copied from CodeFormer repository. Please see comment in modules/codeformer_model.py
  2. '''
  3. VQGAN code, adapted from the original created by the Unleashing Transformers authors:
  4. https://github.com/samb-t/unleashing-transformers/blob/master/models/vqgan.py
  5. '''
  6. import torch
  7. import torch.nn as nn
  8. import torch.nn.functional as F
  9. from basicsr.utils import get_root_logger
  10. from basicsr.utils.registry import ARCH_REGISTRY
  11. def normalize(in_channels):
  12. return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
  13. @torch.jit.script
  14. def swish(x):
  15. return x*torch.sigmoid(x)
  16. # Define VQVAE classes
  17. class VectorQuantizer(nn.Module):
  18. def __init__(self, codebook_size, emb_dim, beta):
  19. super(VectorQuantizer, self).__init__()
  20. self.codebook_size = codebook_size # number of embeddings
  21. self.emb_dim = emb_dim # dimension of embedding
  22. self.beta = beta # commitment cost used in loss term, beta * ||z_e(x)-sg[e]||^2
  23. self.embedding = nn.Embedding(self.codebook_size, self.emb_dim)
  24. self.embedding.weight.data.uniform_(-1.0 / self.codebook_size, 1.0 / self.codebook_size)
  25. def forward(self, z):
  26. # reshape z -> (batch, height, width, channel) and flatten
  27. z = z.permute(0, 2, 3, 1).contiguous()
  28. z_flattened = z.view(-1, self.emb_dim)
  29. # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
  30. d = (z_flattened ** 2).sum(dim=1, keepdim=True) + (self.embedding.weight**2).sum(1) - \
  31. 2 * torch.matmul(z_flattened, self.embedding.weight.t())
  32. mean_distance = torch.mean(d)
  33. # find closest encodings
  34. # min_encoding_indices = torch.argmin(d, dim=1).unsqueeze(1)
  35. min_encoding_scores, min_encoding_indices = torch.topk(d, 1, dim=1, largest=False)
  36. # [0-1], higher score, higher confidence
  37. min_encoding_scores = torch.exp(-min_encoding_scores/10)
  38. min_encodings = torch.zeros(min_encoding_indices.shape[0], self.codebook_size).to(z)
  39. min_encodings.scatter_(1, min_encoding_indices, 1)
  40. # get quantized latent vectors
  41. z_q = torch.matmul(min_encodings, self.embedding.weight).view(z.shape)
  42. # compute loss for embedding
  43. loss = torch.mean((z_q.detach()-z)**2) + self.beta * torch.mean((z_q - z.detach()) ** 2)
  44. # preserve gradients
  45. z_q = z + (z_q - z).detach()
  46. # perplexity
  47. e_mean = torch.mean(min_encodings, dim=0)
  48. perplexity = torch.exp(-torch.sum(e_mean * torch.log(e_mean + 1e-10)))
  49. # reshape back to match original input shape
  50. z_q = z_q.permute(0, 3, 1, 2).contiguous()
  51. return z_q, loss, {
  52. "perplexity": perplexity,
  53. "min_encodings": min_encodings,
  54. "min_encoding_indices": min_encoding_indices,
  55. "min_encoding_scores": min_encoding_scores,
  56. "mean_distance": mean_distance
  57. }
  58. def get_codebook_feat(self, indices, shape):
  59. # input indices: batch*token_num -> (batch*token_num)*1
  60. # shape: batch, height, width, channel
  61. indices = indices.view(-1,1)
  62. min_encodings = torch.zeros(indices.shape[0], self.codebook_size).to(indices)
  63. min_encodings.scatter_(1, indices, 1)
  64. # get quantized latent vectors
  65. z_q = torch.matmul(min_encodings.float(), self.embedding.weight)
  66. if shape is not None: # reshape back to match original input shape
  67. z_q = z_q.view(shape).permute(0, 3, 1, 2).contiguous()
  68. return z_q
  69. class GumbelQuantizer(nn.Module):
  70. def __init__(self, codebook_size, emb_dim, num_hiddens, straight_through=False, kl_weight=5e-4, temp_init=1.0):
  71. super().__init__()
  72. self.codebook_size = codebook_size # number of embeddings
  73. self.emb_dim = emb_dim # dimension of embedding
  74. self.straight_through = straight_through
  75. self.temperature = temp_init
  76. self.kl_weight = kl_weight
  77. self.proj = nn.Conv2d(num_hiddens, codebook_size, 1) # projects last encoder layer to quantized logits
  78. self.embed = nn.Embedding(codebook_size, emb_dim)
  79. def forward(self, z):
  80. hard = self.straight_through if self.training else True
  81. logits = self.proj(z)
  82. soft_one_hot = F.gumbel_softmax(logits, tau=self.temperature, dim=1, hard=hard)
  83. z_q = torch.einsum("b n h w, n d -> b d h w", soft_one_hot, self.embed.weight)
  84. # + kl divergence to the prior loss
  85. qy = F.softmax(logits, dim=1)
  86. diff = self.kl_weight * torch.sum(qy * torch.log(qy * self.codebook_size + 1e-10), dim=1).mean()
  87. min_encoding_indices = soft_one_hot.argmax(dim=1)
  88. return z_q, diff, {
  89. "min_encoding_indices": min_encoding_indices
  90. }
  91. class Downsample(nn.Module):
  92. def __init__(self, in_channels):
  93. super().__init__()
  94. self.conv = torch.nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=0)
  95. def forward(self, x):
  96. pad = (0, 1, 0, 1)
  97. x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
  98. x = self.conv(x)
  99. return x
  100. class Upsample(nn.Module):
  101. def __init__(self, in_channels):
  102. super().__init__()
  103. self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)
  104. def forward(self, x):
  105. x = F.interpolate(x, scale_factor=2.0, mode="nearest")
  106. x = self.conv(x)
  107. return x
  108. class ResBlock(nn.Module):
  109. def __init__(self, in_channels, out_channels=None):
  110. super(ResBlock, self).__init__()
  111. self.in_channels = in_channels
  112. self.out_channels = in_channels if out_channels is None else out_channels
  113. self.norm1 = normalize(in_channels)
  114. self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
  115. self.norm2 = normalize(out_channels)
  116. self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
  117. if self.in_channels != self.out_channels:
  118. self.conv_out = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
  119. def forward(self, x_in):
  120. x = x_in
  121. x = self.norm1(x)
  122. x = swish(x)
  123. x = self.conv1(x)
  124. x = self.norm2(x)
  125. x = swish(x)
  126. x = self.conv2(x)
  127. if self.in_channels != self.out_channels:
  128. x_in = self.conv_out(x_in)
  129. return x + x_in
  130. class AttnBlock(nn.Module):
  131. def __init__(self, in_channels):
  132. super().__init__()
  133. self.in_channels = in_channels
  134. self.norm = normalize(in_channels)
  135. self.q = torch.nn.Conv2d(
  136. in_channels,
  137. in_channels,
  138. kernel_size=1,
  139. stride=1,
  140. padding=0
  141. )
  142. self.k = torch.nn.Conv2d(
  143. in_channels,
  144. in_channels,
  145. kernel_size=1,
  146. stride=1,
  147. padding=0
  148. )
  149. self.v = torch.nn.Conv2d(
  150. in_channels,
  151. in_channels,
  152. kernel_size=1,
  153. stride=1,
  154. padding=0
  155. )
  156. self.proj_out = torch.nn.Conv2d(
  157. in_channels,
  158. in_channels,
  159. kernel_size=1,
  160. stride=1,
  161. padding=0
  162. )
  163. def forward(self, x):
  164. h_ = x
  165. h_ = self.norm(h_)
  166. q = self.q(h_)
  167. k = self.k(h_)
  168. v = self.v(h_)
  169. # compute attention
  170. b, c, h, w = q.shape
  171. q = q.reshape(b, c, h*w)
  172. q = q.permute(0, 2, 1)
  173. k = k.reshape(b, c, h*w)
  174. w_ = torch.bmm(q, k)
  175. w_ = w_ * (int(c)**(-0.5))
  176. w_ = F.softmax(w_, dim=2)
  177. # attend to values
  178. v = v.reshape(b, c, h*w)
  179. w_ = w_.permute(0, 2, 1)
  180. h_ = torch.bmm(v, w_)
  181. h_ = h_.reshape(b, c, h, w)
  182. h_ = self.proj_out(h_)
  183. return x+h_
  184. class Encoder(nn.Module):
  185. def __init__(self, in_channels, nf, emb_dim, ch_mult, num_res_blocks, resolution, attn_resolutions):
  186. super().__init__()
  187. self.nf = nf
  188. self.num_resolutions = len(ch_mult)
  189. self.num_res_blocks = num_res_blocks
  190. self.resolution = resolution
  191. self.attn_resolutions = attn_resolutions
  192. curr_res = self.resolution
  193. in_ch_mult = (1,)+tuple(ch_mult)
  194. blocks = []
  195. # initial convultion
  196. blocks.append(nn.Conv2d(in_channels, nf, kernel_size=3, stride=1, padding=1))
  197. # residual and downsampling blocks, with attention on smaller res (16x16)
  198. for i in range(self.num_resolutions):
  199. block_in_ch = nf * in_ch_mult[i]
  200. block_out_ch = nf * ch_mult[i]
  201. for _ in range(self.num_res_blocks):
  202. blocks.append(ResBlock(block_in_ch, block_out_ch))
  203. block_in_ch = block_out_ch
  204. if curr_res in attn_resolutions:
  205. blocks.append(AttnBlock(block_in_ch))
  206. if i != self.num_resolutions - 1:
  207. blocks.append(Downsample(block_in_ch))
  208. curr_res = curr_res // 2
  209. # non-local attention block
  210. blocks.append(ResBlock(block_in_ch, block_in_ch))
  211. blocks.append(AttnBlock(block_in_ch))
  212. blocks.append(ResBlock(block_in_ch, block_in_ch))
  213. # normalise and convert to latent size
  214. blocks.append(normalize(block_in_ch))
  215. blocks.append(nn.Conv2d(block_in_ch, emb_dim, kernel_size=3, stride=1, padding=1))
  216. self.blocks = nn.ModuleList(blocks)
  217. def forward(self, x):
  218. for block in self.blocks:
  219. x = block(x)
  220. return x
  221. class Generator(nn.Module):
  222. def __init__(self, nf, emb_dim, ch_mult, res_blocks, img_size, attn_resolutions):
  223. super().__init__()
  224. self.nf = nf
  225. self.ch_mult = ch_mult
  226. self.num_resolutions = len(self.ch_mult)
  227. self.num_res_blocks = res_blocks
  228. self.resolution = img_size
  229. self.attn_resolutions = attn_resolutions
  230. self.in_channels = emb_dim
  231. self.out_channels = 3
  232. block_in_ch = self.nf * self.ch_mult[-1]
  233. curr_res = self.resolution // 2 ** (self.num_resolutions-1)
  234. blocks = []
  235. # initial conv
  236. blocks.append(nn.Conv2d(self.in_channels, block_in_ch, kernel_size=3, stride=1, padding=1))
  237. # non-local attention block
  238. blocks.append(ResBlock(block_in_ch, block_in_ch))
  239. blocks.append(AttnBlock(block_in_ch))
  240. blocks.append(ResBlock(block_in_ch, block_in_ch))
  241. for i in reversed(range(self.num_resolutions)):
  242. block_out_ch = self.nf * self.ch_mult[i]
  243. for _ in range(self.num_res_blocks):
  244. blocks.append(ResBlock(block_in_ch, block_out_ch))
  245. block_in_ch = block_out_ch
  246. if curr_res in self.attn_resolutions:
  247. blocks.append(AttnBlock(block_in_ch))
  248. if i != 0:
  249. blocks.append(Upsample(block_in_ch))
  250. curr_res = curr_res * 2
  251. blocks.append(normalize(block_in_ch))
  252. blocks.append(nn.Conv2d(block_in_ch, self.out_channels, kernel_size=3, stride=1, padding=1))
  253. self.blocks = nn.ModuleList(blocks)
  254. def forward(self, x):
  255. for block in self.blocks:
  256. x = block(x)
  257. return x
  258. @ARCH_REGISTRY.register()
  259. class VQAutoEncoder(nn.Module):
  260. def __init__(self, img_size, nf, ch_mult, quantizer="nearest", res_blocks=2, attn_resolutions=None, codebook_size=1024, emb_dim=256,
  261. beta=0.25, gumbel_straight_through=False, gumbel_kl_weight=1e-8, model_path=None):
  262. super().__init__()
  263. logger = get_root_logger()
  264. self.in_channels = 3
  265. self.nf = nf
  266. self.n_blocks = res_blocks
  267. self.codebook_size = codebook_size
  268. self.embed_dim = emb_dim
  269. self.ch_mult = ch_mult
  270. self.resolution = img_size
  271. self.attn_resolutions = attn_resolutions or [16]
  272. self.quantizer_type = quantizer
  273. self.encoder = Encoder(
  274. self.in_channels,
  275. self.nf,
  276. self.embed_dim,
  277. self.ch_mult,
  278. self.n_blocks,
  279. self.resolution,
  280. self.attn_resolutions
  281. )
  282. if self.quantizer_type == "nearest":
  283. self.beta = beta #0.25
  284. self.quantize = VectorQuantizer(self.codebook_size, self.embed_dim, self.beta)
  285. elif self.quantizer_type == "gumbel":
  286. self.gumbel_num_hiddens = emb_dim
  287. self.straight_through = gumbel_straight_through
  288. self.kl_weight = gumbel_kl_weight
  289. self.quantize = GumbelQuantizer(
  290. self.codebook_size,
  291. self.embed_dim,
  292. self.gumbel_num_hiddens,
  293. self.straight_through,
  294. self.kl_weight
  295. )
  296. self.generator = Generator(
  297. self.nf,
  298. self.embed_dim,
  299. self.ch_mult,
  300. self.n_blocks,
  301. self.resolution,
  302. self.attn_resolutions
  303. )
  304. if model_path is not None:
  305. chkpt = torch.load(model_path, map_location='cpu')
  306. if 'params_ema' in chkpt:
  307. self.load_state_dict(torch.load(model_path, map_location='cpu')['params_ema'])
  308. logger.info(f'vqgan is loaded from: {model_path} [params_ema]')
  309. elif 'params' in chkpt:
  310. self.load_state_dict(torch.load(model_path, map_location='cpu')['params'])
  311. logger.info(f'vqgan is loaded from: {model_path} [params]')
  312. else:
  313. raise ValueError('Wrong params!')
  314. def forward(self, x):
  315. x = self.encoder(x)
  316. quant, codebook_loss, quant_stats = self.quantize(x)
  317. x = self.generator(quant)
  318. return x, codebook_loss, quant_stats
  319. # patch based discriminator
  320. @ARCH_REGISTRY.register()
  321. class VQGANDiscriminator(nn.Module):
  322. def __init__(self, nc=3, ndf=64, n_layers=4, model_path=None):
  323. super().__init__()
  324. layers = [nn.Conv2d(nc, ndf, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(0.2, True)]
  325. ndf_mult = 1
  326. ndf_mult_prev = 1
  327. for n in range(1, n_layers): # gradually increase the number of filters
  328. ndf_mult_prev = ndf_mult
  329. ndf_mult = min(2 ** n, 8)
  330. layers += [
  331. nn.Conv2d(ndf * ndf_mult_prev, ndf * ndf_mult, kernel_size=4, stride=2, padding=1, bias=False),
  332. nn.BatchNorm2d(ndf * ndf_mult),
  333. nn.LeakyReLU(0.2, True)
  334. ]
  335. ndf_mult_prev = ndf_mult
  336. ndf_mult = min(2 ** n_layers, 8)
  337. layers += [
  338. nn.Conv2d(ndf * ndf_mult_prev, ndf * ndf_mult, kernel_size=4, stride=1, padding=1, bias=False),
  339. nn.BatchNorm2d(ndf * ndf_mult),
  340. nn.LeakyReLU(0.2, True)
  341. ]
  342. layers += [
  343. nn.Conv2d(ndf * ndf_mult, 1, kernel_size=4, stride=1, padding=1)] # output 1 channel prediction map
  344. self.main = nn.Sequential(*layers)
  345. if model_path is not None:
  346. chkpt = torch.load(model_path, map_location='cpu')
  347. if 'params_d' in chkpt:
  348. self.load_state_dict(torch.load(model_path, map_location='cpu')['params_d'])
  349. elif 'params' in chkpt:
  350. self.load_state_dict(torch.load(model_path, map_location='cpu')['params'])
  351. else:
  352. raise ValueError('Wrong params!')
  353. def forward(self, x):
  354. return self.main(x)