"""v55: XOR-residual binary transformer. Standard transformer: x_new = sign(x + attn(x) + ffn(x)) — majority vote. v55: x_new = x ⊙ attn(x) ⊙ ffn(x) — elementwise XOR. For ±1 vectors, elementwise multiply IS XOR. Unlike majority-vote-sum, XOR preserves all three bits of information in a different algebra: it's invertible in a group-theoretic sense (commutative, associative, own inverse). This is a fundamentally different binary residual operator. Every residual stream value is strictly ±1 at every step. Attention is still Gumbel hard-argmax. FFN is still XNOR gated. Weights ±1. Nothing float anywhere. Config: v17 shape (d=512, L=4, d_ff=192, 5.52M), 10K steps. """ import math import torch import torch.nn as nn import torch.nn.functional as F from model import sign_ste, BitLinear, BitFFN, BinaryEmbedding from model_v18 import IntBinaryAttention class BitBlockV55(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) def forward(self, x): a = self.attn(x) f = self.ffn(x) return x * a * f # ±1 elementwise XOR of three ±1 tensors class BitLMv55(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([ BitBlockV55(d_model, n_heads, d_ff) 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__': from model_v16 import set_gumbel_tau set_gumbel_tau(0.5) m = BitLMv55(d_model=512, n_layers=4, d_ff=192) n = sum(p.numel() for p in m.parameters()) print(f'v55 XOR-res: {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')