File size: 4,005 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
"""v37: Pinch-waist architecture — per-layer d_ff redistribution.

Layer ablation on v29 showed:
  L0 (+1.42 BPC when ablated), L9 (+0.41), L1 (+0.55), L8 (+0.30)
  vs. middle layers at +0.10-0.17.
Hypothesis: allocate d_ff proportionally to ablation importance. Keep d_model
uniform (residual stream requires it), let only d_ff vary per layer.

Total FFN params preserved: baseline 8 * (3*d*d_ff_uniform) = 8 * 393K = 3.14M.
Pinch-waist: wider d_ff at boundary layers, narrower in the middle.
"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F

from model import sign_ste, sign_ste_clipped, BitLinear, BinaryEmbedding
from model_v18 import IntBinaryAttention


class BitFFNVar(nn.Module):
    """BitFFN with configurable d_ff per instance."""
    def __init__(self, d_model, d_ff):
        super().__init__()
        self.gate = BitLinear(d_model, d_ff, binarize_input=True)
        self.up = BitLinear(d_model, d_ff, binarize_input=True)
        self.down = BitLinear(d_ff, d_model, binarize_input=True)

    def forward(self, x):
        return self.down(self.gate(x) * self.up(x))


class BitBlockV37(nn.Module):
    def __init__(self, d_model, n_heads, d_ff):
        super().__init__()
        self.attn = IntBinaryAttention(d_model, n_heads)
        self.ffn = BitFFNVar(d_model, d_ff)

    def forward(self, x):
        a = self.attn(x)
        f = self.ffn(x)
        return sign_ste(x + a + f)


class BitLMv37(nn.Module):
    """Variable d_ff per layer. `d_ffs` is a list of length n_layers."""
    def __init__(self, vocab_size=128, d_model=256, d_ffs=None, n_heads=8,
                 max_seq_len=256):
        super().__init__()
        self.vocab_size = vocab_size
        self.d_model = d_model
        self.n_layers = len(d_ffs)
        self.max_seq_len = max_seq_len
        self.d_ffs = d_ffs
        self.embed = BinaryEmbedding(vocab_size, d_model)
        self.blocks = nn.ModuleList([
            BitBlockV37(d_model, n_heads, d_ff) for d_ff in d_ffs
        ])
        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__':
    from model_v16 import set_gumbel_tau
    set_gumbel_tau(0.5)
    # Pinch-waist matching 5M baseline total FFN params (8 * 512 = 4096 total ffn-width)
    # Distribution: [1024, 512, 256, 256, 256, 256, 512, 1024] = 4096 ✓
    d_ffs = [1024, 512, 256, 256, 256, 256, 512, 1024]
    m = BitLMv37(vocab_size=128, d_model=256, d_ffs=d_ffs, n_heads=8, max_seq_len=256)
    n = sum(p.numel() for p in m.parameters())
    print(f'v37 pinch-waist: {n:,} params ({n/1e6:.2f}M), d_ffs={d_ffs}')
    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')