File size: 3,612 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange, reduce, pack, unpack


class BinaryQuantizer(nn.Module):
    def __init__(self, codebook_size, emb_dim, num_hiddens, use_tanh=False):
        super().__init__()
        self.codebook_size = codebook_size  # number of embeddings
        self.emb_dim = emb_dim  # dimension of embedding
        act = nn.Sigmoid
        if use_tanh:
            act = nn.Tanh
        self.proj = nn.Sequential(
            nn.Conv1d(num_hiddens, codebook_size, 1),  # projects last encoder layer to quantized logits
            act(),
            )
        self.embed = nn.Embedding(codebook_size, emb_dim)
        self.use_tanh = use_tanh

    def quantizer(self, x, deterministic=False):
        if self.use_tanh:
            x = x * 0.5 + 0.5
            if deterministic:
                x = (x > 0.5) * 1.0 
            else:
                x = torch.bernoulli(x)
            x = (x - 0.5) * 2.0
            return x
            
        else:
            if deterministic:
                x = (x > 0.5) * 1.0 
                return x
            else:
                return torch.bernoulli(x)

    def forward(self, h, deterministic=False):

        z = self.proj(h)

        # code_book_loss = F.binary_cross_entropy_with_logits(z, (torch.sigmoid(z.detach())>0.5)*1.0)
        code_book_loss = (torch.sigmoid(z) * (1 - torch.sigmoid(z))).mean()

        z_b = self.quantizer(z, deterministic=deterministic)

        z_flow = z_b.detach() + z - z.detach()

        z_q = torch.einsum("b n h, n d -> b d h", z_flow, self.embed.weight)

        return z_q,  code_book_loss, {
            "binary_code": z_b.detach()
        }, z_b.detach()


class BAEQuantizerWrapper(nn.Module):
    def __init__(self, emb_dim, n_bit):
        super().__init__()
        self.quantizer = BinaryQuantizer(n_bit, emb_dim, emb_dim, use_tanh=False)
        self.n_bit = n_bit

    def forward(self, x, deterministic=False):
        x_q, loss, _, binary_code = self.quantizer(x, deterministic=deterministic)
        token_each = 1

        binary_code = rearrange(binary_code, 'b c h -> b h c') # b, 256, 64
        binary_code =  torch.stack(torch.chunk(binary_code, token_each, dim=-1), 2) # b, 256, 4, 16 
        multipler = 2 ** (torch.arange(self.n_bit-1, -1, -1)).to(x.device)
        indices = reduce(binary_code.long() * multipler,'b n m c -> b n m', 'sum') #b, 256, token_each
        return x_q, loss, indices.squeeze(-1)

    def decode_code(self, indices):
        
        all_codes = torch.arange(int(2 ** self.n_bit))  #tensor([    0,     1,     2,  ..., 65533, 65534, 65535])
        multipler = 2 ** (torch.arange(self.n_bit-1, -1, -1)) #tensor([32768, 16384, 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1])
        codebook = ((all_codes[..., None] & multipler) != 0).float().to(indices.device) #8, 256, 4, 16
        codes = codebook[indices]
        codes = rearrange(codes, 'b l c -> b c l')
        x = torch.einsum("b n h, n d -> b d h", codes, self.quantizer.embed.weight) 
        return x
        # codes = codes.reshape(bs, -1, latent_size, latent_size)
        # sample = binaryae.decode(codes, is_bin=True)
        
if __name__ == '__main__':
    emb_dim = 256
    n_bit = 11
    model = BAEQuantizerWrapper(emb_dim, n_bit)
    x = torch.randn(1, emb_dim, 21)
    x_q, loss, indices = model(x)


    print(x_q.shape, indices.shape, indices.min(), indices.max())
    decoded = model.decode_code(indices)
    print(decoded.shape, decoded.min(), decoded.max())
    print((decoded - x_q).abs().max(), loss)