File size: 998 Bytes
138fdcc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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) |