from vector_quantize_pytorch import FSQ import torch import torch.nn as nn class FSQWrapper(nn.Module): def __init__(self, dim, levels): super().__init__() level_dim = len(levels) self.quantizer = FSQ( levels = levels ) self.down = nn.Linear(dim, level_dim) self.up = nn.Linear(level_dim, dim) def forward(self, x): x = x.transpose(1,2) x = self.down(x) z_q, indices = self.quantizer(x) x_q = self.up(z_q) x_q = x_q.transpose(1,2) loss = torch.tensor(0.0).to(x.device) return x_q, indices, loss def decode(self, indices): z_q = self.quantizer.indices_to_codes(indices) x_q = self.up(z_q) return x_q.transpose(1,2) if __name__ == '__main__': model = FSQWrapper(512, [8,4,4,4]) x = torch.randn(1, 512, 10000) x_q, indices, loss = model(x) x_q = model.decode(indices) print(indices.min(), indices.max()) print(loss)