File size: 3,155 Bytes
4754707
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""v46: Float residual stream. Every WEIGHT is ±1; the residual stream between
blocks is not sign()'d.

v18/v17 force x = sign(x + a + f) at every block. That means the entire model
lives in a ±1 vector space between layers — a crushing constraint. Each
BitLinear binarizes its input anyway via sign_ste_clipped, so removing the
outer sign on the residual costs nothing in "1-bit compute": every matmul is
still XNOR-popcount, every weight is still ±1.

What changes: residual stream accumulates as int/float across depth. The
model now has float-valued activations (small dynamic range: sum of L ±1
vectors). Storage is still strictly 1-bit per parameter.

This is what BitNet/1-bit-LLMs actually do. Our "maximalist" framing was
pessimistic about this tradeoff.
"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F

from model import sign_ste, BitLinear, BitFFN, BinaryEmbedding
from model_v18 import IntBinaryAttention


class BitBlockV46(nn.Module):
    def __init__(self, d_model, n_heads, d_ff):
        super().__init__()
        self.attn = IntBinaryAttention(d_model, n_heads)
        self.ffn = BitFFN(d_model, d_ff)

    def forward(self, x):
        a = self.attn(x)   # BitLinear inside binarizes x → ±1 internally
        f = self.ffn(x)
        return x + a + f   # NO sign on residual — float/int accumulation


class BitLMv46(nn.Module):
    def __init__(self, vocab_size=128, d_model=256, n_layers=8, n_heads=8,
                 d_ff=512, max_seq_len=256):
        super().__init__()
        self.vocab_size = vocab_size
        self.d_model = d_model
        self.n_layers = n_layers
        self.max_seq_len = max_seq_len
        self.embed = BinaryEmbedding(vocab_size, d_model)
        self.blocks = nn.ModuleList([
            BitBlockV46(d_model, n_heads, d_ff) for _ in range(n_layers)
        ])
        self.out_codebook = nn.Parameter(torch.randn(vocab_size, d_model) * 0.02)
        self.logit_scale = nn.Parameter(torch.tensor(1.0 / math.sqrt(d_model)))
        self.out_bias = nn.Parameter(torch.zeros(vocab_size))

    def forward(self, idx, targets=None):
        x = self.embed(idx)
        for blk in self.blocks:
            x = blk(x)
        # Head: binarize residual once, then match against binary codebook
        x = sign_ste(x)
        W_out = sign_ste(self.out_codebook)
        scores = torch.matmul(x, W_out.t())
        logits = scores * self.logit_scale + self.out_bias
        loss = None
        if targets is not None:
            loss = F.cross_entropy(logits.view(-1, self.vocab_size), targets.view(-1))
        return logits, loss


if __name__ == '__main__':
    from model_v16 import set_gumbel_tau
    set_gumbel_tau(0.5)
    for (D, L, d_ff) in ((256, 8, 512), (512, 4, 192), (336, 4, 192)):
        m = BitLMv46(d_model=D, n_layers=L, d_ff=d_ff)
        n = sum(p.numel() for p in m.parameters())
        print(f'D={D} L={L} d_ff={d_ff}: {n:,} ({n/1e6:.3f}M)')
    m = BitLMv46()
    x = torch.randint(0, 128, (2, 64))
    y = torch.randint(0, 128, (2, 64))
    logits, loss = m(x, y)
    loss.backward()
    print(f'loss={loss.item():.3f}, backward OK')