File size: 7,031 Bytes
6f2ed01 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | #!/usr/bin/env python
"""ISS: Internal State Stability. (protocol 7, J-Lens spec 10)
python src/iss.py --model Llama-3.2-1B --transport raw # ablation
python src/iss.py --model Llama-3.2-1B --transport jlens # official
The state preparation (transport -> residualise -> whiten -> family centroid)
lives in states.py so that ISS and KTS provably score the same vectors. What is
here is only the ISS-specific part:
S+ same fact, across condition-family pairs
S- same relation, different fact, symmetric in the family pair
ISS = (S+ - S-) / (1 - S- + eps)
Raw-ISS is NOT the official metric (J-Lens spec 11). It exists to prove the
data loading, family aggregation and negative sampling are right before the
Jacobian transport is layered on top (spec 21, step 1).
"""
import os, sys, time, argparse
import numpy as np
import torch
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import mcommon as mc
from states import StateLoader
def iss_one_layer(V, mask, by_rel, negatives, eps):
"""S+, S- and ISS for every fact at one layer."""
F, T, _ = V.shape
dev = V.device
s_pos = torch.zeros(F, device=dev)
s_neg = torch.zeros(F, device=dev)
n_pos = torch.zeros(F, device=dev)
n_neg = torch.zeros(F, device=dev)
zero = torch.zeros(F, device=dev)
for t in range(T):
for u in range(t + 1, T):
both = mask[:, t] & mask[:, u]
if not bool(both.any()):
continue
s_pos += torch.where(both, (V[:, t] * V[:, u]).sum(-1), zero)
n_pos += both.float()
# Protocol 7.8: same-relation background, symmetrised over the pair
# so a family that sits globally closer to everything cannot inflate
# the score. Done per relation to keep each similarity block small.
for members in by_rel.values():
idx = [i for i in members if bool(both[i])]
if len(idx) < 2:
continue
ii = torch.tensor(idx, device=dev)
Sab = V[ii, t] @ V[ii, u].T
pos = {f: j for j, f in enumerate(idx)}
for f in idx:
negs = [pos[g] for g in negatives[f] if g in pos]
if not negs:
continue
jj = torch.tensor(negs, device=dev)
j0 = pos[f]
s_neg[f] += 0.5 * (Sab[j0, jj].mean() + Sab[jj, j0].mean())
n_neg[f] += 1
sp = s_pos / n_pos.clamp_min(1)
sn = s_neg / n_neg.clamp_min(1)
return sp, sn, (sp - sn) / (1.0 - sn + eps), (n_pos > 0) & (n_neg > 0)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--model", required=True)
ap.add_argument("--transport", choices=["raw", "jlens"], default="raw")
ap.add_argument("--coverage", choices=["complete_family", "full_set"], default=None)
ap.add_argument("--device", default="auto")
ap.add_argument("--shuffle-seed", type=int, default=None,
help="protocol 18.1 control: destroy fact identity; ISS must collapse")
args = ap.parse_args()
C = mc.cfg()
icfg = C["iss"]
eps = float(icfg["eps"])
S = StateLoader(args.model, args.transport, args.coverage, args.device,
shuffle_seed=args.shuffle_seed)
negatives = mc.negative_sample(S.keep_facts, S.rel_of,
icfg["max_negatives"], icfg["negative_seed"])
negatives = {S.fidx[f]: [S.fidx[g] for g in gs] for f, gs in negatives.items()}
F = S.n_facts
per_layer, t0 = {}, time.time()
for l in S.window:
V, mask = S.centroids(l)
sp, sn, iss, valid = iss_one_layer(V, mask, S.by_rel, negatives, eps)
per_layer[l] = {"s_pos": sp.cpu().numpy(), "s_neg": sn.cpu().numpy(),
"iss": iss.cpu().numpy(), "valid": valid.cpu().numpy()}
print(f" L{l:03d} ISS={float(iss[valid].mean()):+.4f} "
f"S+={float(sp[valid].mean()):.4f} S-={float(sn[valid].mean()):.4f}",
flush=True)
del V, mask
if S.dev == "cuda":
torch.cuda.empty_cache()
# ---- protocol 7.10: window mean, peak, late
stack = np.stack([per_layer[l]["iss"] for l in S.window])
vmask = np.stack([per_layer[l]["valid"] for l in S.window])
stack = np.where(vmask, stack, np.nan)
late_rows = [i for i, l in enumerate(S.window) if l in S.late]
with np.errstate(invalid="ignore"):
iss_f = np.nanmean(stack, axis=0)
peak_f = np.nanmax(stack, axis=0)
late_f = np.nanmean(stack[late_rows], axis=0) if late_rows else np.full(F, np.nan)
rows = [{"model": args.model, "transport": args.transport, "fact_id": f,
"relation": S.rel_of[f], "iss": float(iss_f[i]),
"iss_peak": float(peak_f[i]), "iss_late": float(late_f[i]),
"layers_used": S.window}
for i, f in enumerate(S.keep_facts) if np.isfinite(iss_f[i])]
tag = f"{args.model}.{args.transport}.{S.mode}"
if args.shuffle_seed is not None:
tag += f".shuffled{args.shuffle_seed}"
mc.write_jsonl(mc.out("metrics", "iss", f"{tag}.per_fact.jsonl"), rows)
mc.write_jsonl(mc.out("metrics", "iss", f"{tag}.per_fact_layer.jsonl"),
[{"model": args.model, "transport": args.transport,
"fact_id": f, "layer": l,
"iss": float(per_layer[l]["iss"][i]),
"s_positive": float(per_layer[l]["s_pos"][i]),
"s_background": float(per_layer[l]["s_neg"][i])}
for l in S.window for i, f in enumerate(S.keep_facts)
if per_layer[l]["valid"][i]])
vals = {r["fact_id"]: r["iss"] for r in rows}
boot = mc.relation_clustered_bootstrap(
vals, S.rel_of, C["bootstrap"]["n_resamples"], C["bootstrap"]["seed"],
C["bootstrap"]["ci"])
summary = {
"model": args.model, "transport": args.transport, "coverage_mode": S.mode,
"official": args.transport == "jlens" and args.shuffle_seed is None,
"shuffle_control": args.shuffle_seed is not None,
"n_facts": len(rows), "layers": S.window,
"iss": boot["mean"], "iss_ci95": [boot["lo"], boot["hi"]],
"iss_peak": float(np.nanmean(peak_f)), "iss_late": float(np.nanmean(late_f)),
"s_positive": float(np.nanmean([per_layer[l]["s_pos"] for l in S.window])),
"s_background": float(np.nanmean([per_layer[l]["s_neg"] for l in S.window])),
"per_layer_iss": {str(l): float(np.nanmean(np.where(
per_layer[l]["valid"], per_layer[l]["iss"], np.nan))) for l in S.window},
"seconds": round(time.time() - t0, 1),
}
mc.write_json(mc.out("metrics", "iss", f"{tag}.summary.json"), summary)
print(f"[{args.model}] {args.transport}-ISS = {boot['mean']:+.4f} "
f"[{boot['lo']:+.4f},{boot['hi']:+.4f}] n={len(rows)} ISS_DONE", flush=True)
if __name__ == "__main__":
main()
|