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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
eval_help_shatter.py — the REAL eMoE metric (current-state §10.5 step 3).
|
| 3 |
+
|
| 4 |
+
VAL 2.0889 says the hypernetwork GENERALIZES (held-out loss is low). It does NOT
|
| 5 |
+
say whether a minted adapter HELPS or SHATTERS on a novel request. This script
|
| 6 |
+
answers that, per task, by comparing — on the EXACT VAL loss construction
|
| 7 |
+
(train_hyper_sft.make_batch, output-only masking, ignore_index=-1) — the loss of
|
| 8 |
+
the gold output under:
|
| 9 |
+
|
| 10 |
+
(a) the RIGHT-z minted adapter (hyper(z_task) -> set_deltas)
|
| 11 |
+
(b) the bare frozen base (set_deltas(None)) [z-independent]
|
| 12 |
+
(c) OPTIONAL a WRONG-z adapter (a neighbor task's z) [conditioning check]
|
| 13 |
+
|
| 14 |
+
delta_help = loss_base - loss_adapt ( > 0 => adapter HELPS )
|
| 15 |
+
( < 0 => adapter SHATTERS )
|
| 16 |
+
|
| 17 |
+
It then buckets every (task, variant) point by its nearest-TRAIN-cluster cosine
|
| 18 |
+
distance — the SAME geometry the controller uses — and asks the question the
|
| 19 |
+
migration plan poses: *does the banked distance threshold separate help from
|
| 20 |
+
shatter?* Reported honestly. Per design (current-state §3) distance is NOVELTY,
|
| 21 |
+
not TRUST — shatter is meant to be CAUGHT by the verifier, not PREDICTED by
|
| 22 |
+
distance — so weak separation here is the expected, on-philosophy outcome, and
|
| 23 |
+
strong separation would be a (welcome) bonus, not a load-bearing assumption.
|
| 24 |
+
|
| 25 |
+
WHY (task, variant) GRANULARITY: at serve time a single descriptor is encoded to
|
| 26 |
+
ONE z (the noisier "C" regime the taus were banked from). Each cached variant is
|
| 27 |
+
one such z, so per-(task,variant) is the serve-faithful unit. Per-task headline
|
| 28 |
+
numbers average over a task's variants.
|
| 29 |
+
|
| 30 |
+
RUN (on the pod, with the v12 artifacts):
|
| 31 |
+
python eval_help_shatter.py \
|
| 32 |
+
--base_ckpt ckpt_v12_190m_best.pt \
|
| 33 |
+
--hyper_ckpt hyper_ckpt_v12.best.pt \
|
| 34 |
+
--z_cache runs/hyper_v1/z_cache.pt \
|
| 35 |
+
--tasks data/hyper_v1.jsonl \
|
| 36 |
+
--val_frac 0.15 --seed 0 \
|
| 37 |
+
--tau_rag_on 0.287 --tau_k_escalate 0.308 \
|
| 38 |
+
--val_anchor 2.0889 \
|
| 39 |
+
--wrong_z --out runs/hyper_v1/help_shatter.jsonl
|
| 40 |
+
|
| 41 |
+
Logic-only self-test (no torch / no artifacts): python eval_help_shatter.py --self_test
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
from __future__ import annotations
|
| 45 |
+
|
| 46 |
+
import argparse
|
| 47 |
+
import json
|
| 48 |
+
import math
|
| 49 |
+
import os
|
| 50 |
+
import sys
|
| 51 |
+
from statistics import mean, median
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# ---------------------------------------------------------------------------
|
| 55 |
+
# Pure-python aggregation / separation logic (self-testable without torch)
|
| 56 |
+
# ---------------------------------------------------------------------------
|
| 57 |
+
|
| 58 |
+
def _auc(scores: list[float], labels: list[int]) -> float:
|
| 59 |
+
"""AUC of `score` predicting label==1, via the rank-sum identity. 0.5 = no
|
| 60 |
+
signal. Used to ask: does nearest-cluster DISTANCE predict SHATTER?"""
|
| 61 |
+
pos = [s for s, y in zip(scores, labels) if y == 1]
|
| 62 |
+
neg = [s for s, y in zip(scores, labels) if y == 0]
|
| 63 |
+
if not pos or not neg:
|
| 64 |
+
return float("nan")
|
| 65 |
+
order = sorted(range(len(scores)), key=lambda i: scores[i])
|
| 66 |
+
ranks = [0.0] * len(scores)
|
| 67 |
+
i = 0
|
| 68 |
+
while i < len(order): # average ranks within ties
|
| 69 |
+
j = i
|
| 70 |
+
while j < len(order) and scores[order[j]] == scores[order[i]]:
|
| 71 |
+
j += 1
|
| 72 |
+
avg = (i + j - 1) / 2.0 + 1.0
|
| 73 |
+
for k in range(i, j):
|
| 74 |
+
ranks[order[k]] = avg
|
| 75 |
+
i = j
|
| 76 |
+
rank_sum_pos = sum(ranks[i] for i in range(len(scores)) if labels[i] == 1)
|
| 77 |
+
n_pos, n_neg = len(pos), len(neg)
|
| 78 |
+
return (rank_sum_pos - n_pos * (n_pos + 1) / 2.0) / (n_pos * n_neg)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _bucket(d: float, tau_rag: float, tau_k: float) -> str:
|
| 82 |
+
if d < tau_rag:
|
| 83 |
+
return "in_dist" # below tau_rag_on: controller trusts the mint, RAG off, k=1
|
| 84 |
+
if d < tau_k:
|
| 85 |
+
return "mid" # RAG fires, still k=1
|
| 86 |
+
return "ood" # >= tau_k_escalate: RAG + escalation
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def summarize(records: list[dict], *, tau_rag: float, tau_k: float,
|
| 90 |
+
shatter_eps: float, val_anchor: float | None) -> dict:
|
| 91 |
+
"""records: per-(task,variant) dicts with keys
|
| 92 |
+
task_id, variant, loss_base, loss_adapt, delta, dist."""
|
| 93 |
+
n = len(records)
|
| 94 |
+
deltas = [r["delta"] for r in records]
|
| 95 |
+
helps = [1 if d > 0 else 0 for r, d in zip(records, deltas)]
|
| 96 |
+
shatters = [1 if d < -shatter_eps else 0 for d in deltas]
|
| 97 |
+
|
| 98 |
+
# per-task headline (mean delta over a task's variants)
|
| 99 |
+
by_task: dict[str, list[float]] = {}
|
| 100 |
+
base_by_task: dict[str, float] = {}
|
| 101 |
+
for r in records:
|
| 102 |
+
by_task.setdefault(r["task_id"], []).append(r["delta"])
|
| 103 |
+
base_by_task[r["task_id"]] = r["loss_base"]
|
| 104 |
+
task_delta = {t: mean(v) for t, v in by_task.items()}
|
| 105 |
+
task_help = sum(1 for v in task_delta.values() if v > 0)
|
| 106 |
+
task_shatter = sum(1 for v in task_delta.values() if v < -shatter_eps)
|
| 107 |
+
n_tasks = len(task_delta)
|
| 108 |
+
|
| 109 |
+
out = {
|
| 110 |
+
"n_points": n,
|
| 111 |
+
"n_tasks": n_tasks,
|
| 112 |
+
"mean_loss_base": mean(r["loss_base"] for r in records),
|
| 113 |
+
"mean_loss_adapt": mean(r["loss_adapt"] for r in records),
|
| 114 |
+
"mean_delta": mean(deltas),
|
| 115 |
+
"median_delta": median(deltas),
|
| 116 |
+
"help_rate_points": sum(helps) / n if n else float("nan"),
|
| 117 |
+
"shatter_rate_points": sum(shatters) / n if n else float("nan"),
|
| 118 |
+
"help_rate_tasks": task_help / n_tasks if n_tasks else float("nan"),
|
| 119 |
+
"shatter_rate_tasks": task_shatter / n_tasks if n_tasks else float("nan"),
|
| 120 |
+
"shatter_eps": shatter_eps,
|
| 121 |
+
}
|
| 122 |
+
if val_anchor is not None:
|
| 123 |
+
out["val_anchor"] = val_anchor
|
| 124 |
+
out["adapt_vs_anchor"] = out["mean_loss_adapt"] - val_anchor
|
| 125 |
+
|
| 126 |
+
# by-distance buckets
|
| 127 |
+
buckets: dict[str, list[dict]] = {"in_dist": [], "mid": [], "ood": []}
|
| 128 |
+
for r in records:
|
| 129 |
+
buckets[_bucket(r["dist"], tau_rag, tau_k)].append(r)
|
| 130 |
+
out["by_bucket"] = {}
|
| 131 |
+
for name, rs in buckets.items():
|
| 132 |
+
if not rs:
|
| 133 |
+
out["by_bucket"][name] = {"n": 0}
|
| 134 |
+
continue
|
| 135 |
+
ds = [r["delta"] for r in rs]
|
| 136 |
+
out["by_bucket"][name] = {
|
| 137 |
+
"n": len(rs),
|
| 138 |
+
"mean_delta": mean(ds),
|
| 139 |
+
"help_rate": sum(1 for d in ds if d > 0) / len(ds),
|
| 140 |
+
"shatter_rate": sum(1 for d in ds if d < -shatter_eps) / len(ds),
|
| 141 |
+
"mean_dist": mean(r["dist"] for r in rs),
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
# THE migration question: does distance predict shatter?
|
| 145 |
+
dist_all = [r["dist"] for r in records]
|
| 146 |
+
out["dist_predicts_shatter_auc"] = _auc(dist_all, shatters)
|
| 147 |
+
sh_d = [r["dist"] for r, s in zip(records, shatters) if s]
|
| 148 |
+
hp_d = [r["dist"] for r, s in zip(records, shatters) if not s]
|
| 149 |
+
out["mean_dist_shatter"] = mean(sh_d) if sh_d else float("nan")
|
| 150 |
+
out["mean_dist_nonshatter"] = mean(hp_d) if hp_d else float("nan")
|
| 151 |
+
return out
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def print_report(s: dict, *, tau_rag: float, tau_k: float) -> None:
|
| 155 |
+
p = lambda *a: print(*a)
|
| 156 |
+
p("\n" + "=" * 70)
|
| 157 |
+
p("HELP vs SHATTER — right-z adapted loss vs bare base (VAL construction)")
|
| 158 |
+
p("=" * 70)
|
| 159 |
+
p(f"points (task,variant): {s['n_points']} tasks: {s['n_tasks']}")
|
| 160 |
+
p(f"mean loss base={s['mean_loss_base']:.4f} adapt={s['mean_loss_adapt']:.4f}"
|
| 161 |
+
f" (delta {s['mean_delta']:+.4f}, median {s['median_delta']:+.4f})")
|
| 162 |
+
if "val_anchor" in s:
|
| 163 |
+
flag = " <-- WARN: >0.3 off, config may differ from the trained run" \
|
| 164 |
+
if abs(s["adapt_vs_anchor"]) > 0.30 else ""
|
| 165 |
+
p(f"anchor: VAL floor {s['val_anchor']:.4f}; mean adapt is "
|
| 166 |
+
f"{s['adapt_vs_anchor']:+.4f} vs floor{flag}")
|
| 167 |
+
p(f"\nHELP rate tasks={s['help_rate_tasks']*100:5.1f}% "
|
| 168 |
+
f"points={s['help_rate_points']*100:5.1f}% (delta > 0)")
|
| 169 |
+
p(f"SHATTER rate tasks={s['shatter_rate_tasks']*100:5.1f}% "
|
| 170 |
+
f"points={s['shatter_rate_points']*100:5.1f}% (delta < -{s['shatter_eps']})")
|
| 171 |
+
if "conditioning_win_rate" in s:
|
| 172 |
+
p(f"\nCONDITIONING (right-z beats wrong-z): "
|
| 173 |
+
f"{s['conditioning_win_rate']*100:5.1f}% of tasks "
|
| 174 |
+
f"(mean gap {s['conditioning_mean_gap']:+.4f} nats)")
|
| 175 |
+
p(f"\nby nearest-cluster distance bucket "
|
| 176 |
+
f"(in<{tau_rag} | mid<{tau_k} | ood>={tau_k}):")
|
| 177 |
+
p(f" {'bucket':<9}{'n':>6}{'mean_d':>9}{'help%':>8}{'shatter%':>10}{'mean_delta':>12}")
|
| 178 |
+
for name in ("in_dist", "mid", "ood"):
|
| 179 |
+
b = s["by_bucket"][name]
|
| 180 |
+
if b["n"] == 0:
|
| 181 |
+
p(f" {name:<9}{0:>6}{'—':>9}{'—':>8}{'—':>10}{'—':>12}")
|
| 182 |
+
continue
|
| 183 |
+
p(f" {name:<9}{b['n']:>6}{b['mean_dist']:>9.3f}"
|
| 184 |
+
f"{b['help_rate']*100:>7.1f}%{b['shatter_rate']*100:>9.1f}%"
|
| 185 |
+
f"{b['mean_delta']:>+12.4f}")
|
| 186 |
+
auc = s["dist_predicts_shatter_auc"]
|
| 187 |
+
p(f"\nDOES DISTANCE PREDICT SHATTER? AUC = {auc:.3f} "
|
| 188 |
+
f"(0.5 = no signal; mean dist shatter={s['mean_dist_shatter']:.3f} "
|
| 189 |
+
f"vs non-shatter={s['mean_dist_nonshatter']:.3f})")
|
| 190 |
+
if not math.isnan(auc):
|
| 191 |
+
if auc < 0.60:
|
| 192 |
+
p(" -> WEAK/NONE. Consistent with the design: distance is novelty, not")
|
| 193 |
+
p(" trust. Shatter must be CAUGHT by the verifier, not gated on distance.")
|
| 194 |
+
p(" The banked taus stay justified as RAG/k (novelty) knobs, NOT as a")
|
| 195 |
+
p(" shatter gate. Do NOT re-couple distance->alpha on this.")
|
| 196 |
+
else:
|
| 197 |
+
p(" -> Some separation. A BONUS signal, but per current-state §3 it enters")
|
| 198 |
+
p(" as a NEW knob only after replication; it does not silently gate alpha.")
|
| 199 |
+
p("=" * 70 + "\n")
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ---------------------------------------------------------------------------
|
| 203 |
+
# Heavy path — runs on the pod with torch + the real artifacts
|
| 204 |
+
# ---------------------------------------------------------------------------
|
| 205 |
+
|
| 206 |
+
def run_eval(args) -> None:
|
| 207 |
+
import numpy as np
|
| 208 |
+
import torch
|
| 209 |
+
import tok_v9
|
| 210 |
+
from train_hyper_sft import make_batch, load_tasks
|
| 211 |
+
from runtime_adapters import (HyperExpertRunner, GenConfig, build_cluster_index,
|
| 212 |
+
_replicate_split, _unit)
|
| 213 |
+
|
| 214 |
+
tok = tok_v9.build()
|
| 215 |
+
runner = HyperExpertRunner(args.base_ckpt, args.hyper_ckpt, tok,
|
| 216 |
+
device=args.device, gen=GenConfig())
|
| 217 |
+
adapted, hyper = runner.adapted, runner.hyper
|
| 218 |
+
block, dev, d_z = runner.block_size, runner.device, runner.d_z
|
| 219 |
+
|
| 220 |
+
# exact trainer split -> the val tasks the hyper NEVER trained on
|
| 221 |
+
tasks = load_tasks(args.tasks)
|
| 222 |
+
_, val_tasks = _replicate_split(tasks, args.val_frac, args.seed)
|
| 223 |
+
z_cache = torch.load(args.z_cache, map_location="cpu")
|
| 224 |
+
|
| 225 |
+
# controller geometry: nearest TRAIN cluster (scope='train' == §10 calibration)
|
| 226 |
+
clusters, cinfo = build_cluster_index(args.tasks, args.z_cache,
|
| 227 |
+
val_frac=args.val_frac, seed=args.seed,
|
| 228 |
+
scope="train")
|
| 229 |
+
print(f"[eval] {len(val_tasks)} val tasks | {cinfo['n_clusters']} train clusters "
|
| 230 |
+
f"| d_z {d_z} | device {dev}")
|
| 231 |
+
|
| 232 |
+
# mean-z per val task (for the optional wrong-z neighbor pairing)
|
| 233 |
+
def mean_z(tid):
|
| 234 |
+
Z = np.asarray(z_cache[tid].float().cpu().numpy(), dtype=np.float32)
|
| 235 |
+
if Z.ndim == 1:
|
| 236 |
+
Z = Z[None, :]
|
| 237 |
+
return _unit(Z.mean(0))
|
| 238 |
+
|
| 239 |
+
records: list[dict] = []
|
| 240 |
+
cond_gaps: list[float] = []
|
| 241 |
+
skipped = 0
|
| 242 |
+
val_ids = [t["task_id"] for t in val_tasks]
|
| 243 |
+
|
| 244 |
+
with torch.no_grad():
|
| 245 |
+
for i, t in enumerate(val_tasks):
|
| 246 |
+
tid = t["task_id"]
|
| 247 |
+
examples = t.get("eval_examples") or t.get("train_examples")
|
| 248 |
+
if not examples or tid not in z_cache:
|
| 249 |
+
skipped += 1
|
| 250 |
+
continue
|
| 251 |
+
b = make_batch(examples, tok, block, dev) # (X, Y), output-only mask
|
| 252 |
+
if b is None:
|
| 253 |
+
skipped += 1
|
| 254 |
+
continue
|
| 255 |
+
|
| 256 |
+
# (b) bare base — z-independent, compute once
|
| 257 |
+
adapted.set_deltas(None)
|
| 258 |
+
loss_base = float(adapted(*b)[1].item())
|
| 259 |
+
|
| 260 |
+
# (a) right-z, per cached variant (serve-faithful single-descriptor z)
|
| 261 |
+
Z = z_cache[tid]
|
| 262 |
+
Z = Z[None, :] if Z.ndim == 1 else Z
|
| 263 |
+
n_var = Z.shape[0] if args.max_variants <= 0 else min(args.max_variants, Z.shape[0])
|
| 264 |
+
adapt_losses = []
|
| 265 |
+
for v in range(n_var):
|
| 266 |
+
z = Z[v].float().to(dev)
|
| 267 |
+
dist_v = float(clusters.nearest(z.cpu().numpy())[0])
|
| 268 |
+
adapted.set_deltas(hyper(z))
|
| 269 |
+
lv = float(adapted(*b)[1].item())
|
| 270 |
+
adapt_losses.append(lv)
|
| 271 |
+
records.append({"task_id": tid, "variant": v,
|
| 272 |
+
"loss_base": loss_base, "loss_adapt": lv,
|
| 273 |
+
"delta": loss_base - lv, "dist": dist_v})
|
| 274 |
+
|
| 275 |
+
# (c) wrong-z conditioning check: a NEIGHBOR task's mean z
|
| 276 |
+
if args.wrong_z and len(val_ids) > 1:
|
| 277 |
+
wrong_tid = val_ids[(i + 1) % len(val_ids)]
|
| 278 |
+
if wrong_tid in z_cache:
|
| 279 |
+
zw = torch.as_tensor(mean_z(wrong_tid), device=dev)
|
| 280 |
+
adapted.set_deltas(hyper(zw))
|
| 281 |
+
loss_wrong = float(adapted(*b)[1].item())
|
| 282 |
+
cond_gaps.append(loss_wrong - mean(adapt_losses)) # >0 => right better
|
| 283 |
+
|
| 284 |
+
if (i + 1) % 25 == 0:
|
| 285 |
+
print(f" [{i+1}/{len(val_tasks)}] last base={loss_base:.3f} "
|
| 286 |
+
f"adapt={mean(adapt_losses):.3f}", flush=True)
|
| 287 |
+
|
| 288 |
+
if not records:
|
| 289 |
+
raise SystemExit("no records — check that z_cache keys match val task_ids "
|
| 290 |
+
"and tasks have eval_examples/train_examples.")
|
| 291 |
+
if skipped:
|
| 292 |
+
print(f"[eval] skipped {skipped} val tasks (no examples / not in cache)")
|
| 293 |
+
|
| 294 |
+
s = summarize(records, tau_rag=args.tau_rag_on, tau_k=args.tau_k_escalate,
|
| 295 |
+
shatter_eps=args.shatter_eps, val_anchor=args.val_anchor)
|
| 296 |
+
if cond_gaps:
|
| 297 |
+
s["conditioning_win_rate"] = sum(1 for g in cond_gaps if g > 0) / len(cond_gaps)
|
| 298 |
+
s["conditioning_mean_gap"] = mean(cond_gaps)
|
| 299 |
+
|
| 300 |
+
print_report(s, tau_rag=args.tau_rag_on, tau_k=args.tau_k_escalate)
|
| 301 |
+
|
| 302 |
+
if args.out:
|
| 303 |
+
os.makedirs(os.path.dirname(args.out) or ".", exist_ok=True)
|
| 304 |
+
with open(args.out, "w") as f:
|
| 305 |
+
for r in records:
|
| 306 |
+
f.write(json.dumps(r) + "\n")
|
| 307 |
+
with open(args.out.rsplit(".", 1)[0] + ".summary.json", "w") as f:
|
| 308 |
+
json.dump(s, f, indent=2)
|
| 309 |
+
print(f"[eval] wrote {len(records)} records -> {args.out}")
|
| 310 |
+
print(f"[eval] wrote summary -> {args.out.rsplit('.', 1)[0]}.summary.json")
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
# ---------------------------------------------------------------------------
|
| 314 |
+
# Self-test — aggregation + separation logic only (no torch / artifacts)
|
| 315 |
+
# ---------------------------------------------------------------------------
|
| 316 |
+
|
| 317 |
+
def _self_test() -> None:
|
| 318 |
+
print("== eval_help_shatter self-test (pure python) ==")
|
| 319 |
+
res = []
|
| 320 |
+
|
| 321 |
+
# AUC sanity: perfectly separable, anti-separable, random
|
| 322 |
+
assert abs(_auc([1, 2, 3, 4], [0, 0, 1, 1]) - 1.0) < 1e-9
|
| 323 |
+
assert abs(_auc([1, 2, 3, 4], [1, 1, 0, 0]) - 0.0) < 1e-9
|
| 324 |
+
assert abs(_auc([1, 1, 2, 2], [0, 1, 0, 1]) - 0.5) < 1e-9 # ties -> chance
|
| 325 |
+
res.append(("auc", "1.0 / 0.0 / 0.5"))
|
| 326 |
+
|
| 327 |
+
# bucketing boundaries are half-open as documented
|
| 328 |
+
assert _bucket(0.20, 0.287, 0.308) == "in_dist"
|
| 329 |
+
assert _bucket(0.287, 0.287, 0.308) == "mid" # >= tau_rag_on
|
| 330 |
+
assert _bucket(0.308, 0.287, 0.308) == "ood" # >= tau_k_escalate
|
| 331 |
+
res.append(("bucket boundaries", "half-open at tau"))
|
| 332 |
+
|
| 333 |
+
# summarize: a help-heavy set with a few shatters, distance UNCORRELATED
|
| 334 |
+
# with shatter (the on-design case) -> AUC ~ 0.5, help rate high.
|
| 335 |
+
recs = []
|
| 336 |
+
for k in range(40):
|
| 337 |
+
d = 0.10 + 0.005 * k # spread of distances
|
| 338 |
+
# most help (+0.4), every 9th shatters (-0.3) regardless of distance
|
| 339 |
+
delta = -0.3 if k % 9 == 0 else 0.4
|
| 340 |
+
recs.append({"task_id": f"t{k}", "variant": 0,
|
| 341 |
+
"loss_base": 3.0, "loss_adapt": 3.0 - delta,
|
| 342 |
+
"delta": delta, "dist": d})
|
| 343 |
+
s = summarize(recs, tau_rag=0.287, tau_k=0.308, shatter_eps=0.05, val_anchor=2.6)
|
| 344 |
+
assert s["n_points"] == 40 and s["n_tasks"] == 40
|
| 345 |
+
assert s["help_rate_points"] > 0.8 and s["shatter_rate_points"] > 0.0
|
| 346 |
+
assert 0.30 < s["dist_predicts_shatter_auc"] < 0.70, s["dist_predicts_shatter_auc"]
|
| 347 |
+
assert s["mean_loss_base"] == 3.0
|
| 348 |
+
assert abs(s["adapt_vs_anchor"] - (s["mean_loss_adapt"] - 2.6)) < 1e-9
|
| 349 |
+
res.append(("summarize uncorrelated", f"AUC={s['dist_predicts_shatter_auc']:.2f} "
|
| 350 |
+
f"help={s['help_rate_points']:.2f}"))
|
| 351 |
+
|
| 352 |
+
# summarize: distance DOES predict shatter (far -> shatter) -> AUC high
|
| 353 |
+
recs2 = []
|
| 354 |
+
for k in range(40):
|
| 355 |
+
d = 0.10 + 0.006 * k
|
| 356 |
+
delta = -0.3 if d > 0.30 else 0.4 # shatter only when far
|
| 357 |
+
recs2.append({"task_id": f"t{k}", "variant": 0,
|
| 358 |
+
"loss_base": 3.0, "loss_adapt": 3.0 - delta,
|
| 359 |
+
"delta": delta, "dist": d})
|
| 360 |
+
s2 = summarize(recs2, tau_rag=0.287, tau_k=0.308, shatter_eps=0.05, val_anchor=None)
|
| 361 |
+
assert s2["dist_predicts_shatter_auc"] > 0.85, s2["dist_predicts_shatter_auc"]
|
| 362 |
+
assert s2["by_bucket"]["ood"]["shatter_rate"] > s2["by_bucket"]["in_dist"]["shatter_rate"]
|
| 363 |
+
res.append(("summarize correlated", f"AUC={s2['dist_predicts_shatter_auc']:.2f}"))
|
| 364 |
+
|
| 365 |
+
print()
|
| 366 |
+
for k, v in res:
|
| 367 |
+
print(f" [ok ] {k:<26} -> {v}")
|
| 368 |
+
print(f"ALL {len(res)}/{len(res)} LOGIC TESTS PASSED.")
|
| 369 |
+
print("(the torch/artifact path runs on the pod via run_eval)")
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def main() -> None:
|
| 373 |
+
ap = argparse.ArgumentParser(description="eMoE help-vs-shatter eval (step 3)")
|
| 374 |
+
ap.add_argument("--self_test", action="store_true")
|
| 375 |
+
ap.add_argument("--base_ckpt", default="ckpt_v12_190m_best.pt")
|
| 376 |
+
ap.add_argument("--hyper_ckpt", default="hyper_ckpt_v12.best.pt")
|
| 377 |
+
ap.add_argument("--z_cache", default="runs/hyper_v1/z_cache.pt")
|
| 378 |
+
ap.add_argument("--tasks", default="data/hyper_v1.jsonl")
|
| 379 |
+
ap.add_argument("--val_frac", type=float, default=0.15)
|
| 380 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 381 |
+
ap.add_argument("--device", default=None)
|
| 382 |
+
ap.add_argument("--max_variants", type=int, default=0,
|
| 383 |
+
help="cap cached z variants per task (0 = all)")
|
| 384 |
+
ap.add_argument("--wrong_z", action="store_true",
|
| 385 |
+
help="also measure a neighbor-task's z (conditioning check)")
|
| 386 |
+
ap.add_argument("--tau_rag_on", type=float, default=0.287,
|
| 387 |
+
help="banked from serve_emoe.py --geometry (C) p90")
|
| 388 |
+
ap.add_argument("--tau_k_escalate", type=float, default=0.308,
|
| 389 |
+
help="banked from serve_emoe.py --geometry (C) p95")
|
| 390 |
+
ap.add_argument("--shatter_eps", type=float, default=0.05,
|
| 391 |
+
help="delta below -eps counts as shatter (nats)")
|
| 392 |
+
ap.add_argument("--val_anchor", type=float, default=None,
|
| 393 |
+
help="VAL floor to sanity-check mean adapt loss against (e.g. 2.0889)")
|
| 394 |
+
ap.add_argument("--out", default="")
|
| 395 |
+
args = ap.parse_args()
|
| 396 |
+
|
| 397 |
+
if args.self_test:
|
| 398 |
+
_self_test()
|
| 399 |
+
return
|
| 400 |
+
run_eval(args)
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
if __name__ == "__main__":
|
| 404 |
+
main()
|