File size: 4,394 Bytes
4754707
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
"""v13: time-multiplexed v3 (Issue 3 — state-capacity isolation).

Each transformer block is run T=4 times per token position with fresh ±1 random
masks injected as XNOR-noise on the hidden state. The T per-pass outputs are
summed in integer space and sign'd at the end to stay ±1 at block output.

The per-pass hidden state is strictly ±1; the temporal average over T passes
carries up to log₂(T+1) ≈ 2.3-bit resolution per bit, giving the state
effectively more capacity without changing the physical representation width.

Param count matches v3 exactly; compute cost is T× per block.
"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F

from model import sign_ste, sign_ste_clipped, BitLinear, BiAttention, BitFFN, BinaryEmbedding


class BitBlockV13(nn.Module):
    def __init__(self, d_model, n_heads, d_ff, T=4, mask_prob=0.25):
        super().__init__()
        self.attn = BiAttention(d_model, n_heads)
        self.ffn = BitFFN(d_model, d_ff)
        self.T = T
        self.mask_prob = mask_prob

    def forward(self, x):
        # x is ±1
        if self.training and self.T > 1:
            accum = torch.zeros_like(x)
            for t in range(self.T):
                # Apply fresh XNOR mask: elementwise flip with probability mask_prob
                flip = (torch.rand_like(x) < self.mask_prob).float() * 2 - 1  # -1 at flip, +1 otherwise
                flip = flip * -1 + 1  # so it's +1 (no flip) / -1 (flip) ... actually let me redo
                # Simpler: mask = sign(rand - mask_prob*0.5), but just use bern flip
                r = torch.rand_like(x)
                sign_flip = torch.where(r < self.mask_prob,
                                         -torch.ones_like(x),
                                         torch.ones_like(x))  # ±1
                x_masked = x * sign_flip  # still ±1
                a = self.attn(x_masked)
                f = self.ffn(x_masked)
                accum = accum + x_masked + a + f
            # Sign at end: accum has values in [-3T, +3T]
            return sign_ste(accum)
        else:
            a = self.attn(x)
            f = self.ffn(x)
            return sign_ste(x + a + f)


class BitLMv13(nn.Module):
    def __init__(self, vocab_size=128, d_model=256, n_layers=8, n_heads=8, d_ff=512, max_seq_len=256,
                 T=4, mask_prob=0.25):
        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([
            BitBlockV13(d_model, n_heads, d_ff, T=T, mask_prob=mask_prob) 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 = BitLMv13()
    n = sum(p.numel() for p in m.parameters())
    print(f"v13 params: {n:,} ({n/1e6:.2f}M)")
    x = torch.randint(0, 128, (2, 64))
    y = torch.randint(0, 128, (2, 64))
    m.train()
    logits, loss = m(x, y)
    print("logits:", logits.shape, "loss:", loss.item())
    loss.backward()
    print("backward OK")