"""v38: BitMixer — drop attention entirely. Deep analysis on v29 showed 102 of 120 attention heads collapsed to static local/positional patterns; only 6 heads were content-sensitive. Binary attention with ±1 QK + ALiBi cannot form content-addressable routing. Honest response: replace the attention module with a static binary mix of tokens — a single causal-masked (T × T) ±1 weight matrix per layer, applied per-channel. Every signal path remains strictly ±1: x (±1) -> W_mix (±1, T×T, causal) @ x -> rowwise rescale -> sign_ste -> ±1 No Q/K/V, no softmax, no ALiBi. Like MLP-Mixer but everything is binary. If this matches v17 (1.68 BPC) at 5M/10K, binary attention was deadweight. """ import math import torch import torch.nn as nn import torch.nn.functional as F from model import sign_ste, sign_ste_clipped, BitLinear, BinaryEmbedding class BitTokenMix(nn.Module): """Static causal ±1 token-mix. Shared across channels, independent across layers.""" def __init__(self, max_seq_len): super().__init__() self.max_seq_len = max_seq_len # Latent float weight; forward uses sign(weight) * causal_mask. self.weight = nn.Parameter(torch.randn(max_seq_len, max_seq_len) * 0.02) mask = torch.tril(torch.ones(max_seq_len, max_seq_len)) self.register_buffer('causal_mask', mask) # Row t has t+1 non-zero entries; std of signed sum ~ sqrt(t+1). row_norm = 1.0 / torch.sqrt(torch.arange(1, max_seq_len + 1).float()) self.register_buffer('row_norm', row_norm) def forward(self, x): B, T, D = x.shape W = sign_ste(self.weight[:T, :T]) W = W * self.causal_mask[:T, :T] # y[b, t, d] = sum_s W[t, s] x[b, s, d] => (B,D,T) @ W.T -> (B,D,T) x_bdt = x.transpose(1, 2) y_bdt = x_bdt @ W.t() y_bdt = y_bdt * self.row_norm[:T].view(1, 1, T) return sign_ste_clipped(y_bdt.transpose(1, 2)) class BitFFNV38(nn.Module): def __init__(self, d_model, d_ff): super().__init__() self.gate = BitLinear(d_model, d_ff, binarize_input=True) self.up = BitLinear(d_model, d_ff, binarize_input=True) self.down = BitLinear(d_ff, d_model, binarize_input=True) def forward(self, x): return self.down(self.gate(x) * self.up(x)) class BitBlockV38(nn.Module): def __init__(self, d_model, d_ff, max_seq_len): super().__init__() self.mix = BitTokenMix(max_seq_len) self.ffn = BitFFNV38(d_model, d_ff) def forward(self, x): m = self.mix(x) f = self.ffn(x) return sign_ste(x + m + f) class BitLMv38(nn.Module): def __init__(self, vocab_size=128, d_model=256, n_layers=8, d_ff=720, max_seq_len=256): super().__init__() self.vocab_size = vocab_size self.d_model = d_model self.n_layers = n_layers self.d_ff = d_ff self.max_seq_len = max_seq_len self.embed = BinaryEmbedding(vocab_size, d_model) self.blocks = nn.ModuleList([ BitBlockV38(d_model, d_ff, max_seq_len) 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 @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__': m = BitLMv38(vocab_size=128, d_model=256, n_layers=8, d_ff=720, max_seq_len=256) n = sum(p.numel() for p in m.parameters()) print(f'v38 BitMixer: {n:,} params ({n/1e6:.2f}M), d_ff=720') 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')