File size: 3,250 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
"""v54: Bit-level language model. Vocab = 2 (±1 for 0/1).

Instead of char-level 128-way softmax output, the model predicts one BIT at a
time. Each char is decomposed into 7 ±1 bits. For TinyStories (vocab=128),
this is exact and lossless. Training loss is binary cross-entropy per bit.
To compare apples-to-apples with char-level BPC, we aggregate:
    char_BPC = 7 × (bit_CE_in_nats / ln(2))

The model is strict ±1 everywhere (v17-style): Gumbel hard-argmax attention,
sign_ste residual, no RMSNorm, no α scales, no softmax over positions. Only
the output is a tiny 2-class softmax.

Why this could unlock 1.3 BPC per char:
  - Each prediction is a single binary decision — the simplest possible task
    for a ±1 network.
  - High-order bits of ASCII are nearly deterministic (space/letters ≈ 0x2_-
    0x7_), so most bits are easy; the model only has to work hard on the low-
    order bits where it can spend its capacity.
  - Training dynamics on binary targets are much better-matched to binary
    networks than 128-way softmax.

Config: d_model=256, n_layers=8, n_heads=8, d_ff=512 — v18 defaults, strict ±1.
"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F

from model import sign_ste
from model_v18 import BitBlockV18


class BitLevelLM(nn.Module):
    """Bit-level ±1 transformer. Vocab = 2."""
    def __init__(self, d_model=256, n_layers=8, n_heads=8, d_ff=512, max_seq_len=1792):
        super().__init__()
        self.vocab_size = 2
        self.d_model = d_model
        self.n_layers = n_layers
        self.max_seq_len = max_seq_len
        # Bit embedding: 2 codes (for 0 and 1), each a ±1 vector of dim d_model.
        # Latent float; sign()'d at forward.
        self.embed_raw = nn.Parameter(torch.randn(2, d_model) * 0.02)
        self.blocks = nn.ModuleList([
            BitBlockV18(d_model, n_heads, d_ff) for _ in range(n_layers)
        ])
        # Binary output: 2 codes.
        self.out_codebook = nn.Parameter(torch.randn(2, d_model) * 0.02)
        self.logit_scale = nn.Parameter(torch.tensor(1.0 / math.sqrt(d_model)))
        self.out_bias = nn.Parameter(torch.zeros(2))

    def forward(self, idx, targets=None):
        # idx: (B, T) int64 in {0, 1}
        W_embed = sign_ste(self.embed_raw)      # (2, D) ±1
        x = W_embed[idx]                         # (B, T, D) ±1
        for blk in self.blocks:
            x = blk(x)
        W_out = sign_ste(self.out_codebook)     # (2, D) ±1
        scores = torch.matmul(x, W_out.t())     # (B, T, 2) integer popcount
        logits = scores * self.logit_scale + self.out_bias
        loss = None
        if targets is not None:
            loss = F.cross_entropy(logits.view(-1, 2), targets.view(-1))
        return logits, loss


if __name__ == '__main__':
    from model_v16 import set_gumbel_tau
    set_gumbel_tau(0.5)
    m = BitLevelLM(d_model=256, n_layers=8, n_heads=8, d_ff=512, max_seq_len=1792)
    n = sum(p.numel() for p in m.parameters())
    print(f'bit-level: {n:,} ({n/1e6:.3f}M)')
    x = torch.randint(0, 2, (2, 64))
    y = torch.randint(0, 2, (2, 64))
    logits, loss = m(x, y)
    loss.backward()
    print(f'loss={loss.item():.3f}, backward OK, logits shape={tuple(logits.shape)}')