bitnet-1bitllm / vm_backup /code /model_v54.py
hidude562's picture
1bitllm code (checkpoints to follow)
4754707 verified
"""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)}')