bitnet-1bitllm / vm_backup /code /model_v23.py
hidude562's picture
1bitllm code (checkpoints to follow)
4754707 verified
"""v23: Track IV.B — multi-prototype output head.
Standard v18 head: logit[c] = popcount(h ⊕ embed[c]) # single ±1 prototype per char
v23 head: logit[c] = max_k popcount(h ⊕ proto[c, k]) # K prototypes per char
The max-over-k captures multi-modal character distributions that a single ±1
prototype cannot represent. Still pure-integer: each popcount is a standard
XNOR-popcount, max is an integer compare tree. Inference cost: K× more
popcounts at the head, negligible because head is ~1% of FLOPs.
Training: use log-sum-exp as a soft-max at train time (collapses to max at τ→0
with the annealed Gumbel temperature we already use).
"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from model import sign_ste, sign_ste_clipped, BitLinear, BitFFN, BinaryEmbedding
from model_v18 import IntBinaryAttention
from model_v16 import set_gumbel_tau
class BitBlockV23(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) # standard v18 FFN
def forward(self, x):
a = self.attn(x)
f = self.ffn(x)
return sign_ste(x + a + f)
class BitLMv23(nn.Module):
def __init__(self, vocab_size=128, d_model=256, n_layers=8, n_heads=8, d_ff=512,
max_seq_len=256, K_proto=4):
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.K = K_proto
self.embed = BinaryEmbedding(vocab_size, d_model)
self.blocks = nn.ModuleList([
BitBlockV23(d_model, n_heads, d_ff) for _ in range(n_layers)
])
# Multi-prototype output: (vocab_size, K, d_model) ±1 via sign_ste
self.out_codebook = nn.Parameter(torch.randn(vocab_size, K_proto, 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) # (V, K, D)
# Scores: (B, T, D) × (V, K, D) -> (B, T, V, K)
scores = torch.einsum('btd,vkd->btvk', x, W_out)
# Soft-max at train (smooth over K), hard-max at inference-eval.
# Using logsumexp with a learned inverse-temperature eases training.
# Collapses to max as the network matures (the learned scale grows).
scaled = scores * self.logit_scale # (B, T, V, K)
# Use logsumexp over K dim: logsumexp ≈ max when scaled values are peaked.
logits = torch.logsumexp(scaled, dim=-1) + self.out_bias # (B, T, V)
loss = None
if targets is not None:
loss = F.cross_entropy(logits.view(-1, self.vocab_size), targets.view(-1))
return logits, loss
@torch.no_grad()
def forward_eval_argmax(self, idx):
"""Hard-max variant for inference — pure integer."""
x = self.embed(idx)
for blk in self.blocks:
x = blk(x)
W_out = sign_ste(self.out_codebook)
scores = torch.einsum('btd,vkd->btvk', x, W_out) # integer popcount
best_over_k, _ = scores.max(dim=-1) # (B, T, V)
return best_over_k
@torch.no_grad()
def generate(self, idx, max_new_tokens=200, temperature=1.0, top_k=None):
self.eval()
for _ in range(max_new_tokens):
idx_cond = idx[:, -self.max_seq_len:]
logits, _ = self(idx_cond)
logits = logits[:, -1, :] / max(temperature, 1e-5)
if top_k is not None:
v, _ = torch.topk(logits, top_k)
logits[logits < v[:, [-1]]] = -float('inf')
probs = F.softmax(logits, dim=-1)
nxt = torch.multinomial(probs, num_samples=1)
idx = torch.cat([idx, nxt], dim=1)
return idx
if __name__ == '__main__':
set_gumbel_tau(0.5)
for K in [2, 4, 8]:
m = BitLMv23(K_proto=K)
n = sum(p.numel() for p in m.parameters())
print(f'v23 K={K}: {n:,} params ({n/1e6:.2f}M)')
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')