alandao commited on
Commit
bb9a010
1 Parent(s): ddf288e

Upload vqvae.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. vqvae.py +40 -0
vqvae.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ from torch import nn
4
+ from modules import Encoder, Decoder
5
+ from modules import Codebook
6
+
7
+
8
+ class VQBASE(nn.Module):
9
+ def __init__(self, ddconfig, n_embed, embed_dim, init_steps, reservoir_size):
10
+ super(VQBASE, self).__init__()
11
+ self.encoder = Encoder(**ddconfig)
12
+ self.decoder = Decoder(**ddconfig)
13
+ self.quantize = Codebook(n_embed, embed_dim, beta=0.25, init_steps=init_steps, reservoir_size=reservoir_size) # TODO: change length_one_epoch
14
+ self.quant_conv = nn.Sequential(
15
+ nn.Conv2d(ddconfig["z_channels"], embed_dim, 1),
16
+ nn.SyncBatchNorm(embed_dim)
17
+ )
18
+ self.post_quant_conv = nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
19
+
20
+ def encode(self, x):
21
+ h = self.encoder(x)
22
+ h = self.quant_conv(h)
23
+ quant, emb_loss, info = self.quantize(h)
24
+ return quant, emb_loss, info
25
+
26
+ def decode(self, quant):
27
+ quant = self.post_quant_conv(quant)
28
+ dec = self.decoder(quant)
29
+ return dec
30
+
31
+ def decode_code(self, code_b):
32
+ quant_b = self.quantize.embed_code(code_b)
33
+ dec = self.decode(quant_b)
34
+ return dec
35
+
36
+ def forward(self, input):
37
+ quant, diff = self.encode(input)
38
+ dec = self.decode(quant)
39
+ return dec, diff
40
+