"""v12: noise-annealed STE on v3 architecture (Issue 2 isolation). Self-contained reimplementation of v3 where every sign-STE gets annealed additive Gaussian noise during training: sign(x + N(0, σ²)). σ anneals 1.0 -> 0.05 over training, injected via module-level holder. """ import math import torch import torch.nn as nn import torch.nn.functional as F # Module-level noise sigma; training script calls v12_set_sigma(). _NOISE = {'sigma': 0.0} def set_noise_sigma(sigma: float): _NOISE['sigma'] = float(sigma) def _sigma(): return _NOISE['sigma'] def sign_ste_noisy(x): sigma = _sigma() if sigma > 1e-8 and x.requires_grad: x_n = x + torch.randn_like(x) * sigma else: x_n = x out = torch.where(x_n >= 0, torch.ones_like(x), -torch.ones_like(x)) return x + (out - x).detach() def sign_ste_clipped_noisy(x): sigma = _sigma() if sigma > 1e-8 and x.requires_grad: x_n = x + torch.randn_like(x) * sigma else: x_n = x out = torch.where(x_n >= 0, torch.ones_like(x), -torch.ones_like(x)) x_clip = torch.clamp(x, -1.0, 1.0) return x_clip + (out - x_clip).detach() def sign_ste_clean(x): """Non-noisy sign STE for activations.""" out = torch.where(x >= 0, torch.ones_like(x), -torch.ones_like(x)) return x + (out - x).detach() def sign_ste_clipped_clean(x): out = torch.where(x >= 0, torch.ones_like(x), -torch.ones_like(x)) x_clip = torch.clamp(x, -1.0, 1.0) return x_clip + (out - x_clip).detach() class BitLinearRawN(nn.Module): """Weights use noisy STE (for exploration); activations use clean STE.""" def __init__(self, in_features, out_features, binarize_input=True): super().__init__() self.in_features = in_features self.out_features = out_features self.binarize_input = binarize_input self.weight = nn.Parameter(torch.randn(out_features, in_features) * 0.02) def forward(self, x): W = sign_ste_noisy(self.weight) # noise on weight if self.binarize_input: x = sign_ste_clipped_clean(x) # clean STE on activations return F.linear(x, W) class BitLinearN(nn.Module): def __init__(self, in_features, out_features, binarize_input=True): super().__init__() self.raw = BitLinearRawN(in_features, out_features, binarize_input=binarize_input) self.threshold = nn.Parameter(torch.zeros(out_features)) self.scale = 1.0 / math.sqrt(in_features) def forward(self, x): s = self.raw(x) * self.scale - self.threshold return sign_ste_clipped_clean(s) class BiAttentionN(nn.Module): def __init__(self, d_model, n_heads): 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.q_proj = BitLinearN(d_model, d_model) self.k_proj = BitLinearN(d_model, d_model) self.v_proj = BitLinearN(d_model, d_model) self.o_proj = BitLinearN(d_model, d_model) self.attn_threshold = nn.Parameter(torch.zeros(n_heads)) slopes = torch.tensor([2.0 ** (i - 2) for i in range(n_heads)]) self.register_buffer('alibi_slopes', slopes) self.register_buffer('_causal_mask', torch.empty(0), persistent=False) def _get_mask(self, T, device): if self._causal_mask.shape[-1] < T or self._causal_mask.device != device: m = torch.triu(torch.ones(T, T, device=device, dtype=torch.bool), diagonal=1) self._causal_mask = m return self._causal_mask[:T, :T] def forward(self, x): B, T, D = x.shape H, Dh = self.n_heads, self.head_dim 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)) / math.sqrt(Dh) pos = torch.arange(T, device=x.device).float() dist = (pos.unsqueeze(0) - pos.unsqueeze(1)).abs() alibi_bias = self.alibi_slopes.view(1, H, 1, 1) * dist.view(1, 1, T, T) / math.sqrt(Dh) scores = scores - alibi_bias mask = self._get_mask(T, x.device) scores = scores.masked_fill(mask, -1e9) tau = self.attn_threshold.view(1, H, 1, 1) A = sign_ste_clipped_clean(scores - tau) A = A.masked_fill(mask, -1.0) O = torch.matmul(A, V) O = O.transpose(1, 2).contiguous().view(B, T, D) return self.o_proj(O) class BitFFNN(nn.Module): def __init__(self, d_model, d_ff): super().__init__() self.gate = BitLinearN(d_model, d_ff) self.up = BitLinearN(d_model, d_ff) self.down = BitLinearN(d_ff, d_model) def forward(self, x): return self.down(self.gate(x) * self.up(x)) class BitBlockN(nn.Module): def __init__(self, d_model, n_heads, d_ff): super().__init__() self.attn = BiAttentionN(d_model, n_heads) self.ffn = BitFFNN(d_model, d_ff) def forward(self, x): a = self.attn(x) f = self.ffn(x) return sign_ste_clean(x + a + f) class BinaryEmbeddingN(nn.Module): def __init__(self, vocab_size, d_model): super().__init__() self.vocab_size = vocab_size self.d_model = d_model self.weight = nn.Parameter(torch.randn(vocab_size, d_model) * 0.02) def forward(self, idx): W = sign_ste_noisy(self.weight) return F.embedding(idx, W) class BitLMv12(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 = BinaryEmbeddingN(vocab_size, d_model) self.blocks = nn.ModuleList([BitBlockN(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_noisy(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__': set_noise_sigma(0.5) m = BitLMv12() n = sum(p.numel() for p in m.parameters()) print(f"v12 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")