File size: 8,138 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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/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()