bitnet-1bitllm / vm_backup /code /model_v43.py
hidude562's picture
1bitllm code (checkpoints to follow)
4754707 verified
"""v43: Doubled-Binary — each BitLinear has TWO ±1 weight matrices summed.
Effective weights take values in {-2, 0, +2}: ternary with a neutral/zero state.
This is still pure 1-bit-per-parameter (every stored weight is ±1 via sign STE).
Motivation: analysis on v29 showed 25–30% of latent weights have |w| < 0.01 —
the training signal wants them near zero, but sign() forces ±1 regardless. The
model is being forced to commit weights that "don't want to be committed,"
creating noise. Doubled binary lets two opposing ±1 values cancel (sum=0), so
the effective weight can be zero. Same 1-bit storage, more expressive.
v17 shape with 2x weight count: d_model=336 (from 512), n_layers=4, d_ff=192.
Target: 5.26M ≈ 5.52M v17 baseline.
"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from model import sign_ste, sign_ste_clipped, BinaryEmbedding
from model_v16 import gumbel_hard_attention
class DoubledBitLinearRaw(nn.Module):
"""Two ±1 weight matrices summed: effective W_eff in {-2, 0, +2}."""
def __init__(self, in_features, out_features, binarize_input=True):
super().__init__()
self.in_features = in_features
self.out_features = out_features
self.binarize_input = binarize_input
self.weight_a = nn.Parameter(torch.randn(out_features, in_features) * 0.02)
self.weight_b = nn.Parameter(torch.randn(out_features, in_features) * 0.02)
def forward(self, x):
W = sign_ste(self.weight_a) + sign_ste(self.weight_b) # {-2, 0, 2}
if self.binarize_input:
x = sign_ste_clipped(x)
return F.linear(x, W)
class DoubledBitLinear(nn.Module):
"""DoubledBitLinearRaw + learned threshold + sign. Returns ±1.
Sum of two ±1 matrices has effective values in {-2, 0, 2}. The raw popcount
output variance is ~2x standard BitLinear, so we scale by 1/(2·sqrt(in)).
"""
def __init__(self, in_features, out_features, binarize_input=True):
super().__init__()
self.raw = DoubledBitLinearRaw(in_features, out_features, binarize_input=binarize_input)
self.threshold = nn.Parameter(torch.zeros(out_features))
# Scale by 1/(2·sqrt(in)) since effective |w| can be 2 and sum over in_features.
self.scale = 1.0 / (2.0 * math.sqrt(in_features))
def forward(self, x):
s = self.raw(x) * self.scale - self.threshold
return sign_ste_clipped(s)
class DoubledBitFFN(nn.Module):
def __init__(self, d_model, d_ff):
super().__init__()
self.gate = DoubledBitLinear(d_model, d_ff, binarize_input=True)
self.up = DoubledBitLinear(d_model, d_ff, binarize_input=True)
self.down = DoubledBitLinear(d_ff, d_model, binarize_input=True)
def forward(self, x):
return self.down(self.gate(x) * self.up(x))
class DoubledIntBinaryAttention(nn.Module):
"""v18 attention with DoubledBitLinear Q/K/V/O."""
def __init__(self, d_model, n_heads):
super().__init__()
assert d_model % n_heads == 0
self.d_model = d_model
self.n_heads = n_heads
self.head_dim = d_model // n_heads
self.q_proj = DoubledBitLinear(d_model, d_model)
self.k_proj = DoubledBitLinear(d_model, d_model)
self.v_proj = DoubledBitLinear(d_model, d_model)
self.o_proj = DoubledBitLinear(d_model, d_model)
slopes = torch.tensor([1 << i for i in range(n_heads)], dtype=torch.long)
self.register_buffer('alibi_slopes_int', slopes)
def forward(self, x):
B, T, D = x.shape
H, Dh = self.n_heads, self.head_dim
Q = self.q_proj(x).view(B, T, H, Dh).transpose(1, 2)
K = self.k_proj(x).view(B, T, H, Dh).transpose(1, 2)
V = self.v_proj(x).view(B, T, H, Dh).transpose(1, 2)
scores = torch.matmul(Q, K.transpose(-2, -1))
pos = torch.arange(T, device=x.device)
dist = (pos.unsqueeze(0) - pos.unsqueeze(1)).abs()
alibi = self.alibi_slopes_int.view(1, H, 1, 1).to(scores.dtype) \
* dist.view(1, 1, T, T).to(scores.dtype)
scores = scores - alibi
mask = torch.triu(torch.ones(T, T, device=x.device, dtype=torch.bool), diagonal=1)
A = gumbel_hard_attention(scores, mask=mask)
O = torch.matmul(A, V)
O = O.transpose(1, 2).contiguous().view(B, T, D)
return self.o_proj(O)
class BitBlockV43(nn.Module):
def __init__(self, d_model, n_heads, d_ff):
super().__init__()
self.attn = DoubledIntBinaryAttention(d_model, n_heads)
self.ffn = DoubledBitFFN(d_model, d_ff)
def forward(self, x):
a = self.attn(x)
f = self.ffn(x)
return sign_ste(x + a + f)
class BitLMv43(nn.Module):
def __init__(self, vocab_size=128, d_model=336, n_layers=4, n_heads=8,
d_ff=192, 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([
BitBlockV43(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)
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, d_ff) in ((320, 240), (336, 192), (336, 208)):
m = BitLMv43(d_model=D, d_ff=d_ff)
n = sum(p.numel() for p in m.parameters())
print(f'D={D}, d_ff={d_ff}: {n:,} ({n/1e6:.3f}M)')
m = BitLMv43()
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')