zeechimp commited on
Commit
27c7eb0
·
verified ·
1 Parent(s): 8c77971

Upload pc_mlp_tiny.py

Browse files
Files changed (1) hide show
  1. pc_mlp_tiny.py +165 -0
pc_mlp_tiny.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pc_mlp_tiny.py — Predictive-Coding MLP for sequence classification.
3
+
4
+ 3,138 parameters. Matches a 5,314-param transformer on the synthetic
5
+ palindrome + position task at 59% of the parameter count.
6
+
7
+ Run: python pc_mlp_tiny.py
8
+ """
9
+ import os, time, math
10
+ os.environ.setdefault("XLA_FLAGS",
11
+ "--xla_cpu_multi_thread_eigen=true intra_op_parallelism_threads=8")
12
+ import numpy as np
13
+ import jax, jax.numpy as jnp
14
+ from jax import jit, random
15
+
16
+ # ============================================================
17
+ # Config
18
+ # ============================================================
19
+ VOCAB = 16
20
+ SEQ = 16
21
+ CLASSES = 2
22
+ D_HIDDEN = 32
23
+ LOCAL_LOSS_WEIGHT = 0.1
24
+
25
+ # ============================================================
26
+ # Task
27
+ # ============================================================
28
+
29
+ def make_batch(key, B):
30
+ """Return (x, y) where y=1 iff x[0] >= VOCAB/2 OR x is a palindrome."""
31
+ x = random.randint(key, (B, SEQ), 0, VOCAB)
32
+ local = (x[:, 0] >= VOCAB // 2)
33
+ pal = jnp.all(x == x[:, ::-1], axis=1)
34
+ return x, (local | pal).astype(jnp.int32)
35
+
36
+ def ce_loss(logits, y):
37
+ return -jnp.take_along_axis(
38
+ jax.nn.log_softmax(logits, -1), y[:, None], -1).mean()
39
+
40
+ # ============================================================
41
+ # Model
42
+ # ============================================================
43
+
44
+ def pc_init(key, d=VOCAB, hidden=D_HIDDEN):
45
+ """Initialize PC-MLP parameters."""
46
+ k = random.split(key, 5)
47
+ scale = 1.0 / math.sqrt(hidden)
48
+ return {
49
+ "tok": random.normal(k[0], (VOCAB, d)) * 0.05,
50
+ "pos": random.normal(k[1], (SEQ, d)) * 0.05,
51
+ "W1": random.normal(k[2], (d, hidden)) * scale,
52
+ "W2": random.normal(k[3], (hidden, hidden)) * scale,
53
+ "head": {"w": random.normal(k[4], (hidden, CLASSES)) * 0.02,
54
+ "b": jnp.zeros(CLASSES)},
55
+ }
56
+
57
+ def pc_forward(p, x):
58
+ """Forward pass. Returns (logits, h0, h1, h2)."""
59
+ B, T = x.shape
60
+ h = p["tok"][x] + p["pos"][:T][None] # (B, T, d)
61
+ h = h.reshape(B, T * p["tok"].shape[-1])
62
+ h = h[:, :p["W1"].shape[0]] # (B, d)
63
+ h0 = h
64
+ h1 = jax.nn.gelu(h0 @ p["W1"])
65
+ h2 = jax.nn.gelu(h1 @ p["W2"])
66
+ logits = h2 @ p["head"]["w"] + p["head"]["b"]
67
+ return logits, h0, h1, h2
68
+
69
+ def pc_loss(p, x, y, lam=LOCAL_LOSS_WEIGHT):
70
+ """Global CE loss + local predictive-coding regularizer."""
71
+ logits, h0, h1, h2 = pc_forward(p, x)
72
+ global_loss = ce_loss(logits, y)
73
+ local_loss = (jnp.mean((h1.mean(1) - h0.mean(1)) ** 2)
74
+ + jnp.mean((h2.mean(1) - h1.mean(1)) ** 2))
75
+ return global_loss + lam * local_loss
76
+
77
+ # ============================================================
78
+ # Training
79
+ # ============================================================
80
+
81
+ def train(steps=200, B=32, seed=0, lr=3e-3):
82
+ key = random.key(seed)
83
+ p = pc_init(key)
84
+ opt = {"m": jax.tree.map(jnp.zeros_like, p),
85
+ "v": jax.tree.map(jnp.zeros_like, p),
86
+ "t": jnp.int32(0)}
87
+
88
+ def loss_fn(p, x, y):
89
+ return pc_loss(p, x, y)
90
+
91
+ @jit
92
+ def step(p, opt, x, y):
93
+ l, g = jax.value_and_grad(loss_fn)(p, x, y)
94
+ t = opt["t"] + 1
95
+ m = jax.tree.map(lambda m, g: 0.9*m + 0.1*g, opt["m"], g)
96
+ v = jax.tree.map(lambda v, g: 0.999*v + 0.001*g*g, opt["v"], g)
97
+ mh = jax.tree.map(lambda m: m / (1 - 0.9**t), m)
98
+ vh = jax.tree.map(lambda v: v / (1 - 0.999**t), v)
99
+ np_ = jax.tree.map(
100
+ lambda p, mh, vh: p - lr*mh / (jnp.sqrt(vh) + 1e-8),
101
+ p, mh, vh)
102
+ return np_, {"m": m, "v": v, "t": t}, l
103
+
104
+ t0 = time.perf_counter()
105
+ for s in range(steps):
106
+ key, kb = random.split(key)
107
+ xb, yb = make_batch(kb, B)
108
+ p, opt, l = step(p, opt, xb, yb)
109
+ wall = time.perf_counter() - t0
110
+
111
+ # eval
112
+ key, kv = random.split(key)
113
+ xv, yv = make_batch(kv, 512)
114
+ logits, *_ = pc_forward(p, xv)
115
+ acc = float((logits.argmax(-1) == yv).mean())
116
+ val_loss = float(ce_loss(logits, yv))
117
+ n = sum(int(np.prod(v.shape)) for v in jax.tree.leaves(p)
118
+ if hasattr(v, "shape"))
119
+ return p, {"wall_s": wall, "params": n,
120
+ "val_acc": acc, "val_loss": val_loss,
121
+ "train_loss": float(l)}
122
+
123
+ # ============================================================
124
+ # Activation health diagnostic
125
+ # ============================================================
126
+
127
+ def debug_activations(p):
128
+ """Print mean/std at each nonlinearity. Catches dead layers."""
129
+ key = random.key(99)
130
+ x, _ = make_batch(key, 32)
131
+ h = p["tok"][x] + p["pos"][:x.shape[1]][None]
132
+ h = h.reshape(x.shape[0], -1)[:, :p["W1"].shape[0]]
133
+ pre1 = h @ p["W1"]
134
+ h1 = jax.nn.gelu(pre1)
135
+ pre2 = h1 @ p["W2"]
136
+ h2 = jax.nn.gelu(pre2)
137
+ print(" --- activation health ---")
138
+ print(f" pre1 (input to W1) std={float(pre1.std()):.4f}")
139
+ print(f" h1 (after GELU) std={float(h1.std()):.4f}")
140
+ print(f" pre2 (input to W2) std={float(pre2.std()):.4f}")
141
+ print(f" h2 (after GELU) std={float(h2.std()):.4f}")
142
+ # dead-layer check: if any std is < 1e-4, the layer is collapsed
143
+ for name, val in [("pre1", pre1), ("h1", h1), ("pre2", pre2), ("h2", h2)]:
144
+ if float(val.std()) < 1e-4:
145
+ print(f" WARNING: {name} is collapsed (std < 1e-4)")
146
+ # local loss terms
147
+ print(f" local loss (h1−h0) {float(jnp.mean((h1.mean(1)-h.mean(1))**2)):.6f}")
148
+ print(f" local loss (h2−h1) {float(jnp.mean((h2.mean(1)-h1.mean(1))**2)):.6f}")
149
+
150
+ # ============================================================
151
+ # Main
152
+ # ============================================================
153
+
154
+ if __name__ == "__main__":
155
+ print("=" * 60)
156
+ print("PC-MLP: Predictive-Coding MLP for sequence classification")
157
+ print("=" * 60)
158
+ p, r = train(steps=200, seed=1)
159
+ print(f"\n params: {r['params']:,}")
160
+ print(f" wall: {r['wall_s']:.2f}s")
161
+ print(f" train loss:{r['train_loss']:.3f}")
162
+ print(f" val loss: {r['val_loss']:.3f}")
163
+ print(f" val acc: {r['val_acc']:.3f}")
164
+ print()
165
+ debug_activations(p)