| """v3 variant: parallel attention+FFN residual so the 3-way sum is always odd (no ties). |
| |
| Rationale: the v2 block is |
| x = sign(x + attn(x)) # values {-2, 0, 2}, 0 -> +1 (bias) |
| x = sign(x + ffn(x)) # values {-2, 0, 2}, 0 -> +1 (bias) |
| The sign-on-zero bias pushes every residual toward +1, compounds across 8 layers. |
| |
| v3 block: |
| a = attn(x); f = ffn(x) |
| x_out = sign(x + a + f) # values {-3, -1, 1, 3}, never 0, no bias |
| |
| Same ±1 invariant but strictly unbiased at the residual. |
| """ |
| import math |
| import torch |
| import torch.nn as nn |
| import torch.nn.functional as F |
|
|
| from model import ( |
| sign_ste, sign_ste_clipped, BitLinearRaw, BitLinear, |
| BiAttention, BitFFN, BinaryEmbedding, |
| ) |
|
|
|
|
| class BitBlockV3(nn.Module): |
| def __init__(self, d_model, n_heads, d_ff): |
| super().__init__() |
| self.attn = BiAttention(d_model, n_heads) |
| 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) |
|
|
|
|
| class BitLMv3(nn.Module): |
| def __init__(self, vocab_size=128, d_model=256, n_layers=8, n_heads=8, d_ff=512, 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([ |
| BitBlockV3(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 |
|
|
| @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 = BitLMv3() |
| n = sum(p.numel() for p in m.parameters()) |
| print(f"v3 params: {n:,} ({n/1e6:.2f}M)") |
| x = torch.randint(0, 128, (2, 64)) |
| y = torch.randint(0, 128, (2, 64)) |
| logits, loss = m(x, y) |
| print("logits:", logits.shape, "loss:", loss.item()) |
| loss.backward() |
| print("backward OK") |
|
|