"""v51: v48 + SiLU-gated FFN (true SwiGLU in binary form). v47/v48 FFN: `down(sign(gate(x)) * sign(up(x)))` — the gate*up is XNOR of two ±1 vectors. That throws away 1 bit of gate information per channel. v51 FFN: SwiGLU-style. `down(silu(gate_raw(x)) * sign(up(x)))` where: - gate_raw returns the pre-sign float (α·popcount - threshold) - silu of that is a float - up returns ±1 - product is float - down is a DoubledScaled... wait no, keep it single ±1 per weight. Keeps weights strictly ±1 per stored parameter. The FFN's forward path now produces float activations through the gate branch, matching standard SwiGLU. This is how BitNet-1.58b (and BitNet v1) actually structure FFN. """ 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 from model_v47 import RMSNorm, BitLinearScaled, BitLinearScaledRaw, IntBinaryAttentionScaled class BitFFNSwiGLU(nn.Module): """SwiGLU: silu(gate_raw) * sign(up) → down. gate has float output; up is ±1. down's input is float; it still uses ±1 weights (XNOR-popcount on int8-ish input). """ def __init__(self, d_model, d_ff): super().__init__() # gate returns raw float (no final sign). up returns ±1. self.gate = BitLinearScaledRaw(d_model, d_ff, binarize_input=True) self.up = BitLinearScaled(d_model, d_ff, binarize_input=True) # down takes float input; still binarizes internally. self.down = BitLinearScaledRaw(d_ff, d_model, binarize_input=True) def forward(self, x): g = F.silu(self.gate(x)) # float u = self.up(x) # ±1 return self.down(g * u) # float, returned as raw (into residual) class BitBlockV51(nn.Module): def __init__(self, d_model, n_heads, d_ff): super().__init__() self.norm1 = RMSNorm(d_model) self.attn = IntBinaryAttentionScaled(d_model, n_heads) self.norm2 = RMSNorm(d_model) self.ffn = BitFFNSwiGLU(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 BitLMv51(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([ BitBlockV51(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__': from model_v16 import set_gumbel_tau set_gumbel_tau(0.5) m = BitLMv51(d_model=512, n_layers=4, d_ff=192) n = sum(p.numel() for p in m.parameters()) print(f'v51 SwiGLU: {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')