Path: blob/master/extensions-builtin/LDSR/vqvae_quantize.py
2447 views
# Vendored from https://raw.githubusercontent.com/CompVis/taming-transformers/24268930bf1dce879235a7fddd0b2355b84d7ea6/taming/modules/vqvae/quantize.py,1# where the license is as follows:2#3# Copyright (c) 2020 Patrick Esser and Robin Rombach and Björn Ommer4#5# Permission is hereby granted, free of charge, to any person obtaining a copy6# of this software and associated documentation files (the "Software"), to deal7# in the Software without restriction, including without limitation the rights8# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell9# copies of the Software, and to permit persons to whom the Software is10# furnished to do so, subject to the following conditions:11#12# The above copyright notice and this permission notice shall be included in all13# copies or substantial portions of the Software.14#15# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,16# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF17# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.18# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,19# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR20# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE21# OR OTHER DEALINGS IN THE SOFTWARE./2223import torch24import torch.nn as nn25import numpy as np26from einops import rearrange272829class VectorQuantizer2(nn.Module):30"""31Improved version over VectorQuantizer, can be used as a drop-in replacement. Mostly32avoids costly matrix multiplications and allows for post-hoc remapping of indices.33"""3435# NOTE: due to a bug the beta term was applied to the wrong term. for36# backwards compatibility we use the buggy version by default, but you can37# specify legacy=False to fix it.38def __init__(self, n_e, e_dim, beta, remap=None, unknown_index="random",39sane_index_shape=False, legacy=True):40super().__init__()41self.n_e = n_e42self.e_dim = e_dim43self.beta = beta44self.legacy = legacy4546self.embedding = nn.Embedding(self.n_e, self.e_dim)47self.embedding.weight.data.uniform_(-1.0 / self.n_e, 1.0 / self.n_e)4849self.remap = remap50if self.remap is not None:51self.register_buffer("used", torch.tensor(np.load(self.remap)))52self.re_embed = self.used.shape[0]53self.unknown_index = unknown_index # "random" or "extra" or integer54if self.unknown_index == "extra":55self.unknown_index = self.re_embed56self.re_embed = self.re_embed + 157print(f"Remapping {self.n_e} indices to {self.re_embed} indices. "58f"Using {self.unknown_index} for unknown indices.")59else:60self.re_embed = n_e6162self.sane_index_shape = sane_index_shape6364def remap_to_used(self, inds):65ishape = inds.shape66assert len(ishape) > 167inds = inds.reshape(ishape[0], -1)68used = self.used.to(inds)69match = (inds[:, :, None] == used[None, None, ...]).long()70new = match.argmax(-1)71unknown = match.sum(2) < 172if self.unknown_index == "random":73new[unknown] = torch.randint(0, self.re_embed, size=new[unknown].shape).to(device=new.device)74else:75new[unknown] = self.unknown_index76return new.reshape(ishape)7778def unmap_to_all(self, inds):79ishape = inds.shape80assert len(ishape) > 181inds = inds.reshape(ishape[0], -1)82used = self.used.to(inds)83if self.re_embed > self.used.shape[0]: # extra token84inds[inds >= self.used.shape[0]] = 0 # simply set to zero85back = torch.gather(used[None, :][inds.shape[0] * [0], :], 1, inds)86return back.reshape(ishape)8788def forward(self, z, temp=None, rescale_logits=False, return_logits=False):89assert temp is None or temp == 1.0, "Only for interface compatible with Gumbel"90assert rescale_logits is False, "Only for interface compatible with Gumbel"91assert return_logits is False, "Only for interface compatible with Gumbel"92# reshape z -> (batch, height, width, channel) and flatten93z = rearrange(z, 'b c h w -> b h w c').contiguous()94z_flattened = z.view(-1, self.e_dim)95# distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z9697d = torch.sum(z_flattened ** 2, dim=1, keepdim=True) + \98torch.sum(self.embedding.weight ** 2, dim=1) - 2 * \99torch.einsum('bd,dn->bn', z_flattened, rearrange(self.embedding.weight, 'n d -> d n'))100101min_encoding_indices = torch.argmin(d, dim=1)102z_q = self.embedding(min_encoding_indices).view(z.shape)103perplexity = None104min_encodings = None105106# compute loss for embedding107if not self.legacy:108loss = self.beta * torch.mean((z_q.detach() - z) ** 2) + \109torch.mean((z_q - z.detach()) ** 2)110else:111loss = torch.mean((z_q.detach() - z) ** 2) + self.beta * \112torch.mean((z_q - z.detach()) ** 2)113114# preserve gradients115z_q = z + (z_q - z).detach()116117# reshape back to match original input shape118z_q = rearrange(z_q, 'b h w c -> b c h w').contiguous()119120if self.remap is not None:121min_encoding_indices = min_encoding_indices.reshape(z.shape[0], -1) # add batch axis122min_encoding_indices = self.remap_to_used(min_encoding_indices)123min_encoding_indices = min_encoding_indices.reshape(-1, 1) # flatten124125if self.sane_index_shape:126min_encoding_indices = min_encoding_indices.reshape(127z_q.shape[0], z_q.shape[2], z_q.shape[3])128129return z_q, loss, (perplexity, min_encodings, min_encoding_indices)130131def get_codebook_entry(self, indices, shape):132# shape specifying (batch, height, width, channel)133if self.remap is not None:134indices = indices.reshape(shape[0], -1) # add batch axis135indices = self.unmap_to_all(indices)136indices = indices.reshape(-1) # flatten again137138# get quantized latent vectors139z_q = self.embedding(indices)140141if shape is not None:142z_q = z_q.view(shape)143# reshape back to match original input shape144z_q = z_q.permute(0, 3, 1, 2).contiguous()145146return z_q147148149