vqvae_quantize.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. # Vendored from https://raw.githubusercontent.com/CompVis/taming-transformers/24268930bf1dce879235a7fddd0b2355b84d7ea6/taming/modules/vqvae/quantize.py,
  2. # where the license is as follows:
  3. #
  4. # Copyright (c) 2020 Patrick Esser and Robin Rombach and Björn Ommer
  5. #
  6. # Permission is hereby granted, free of charge, to any person obtaining a copy
  7. # of this software and associated documentation files (the "Software"), to deal
  8. # in the Software without restriction, including without limitation the rights
  9. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. # copies of the Software, and to permit persons to whom the Software is
  11. # furnished to do so, subject to the following conditions:
  12. #
  13. # The above copyright notice and this permission notice shall be included in all
  14. # copies or substantial portions of the Software.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  19. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  20. # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  21. # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
  22. # OR OTHER DEALINGS IN THE SOFTWARE./
  23. import torch
  24. import torch.nn as nn
  25. import numpy as np
  26. from einops import rearrange
  27. class VectorQuantizer2(nn.Module):
  28. """
  29. Improved version over VectorQuantizer, can be used as a drop-in replacement. Mostly
  30. avoids costly matrix multiplications and allows for post-hoc remapping of indices.
  31. """
  32. # NOTE: due to a bug the beta term was applied to the wrong term. for
  33. # backwards compatibility we use the buggy version by default, but you can
  34. # specify legacy=False to fix it.
  35. def __init__(self, n_e, e_dim, beta, remap=None, unknown_index="random",
  36. sane_index_shape=False, legacy=True):
  37. super().__init__()
  38. self.n_e = n_e
  39. self.e_dim = e_dim
  40. self.beta = beta
  41. self.legacy = legacy
  42. self.embedding = nn.Embedding(self.n_e, self.e_dim)
  43. self.embedding.weight.data.uniform_(-1.0 / self.n_e, 1.0 / self.n_e)
  44. self.remap = remap
  45. if self.remap is not None:
  46. self.register_buffer("used", torch.tensor(np.load(self.remap)))
  47. self.re_embed = self.used.shape[0]
  48. self.unknown_index = unknown_index # "random" or "extra" or integer
  49. if self.unknown_index == "extra":
  50. self.unknown_index = self.re_embed
  51. self.re_embed = self.re_embed + 1
  52. print(f"Remapping {self.n_e} indices to {self.re_embed} indices. "
  53. f"Using {self.unknown_index} for unknown indices.")
  54. else:
  55. self.re_embed = n_e
  56. self.sane_index_shape = sane_index_shape
  57. def remap_to_used(self, inds):
  58. ishape = inds.shape
  59. assert len(ishape) > 1
  60. inds = inds.reshape(ishape[0], -1)
  61. used = self.used.to(inds)
  62. match = (inds[:, :, None] == used[None, None, ...]).long()
  63. new = match.argmax(-1)
  64. unknown = match.sum(2) < 1
  65. if self.unknown_index == "random":
  66. new[unknown] = torch.randint(0, self.re_embed, size=new[unknown].shape).to(device=new.device)
  67. else:
  68. new[unknown] = self.unknown_index
  69. return new.reshape(ishape)
  70. def unmap_to_all(self, inds):
  71. ishape = inds.shape
  72. assert len(ishape) > 1
  73. inds = inds.reshape(ishape[0], -1)
  74. used = self.used.to(inds)
  75. if self.re_embed > self.used.shape[0]: # extra token
  76. inds[inds >= self.used.shape[0]] = 0 # simply set to zero
  77. back = torch.gather(used[None, :][inds.shape[0] * [0], :], 1, inds)
  78. return back.reshape(ishape)
  79. def forward(self, z, temp=None, rescale_logits=False, return_logits=False):
  80. assert temp is None or temp == 1.0, "Only for interface compatible with Gumbel"
  81. assert rescale_logits is False, "Only for interface compatible with Gumbel"
  82. assert return_logits is False, "Only for interface compatible with Gumbel"
  83. # reshape z -> (batch, height, width, channel) and flatten
  84. z = rearrange(z, 'b c h w -> b h w c').contiguous()
  85. z_flattened = z.view(-1, self.e_dim)
  86. # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
  87. d = torch.sum(z_flattened ** 2, dim=1, keepdim=True) + \
  88. torch.sum(self.embedding.weight ** 2, dim=1) - 2 * \
  89. torch.einsum('bd,dn->bn', z_flattened, rearrange(self.embedding.weight, 'n d -> d n'))
  90. min_encoding_indices = torch.argmin(d, dim=1)
  91. z_q = self.embedding(min_encoding_indices).view(z.shape)
  92. perplexity = None
  93. min_encodings = None
  94. # compute loss for embedding
  95. if not self.legacy:
  96. loss = self.beta * torch.mean((z_q.detach() - z) ** 2) + \
  97. torch.mean((z_q - z.detach()) ** 2)
  98. else:
  99. loss = torch.mean((z_q.detach() - z) ** 2) + self.beta * \
  100. torch.mean((z_q - z.detach()) ** 2)
  101. # preserve gradients
  102. z_q = z + (z_q - z).detach()
  103. # reshape back to match original input shape
  104. z_q = rearrange(z_q, 'b h w c -> b c h w').contiguous()
  105. if self.remap is not None:
  106. min_encoding_indices = min_encoding_indices.reshape(z.shape[0], -1) # add batch axis
  107. min_encoding_indices = self.remap_to_used(min_encoding_indices)
  108. min_encoding_indices = min_encoding_indices.reshape(-1, 1) # flatten
  109. if self.sane_index_shape:
  110. min_encoding_indices = min_encoding_indices.reshape(
  111. z_q.shape[0], z_q.shape[2], z_q.shape[3])
  112. return z_q, loss, (perplexity, min_encodings, min_encoding_indices)
  113. def get_codebook_entry(self, indices, shape):
  114. # shape specifying (batch, height, width, channel)
  115. if self.remap is not None:
  116. indices = indices.reshape(shape[0], -1) # add batch axis
  117. indices = self.unmap_to_all(indices)
  118. indices = indices.reshape(-1) # flatten again
  119. # get quantized latent vectors
  120. z_q = self.embedding(indices)
  121. if shape is not None:
  122. z_q = z_q.view(shape)
  123. # reshape back to match original input shape
  124. z_q = z_q.permute(0, 3, 1, 2).contiguous()
  125. return z_q