""" Pre-registered Empirical Adjudication — Predictions 2 & 3 (Codex Round 2) Exact specification from exp3_dual_ai_dialogue/round2_codex.md: - Architecture: Nanda et al. (2023, arXiv:2301.05217) 1-layer ReLU Transformer p = 113, d_model = 128, n_heads = 4, d_head = 32, d_mlp = 512, no LayerNorm. - Data & Training: 30% of ordered pairs (a, b) in Z_113 x Z_113 for train (3830), 70% test (8939). Full-batch AdamW(lr=1e-3, weight_decay=1.0, betas=(0.9, 0.98)), max 40,000 steps. Seeds 0..4 independently control split & initialization; evaluate every 100 steps. - Checkpoints: - Early: first logged step with train_acc == 1.0 and test_acc < 0.05. - Late: first logged step after Early with test_acc > 0.99. - Prediction 2 (Fourier concentration on W_E[:113]): 1D FFT along residue axis, remove DC, sum conjugate pairs (k, p-k), rank by sum of squared magnitudes across d_model. Top-6 pairs share of total AC energy: Late >= 75% AND (Late - Early) >= 20 percentage points, in >= 4/5 seeds. - Prediction 3 (Causal subspace patching on '=' token MLP post-ReLU activations): Compute training class means mu(s) for s = (a+b) mod p, FFT along s, take real & imag parts of the same checkpoint's Top-6 frequency pairs to span orthonormal basis Q (rank <= 12). On all test triples where (a,b), (a+1,b-1), (a+1,b) are ALL in test: - Same-sum patch from (a+1, b-1) -> mean Euclidean shift of mean-centered logits = D0. - Shifted-sum patch from (a+1, b) -> mean Euclidean shift = D1, and counterfactual steering accuracy to (a+b+1) mod p. - Random same-rank subspace control: mean late steering rate over 20 Haar-random subspaces. Codex Bet (>= 4/5 seeds): Late D0 < D1 / 3, steering rises from Early < 10% to Late > 90%, random control Late < 20%. """ import argparse import json import math import time from pathlib import Path import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as nn import torch.nn.functional as F ROOT = Path(__file__).resolve().parent RES_DIR = ROOT / "results" FIG_DIR = ROOT / "figures" RES_DIR.mkdir(parents=True, exist_ok=True) FIG_DIR.mkdir(parents=True, exist_ok=True) P = 113 D_MODEL = 128 N_HEADS = 4 D_MLP = 512 TRAIN_FRAC = 0.3 LR = 1e-3 WD = 1.0 MAX_STEPS = 40000 LOG_EVERY = 100 class ExactNandaTransformer(nn.Module): """Mathematically exact 1-layer ReLU Transformer on [a, b, =] (Nanda et al. 2023).""" def __init__(self, p=P, d_model=D_MODEL, n_heads=N_HEADS, d_mlp=D_MLP): super().__init__() self.p = p self.d_model = d_model self.n_heads = n_heads self.d_head = d_model // n_heads self.W_E = nn.Parameter(torch.randn(p + 1, d_model) / math.sqrt(d_model)) self.W_pos = nn.Parameter(torch.randn(3, d_model) / math.sqrt(d_model)) self.W_Q = nn.Parameter(torch.randn(d_model, d_model) / math.sqrt(d_model)) self.W_K = nn.Parameter(torch.randn(d_model, d_model) / math.sqrt(d_model)) self.W_V = nn.Parameter(torch.randn(d_model, d_model) / math.sqrt(d_model)) self.W_O = nn.Parameter(torch.randn(d_model, d_model) / math.sqrt(d_model)) self.W_in = nn.Parameter(torch.randn(d_model, d_mlp) / math.sqrt(d_model)) self.b_in = nn.Parameter(torch.zeros(d_mlp)) self.W_out = nn.Parameter(torch.randn(d_mlp, d_model) / math.sqrt(d_mlp)) self.b_out = nn.Parameter(torch.zeros(d_model)) self.W_U = nn.Parameter(torch.randn(d_model, p) / math.sqrt(d_model)) def forward_with_cache(self, a: torch.Tensor, b: torch.Tensor): H, dh = self.n_heads, self.d_head tok = self.W_E[: self.p] x0 = tok + self.W_pos[0] x1 = tok + self.W_pos[1] x2 = self.W_E[self.p] + self.W_pos[2] q2 = (x2 @ self.W_Q).view(H, dh) * (1.0 / math.sqrt(dh)) k0 = (x0 @ self.W_K).view(self.p, H, dh) k1 = (x1 @ self.W_K).view(self.p, H, dh) k2 = (x2 @ self.W_K).view(H, dh) s0 = (k0 * q2).sum(-1) s1 = (k1 * q2).sum(-1) s2 = (k2 * q2).sum(-1) v0 = (x0 @ self.W_V).view(self.p, H, dh) v1 = (x1 @ self.W_V).view(self.p, H, dh) v2 = (x2 @ self.W_V).view(1, H, dh) logits_attn = torch.stack([s0[a], s1[b], s2.expand(a.shape[0], H)], dim=-1) attn = F.softmax(logits_attn, dim=-1) ctx = ( attn[..., 0:1] * v0[a] + attn[..., 1:2] * v1[b] + attn[..., 2:3] * v2 ).reshape(-1, self.d_model) resid_mid = x2 + ctx @ self.W_O mlp_act = F.relu(resid_mid @ self.W_in + self.b_in) resid_post = resid_mid + mlp_act @ self.W_out + self.b_out logits = resid_post @ self.W_U return logits, resid_mid, mlp_act def forward(self, a: torch.Tensor, b: torch.Tensor): logits, _, _ = self.forward_with_cache(a, b) return logits def fourier_embedding_audit(W_E_np: np.ndarray) -> dict: """1D FFT along residue axis 0..p-1, remove DC, merge conjugate pairs (k, p-k).""" E = W_E_np[:P, :] # (113, 128) F_E = np.fft.fft(E, axis=0) power_k = np.sum(np.abs(F_E) ** 2, axis=1) # (113,) n_pairs = (P - 1) // 2 # 56 pair_power = np.array([power_k[k] + power_k[P - k] for k in range(1, n_pairs + 1)]) total_ac = float(np.sum(pair_power)) order = np.argsort(pair_power)[::-1] # 0-based index -> frequency k = idx + 1 top6_freqs = [int(idx + 1) for idx in order[:6]] top6_shares = [float(pair_power[idx] / total_ac) for idx in order[:6]] top6_total = float(sum(top6_shares)) return { "top6_freqs": top6_freqs, "top6_individual_shares": top6_shares, "top6_ac_energy_share": top6_total, "pair_power_normalized": [float(x / total_ac) for x in pair_power], } @torch.no_grad() def causal_subspace_audit( model: ExactNandaTransformer, train_a: torch.Tensor, train_b: torch.Tensor, train_mask_2d: np.ndarray, top6_freqs: list[int], seed: int, run_random_controls: bool, ) -> dict: """Exact Prediction 3 causal subspace patching on unseen test triples.""" # 1. Training class means of '=' MLP activations indexed by s = (a+b) mod p _, _, train_mlp = model.forward_with_cache(train_a, train_b) train_s = ((train_a + train_b) % P).numpy() train_mlp_np = train_mlp.numpy() # (N_train, 512) mu = np.zeros((P, D_MLP), dtype=np.float64) for s in range(P): idx = np.where(train_s == s)[0] if len(idx) > 0: mu[s] = train_mlp_np[idx].mean(axis=0) # 2. FFT along s, span real & imag parts of top6_freqs mu_fft = np.fft.fft(mu, axis=0) # (113, 512) complex basis_vecs = [] for k in top6_freqs: basis_vecs.append(mu_fft[k].real) basis_vecs.append(mu_fft[k].imag) M = np.stack(basis_vecs, axis=1) # (512, 12) U, S_vals, _ = np.linalg.svd(M, full_matrices=False) rank = int(np.sum(S_vals > 1e-10 * S_vals[0])) Q = U[:, :rank].astype(np.float32) # (512, rank) # 3. Collect all unseen test triples: (a,b), (a+1,b-1), (a+1,b) all in test triples_a, triples_b = [], [] for a_i in range(P): a1 = (a_i + 1) % P for b_i in range(P): if train_mask_2d[a_i, b_i]: continue bm1 = (b_i - 1) % P if (not train_mask_2d[a1, bm1]) and (not train_mask_2d[a1, b_i]): triples_a.append(a_i) triples_b.append(b_i) ta = torch.tensor(triples_a, dtype=torch.long) tb = torch.tensor(triples_b, dtype=torch.long) ta1 = (ta + 1) % P tbm1 = (tb - 1) % P base_s = (ta + tb) % P target_s1 = (base_s + 1) % P # Forward on base and two donors logits_0, resid_mid_0, h_0 = model.forward_with_cache(ta, tb) _, _, h_same = model.forward_with_cache(ta1, tbm1) _, _, h_shift = model.forward_with_cache(ta1, tb) Q_t = torch.from_numpy(Q) # (512, rank) W_out = model.W_out b_out = model.b_out W_U = model.W_U def run_patch(h_donor: torch.Tensor, Q_mat: torch.Tensor): delta = (h_donor - h_0) @ Q_mat @ Q_mat.T h_patched = h_0 + delta logits_p = (resid_mid_0 + h_patched @ W_out + b_out) @ W_U return logits_p l0_c = logits_0 - logits_0.mean(dim=-1, keepdim=True) logits_same = run_patch(h_same, Q_t) lsame_c = logits_same - logits_same.mean(dim=-1, keepdim=True) D0 = float(torch.linalg.vector_norm(lsame_c - l0_c, dim=-1).mean().item()) same_preserve_acc = float((logits_same.argmax(dim=-1) == base_s).float().mean().item()) logits_shift = run_patch(h_shift, Q_t) lshift_c = logits_shift - logits_shift.mean(dim=-1, keepdim=True) D1 = float(torch.linalg.vector_norm(lshift_c - l0_c, dim=-1).mean().item()) shift_steer_acc = float((logits_shift.argmax(dim=-1) == target_s1).float().mean().item()) base_acc = float((logits_0.argmax(dim=-1) == base_s).float().mean().item()) res = { "n_unseen_triples": int(len(triples_a)), "subspace_rank": rank, "base_triple_acc": base_acc, "D0_same_sum_logit_shift": D0, "D1_shifted_sum_logit_shift": D1, "D0_over_D1": float(D0 / max(1e-12, D1)), "same_sum_preserve_acc": same_preserve_acc, "shifted_sum_steer_to_s_plus_1": shift_steer_acc, } if run_random_controls: rng = np.random.default_rng(70000 + seed) rand_accs = [] for _ in range(20): G = rng.standard_normal((D_MLP, rank)) Qr, _ = np.linalg.qr(G) Qr_t = torch.from_numpy(Qr[:, :rank].astype(np.float32)) logits_r = run_patch(h_shift, Qr_t) rand_accs.append(float((logits_r.argmax(dim=-1) == target_s1).float().mean().item())) res["random_control_20_mean_steer"] = float(np.mean(rand_accs)) res["random_control_20_std_steer"] = float(np.std(rand_accs)) res["random_control_20_max_steer"] = float(np.max(rand_accs)) return res def run_seed(seed: int, threads: int): torch.set_num_threads(threads) t0 = time.time() # Seed controls split & init rng = np.random.default_rng(seed) all_pairs = np.array([(a, b) for a in range(P) for b in range(P)], dtype=np.int64) perm = rng.permutation(len(all_pairs)) n_train = int(round(len(all_pairs) * TRAIN_FRAC)) train_pairs = all_pairs[perm[:n_train]] test_pairs = all_pairs[perm[n_train:]] train_mask_2d = np.zeros((P, P), dtype=bool) train_mask_2d[train_pairs[:, 0], train_pairs[:, 1]] = True train_a = torch.from_numpy(train_pairs[:, 0]) train_b = torch.from_numpy(train_pairs[:, 1]) train_y = (train_a + train_b) % P test_a = torch.from_numpy(test_pairs[:, 0]) test_b = torch.from_numpy(test_pairs[:, 1]) test_y = (test_a + test_b) % P torch.manual_seed(seed) model = ExactNandaTransformer() opt = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=WD, betas=(0.9, 0.98)) history = [] early_ckpt = None late_ckpt = None extra_after_late = 600 # record 600 steps past Late so plot shows crisp plateau for step in range(MAX_STEPS + 1): if step % LOG_EVERY == 0: with torch.no_grad(): tr_logits = model(train_a, train_b) te_logits = model(test_a, test_b) tr_loss = float(F.cross_entropy(tr_logits.double(), train_y).item()) te_loss = float(F.cross_entropy(te_logits.double(), test_y).item()) tr_acc = float((tr_logits.argmax(dim=-1) == train_y).float().mean().item()) te_acc = float((te_logits.argmax(dim=-1) == test_y).float().mean().item()) f_now = fourier_embedding_audit(model.W_E.detach().numpy()) history.append({ "step": step, "train_loss": tr_loss, "test_loss": te_loss, "train_acc": tr_acc, "test_acc": te_acc, "top6_ac_share": f_now["top6_ac_energy_share"], }) if early_ckpt is None and tr_acc == 1.0 and te_acc < 0.05: causal = causal_subspace_audit( model, train_a, train_b, train_mask_2d, f_now["top6_freqs"], seed, run_random_controls=False ) early_ckpt = { "step": step, "train_acc": tr_acc, "test_acc": te_acc, "fourier": f_now, "causal": causal, } print( f"[seed={seed}] EARLY @ step {step}: tr={tr_acc:.4f} te={te_acc:.4f} " f"top6={f_now['top6_ac_energy_share']:.3f} steer={causal['shifted_sum_steer_to_s_plus_1']:.3f} ({time.time()-t0:.1f}s)", flush=True, ) if early_ckpt is not None and late_ckpt is None and step > early_ckpt["step"] and te_acc > 0.99: causal = causal_subspace_audit( model, train_a, train_b, train_mask_2d, f_now["top6_freqs"], seed, run_random_controls=True ) late_ckpt = { "step": step, "train_acc": tr_acc, "test_acc": te_acc, "fourier": f_now, "causal": causal, } print( f"[seed={seed}] LATE @ step {step}: tr={tr_acc:.4f} te={te_acc:.4f} " f"top6={f_now['top6_ac_energy_share']:.3f} D0/D1={causal['D0_over_D1']:.3f} " f"steer={causal['shifted_sum_steer_to_s_plus_1']:.3f} rand={causal['random_control_20_mean_steer']:.3f} ({time.time()-t0:.1f}s)", flush=True, ) if step % 2000 == 0: print( f"[seed={seed}] step={step:5d} tr_acc={tr_acc:.4f} te_acc={te_acc:.4f} " f"top6={f_now['top6_ac_energy_share']:.3f} ({time.time()-t0:.1f}s)", flush=True, ) if late_ckpt is not None and step >= late_ckpt["step"] + extra_after_late: break if step == MAX_STEPS: break logits = model(train_a, train_b) loss = F.cross_entropy(logits.double(), train_y) opt.zero_grad() loss.backward() opt.step() out = { "seed": seed, "p": P, "n_train": n_train, "n_test": len(test_pairs), "elapsed_sec": round(time.time() - t0, 2), "early": early_ckpt, "late": late_ckpt, "history": history, } out_file = RES_DIR / f"grokking_seed_{seed}.json" out_file.write_text(json.dumps(out, indent=2), encoding="utf-8") print(f"[seed={seed}] Saved {out_file} in {time.time()-t0:.1f}s", flush=True) def aggregate(): seed_files = [RES_DIR / f"grokking_seed_{s}.json" for s in range(5)] seeds_data = [json.loads(f.read_text(encoding="utf-8")) for f in seed_files] p2_passes = 0 p3_passes = 0 per_seed_table = [] for d in seeds_data: s = d["seed"] e, l = d["early"], d["late"] if e is None or l is None: per_seed_table.append({"seed": s, "missing_checkpoint": True, "p2_pass": False, "p3_pass": False}) continue e_top6 = e["fourier"]["top6_ac_energy_share"] l_top6 = l["fourier"]["top6_ac_energy_share"] p2_ok = (l_top6 >= 0.75) and ((l_top6 - e_top6) >= 0.20) D0 = l["causal"]["D0_same_sum_logit_shift"] D1 = l["causal"]["D1_shifted_sum_logit_shift"] e_steer = e["causal"]["shifted_sum_steer_to_s_plus_1"] l_steer = l["causal"]["shifted_sum_steer_to_s_plus_1"] r_steer = l["causal"]["random_control_20_mean_steer"] p3_ok = (D0 < D1 / 3.0) and (e_steer < 0.10) and (l_steer > 0.90) and (r_steer < 0.20) p2_passes += int(p2_ok) p3_passes += int(p3_ok) per_seed_table.append({ "seed": s, "early_step": e["step"], "late_step": l["step"], "early_top6": e_top6, "late_top6": l_top6, "delta_top6": l_top6 - e_top6, "late_top6_freqs": l["fourier"]["top6_freqs"], "D0": D0, "D1": D1, "D0_over_D1": D0 / max(1e-12, D1), "early_steer": e_steer, "late_steer": l_steer, "random_control_steer": r_steer, "same_sum_preserve_acc": l["causal"]["same_sum_preserve_acc"], "n_unseen_triples": l["causal"]["n_unseen_triples"], "subspace_rank": l["causal"]["subspace_rank"], "p2_pass": p2_ok, "p3_pass": p3_ok, }) summary = { "per_seed": per_seed_table, "prediction2_pass_count": p2_passes, "prediction2_overall_pass": p2_passes >= 4, "prediction3_pass_count": p3_passes, "prediction3_overall_pass": p3_passes >= 4, } out_path = RES_DIR / "predictions23_grokking_summary.json" out_path.write_text(json.dumps(summary, indent=2), encoding="utf-8") print(json.dumps(summary, indent=2)) # --- Plot Publication-Grade 3-Panel Grokking & Causal Patching Figure --- plt.rcParams.update({ "font.family": "DejaVu Sans", "font.size": 9.2, "axes.spines.top": False, "axes.spines.right": False, "figure.facecolor": "#fafaf7", "axes.facecolor": "#fafaf7", "text.color": "#182d40", "axes.labelcolor": "#182d40", "xtick.color": "#526677", "ytick.color": "#526677", "axes.edgecolor": "#9aa9b2", }) fig = plt.figure(figsize=(12.6, 5.2)) gs = fig.add_gridspec(1, 3, width_ratios=[1.25, 1.0, 1.15], left=0.06, right=0.98, top=0.77, bottom=0.17, wspace=0.30) ax1, ax2, ax3 = [fig.add_subplot(gs[i]) for i in range(3)] fig.text(0.06, 0.94, "Pre-registered Tests 2 & 3: Grokking Phase Transition & Causal Subspace Patching", family="DejaVu Serif", fontsize=15, color="#182d40", va="top") fig.text(0.06, 0.875, "Nanda 1-layer ReLU Transformer · (a + b) mod 113 · 30% train · 5 seeds (0–4) · AdamW wd=1.0", fontsize=9.2, color="#526677", va="top") # Panel a: Grokking learning curves (all 5 seeds, train/test acc + top-6 Fourier share) for d in seeds_data: hist = d["history"] steps = [h["step"] for h in hist] tr = [h["train_acc"] for h in hist] te = [h["test_acc"] for h in hist] f6 = [h["top6_ac_share"] for h in hist] alpha = 0.85 if d["seed"] == 0 else 0.35 lw = 2.0 if d["seed"] == 0 else 1.2 ax1.plot(steps, tr, color="#7f8c9a", ls="--", alpha=alpha * 0.85, lw=lw, label="Train acc" if d["seed"] == 0 else None) ax1.plot(steps, te, color="#245aa5", alpha=alpha, lw=lw, label="Test acc (Grokking)" if d["seed"] == 0 else None) ax1.plot(steps, f6, color="#007c76", alpha=alpha, lw=lw, label="Top-6 Fourier AC energy" if d["seed"] == 0 else None) ax1.axhline(0.75, color="#007c76", ls=":", lw=0.9, alpha=0.7) ax1.set_xlabel("Optimization step") ax1.set_ylabel("Accuracy / Energy share") ax1.set_ylim(-0.03, 1.05) ax1.set_title("a Memorization → Fourier circuit", loc="left", fontweight="bold", fontsize=10.3, pad=10) ax1.grid(axis="y", color="#8395a5", alpha=0.22, lw=0.6) ax1.legend(loc="center right", frameon=False, fontsize=8.3) # Panel b: Seed 0 Fourier spectrum Early vs Late d0 = seeds_data[0] if d0["early"] and d0["late"]: ks = np.arange(1, (P - 1) // 2 + 1) p_e = np.array(d0["early"]["fourier"]["pair_power_normalized"]) p_l = np.array(d0["late"]["fourier"]["pair_power_normalized"]) ax2.bar(ks, p_l, width=0.85, color="#007c76", alpha=0.88, label=f"Late (step {d0['late']['step']})") ax2.plot(ks, p_e, color="#ae482c", lw=1.3, alpha=0.85, label=f"Early (step {d0['early']['step']})") ax2.set_ylim(0, max(float(p_l.max()) * 1.25, 0.18)) ax2.set_xlabel("Conjugate frequency pair k") ax2.set_ylabel("Normalized AC energy") ax2.set_title("b Embedding DFT spectrum (seed 0)", loc="left", fontweight="bold", fontsize=10.3, pad=10) ax2.grid(axis="y", color="#8395a5", alpha=0.22, lw=0.6) ax2.legend(loc="upper center", frameon=False, fontsize=8.2) # Panel c: Causal Subspace Patching across all 5 seeds valid_rows = [r for r in per_seed_table if not r.get("missing_checkpoint")] if valid_rows: labels = ["Early\n(s+1 steer)", "Late\n(s+1 steer)", "Late\n(rand ctrl)", "Late\n(D0/D1 ratio)"] vals_lists = [ [r["early_steer"] for r in valid_rows], [r["late_steer"] for r in valid_rows], [r["random_control_steer"] for r in valid_rows], [r["D0_over_D1"] for r in valid_rows], ] cols = ["#ae482c", "#245aa5", "#7f8c9a", "#007c76"] means = [float(np.mean(v)) for v in vals_lists] xs = np.arange(len(labels)) ax3.bar(xs, means, width=0.52, color=cols, alpha=0.82) for i, vlist in enumerate(vals_lists): jitter = np.linspace(-0.12, 0.12, len(vlist)) ax3.scatter(xs[i] + jitter, vlist, color="#182d40", s=18, zorder=5) top_y = max(means[i], max(vlist)) ax3.text(xs[i], top_y + 0.035, f"μ={means[i]:.3f}", ha="center", va="bottom", fontsize=8.3, fontweight="bold") ax3.axhline(0.90, color="#245aa5", ls=":", lw=0.9, alpha=0.7) ax3.axhline(1 / 3, color="#007c76", ls="-.", lw=0.9, alpha=0.7) ax3.axhline(0.20, color="#7f8c9a", ls="--", lw=0.8, alpha=0.7) ax3.set_xticks(xs) ax3.set_xticklabels(labels, fontsize=8.2) ax3.set_ylim(0, 1.15) ax3.set_ylabel("Rate / Ratio") ax3.set_title("c Causal patching (all 5 seeds)", loc="left", fontweight="bold", fontsize=10.3, pad=10) ax3.grid(axis="y", color="#8395a5", alpha=0.22, lw=0.6) fig.savefig(FIG_DIR / "fig2_predictions23_grokking_causal.png", dpi=300) plt.close(fig) print(f"Saved figure to {FIG_DIR / 'fig2_predictions23_grokking_causal.png'}") def main(): parser = argparse.ArgumentParser() parser.add_argument("--seed", type=int, default=None) parser.add_argument("--threads", type=int, default=3) parser.add_argument("--aggregate", action="store_true") args = parser.parse_args() if args.aggregate: aggregate() elif args.seed is not None: run_seed(args.seed, args.threads) else: for s in range(5): run_seed(s, args.threads) aggregate() if __name__ == "__main__": main()