#!/usr/bin/env python3 # ============================================================================= # Project : modelmap # File : experiments/micro/expC_causal_verification/implementation/benchmark_v4.py # Purpose : Run #4 — the narrowed early-band claim, everything fresh # Author : Simon-Pierre Boucher # Contact : contact@spboucher.ai # Website : https://modelmap.io # Created : 2026-08-12 # Modified : 2026-08-12 # Platform : macOS / Apple Silicon (arm64) — MLX / Metal # License : All rights reserved (research code) # ============================================================================= """expC run #4 (hypothesis registered before this run). Band claim: early-band (layers 2-15) mean specific damage >= 2.5 in EVERY of six fresh direction sources (disjoint halves of A and B + two fresh bootstraps), on a fresh behavioral bank. Late band reported, no claim. """ from __future__ import annotations import json import random import subprocess import sys import time from pathlib import Path import numpy as np ROOT = Path(__file__).resolve().parents[4] sys.path.insert(0, str(ROOT / "src")) sys.path.insert(0, str(ROOT / "benchmarks")) from hardware_manifest import manifest from modelmap.capture.mlx_capture import capture_pooled, install_taps MODEL = "mlx-community/Qwen3-0.6B-4bit" N_RANDOM_DIRS = 3 SEED = 780 EARLY = slice(2, 16) LATE = slice(20, 28) BAR = 2.5 NOUN_PAIRS = [("key", "keys"), ("crate", "crates"), ("report", "reports"), ("valve", "valves"), ("ticket", "tickets"), ("ladder", "ladders"), ("sample", "samples"), ("cable", "cables"), ("permit", "permits"), ("beacon", "beacons"), ("filter", "filters"), ("stamp", "stamps")] FRESH_NEAR = ["past the boiler room", "near the loading dock", "behind the ticket booth", "under the mezzanine", "beside the flagpole", "opposite the greenhouse", "inside the stairwell", "along the towpath"] def directions_from(reps, labels, idx): dirs, mus = [], [] r, l = reps[idx], labels[idx] for layer in range(reps.shape[1]): x = r[:, layer, :] mu = x.mean(0) u = x[l == "correct"].mean(0) - x[l == "violated"].mean(0) u = u / (np.linalg.norm(u) + 1e-8) dirs.append(u); mus.append(mu) return dirs, mus def main() -> int: import mlx.core as mx from mlx_lm import load t0 = time.time() model, tokenizer = load(MODEL) taps = install_taps(model) n_layers = len(taps) rng = random.Random(SEED) combos = [(n, loc) for n in NOUN_PAIRS for loc in FRESH_NEAR] rng.shuffle(combos) pairs = [] for (sg, pl), loc in combos: pairs.append({"prefix": f"The {sg} {loc}", "singular": True}) pairs.append({"prefix": f"The {pl} {loc}", "singular": False}) prefix_ids = [tokenizer.encode(p["prefix"]) for p in pairs] id_is, id_are = tokenizer.encode(" is")[0], tokenizer.encode(" are")[0] def margin() -> float: out = [] for ids, p in zip(prefix_ids, pairs): logits = model(mx.array([ids]))[0, -1, :] mx.eval(logits) m = float(logits[id_is] - logits[id_are]) out.append(m if p["singular"] else -m) return float(np.mean(out)) def erase_fn(u_np, mu_np): u = mx.array(u_np.astype(np.float32)) mu = mx.array(mu_np.astype(np.float32)) def fn(out): h = out.astype(mx.float32) coef = ((h - mu) * u).sum(axis=-1, keepdims=True) return (h - coef * u).astype(out.dtype) return fn base_m = margin() print(f"fresh bank: {len(pairs)} pairs | baseline margin {base_m:+.4f}", flush=True) # fresh direction sources: disjoint halves + fresh bootstraps reps_cache = {} for s in ("A", "B"): items = [json.loads(l) for l in (ROOT / "benchmarks" / "promptsets" / f"agreement_{s}.jsonl").read_text().splitlines()] toks = [tokenizer.encode(it["text"]) for it in items] labels = np.array([it["label"] for it in items]) print(f"capture agreement_{s}…", flush=True) reps_cache[s] = (capture_pooled(model, taps, toks)["mean"], labels) sources = {} for s in ("A", "B"): reps, labels = reps_cache[s] n = len(labels) perm = np.random.default_rng(SEED + ord(s)).permutation(n) sources[f"{s}half1"] = directions_from(reps, labels, perm[: n // 2]) sources[f"{s}half2"] = directions_from(reps, labels, perm[n // 2:]) boot = np.random.default_rng(200 + ord(s)).integers(0, n, n) sources[f"boot{s}"] = directions_from(reps, labels, boot) del sources["bootB"] # keep 6 by hypothesis? A/B halves (4) + bootA + bootB = 6 — keep both sources["bootB"] = directions_from(reps_cache["B"][0], reps_cache["B"][1], np.random.default_rng(202).integers(0, len(reps_cache["B"][1]), len(reps_cache["B"][1]))) rand_damage = [] d_model = reps_cache["A"][0].shape[-1] for layer in range(n_layers): ms = [] for s in range(N_RANDOM_DIRS): ru = np.random.default_rng(2000 * layer + s).standard_normal(d_model) ru /= np.linalg.norm(ru) taps[layer].edit = erase_fn(ru.astype(np.float32), sources["Ahalf1"][1][layer]) ms.append(margin()) taps[layer].edit = None rand_damage.append(base_m - float(np.mean(ms))) print("random-direction controls done", flush=True) profiles, bands = {}, {} for name, (dirs, mus) in sources.items(): prof = [] for layer in range(n_layers): taps[layer].edit = erase_fn(dirs[layer], mus[layer]) m = margin() taps[layer].edit = None prof.append((base_m - m) - rand_damage[layer]) profiles[name] = prof bands[name] = {"early_mean": float(np.mean(prof[EARLY])), "late_mean": float(np.mean(prof[LATE]))} print(f"{name:8s} early={bands[name]['early_mean']:+.3f} late={bands[name]['late_mean']:+.3f}", flush=True) early_means = [bands[n]["early_mean"] for n in sources] passes = bool(all(e >= BAR for e in early_means)) print(f"BAND CLAIM (early mean >= {BAR} in every source): " f"min={min(early_means):+.3f} -> passes={passes}") arr = np.array(list(profiles.values())) commit = subprocess.run(["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True, check=False).stdout.strip() ts = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()) outdir = ROOT / "results" / "expC_causal_verification" / ts outdir.mkdir(parents=True) (outdir / "results.json").write_text(json.dumps({ "experiment": "expC_causal_verification", "run": 4, "scope": "narrowed early-band claim, fresh sources + fresh behavioral bank", "commit": commit, "config": {"model": MODEL, "sources": list(sources), "bar": BAR, "early_layers": [2, 15], "late_layers": [20, 27], "n_random_dirs": N_RANDOM_DIRS, "n_pairs": len(pairs), "seed": SEED}, "manifest": manifest(), "baseline_margin": base_m, "random_direction_damage": rand_damage, "profiles": profiles, "bands": bands, "profile_mean": arr.mean(axis=0).tolist(), "profile_min": arr.min(axis=0).tolist(), "band_claim": {"bar": BAR, "early_means": early_means, "min_early_mean": float(min(early_means)), "passes": passes}, "wall_seconds": round(time.time() - t0, 1), }, indent=2) + "\n") print(f"results -> {outdir / 'results.json'}") return 0 if __name__ == "__main__": sys.exit(main())