LucasLoading's picture
Upload 30 files
6f2ed01 verified
Raw
History Blame Contribute Delete
8.14 kB
#!/usr/bin/env python
"""KTS: Knowledge Topology Stability. (protocol 8-11)
python src/kts.py --model Llama-3.2-1B --transport raw
python src/kts.py --model Llama-3.2-1B --transport jlens
Two components, both computed per relation and then macro-averaged so that the
largest relations cannot dominate (protocol 9.1):
KTS-Geo Spearman correlation between the within-relation pairwise distance
matrices under the two condition families. Rotation, translation and
isotropic scaling are all invisible to it -- protocol 8.1 says that
is intended: different phrasings may use different internal
implementations as long as relative structure survives.
KTS-ID Cross-condition nearest-neighbour retrieval of the fact itself,
among same-relation facts, both directions, chance-corrected.
Global geometry can look preserved while individual identities swap,
which is exactly what this catches.
composite = harmonic mean of the two, so a model cannot buy a high KTS with one
component alone (protocol 11).
"""
import os, sys, json, time, argparse, itertools
import numpy as np
import torch
from scipy.stats import spearmanr
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import mcommon as mc
from states import StateLoader
def geo_pair(Va, Vb, members, eps):
"""Spearman between within-relation distance matrices (protocol 9.1-9.2)."""
idx = torch.tensor(members, device=Va.device)
A, B = Va[idx], Vb[idx]
Da = 1.0 - (A @ A.T)
Db = 1.0 - (B @ B.T)
iu = torch.triu_indices(len(members), len(members), offset=1)
da = Da[iu[0], iu[1]].cpu().numpy()
db = Db[iu[0], iu[1]].cpu().numpy()
if da.size < 2 or np.std(da) < eps or np.std(db) < eps:
return None
rho = spearmanr(da, db).statistic
return None if not np.isfinite(rho) else float(rho)
def id_pair(Va, Vb, members):
"""Symmetric chance-corrected top-1 identity, plus top-5 and MRR.
Retrieval is restricted to same-relation facts (protocol 10.1): matching
"the capital of France" against a manufacturer fact would be trivial and
would inflate the score.
"""
idx = torch.tensor(members, device=Va.device)
A, B = Va[idx], Vb[idx]
n = len(members)
gold = torch.arange(n, device=A.device)
def side(X, Y):
S = X @ Y.T
rank = (S > S.gather(1, gold[:, None])).sum(1) # 0 = correct is top
top1 = (rank == 0).float().mean().item()
top5 = (rank < 5).float().mean().item()
mrr = (1.0 / (rank.float() + 1)).mean().item()
return top1, top5, mrr
a = side(A, B)
b = side(B, A)
top1 = 0.5 * (a[0] + b[0])
chance = 1.0 / n
adj = (top1 - chance) / max(1.0 - chance, 1e-12)
return {"top1_symmetric": top1, "top5_symmetric": 0.5 * (a[1] + b[1]),
"mrr_symmetric": 0.5 * (a[2] + b[2]), "chance": chance,
"chance_corrected": float(np.clip(adj, 0.0, 1.0)), "n": n}
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: KTS-ID must fall to chance, KTS-Geo to ~0")
args = ap.parse_args()
C = mc.cfg()
kcfg = C["kts"]
eps = float(kcfg["eps"])
min_facts = kcfg["min_facts_per_relation"]
S = StateLoader(args.model, args.transport, args.coverage, args.device,
shuffle_seed=args.shuffle_seed)
fams = S.families
pairs = list(itertools.combinations(range(len(fams)), 2))
t0 = time.time()
per_layer_pair = []
for l in S.window:
V, mask = S.centroids(l)
for (a, b) in pairs:
both = mask[:, a] & mask[:, b]
geos, ids, shared = [], [], int(both.sum())
for rel, members in S.by_rel.items():
m = [i for i in members if bool(both[i])]
if len(m) < min_facts: # protocol 9.1
continue
g = geo_pair(V[:, a], V[:, b], m, eps)
if g is not None:
geos.append(g)
ids.append(id_pair(V[:, a], V[:, b], m))
if not geos or not ids:
continue
geo = float(np.mean(geos))
geo01 = (geo + 1.0) / 2.0 # protocol 9.3
idv = float(np.mean([x["chance_corrected"] for x in ids]))
per_layer_pair.append({
"model": args.model, "transport": args.transport, "layer": l,
"pair": f"{fams[a]}__{fams[b]}", "shared_facts": shared,
"relations_used": len(ids),
"kts_geo_raw": geo, "kts_geo": geo01, "kts_id": idv,
"kts": 2 * geo01 * idv / (geo01 + idv + eps), # protocol 11
"top1": float(np.mean([x["top1_symmetric"] for x in ids])),
"top5": float(np.mean([x["top5_symmetric"] for x in ids])),
"mrr": float(np.mean([x["mrr_symmetric"] for x in ids])),
})
del V, mask
if S.dev == "cuda":
torch.cuda.empty_cache()
lay = [r for r in per_layer_pair if r["layer"] == l]
print(f" L{l:03d} geo={np.mean([r['kts_geo'] for r in lay]):.4f} "
f"id={np.mean([r['kts_id'] for r in lay]):.4f} "
f"kts={np.mean([r['kts'] for r in lay]):.4f}", flush=True)
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", "kts", f"{tag}.per_pair_layer.jsonl"), per_layer_pair)
# Protocol 11.1: every family pair counts equally. Weighting by shared facts
# would let the widest-coverage pairs decide the number.
def agg(rows, key):
by_layer = {}
for r in rows:
by_layer.setdefault(r["layer"], []).append(r[key])
return float(np.mean([np.mean(v) for v in by_layer.values()]))
pair_summary = {}
for p in sorted({r["pair"] for r in per_layer_pair}):
rows = [r for r in per_layer_pair if r["pair"] == p]
pair_summary[p] = {
"shared_facts": rows[0]["shared_facts"],
"kts_geo": float(np.mean([r["kts_geo"] for r in rows])),
"kts_geo_raw": float(np.mean([r["kts_geo_raw"] for r in rows])),
"kts_id": float(np.mean([r["kts_id"] for r in rows])),
"kts": float(np.mean([r["kts"] for r in rows])),
"top1": float(np.mean([r["top1"] for r in rows])),
"top5": float(np.mean([r["top5"] for r in rows])),
"mrr": float(np.mean([r["mrr"] for r in rows])),
}
summary = {
"model": args.model, "transport": args.transport,
"official": args.transport == "jlens" and args.shuffle_seed is None,
"shuffle_control": args.shuffle_seed is not None, "coverage_mode": S.mode,
"layers": S.window, "n_facts": S.n_facts,
"kts_geo": agg(per_layer_pair, "kts_geo"),
"kts_geo_raw_spearman": agg(per_layer_pair, "kts_geo_raw"),
"kts_id": agg(per_layer_pair, "kts_id"),
"kts": agg(per_layer_pair, "kts"),
"top1": agg(per_layer_pair, "top1"),
"top5": agg(per_layer_pair, "top5"),
"mrr": agg(per_layer_pair, "mrr"),
"family_pairs": pair_summary,
"per_layer_kts": {str(l): float(np.mean([r["kts"] for r in per_layer_pair
if r["layer"] == l]))
for l in S.window},
"seconds": round(time.time() - t0, 1),
}
mc.write_json(mc.out("metrics", "kts", f"{tag}.summary.json"), summary)
print(f"[{args.model}] {args.transport} KTS-Geo={summary['kts_geo']:.4f} "
f"KTS-ID={summary['kts_id']:.4f} KTS={summary['kts']:.4f} KTS_DONE",
flush=True)
if __name__ == "__main__":
main()