| """v52: v48 BitNet + standard softmax attention (not Gumbel-argmax). |
| |
| Our v16→v48 chain has always used Gumbel hard-attention where each query |
| attends to exactly ONE position. That's a severe restriction — every real |
| 1-bit LLM paper uses vanilla softmax attention on float scores derived |
| from ±1 QK. Weights stay ±1; attention matrix A is a float softmax over |
| the ±1-derived integer scores. |
| |
| Change from v48: gumbel_hard_attention(…) → softmax(scores, dim=-1). |
| Everything else identical. |
| """ |
| 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_v47 import RMSNorm, BitLinearScaled, BitLinearScaledRaw, BitFFNScaled |
|
|
|
|
| class SoftmaxBinaryAttention(nn.Module): |
| """±1 Q/K/V/O weights; vanilla softmax attention over scaled integer scores.""" |
| 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 = BitLinearScaled(d_model, d_model) |
| self.k_proj = BitLinearScaled(d_model, d_model) |
| self.v_proj = BitLinearScaled(d_model, d_model) |
| self.o_proj = BitLinearScaledRaw(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) |
| self.scale = 1.0 / math.sqrt(self.head_dim) |
|
|
| 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)) * self.scale |
| 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) * self.scale |
| scores = scores - alibi |
|
|
| mask = torch.triu(torch.ones(T, T, device=x.device, dtype=torch.bool), diagonal=1) |
| scores = scores.masked_fill(mask, float('-inf')) |
| A = F.softmax(scores, dim=-1) |
| O = torch.matmul(A, V) |
| O = O.transpose(1, 2).contiguous().view(B, T, D) |
| return self.o_proj(O) |
|
|
|
|
| class BitBlockV52(nn.Module): |
| def __init__(self, d_model, n_heads, d_ff): |
| super().__init__() |
| self.norm1 = RMSNorm(d_model) |
| self.attn = SoftmaxBinaryAttention(d_model, n_heads) |
| self.norm2 = RMSNorm(d_model) |
| self.ffn = BitFFNScaled(d_model, d_ff) |
|
|
| def forward(self, x): |
| x = x + self.attn(self.norm1(x)) |
| x = x + self.ffn(self.norm2(x)) |
| return x |
|
|
|
|
| class BitLMv52(nn.Module): |
| def __init__(self, vocab_size=128, d_model=512, 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([ |
| BitBlockV52(d_model, n_heads, d_ff) for _ in range(n_layers) |
| ]) |
| self.norm_out = RMSNorm(d_model) |
| 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) |
| x = self.norm_out(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__': |
| m = BitLMv52(d_model=512, n_layers=4, d_ff=192) |
| n = sum(p.numel() for p in m.parameters()) |
| print(f'v52 softmax-attn: {n:,} ({n/1e6:.3f}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') |
|
|