"""v56: Top-K attention with strict ±1 everywhere. Gumbel hard-argmax (v16/v17) forces each query to attend to EXACTLY ONE past position — a crushing expressivity constraint. Top-K relaxes this to K positions (K > 1) while keeping every activation strictly ±1: scores = Q @ K^T (integer popcount) minus ALiBi causal mask top-K per query → indices + gather O = sign_ste(sum of gathered V's) # integer sum of K ±1 vectors, signed Differentiability: top-K is non-differentiable. We use a soft-hard trick: the forward produces hard top-K gather; the backward flows through the scores with straight-through on the top-K set. Implemented by adding a soft-softmax surrogate for gradient + hard top-K for forward. Config: v17 shape (d=512, L=4, d_ff=192, 5.52M). K=4. """ import math import torch import torch.nn as nn import torch.nn.functional as F from model import sign_ste, BitLinear, BitFFN, BinaryEmbedding class TopKBinaryAttention(nn.Module): def __init__(self, d_model, n_heads, top_k=4): 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.top_k = top_k self.q_proj = BitLinear(d_model, d_model) self.k_proj = BitLinear(d_model, d_model) self.v_proj = BitLinear(d_model, d_model) self.o_proj = BitLinear(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, K = self.n_heads, self.head_dim, self.top_k 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) scores = scores.masked_fill(mask, -1e9) # Soft-hard top-K: # - hard: pick top-K, one-hot mask # - soft: softmax over scores for gradient eff_k = min(K, T) top_vals, top_idx = scores.topk(eff_k, dim=-1) # (B, H, T, K) # hard attention mask hard_A = torch.zeros_like(scores) hard_A.scatter_(-1, top_idx, 1.0) # soft softmax (normalized) for backward path soft_A = F.softmax(scores, dim=-1) A = soft_A + (hard_A - soft_A).detach() # STE: forward=hard, backward=soft # Sum of K ±1 V's per query → sign O = torch.matmul(A, V) # (B, H, T, Dh) integer in [-K, K] O = sign_ste(O) # ±1 O = O.transpose(1, 2).contiguous().view(B, T, D) return self.o_proj(O) class BitBlockV56(nn.Module): def __init__(self, d_model, n_heads, d_ff, top_k=4): super().__init__() self.attn = TopKBinaryAttention(d_model, n_heads, top_k=top_k) self.ffn = BitFFN(d_model, d_ff) def forward(self, x): a = self.attn(x) f = self.ffn(x) return sign_ste(x + a + f) # strict ±1 residual class BitLMv56(nn.Module): def __init__(self, vocab_size=128, d_model=512, n_layers=4, n_heads=8, d_ff=192, top_k=4, 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.top_k = top_k self.embed = BinaryEmbedding(vocab_size, d_model) self.blocks = nn.ModuleList([ BitBlockV56(d_model, n_heads, d_ff, top_k=top_k) 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__': m = BitLMv56(d_model=512, n_layers=4, d_ff=192, top_k=4) n = sum(p.numel() for p in m.parameters()) print(f'v56 top-4 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')