#!/usr/bin/env python3 # ============================================================================= # Project : modelmap # File : experiments/micro/expC_causal_verification/implementation/benchmark_v5.py # Purpose : Run #5 — Level-3 path: dose-response steering of the direction # 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 #5 (hypothesis registered before this run). Activation-addition steering of the diff-of-means agreement direction at three early-band layers, doses alpha in {-2,-1,0,+1,+2} x sigma_l; strict monotonicity + halving criterion + random-direction specificity control. """ 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" TEST_LAYERS = (4, 8, 12) DOSES = (-2.0, -1.0, 0.0, 1.0, 2.0) N_RANDOM_DIRS = 3 SEED = 781 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 main() -> int: import mlx.core as mx from mlx_lm import load t0 = time.time() model, tokenizer = load(MODEL) taps = install_taps(model) 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)) # direction + per-layer projection std from agreement_A (the v1 object) items = [json.loads(l) for l in (ROOT / "benchmarks" / "promptsets" / "agreement_A.jsonl").read_text().splitlines()] toks = [tokenizer.encode(it["text"]) for it in items] labels = np.array([it["label"] for it in items]) print("capture agreement_A (direction + sigma)…", flush=True) reps = capture_pooled(model, taps, toks)["mean"] dirs, sigmas = {}, {} for layer in TEST_LAYERS: x = reps[:, layer, :] u = x[labels == "correct"].mean(0) - x[labels == "violated"].mean(0) u = u / (np.linalg.norm(u) + 1e-8) dirs[layer] = u sigmas[layer] = float((x @ u).std()) def add_fn(u_np, delta): d = mx.array((u_np * delta).astype(np.float32)) def fn(out): return (out.astype(mx.float32) + d).astype(out.dtype) return fn base_m = margin() print(f"baseline margin {base_m:+.4f} | pairs {len(pairs)}", flush=True) results = {"per_layer": {}, "baseline_margin": base_m} mono_ok, halve_ok, spec_ok = True, True, True for layer in TEST_LAYERS: dose_margins = {} for a in DOSES: if a == 0.0: dose_margins[a] = base_m continue taps[layer].edit = add_fn(dirs[layer], a * sigmas[layer]) dose_margins[a] = margin() taps[layer].edit = None seq = [dose_margins[a] for a in DOSES] mono = all(seq[i] < seq[i + 1] for i in range(len(seq) - 1)) halve = dose_margins[-2.0] <= 0.5 * base_m rand_changes = [] for s in range(N_RANDOM_DIRS): ru = np.random.default_rng(3000 * layer + s).standard_normal(reps.shape[-1]) ru /= np.linalg.norm(ru) for a in (-2.0, 2.0): taps[layer].edit = add_fn(ru.astype(np.float32), a * sigmas[layer]) rand_changes.append(abs(margin() - base_m)) taps[layer].edit = None spec = float(np.mean(rand_changes)) < 0.25 * base_m mono_ok &= mono; halve_ok &= halve; spec_ok &= spec results["per_layer"][layer] = { "sigma": sigmas[layer], "dose_margins": {str(a): dose_margins[a] for a in DOSES}, "monotone": mono, "halved_at_minus2": halve, "random_dir_mean_abs_change": float(np.mean(rand_changes)), "specific": spec, } print(f"L{layer:02d} doses " + " ".join(f"{a:+.0f}σ:{dose_margins[a]:+.2f}" for a in DOSES) + f" | mono={mono} halve={halve} randΔ={np.mean(rand_changes):.2f} spec={spec}", flush=True) passes = bool(mono_ok and halve_ok and spec_ok) print(f"LEVEL-3 CRITERION: monotone={mono_ok} halved={halve_ok} specific={spec_ok} " f"-> passes={passes}") 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": 5, "scope": "dose-response steering (Level-3 path) at early-band layers", "commit": commit, "config": {"model": MODEL, "test_layers": list(TEST_LAYERS), "doses": list(DOSES), "n_random_dirs": N_RANDOM_DIRS, "n_pairs": len(pairs), "seed": SEED}, "manifest": manifest(), "results": results, "criterion": {"monotone_all": mono_ok, "halved_all": halve_ok, "specific_all": spec_ok, "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())