#!/usr/bin/env python3 """ PART 3 (CPU ONLY): Statistical Analysis ========================================== Loads raw alpha values from GPU pass. Computes bootstrap CIs, TOST equivalence, Cohen's d. No GPU needed. """ import json from pathlib import Path import numpy as np from scipy import stats as sp from google.colab import drive drive.mount("/content/drive", force_remount=False) OUT = Path("/content/drive/MyDrive/topohd_scaled_gib") print("=" * 65) print("PART 3: Statistical Analysis (CPU only)") print("=" * 65) # Load results CHECKPOINT = OUT / "gpu_checkpoint.json" assert CHECKPOINT.exists(), "Run Part 2 (GPU) first" with open(CHECKPOINT) as f: results = json.load(f) TARGET_LAYERS = [8, 16, 24, 32] # Extract methods methods = set() for key in results: if key.startswith("_"): continue parts = key.split("|") if len(parts) == 3: methods.add(parts[1]) methods.discard("random") methods = sorted(methods) print(f" Methods: {methods}") for pt in ["visual", "factual", "math", "gibberish"]: n = results.get(f"_progress_{pt}", 0) print(f" {pt}: {n} prompts") # ---- Compute per-method ratios ---- def get_ratios(pt, mname): """Get alpha/random ratios for a prompt type and method.""" ratios = [] for l in TARGET_LAYERS: vals = results.get(f"{pt}|{mname}|{l}", []) rnds = results.get(f"{pt}|random|{l}", []) if vals and rnds: n = min(len(vals), len(rnds)) for v, r in zip(vals[:n], rnds[:n]): ratios.append(v / (r + 1e-8)) return np.array(ratios) # ---- Bootstrap CI ---- def bootstrap_ci(data, n_boot=10000, ci=0.95): data = np.array(data) if len(data) < 5: return (0, 0, 0) boot_means = [np.mean(np.random.choice(data, len(data), replace=True)) for _ in range(n_boot)] lo = np.percentile(boot_means, (1-ci)/2 * 100) hi = np.percentile(boot_means, (1+ci)/2 * 100) return float(lo), float(np.mean(data)), float(hi) # ---- TOST equivalence test ---- def tost_test(x, y, delta=0.2): """Test if mean(x)/mean(y) is within [1-delta, 1+delta].""" n = min(len(x), len(y)) if n < 10: return (0, 1.0) ratios = x[:n] / (y[:n] + 1e-8) # Lower test: H0: ratio <= 1-delta t_lo, p_lo = sp.ttest_1samp(ratios, 1 - delta) # Upper test: H0: ratio >= 1+delta t_hi, p_hi = sp.ttest_1samp(ratios, 1 + delta) p_tost = max(p_lo/2 if t_lo > 0 else 1.0, p_hi/2 if t_hi < 0 else 1.0) return float(np.mean(ratios)), float(p_tost) # ---- Cohen's d ---- def cohens_d(x, y): if len(x) < 5 or len(y) < 5: return 0 nx, ny = len(x), len(y) sp_val = np.sqrt(((nx-1)*np.var(x, ddof=1) + (ny-1)*np.var(y, ddof=1)) / (nx+ny-2)) return float((np.mean(x) - np.mean(y)) / (sp_val + 1e-8)) # ---- Mann-Whitney U ---- def mannwhitney(x, y): if len(x) < 5 or len(y) < 5: return 1.0 _, p = sp.mannwhitneyu(x, y, alternative='two-sided') return float(p) # ================================================================ # RESULTS TABLE # ================================================================ print(f"\n{'='*80}") print("RESULTS: Scaled Gibberish Test (1000 prompts per type)") print(f"{'='*80}") print(f"\n {'Method':<20} {'Visual':>8} {'Gibber':>8} {'Gib/Vis':>8} " f"{'95% CI':>16} {'TOST p':>8} {'MW p':>8} {'d':>6} {'N':>6}") print(f" {'-'*90}") summary = {} for mname in methods: vis = get_ratios("visual", mname) gib = get_ratios("gibberish", mname) fac = get_ratios("factual", mname) mth = get_ratios("math", mname) if len(vis) < 10 or len(gib) < 10: print(f" {mname:<20} insufficient data (vis={len(vis)}, gib={len(gib)})") continue mv = np.mean(vis) mg = np.mean(gib) gv = mg / (mv + 1e-8) # Bootstrap CI on Gib/Vis ratio n = min(len(vis), len(gib)) gv_samples = gib[:n] / (vis[:n] + 1e-8) ci_lo, ci_mean, ci_hi = bootstrap_ci(gv_samples) # TOST equivalence (delta=0.2: is Gib/Vis within 0.8-1.2?) _, p_tost = tost_test(gib[:n], vis[:n], delta=0.2) # Mann-Whitney (are distributions different?) p_mw = mannwhitney(vis, gib) # Cohen's d d = cohens_d(vis, gib) sig_tost = "***" if p_tost < 0.001 else "**" if p_tost < 0.01 else "*" if p_tost < 0.05 else "" sig_mw = "†" if p_mw < 0.05 else "" summary[mname] = dict( visual=float(mv), gibberish=float(mg), factual=float(np.mean(fac)), math=float(np.mean(mth)), gv_ratio=float(gv), ci_lo=ci_lo, ci_hi=ci_hi, tost_p=float(p_tost), mw_p=float(p_mw), cohens_d=float(d), n_vis=len(vis), n_gib=len(gib)) print(f" {mname:<20} {mv:>7.2f}x {mg:>7.2f}x {gv:>7.2f} " f"[{ci_lo:.2f},{ci_hi:.2f}] " f"{p_tost:>7.4f}{sig_tost} {p_mw:>7.4f}{sig_mw} {d:>5.3f} {n:>5}") # ================================================================ # INTERPRETATION # ================================================================ print(f"\n{'='*80}") print("INTERPRETATION") print(f"{'='*80}") print(f"\n TOST p < 0.05: Gibberish ≈ Visual CONFIRMED within ±0.2 margin") print(f" MW p > 0.05: Distributions NOT significantly different") print(f" |d| < 0.2: Negligible effect size (Cohen)") print(f" |d| < 0.5: Small effect size") n_equiv = sum(1 for s in summary.values() if s["tost_p"] < 0.05) n_nosig = sum(1 for s in summary.values() if s["mw_p"] > 0.05) n_negl = sum(1 for s in summary.values() if abs(s["cohens_d"]) < 0.2) print(f"\n TOST equivalence (p<0.05): {n_equiv}/{len(summary)} methods") print(f" MW not significant (p>0.05): {n_nosig}/{len(summary)} methods") print(f" Negligible effect (|d|<0.2): {n_negl}/{len(summary)} methods") if n_equiv == len(summary): print(f"\n >>> ALL METHODS: Gibberish ≡ Visual (TOST confirmed) <<<") print(f" With N=1000 prompts, the equivalence is statistically airtight.") elif n_equiv > len(summary) * 0.8: print(f"\n >>> MOST METHODS: Gibberish ≡ Visual <<<") else: print(f"\n >>> MIXED: Some methods show small differences <<<") # ---- Per-type breakdown ---- print(f"\n Per-type mean ratio (averaged across methods):") for pt in ["visual", "factual", "math", "gibberish"]: vals = [] for mname in methods: r = get_ratios(pt, mname) if len(r) > 0: vals.append(np.mean(r)) if vals: print(f" {pt:<12}: {np.mean(vals):.2f}x ± {np.std(vals):.2f}") # Save with open(OUT / "statistical_summary.json", "w") as f: json.dump(summary, f, indent=2) print(f"\n Saved to {OUT}/statistical_summary.json")