LucasLoading commited on
Commit
6f2ed01
·
verified ·
1 Parent(s): a836039

Upload 30 files

Browse files
.gitattributes CHANGED
@@ -59,3 +59,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
  ICLR[[:space:]]dataset/evaluation_queries_44416.jsonl filter=lfs diff=lfs merge=lfs -text
 
 
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
  ICLR[[:space:]]dataset/evaluation_queries_44416.jsonl filter=lfs diff=lfs merge=lfs -text
62
+ dataset_upload/data/evaluation_queries_44416.jsonl filter=lfs diff=lfs merge=lfs -text
dataset_upload/.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ *.jsonl filter=lfs diff=lfs merge=lfs -text
dataset_upload/.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ outputs/
2
+ work/
3
+ __pycache__/
4
+ *.pyc
dataset_upload/LICENSE ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Fact Knowledge Stability Benchmark
2
+ Creative Commons Attribution 4.0 International (CC BY 4.0)
3
+
4
+ You are free to share and adapt this material for any purpose, including
5
+ commercially, provided you give appropriate credit, link to the licence, and
6
+ indicate if changes were made.
7
+
8
+ Full text: https://creativecommons.org/licenses/by/4.0/legalcode
9
+
10
+
11
+ UPSTREAM SOURCES AND THEIR TERMS
12
+ --------------------------------
13
+
14
+ The facts in this benchmark are derived from the datasets below. Their terms
15
+ continue to apply to the derived material; CC BY 4.0 was chosen because it is
16
+ compatible with all of them. Please cite the original datasets alongside this
17
+ one.
18
+
19
+ CounterFact MIT License
20
+ Meng et al., "Locating and Editing Factual Associations in GPT" (2022)
21
+
22
+ LAMA / T-REx CC BY 4.0
23
+ Petroni et al., "Language Models as Knowledge Bases?" (2019)
24
+ ElSahar et al., "T-REx: A Large Scale Alignment of Natural Language with
25
+ Knowledge Base Triples" (2018)
26
+
27
+ LAMA / Google-RE CC BY 4.0 (per the LAMA distribution)
28
+ LAMA / ConceptNet CC BY-SA 4.0 (ConceptNet 5)
29
+
30
+ PopQA MIT License
31
+ Mallen et al., "When Not to Trust Language Models" (2023)
32
+
33
+ Wikidata CC0 1.0 (entity identifiers and aliases)
34
+
35
+ The T-REx and Wikidata5M subsets present in the candidate pool were dropped
36
+ before benchmark selection and are not represented in the distributed files.
37
+
38
+ The code under runner/ and metrics/ is released under the MIT License.
dataset_upload/OUTPUT_SCHEMA.md ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Output schema
2
+
3
+ What your model must emit for the shipped scorer and metrics to accept it. If
4
+ you use `runner/eval_run.py` you get this for free; this document exists so you
5
+ can plug in your own inference stack (vLLM, an API, a custom harness) instead.
6
+
7
+ ## Generations — `outputs/evaluation/<model>.jsonl`
8
+
9
+ One JSON object per line, **44,416 lines**, one per `query_id`.
10
+
11
+ ```json
12
+ {
13
+ "query_id": "query_00000001",
14
+ "fact_id": "fact_000602",
15
+ "condition_family": "anchor",
16
+ "model": "my-model",
17
+ "prompt": "Question: Which jurisdiction does Agriculture and Agri-Food Canada have legal force in?\nAnswer with only the shortest correct answer.\nAnswer:",
18
+ "raw_response": " Canada\nExplanation: Agriculture and Agri-Food Canada (AAFC) is a federal department of the Government of Canada",
19
+ "generated_tokens": 24,
20
+ "finish_reason": "length"
21
+ }
22
+ ```
23
+
24
+ | field | required | notes |
25
+ |---|---|---|
26
+ | `query_id` | **yes** | the join key; must match the query bank exactly |
27
+ | `raw_response` | **yes** | continuation only, *not* including the prompt. Do not strip, lowercase, or truncate it — the scorer needs the raw span, and `finish_reason: "length"` mid-sentence output is normal and handled |
28
+ | `fact_id`, `condition_family` | recommended | `judge_run.py` groups by these; it can recover them from the query bank but the files are easier to audit with them present |
29
+ | `model` | recommended | copied onto scored rows |
30
+ | `prompt` | recommended | keeps each file self-documenting about the template used — the cheapest way for a reader to catch a protocol mismatch |
31
+ | `generated_tokens`, `finish_reason` | optional | diagnostics |
32
+
33
+ Order does not matter; the scorer joins on `query_id`. Extra fields are ignored.
34
+
35
+ ### Prompt construction
36
+
37
+ Reproduce `runner/eval_run.py:build_prompt` exactly:
38
+
39
+ ```python
40
+ PROMPT = "Question: {q}\nAnswer with only the shortest correct answer.\nAnswer:"
41
+
42
+ def build_prompt(row):
43
+ if row["condition_family"] == "anchor":
44
+ return PROMPT.format(q=row["query"])
45
+ return f"{row['query']}\nAnswer:"
46
+ ```
47
+
48
+ Anchor is the canonical question and gets the instruction wrapper. Every other
49
+ family already carries its own surface form — that *is* the perturbation — so
50
+ wrapping it would erase the manipulation; it gets only a bare `Answer:` cue.
51
+
52
+ **No chat template, for base and instruct models alike.** See the README.
53
+
54
+ ### Decoding
55
+
56
+ Greedy, `num_beams=1`, `temperature=0.0`, `max_new_tokens=24`,
57
+ `max_prompt_len=192` (left truncation, left padding), `dtype=bfloat16`,
58
+ `seed=20260101`. From `configs/models.yaml:generation`.
59
+
60
+ ## Scored output — `<model>.scored.jsonl`
61
+
62
+ Produced by `runner/scoring_full.py`. One line per generation:
63
+
64
+ ```json
65
+ {
66
+ "query_id": "query_00000001",
67
+ "model": "my-model",
68
+ "fact_id": "fact_000602",
69
+ "relation": "applies_to_jurisdiction",
70
+ "condition_family": "anchor",
71
+ "language": "en",
72
+ "target_slot": "object",
73
+ "answer_type": "place",
74
+ "answer_granularity": "entity",
75
+ "answer_in_subject_surface": true,
76
+ "use_for_main_forward": true,
77
+ "use_for_reverse_analysis": false,
78
+ "use_for_recognition_analysis": false,
79
+ "raw_response": " Canada\nExplanation: ...",
80
+ "span": "Canada",
81
+ "flags": [],
82
+ "label": "correct",
83
+ "matched_alias": "Canada",
84
+ "scorer": "exact_alias",
85
+ "needs_manual_review": false
86
+ }
87
+ ```
88
+
89
+ `label` is one of `correct` / `incorrect` / `ambiguous` / `abstain` /
90
+ `unparseable`. `scorer` names the rule that fired, which is what you inspect
91
+ when a label looks wrong. The per-query booleans are carried through so metric
92
+ code can filter without rejoining the query bank.
93
+
94
+ ## Hidden states — `outputs/hidden/<model>/`
95
+
96
+ Only needed for ISS and KTS. Produced by `metrics/extract_hidden.py`.
97
+
98
+ ```
99
+ L018.npy … L045.npy float16 [n_main_forward_queries, d_model]
100
+ index.json query order, layer list, checksums, `complete` flag
101
+ ```
102
+
103
+ Rows are in the order given by `index.json`, aligned with the 39,260 queries
104
+ carrying `use_for_main_forward`. Layers stored are `{l : l/(L−1) ≥ 0.4}`, where
105
+ `l` indexes decoder blocks and the stored state is the **output** of block `l`
106
+ (`hidden_states[l+1]` in HuggingFace terms).
107
+
108
+ The probe position is the **last valid input token** — the model has read the
109
+ question but has not emitted an answer token. With left padding this is
110
+ position `-1` for every row in a batch.
dataset_upload/README.md ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-4.0
3
+ task_categories:
4
+ - question-answering
5
+ - text-generation
6
+ language:
7
+ - en
8
+ - zh
9
+ - fr
10
+ - es
11
+ - de
12
+ - ru
13
+ size_categories:
14
+ - 10K<n<100K
15
+ pretty_name: Fact Knowledge Stability Benchmark
16
+ tags:
17
+ - factual-knowledge
18
+ - robustness
19
+ - consistency
20
+ - interpretability
21
+ - multilingual
22
+ configs:
23
+ - config_name: queries
24
+ default: true
25
+ data_files: data/evaluation_queries_44416.jsonl
26
+ - config_name: facts
27
+ data_files: data/benchmark_facts_2592.jsonl
28
+ ---
29
+
30
+ # Fact Knowledge Stability Benchmark
31
+
32
+ **2,592 facts × 44,416 queries.** Does a model that knows a fact still know it
33
+ when you rephrase the question, change the answer format, add distracting
34
+ context, or ask in another language?
35
+
36
+ The benchmark pairs **behavioural** stability (what the model *says* across
37
+ perturbations) with **internal** stability (what its residual stream *does*
38
+ across the same perturbations), so the two can be compared on identical inputs.
39
+
40
+ ```python
41
+ from datasets import load_dataset
42
+
43
+ queries = load_dataset("LucasLoading/stable", "queries", split="train")
44
+ facts = load_dataset("LucasLoading/stable", "facts", split="train")
45
+ ```
46
+
47
+ ---
48
+
49
+ ## Read this before you report a number
50
+
51
+ Four properties of this benchmark will silently distort results if you do not
52
+ account for them. They are design decisions, not defects, and each is flagged
53
+ per-row in the data.
54
+
55
+ **1. The facts were selected to be easy.** Candidates were kept only if **all
56
+ five** filter models (Gemma-2-2B-it, Qwen2.5-7B, Mistral-7B-v0.3, Llama-3.1-8B,
57
+ Gemma-2-9B-it) produced the correct first token. That is **10,601 of 1,783,541
58
+ cloze prompts — 0.59%**. This is deliberate: to attribute instability to
59
+ *expression* rather than to *ignorance*, the model has to know the fact in the
60
+ first place. The consequence is that absolute stability scores run high, and
61
+ that the four filter models present in a comparison enjoy a selection advantage
62
+ over models that had no say in what was kept.
63
+
64
+ **2. 750 of 2,592 facts (28.9%) are answerable by copying the subject string.**
65
+ `Airbus A318 → manufacturer → Airbus`. Every fact and every query carries
66
+ `answer_in_subject_surface`; report those two subsets separately.
67
+
68
+ **3. Only four of the eight condition families belong in the main average.**
69
+ Use each row's own boolean, never a hard-coded family list:
70
+
71
+ | flag | rows | meaning |
72
+ |---|---:|---|
73
+ | `use_for_main_forward` | 39,260 | anchor + paraphrase + format + context + multilingual |
74
+ | `use_for_reverse_analysis` | 634 | target slot is the **subject**; report separately |
75
+ | `use_for_recognition_analysis` | 3,412 | diagnostic only |
76
+ | *(none of the above)* | 1,110 | `reverse_illposed`; diagnostic only |
77
+
78
+ **4. `anchor` is the unperturbed baseline, and it holds exactly one query per
79
+ fact.** Its within-family agreement is therefore 1.0 by construction. Including
80
+ it as a fifth equally-weighted family puts a floor under any family-balanced
81
+ consistency score. `configs/metrics.yaml:main_families` controls this; drop
82
+ `anchor` from that list to score the four perturbation families only.
83
+
84
+ ---
85
+
86
+ ## Contents
87
+
88
+ ```
89
+ data/
90
+ benchmark_facts_2592.jsonl 2,592 facts / 21 relations
91
+ evaluation_queries_44416.jsonl 44,416 queries / 8 condition families / 6 languages
92
+ configs/
93
+ metrics.yaml metric hyper-parameters — layer window, whitening, tau_b, bootstrap
94
+ models.yaml the 20 evaluated models + decoding config + judge
95
+ relations.yaml 21 relations, with the two optional exclusion switches
96
+ eval_conditions.yaml condition registry the three booleans are derived from
97
+ protocol/
98
+ evaluation_protocol.md BCS/BES (§4-6), ISS (§7), KTS (§8-11) [Chinese]
99
+ jlens_spec.md Jacobian-transported ISS [Chinese]
100
+ dataset_construction.md how the benchmark was built (archival) [Chinese]
101
+ reconstruction_differences.md documented deviations D1, C1, F1, F2, N1, N2
102
+ runner/
103
+ eval_run.py generation -> outputs/evaluation/<model>.jsonl
104
+ scoring_full.py five-label scorer (correct/incorrect/ambiguous/abstain/unparseable)
105
+ test_scoring.py 31 unit tests for the scorer
106
+ common.py
107
+ metrics/
108
+ extract_hidden.py query-end residual states -> outputs/hidden/<model>/
109
+ iss.py Internal State Stability
110
+ kts.py Knowledge Topology Stability (KTS-Geo + KTS-ID)
111
+ judge_run.py semantic clustering of answers (needs a judge model)
112
+ bcs_bes.py BCS / BES / behaviour classification
113
+ joint.py internal x external correlation
114
+ make_table.py main table
115
+ jlens.py states.py mcommon.py
116
+ OUTPUT_SCHEMA.md what your model must emit to be scorable
117
+ ```
118
+
119
+ **Not included:** the upstream corpora, the dataset build scripts, and the
120
+ hidden-state tensors (1.6–15 GB per model, regenerate with `extract_hidden.py`).
121
+
122
+ ---
123
+
124
+ ## Condition families
125
+
126
+ | family | queries | facts | role |
127
+ |---|---:|---:|---|
128
+ | anchor | 2,592 | 2,592 | unperturbed baseline (1 per fact) |
129
+ | paraphrase | 10,053 | 2,592 | main |
130
+ | format | 7,776 | 2,592 | main |
131
+ | context | 6,829 | 2,591 | main |
132
+ | multilingual | 12,010 | 2,402 | main (zh/fr/es/de/ru) |
133
+ | reverse | 634 | 253 | subject slot; reported separately |
134
+ | recognition | 3,412 | 2,585 | diagnostic |
135
+ | reverse_illposed | 1,110 | 1,110 | diagnostic |
136
+
137
+ Coverage is ragged on purpose — multilingual covers 2,402 facts, context 2,591 —
138
+ so both readings are mandatory (`coverage_modes` in `configs/metrics.yaml`):
139
+ `complete_family` (facts carrying all five) and `full_set` (each fact averaged
140
+ over the families it actually has).
141
+
142
+ ---
143
+
144
+ ## Evaluating your own model
145
+
146
+ Everything below is CPU-only except `eval_run.py`, `extract_hidden.py` and
147
+ `judge_run.py`.
148
+
149
+ ```bash
150
+ pip install -r requirements.txt
151
+
152
+ # optional: keep large outputs off the checkout
153
+ export FKS_OUTPUTS=/path/to/large/disk/fks_work
154
+
155
+ # 1. generate (44,416 queries)
156
+ python runner/eval_run.py --model my-model --model-path org/my-model
157
+
158
+ # 2. score to five labels -> outputs/evaluation/my-model.scored.jsonl
159
+ python runner/scoring_full.py --gen outputs/evaluation/my-model.jsonl
160
+
161
+ # 3. your own metrics on top of the labels, or the ones shipped here:
162
+ python metrics/judge_run.py --model my-model # semantic clustering [GPU]
163
+ python metrics/bcs_bes.py --model my-model # BCS / BES / behaviour
164
+ python metrics/extract_hidden.py --model my-model # residual states [GPU]
165
+ python metrics/iss.py --model my-model --transport raw --device cpu
166
+ python metrics/kts.py --model my-model --transport raw --device cpu
167
+ ```
168
+
169
+ A model not listed in `configs/models.yaml` needs either an entry there or
170
+ `--model-path`; `metrics/*.py` read `n_layers`/`d_model` from that file, so add
171
+ an entry before running the internal metrics.
172
+
173
+ ### The decoding protocol is part of the benchmark
174
+
175
+ Numbers are not comparable unless generation matches
176
+ `configs/models.yaml:generation` exactly:
177
+
178
+ ```yaml
179
+ do_sample: false # greedy
180
+ num_beams: 1
181
+ temperature: 0.0
182
+ max_new_tokens: 24
183
+ max_prompt_len: 192 # effective value; the 96 in models.yaml is raised by eval_run.py
184
+ dtype: bfloat16
185
+ use_chat_template: false # <-- base and instruct get the IDENTICAL raw string
186
+ seed: 20260101
187
+ ```
188
+
189
+ `use_chat_template: false` is not an oversight. Four of the twenty models are
190
+ instruction-tuned; applying a chat template to only those would confound
191
+ post-training with prompt format. The prompt itself is built by
192
+ `runner/eval_run.py:build_prompt` — anchor gets the instruction wrapper,
193
+ perturbed queries carry their own surface form (that *is* the perturbation) and
194
+ receive only a bare `Answer:` cue. `extract_hidden.py` imports that same
195
+ function rather than re-deriving it, so ISS and BCS are always measured on the
196
+ identical prompt.
197
+
198
+ ### Share the scorer, not just the data
199
+
200
+ `runner/scoring_full.py` is shipped so that label boundaries — negation
201
+ handling, year granularity, alias matching — are identical across submissions.
202
+ Re-implementing the five-label extractor makes numbers incomparable in ways that
203
+ are very hard to see. Run `python runner/test_scoring.py` (31 tests) to confirm
204
+ it behaves the same on your machine.
205
+
206
+ ---
207
+
208
+ ## Metrics
209
+
210
+ **External** (from `runner/` + `metrics/judge_run.py` + `metrics/bcs_bes.py`):
211
+
212
+ - **BCS** — family-balanced maximum probability over answer clusters. Graded,
213
+ and note it has a high floor: a model choosing at random between two answers
214
+ scores ≈0.61, not 0.5.
215
+ - **BES** — entropy-based, `1 - H(p)/log A`. Chance floor ≈0.06.
216
+ - **Behaviour classes** — Stable Correct / Stable Wrong / Stable Abstention /
217
+ Unstable, at a pre-registered `tau_b = 0.8` with 0.7/0.9 sensitivity reported.
218
+
219
+ **Internal** (from `metrics/extract_hidden.py` + `iss.py` + `kts.py`):
220
+
221
+ - **ISS** — same-fact cross-condition similarity, corrected against
222
+ same-relation background: `(S⁺ − S⁻)/(1 − S⁻)`. 0 means "no better than
223
+ background".
224
+ - **KTS-Geo** — Spearman between within-relation pairwise distance matrices
225
+ under two conditions; invariant to rotation, translation and isotropic
226
+ scaling. Reported as `(ρ+1)/2` in the summary files, so **its floor is 0.5** —
227
+ use the `kts_geo_raw_spearman` field for anything scale-sensitive.
228
+ - **KTS-ID** — chance-corrected cross-condition nearest-neighbour retrieval of
229
+ the fact itself among same-relation facts.
230
+
231
+ Layer window: `{l : l/(L−1) ≥ 0.4}` (protocol §7.10). Layer `l` is the *output*
232
+ of decoder block `l`, i.e. `hidden_states[l+1]` in HuggingFace indexing. The
233
+ `jlens_window` integers in `models.yaml` are a redundant assertion checked at
234
+ extraction time, not the definition.
235
+
236
+ `metrics/judge_run.py` clusters answers with an instruction-tuned judge
237
+ (default `Qwen/Qwen2.5-32B-Instruct`, ~65 GB). It shares pretraining lineage
238
+ with the four Qwen models in the evaluated set and may favour their phrasing;
239
+ `configs/models.yaml:auxiliary_models.judge.known_bias` records the mitigation.
240
+ The judge is never itself evaluated.
241
+
242
+ ---
243
+
244
+ ## Data schema
245
+
246
+ `benchmark_facts_2592.jsonl`
247
+
248
+ | field | type | notes |
249
+ |---|---|---|
250
+ | `fact_id` | str | `fact_000602` |
251
+ | `subject`, `object` | obj | `canonical`, `entity_id` (Wikidata Q-id), `aliases[]` |
252
+ | `relation` | obj | `relation_id`, `source_relations[]`, `direction` |
253
+ | `qualification_question` | str | canonical question; identical to the anchor query |
254
+ | `sources`, `source_records` | list | provenance |
255
+ | `is_functional` | bool | single-valued; true for all benchmark facts |
256
+ | `answer_type`, `answer_granularity` | str | drives the scorer's year/entity handling |
257
+ | `answer_in_subject_surface` | bool | **750 true** — see caveat 2 |
258
+ | `spec_6_2_flag` | bool | 846 true (`developer of` / `manufacturer of`) |
259
+
260
+ `evaluation_queries_44416.jsonl`
261
+
262
+ | field | type | notes |
263
+ |---|---|---|
264
+ | `query_id`, `fact_id`, `relation` | str | |
265
+ | `condition_family`, `variant_id`, `language` | str | |
266
+ | `query` | str | the surface form actually shown to the model |
267
+ | `target_slot` | str | `object`, or `subject` for reverse |
268
+ | `gold_canonical`, `gold_aliases[]` | str/list | what the scorer accepts |
269
+ | `is_assisted`, `is_well_posed` | bool | |
270
+ | `use_for_main_forward` / `_reverse_analysis` / `_recognition_analysis` | bool | see caveat 3 |
271
+ | `answer_in_subject_surface` | bool | inherited from the fact |
272
+
273
+ ---
274
+
275
+ ## Known deviations
276
+
277
+ Recorded in full in `protocol/reconstruction_differences.md`:
278
+
279
+ - **D1** — two `context` queries whose distractor literally contained the gold
280
+ string were removed by a rule-based guard: 44,418 → **44,416**. The spec
281
+ counts in `configs/eval_conditions.yaml` still read 44,418 and are reconciled
282
+ in that file's `accepted_deviations` block.
283
+ - **C1** — `developer of` / `manufacturer of` (846 facts) are flagged rather
284
+ than dropped; `relations.yaml:drop_spec_6_2_flagged` produces the compliant
285
+ 1,746-fact / 19-relation variant.
286
+ - **F1** — the 28.9% copy-answerable subset (caveat 2).
287
+ - **F2** — 808 exactly duplicated triples among the 8,107 candidates, absorbed
288
+ during entity-aware grouping.
289
+ - **N2** — `capital_of` direction is not normalised; annotated explicitly with
290
+ `direction: inverse` + `inverse_of: capital`.
291
+
292
+ ## Licence and attribution
293
+
294
+ Released under **CC BY 4.0**, inheriting the terms of its sources. Facts derive
295
+ from **CounterFact** (MIT), **LAMA / T-REx** (CC BY 4.0), **LAMA / Google-RE**,
296
+ **LAMA / ConceptNet**, and **PopQA** (MIT); entity ids and aliases come from
297
+ **Wikidata** (CC0). Please cite the original datasets alongside this one.
dataset_upload/configs/eval_conditions.yaml ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Evaluation condition registry (spec sections 2.3, 8, 9, 10).
2
+ #
3
+ # The per-query booleans use_for_main_forward / use_for_reverse_analysis /
4
+ # use_for_recognition_analysis are DERIVED from this file, so a downstream
5
+ # aggregation never has to hard-code which conditions belong in which average.
6
+ #
7
+ # Spec 2.3 / 16: recognition and reverse_illposed must never enter the main
8
+ # forward aggregation, and reverse is reported separately because it changes
9
+ # the target slot from object to subject.
10
+
11
+ conditions:
12
+ anchor:
13
+ role: main
14
+ target_slot: object
15
+ is_assisted: false
16
+ is_well_posed: true
17
+ use_for_main_forward: true
18
+ use_for_reverse_analysis: false
19
+ use_for_recognition_analysis: false
20
+ expected_queries: 2592
21
+ expected_facts: 2592
22
+ description: >
23
+ The canonical qualification question itself. Shares the prompt string with
24
+ the anchor qualification run, so per-condition retention is measured
25
+ against a real measured baseline rather than an assumed 1.0.
26
+
27
+ paraphrase:
28
+ role: main
29
+ target_slot: object
30
+ is_assisted: false
31
+ is_well_posed: true
32
+ use_for_main_forward: true
33
+ use_for_reverse_analysis: false
34
+ use_for_recognition_analysis: false
35
+ expected_queries: 10053
36
+ expected_facts: 2592
37
+ migrated_from: queryA_canonical
38
+ description: >
39
+ Lexical and syntactic rewording, same fact and same target slot.
40
+
41
+ format:
42
+ role: main
43
+ target_slot: object
44
+ is_assisted: false
45
+ is_well_posed: true
46
+ use_for_main_forward: true
47
+ use_for_reverse_analysis: false
48
+ use_for_recognition_analysis: false
49
+ expected_queries: 7776
50
+ expected_facts: 2592
51
+ migrated_from: queryB_paraphrase
52
+ excludes: [mcq]
53
+ description: >
54
+ Question or response format changes with no candidates exposed. MCQ rows
55
+ from the same source file are routed to `recognition` instead (spec 9.3).
56
+
57
+ context:
58
+ role: main
59
+ target_slot: object
60
+ is_assisted: false
61
+ is_well_posed: true
62
+ use_for_main_forward: true
63
+ use_for_reverse_analysis: false
64
+ use_for_recognition_analysis: false
65
+ expected_queries: 6831
66
+ expected_facts: 2591
67
+ migrated_from: queryD_context
68
+ description: >
69
+ Irrelevant or misleading context prepended; the intended query stays
70
+ unambiguous and the correct answer is unchanged.
71
+
72
+ multilingual:
73
+ role: main
74
+ target_slot: object
75
+ is_assisted: false
76
+ is_well_posed: true
77
+ use_for_main_forward: true
78
+ use_for_reverse_analysis: false
79
+ use_for_recognition_analysis: false
80
+ expected_queries: 12010
81
+ expected_facts: 2402
82
+ migrated_from: queryE_multilingual
83
+ languages: [zh, fr, es, de, ru]
84
+ description: >
85
+ Same factual question in another language. Query language is stored in
86
+ the `language` field.
87
+
88
+ reverse:
89
+ role: structural # reported separately, NOT in the main average
90
+ target_slot: subject
91
+ is_assisted: false
92
+ is_well_posed: true
93
+ use_for_main_forward: false
94
+ use_for_reverse_analysis: true
95
+ use_for_recognition_analysis: false
96
+ expected_queries: 634
97
+ expected_facts: 253
98
+ migrated_from: queryC_reverse
99
+ requires: is_inverse_well_posed
100
+ description: >
101
+ (o, r^-1) -> s. Only built where the inverse mapping is unique. Spec 2.3:
102
+ reported separately because the target slot changes.
103
+
104
+ recognition:
105
+ role: diagnostic
106
+ target_slot: object
107
+ is_assisted: true
108
+ is_well_posed: true
109
+ use_for_main_forward: false
110
+ use_for_reverse_analysis: false
111
+ use_for_recognition_analysis: true
112
+ expected_queries: 3412
113
+ expected_facts: 2585
114
+ migrated_from: queryB_paraphrase(fmt=mcq)
115
+ description: >
116
+ Multiple choice. Measures recognition, not unaided retrieval.
117
+
118
+ reverse_illposed:
119
+ role: diagnostic
120
+ target_slot: subject
121
+ is_assisted: false
122
+ is_well_posed: false
123
+ use_for_main_forward: false
124
+ use_for_reverse_analysis: false
125
+ use_for_recognition_analysis: false
126
+ expected_queries: 1110
127
+ expected_facts: 1110
128
+ migrated_from: queryC_reverse(not well_posed)
129
+ description: >
130
+ Reverse queries whose inverse mapping is one-to-many ("What was developed
131
+ by Apple?"). Diagnostic only; never scored in any headline number.
132
+
133
+ # These are the SPEC's counts, not the shipped file's. Two context queries were
134
+ # dropped by a rule-based guard (see accepted_deviations below and protocol
135
+ # reference D1), so evaluation_queries_44416.jsonl really holds 44,416 rows.
136
+ totals:
137
+ expected_total_queries: 44418
138
+ # anchor 2592 + paraphrase 10053 + format 7776 + context 6831 + multilingual 12010
139
+ expected_main_forward_queries: 39262
140
+ expected_benchmark_facts: 2592
141
+ expected_relations: 21
142
+
143
+ # Spec 11: a query is a duplicate when fact_id + normalized text + target slot +
144
+ # condition family all coincide.
145
+ deduplication:
146
+ key: [fact_id, normalized_query, target_slot, condition_family]
147
+ expected_removed_during_migration: 10323
148
+
149
+ # Deviations from the spec counts that have been investigated and written up in
150
+ # outputs/reconstruction_differences.md. Listing one here stops the build from
151
+ # failing on it; an UNLISTED deviation still fails, so a new regression cannot
152
+ # hide behind a documented one.
153
+ accepted_deviations:
154
+ - check: context.queries
155
+ actual: 6829
156
+ expected: 6831
157
+ ref: D1
158
+ - check: total_queries
159
+ actual: 44416
160
+ expected: 44418
161
+ ref: D1
162
+ - check: main_forward_queries
163
+ actual: 39260
164
+ expected: 39262
165
+ ref: D1
dataset_upload/configs/metrics.yaml ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # BCS / BES / ISS / KTS configuration.
2
+ #
3
+ # Protocol: protocol/evaluation_protocol.md
4
+ # J-Lens: protocol/jlens_spec.md
5
+ #
6
+ # Everything that a reviewer could accuse us of tuning post hoc lives here and
7
+ # is frozen before the final evaluation (J-Lens spec 13.3).
8
+
9
+ paths:
10
+ # Relative entries resolve against the repository root; absolute ones are
11
+ # used as-is. Both can be overridden without editing this file:
12
+ #
13
+ # FKS_DATA benchmark_facts_2592.jsonl + evaluation_queries_44416.jsonl
14
+ # FKS_OUTPUTS everything written by the runner and the metrics
15
+ # FKS_MODELS local directory holding model weights (optional, see below)
16
+ #
17
+ # Hidden states are large (~1.6-15 GB per model), so point FKS_OUTPUTS at a
18
+ # scratch volume rather than the repository checkout.
19
+ data: data
20
+ outputs: outputs
21
+
22
+ # ---- condition families -----------------------------------------------------
23
+ # Protocol 1.1. anchor is in T: it is one of the five main retrieval conditions
24
+ # for BCS/BES/ISS/KTS. (The construction-time retention report excluded it,
25
+ # because there it served as the denominator baseline -- a different role.)
26
+ #
27
+ # NOTE. anchor holds exactly one query per fact, so its within-family agreement
28
+ # is 1.0 by construction and it contributes a fixed 1/|T_f| to BCS. Drop it here
29
+ # to score the four perturbation families only; see protocol 4.3.
30
+ main_families: [anchor, paraphrase, format, context, multilingual]
31
+
32
+ # Protocol 1.3. Coverage is not identical across families (multilingual 2,402,
33
+ # context 2,591), so both readings are reported and neither is the silent
34
+ # default. complete_family = the 2,4xx facts carrying all five; full_set = each
35
+ # fact averaged over the families it actually has.
36
+ coverage_modes: [complete_family, full_set]
37
+ headline_coverage: complete_family
38
+
39
+ # ---- hidden state extraction ------------------------------------------------
40
+ extraction:
41
+ # Protocol 2.4: last valid input token, i.e. the model has read the question
42
+ # but has not emitted an answer token. Tokenizers use left padding so this is
43
+ # position -1 for every row in a batch.
44
+ position: query_end
45
+ dtype: float16 # storage only; the forward runs in bfloat16
46
+ batch_size: 64
47
+ max_prompt_len: 192 # same value eval_run.py uses, so prompts are identical
48
+ # Protocol 7.10: window = {l : d_l >= 0.4} with d_l = l/(L-1). Layer l means
49
+ # the OUTPUT of decoder block l, i.e. hidden_states[l+1] in HF indexing.
50
+ window_min_depth: 0.4
51
+ late_min_depth: 0.8 # protocol 7.10 "Late ISS"
52
+
53
+ # ---- ISS --------------------------------------------------------------------
54
+ iss:
55
+ whitening: pca # protocol 7.5
56
+ pca_dim: 512 # min(512, d_m)
57
+ shrinkage: 0.05 # lambda in (Sigma + lambda I)^-1/2, as a fraction of tr(Sigma)/d
58
+ eps: 1.0e-12
59
+ # Protocol 7.8: negatives are same-relation, different-fact. Sampling is fixed
60
+ # once and REUSED for every model, otherwise a model could look stable purely
61
+ # because it drew easier negatives.
62
+ max_negatives: 100
63
+ negative_seed: 20260101
64
+
65
+ # ---- KTS --------------------------------------------------------------------
66
+ kts:
67
+ min_facts_per_relation: 5 # protocol 9.1
68
+ eps: 1.0e-12
69
+
70
+ # ---- behavioural ------------------------------------------------------------
71
+ behavior:
72
+ tau_b: 0.8 # protocol 6, pre-registered
73
+ tau_sensitivity: [0.7, 0.8, 0.9] # protocol 6
74
+
75
+ # ---- statistics -------------------------------------------------------------
76
+ bootstrap:
77
+ n_resamples: 1000 # protocol 14.1
78
+ ci: 0.95
79
+ seed: 20260101
80
+
81
+ # ---- J-Lens estimator (spec 6, 7, 8) ---------------------------------------
82
+ jlens:
83
+ corpus:
84
+ name: NeelNanda/pile-10k # spec 13.1: general text, disjoint from the benchmark
85
+ n_prompts: 128 # spec 8.2 sweeps {32,64,128,256,512}; frozen after the sweep
86
+ seq_len: 128
87
+ seed: 20260101
88
+ estimator:
89
+ oversampling: 64 # spec 6.1 recommends p in {32,64}
90
+ power_iterations: 0
91
+ rank_grid: [64, 128, 256, 512, 1024] # spec 7.3, nested probes
92
+ seeds: [20260101, 20260102, 20260103] # spec 9: >= 3 sketch seeds
93
+ primary_seed: 20260101
94
+ # spec 7.3 / 17. Frozen BEFORE the final benchmark run; a model-layer that
95
+ # fails these is reported as unresolved rather than silently approximated.
96
+ thresholds:
97
+ action_cosine_median_min: 0.99
98
+ action_relative_error_median_max: 0.05
99
+ iss_rank_stability_max: 0.01
100
+ iss_seed_std_max: 0.005
101
+ validation:
102
+ n_held_out_activations: 128 # spec 7.2
103
+ layer_probe: [early, middle, late]
dataset_upload/configs/models.yaml ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model registry. Spec section 4.4: the filtering models must live in
2
+ # configuration rather than being hard-coded.
3
+ #
4
+ # The evaluated set is 5 families x 4 models: four size tiers, and four clean
5
+ # base<->instruct pairs spread across four different families.
6
+ #
7
+ # WEIGHTS. Each entry carries an `hf:` hub id, which is what the runner uses by
8
+ # default. To evaluate a model that is not listed here, either add an entry or
9
+ # pass `--model-path <dir or hub id>` to runner/eval_run.py. To use a local
10
+ # mirror of the listed models, set FKS_MODELS to a directory whose subdirectory
11
+ # names match each entry's `path:`, or uncomment `model_root` below.
12
+ #
13
+ # model_root: /path/to/your/weights
14
+ #
15
+ # `n_layers`, `d_model` and `jlens_window` are recorded for cross-model
16
+ # analysis; jlens_window is a redundant assertion checked at extraction time
17
+ # against layer_window() -- the binding definition is d_l = l/(L-1) >= 0.4
18
+ # (protocol 7.10), not this number.
19
+
20
+ # ---- Stage I: five-model first-token candidate recall -----------------------
21
+ # FROZEN. These five defined the 8,107-fact candidate pool that everything
22
+ # downstream rests on. Changing this list invalidates
23
+ # candidate_known_8107.jsonl and every artefact derived from it, so it must stay
24
+ # fixed even as the evaluated set grows.
25
+ filter_models:
26
+ - {name: Gemma-2-2B-it, path: Gemma-2-2B-it, revision: main}
27
+ - {name: Qwen2.5-7B, path: Qwen2.5-7B, revision: main}
28
+ - {name: Mistral-7B-v0.3, path: Mistral-7B-v0.3, revision: main}
29
+ - {name: Llama-3.1-8B, path: Llama-3.1-8B, revision: main}
30
+ - {name: Gemma-2-9B-it, path: Gemma-2-9B-it, revision: main}
31
+
32
+ # ---- Stage V/VI: the 20 evaluated models ------------------------------------
33
+ # Spec 7.1: qualification produces K_m LABELS only. Adding or removing a model
34
+ # here never changes the benchmark denominator (fixed at 2,592), so this list is
35
+ # safe to extend at any time without invalidating earlier results.
36
+ #
37
+ # n_layers / d_model / jlens_window come from MODEL_SELECTION_20.md, where
38
+ # window = number of layers with normalized depth >= 0.4.
39
+ evaluated_models:
40
+ # ---------------- Llama-3.x ----------------
41
+ - {name: Llama-3.2-1B, path: Llama-3.2-1B, hf: meta-llama/Llama-3.2-1B,
42
+ family: llama-3.x, tier: 1-5B, params_b: 1.24, tuning: base,
43
+ n_layers: 16, d_model: 2048, jlens_window: 10, revision: main}
44
+ - {name: Llama-3.2-3B, path: Llama-3.2-3B, hf: meta-llama/Llama-3.2-3B,
45
+ family: llama-3.x, tier: 1-5B, params_b: 3.21, tuning: base,
46
+ n_layers: 28, d_model: 3072, jlens_window: 17, revision: main}
47
+ - {name: Llama-3.1-8B, path: Llama-3.1-8B, hf: meta-llama/Llama-3.1-8B,
48
+ family: llama-3.x, tier: 5-9B, params_b: 8.03, tuning: base,
49
+ n_layers: 32, d_model: 4096, jlens_window: 19, revision: main,
50
+ pair: llama_8b}
51
+ - {name: Llama-3.1-8B-Instruct, path: Llama-3.1-8B-Instruct,
52
+ hf: meta-llama/Llama-3.1-8B-Instruct,
53
+ family: llama-3.x, tier: 5-9B, params_b: 8.03, tuning: instruct,
54
+ n_layers: 32, d_model: 4096, jlens_window: 19, revision: main,
55
+ pair: llama_8b}
56
+
57
+ # ---------------- Qwen2.5 ----------------
58
+ - {name: Qwen2.5-3B, path: Qwen2.5-3B, hf: Qwen/Qwen2.5-3B,
59
+ family: qwen2.5, tier: 1-5B, params_b: 3.09, tuning: base,
60
+ n_layers: 36, d_model: 2048, jlens_window: 22, revision: main}
61
+ - {name: Qwen2.5-7B, path: Qwen2.5-7B, hf: Qwen/Qwen2.5-7B,
62
+ family: qwen2.5, tier: 5-9B, params_b: 7.62, tuning: base,
63
+ n_layers: 28, d_model: 3584, jlens_window: 17, revision: main,
64
+ pair: qwen_7b}
65
+ - {name: Qwen2.5-7B-Instruct, path: Qwen2.5-7B-Instruct,
66
+ hf: Qwen/Qwen2.5-7B-Instruct,
67
+ family: qwen2.5, tier: 5-9B, params_b: 7.62, tuning: instruct,
68
+ n_layers: 28, d_model: 3584, jlens_window: 17, revision: main,
69
+ pair: qwen_7b}
70
+ - {name: Qwen2.5-32B, path: Qwen2.5-32B, hf: Qwen/Qwen2.5-32B,
71
+ family: qwen2.5, tier: 20B+, params_b: 32.76, tuning: base,
72
+ n_layers: 64, d_model: 5120, jlens_window: 38, revision: main}
73
+
74
+ # ---------------- Mistral ----------------
75
+ - {name: Mistral-7B-v0.3, path: Mistral-7B-v0.3, hf: mistralai/Mistral-7B-v0.3,
76
+ family: mistral, tier: 5-9B, params_b: 7.25, tuning: base,
77
+ n_layers: 32, d_model: 4096, jlens_window: 19, revision: main,
78
+ pair: mistral_7b}
79
+ - {name: Mistral-7B-Instruct-v0.3, path: Mistral-7B-Instruct-v0.3,
80
+ hf: mistralai/Mistral-7B-Instruct-v0.3,
81
+ family: mistral, tier: 5-9B, params_b: 7.25, tuning: instruct,
82
+ n_layers: 32, d_model: 4096, jlens_window: 19, revision: main,
83
+ pair: mistral_7b}
84
+ - {name: Mistral-Nemo-Base-2407, path: Mistral-Nemo-Base-2407,
85
+ hf: mistralai/Mistral-Nemo-Base-2407,
86
+ family: mistral, tier: 9-20B, params_b: 12.25, tuning: base,
87
+ n_layers: 40, d_model: 5120, jlens_window: 24, revision: main}
88
+ - {name: Mistral-Small-24B-Base-2501, path: Mistral-Small-24B-Base-2501,
89
+ hf: mistralai/Mistral-Small-24B-Base-2501,
90
+ family: mistral, tier: 20B+, params_b: 23.57, tuning: base,
91
+ n_layers: 40, d_model: 5120, jlens_window: 24, revision: main}
92
+
93
+ # ---------------- Gemma-2 ----------------
94
+ # Gemma-2 and OLMo-2 publish fp32 safetensors only; they are loaded with
95
+ # dtype=bfloat16, so on-disk size is ~2x the bf16 figure.
96
+ - {name: gemma-2-2b, path: gemma-2-2b, hf: google/gemma-2-2b,
97
+ family: gemma-2, tier: 1-5B, params_b: 2.61, tuning: base,
98
+ n_layers: 26, d_model: 2304, jlens_window: 16, revision: main}
99
+ - {name: gemma-2-9b, path: gemma-2-9b, hf: google/gemma-2-9b,
100
+ family: gemma-2, tier: 9-20B, params_b: 9.24, tuning: base,
101
+ n_layers: 42, d_model: 3584, jlens_window: 25, revision: main,
102
+ pair: gemma_9b}
103
+ - {name: Gemma-2-9B-it, path: Gemma-2-9B-it, hf: google/gemma-2-9b-it,
104
+ family: gemma-2, tier: 9-20B, params_b: 9.24, tuning: instruct,
105
+ n_layers: 42, d_model: 3584, jlens_window: 25, revision: main,
106
+ pair: gemma_9b}
107
+ - {name: gemma-2-27b, path: gemma-2-27b, hf: google/gemma-2-27b,
108
+ family: gemma-2, tier: 20B+, params_b: 27.23, tuning: base,
109
+ n_layers: 46, d_model: 4608, jlens_window: 28, revision: main}
110
+
111
+ # ---------------- OLMo-2 ----------------
112
+ # The only family with all four tiers AND fully public pretraining data, which
113
+ # is what makes "the model never saw this fact" separable from "the model
114
+ # cannot retrieve it".
115
+ - {name: OLMo-2-0425-1B, path: OLMo-2-0425-1B, hf: allenai/OLMo-2-0425-1B,
116
+ family: olmo-2, tier: 1-5B, params_b: 1.48, tuning: base,
117
+ n_layers: 16, d_model: 2048, jlens_window: 10, revision: main}
118
+ - {name: OLMo-2-1124-7B, path: OLMo-2-1124-7B, hf: allenai/OLMo-2-1124-7B,
119
+ family: olmo-2, tier: 5-9B, params_b: 7.30, tuning: base,
120
+ n_layers: 32, d_model: 4096, jlens_window: 19, revision: main}
121
+ - {name: OLMo-2-1124-13B, path: OLMo-2-1124-13B, hf: allenai/OLMo-2-1124-13B,
122
+ family: olmo-2, tier: 9-20B, params_b: 13.72, tuning: base,
123
+ n_layers: 40, d_model: 5120, jlens_window: 24, revision: main}
124
+ - {name: OLMo-2-0325-32B, path: OLMo-2-0325-32B, hf: allenai/OLMo-2-0325-32B,
125
+ family: olmo-2, tier: 20B+, params_b: 32.23, tuning: base,
126
+ n_layers: 64, d_model: 5120, jlens_window: 38, revision: main}
127
+
128
+ # ---- base <-> instruct pairs (MODEL_SELECTION_20.md section 4) --------------
129
+ # Same weights lineage, same tokenizer, same size; only post-training differs.
130
+ # If BES improves while ISS does not, instruction tuning stabilised EXPRESSION
131
+ # rather than KNOWLEDGE.
132
+ tuning_pairs:
133
+ llama_8b: {base: Llama-3.1-8B, instruct: Llama-3.1-8B-Instruct, family: llama-3.x, tier: 5-9B}
134
+ qwen_7b: {base: Qwen2.5-7B, instruct: Qwen2.5-7B-Instruct, family: qwen2.5, tier: 5-9B}
135
+ mistral_7b: {base: Mistral-7B-v0.3, instruct: Mistral-7B-Instruct-v0.3, family: mistral, tier: 5-9B}
136
+ gemma_9b: {base: gemma-2-9b, instruct: Gemma-2-9B-it, family: gemma-2, tier: 9-20B}
137
+
138
+ # ---- models that do NOT occupy an evaluated slot ----------------------------
139
+ auxiliary_models:
140
+ stage_a_calibration:
141
+ name: Qwen2.5-0.5B
142
+ path: Qwen2.5-0.5B
143
+ hf: Qwen/Qwen2.5-0.5B
144
+ params_b: 0.49
145
+ n_layers: 24
146
+ d_model: 896
147
+ reason: exact full-matrix reference for J-Lens (J-Lens spec section 5)
148
+ judge:
149
+ name: Qwen2.5-32B-Instruct
150
+ path: Qwen2.5-32B-Instruct
151
+ hf: Qwen/Qwen2.5-32B-Instruct
152
+ params_b: 32.76
153
+ n_layers: 64
154
+ d_model: 5120
155
+ reason: semantic clustering judge (evaluation protocol section 3)
156
+ # Must be instruct (structured JSON output) and multilingual-strong: 12,010
157
+ # of 44,416 queries are zh/fr/es/de/ru.
158
+ known_bias: >
159
+ shares pretraining lineage with the four evaluated Qwen models and may
160
+ systematically favour their phrasing. Mitigation: agreement check against
161
+ src/scoring_full.py on a stratified sample, and optionally a second judge
162
+ (gemma-2-27b-it) on a subsample. The judge is never itself evaluated.
163
+
164
+ # ---- excluded, with reasons (MODEL_SELECTION_20.md section 9) ---------------
165
+ excluded_models:
166
+ - {name: Llama-3.1-70B, reason: "bf16 weights 141 GB vs 143 GB H200; quantisation would alter hidden states and break ISS/KTS comparability"}
167
+ - {name: Qwen2.5-14B, reason: "could fill 9-20B but dropped to keep families balanced at 4 each; that tier still has 3 base models. Weights remain under Model/ but are not evaluated."}
168
+ - {name: Llama-2-13B, reason: "different generation from Llama-3; mixing would break the family axis"}
169
+ - {name: Phi-3/Phi-4, reason: "heavily synthetic training data; atypical knowledge profile"}
170
+ - {name: Yi/InternLM/GLM, reason: "adds family breadth but no new scientific axis"}
171
+
172
+ # ---- Stage V/VI generation configuration (spec section 7.3) -----------------
173
+ generation:
174
+ do_sample: false
175
+ num_beams: 1
176
+ temperature: 0.0
177
+ max_new_tokens: 24
178
+ max_prompt_len: 96
179
+ batch_size: 96
180
+ dtype: bfloat16
181
+ # Spec 7.2: identical raw prompt string for base and instruct models, so no
182
+ # chat template is ever applied. This matters more with 4 instruct models in
183
+ # the set: giving only those a chat template would confound tuning with format.
184
+ use_chat_template: false
185
+ seed: 20260101
dataset_upload/configs/relations.yaml ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Relation registry for the benchmark (spec sections 2.2, 5.4, 6.2).
2
+ #
3
+ # Per relation:
4
+ # relation_id canonical snake_case name used in outputs
5
+ # source_relations Wikidata property ids (or source-native names) that map here
6
+ # direction forward = subject + relation -> object, matching spec 2.2.
7
+ # inverse = the source stores the pair the other way round.
8
+ # is_functional the object is single- or approximately single-valued
9
+ # is_inverse_well_posed object determines subject uniquely -> reverse queries
10
+ # are meaningful; false means reverse goes to reverse_illposed
11
+ # answer_type / answer_granularity drive scoring and reporting breakdowns
12
+ # qualification canonical anchor question, slot {s}. Verified NOT to collide
13
+ # with any evaluation perturbation template (spec 16).
14
+ # spec_6_2_flag set when spec section 6.2 names this relation as unsuitable
15
+ # while the required count of 2,592 needs it. See
16
+ # outputs/reconstruction_differences.md.
17
+
18
+ # Global switches ------------------------------------------------------------
19
+ options:
20
+ # Spec 2.2 forbids mixing triple directions. P1376 ("X is the capital of Y")
21
+ # is stored inverse to P36. Flipping it merges those facts into `capital` and
22
+ # changes the benchmark size, which spec 10 forbids doing silently. Default
23
+ # false reproduces 2,592; set true only together with a差异 entry.
24
+ normalize_inverse_direction: false
25
+ # Spec 6.2 lists developer/manufacturer as unsuitable, but excluding them
26
+ # cannot reach the required 2,592. Default false keeps them and flags them.
27
+ drop_spec_6_2_flagged: false
28
+
29
+ relations:
30
+ - relation_id: native_language
31
+ source_relations: [P103]
32
+ direction: forward
33
+ is_functional: true
34
+ is_inverse_well_posed: false
35
+ answer_type: language
36
+ answer_granularity: entity
37
+ qualification: "Which language did {s} grow up speaking?"
38
+
39
+ - relation_id: manufacturer
40
+ source_relations: [P176]
41
+ direction: forward
42
+ is_functional: true
43
+ is_inverse_well_posed: false
44
+ answer_type: organization
45
+ answer_granularity: entity
46
+ qualification: "Which company builds {s}?"
47
+ spec_6_2_flag: unsuitable_named_in_spec
48
+
49
+ - relation_id: developer
50
+ source_relations: [P178]
51
+ direction: forward
52
+ is_functional: true
53
+ is_inverse_well_posed: false
54
+ answer_type: organization
55
+ answer_granularity: entity
56
+ qualification: "Which company or person created {s}?"
57
+ spec_6_2_flag: unsuitable_named_in_spec
58
+
59
+ - relation_id: country
60
+ source_relations: [P17]
61
+ direction: forward
62
+ is_functional: true
63
+ is_inverse_well_posed: false
64
+ answer_type: country
65
+ answer_granularity: entity
66
+ qualification: "Which country does {s} belong to?"
67
+
68
+ - relation_id: original_network
69
+ source_relations: [P449]
70
+ direction: forward
71
+ is_functional: true
72
+ is_inverse_well_posed: false
73
+ answer_type: organization
74
+ answer_granularity: entity
75
+ qualification: "Which network first broadcast {s}?"
76
+
77
+ - relation_id: headquarters_location
78
+ source_relations: [P159]
79
+ direction: forward
80
+ is_functional: true
81
+ is_inverse_well_posed: false
82
+ answer_type: city
83
+ answer_granularity: entity
84
+ qualification: "Which city hosts the main offices of {s}?"
85
+
86
+ - relation_id: capital
87
+ source_relations: [P36]
88
+ direction: forward
89
+ is_functional: true
90
+ is_inverse_well_posed: true
91
+ answer_type: city
92
+ answer_granularity: entity
93
+ qualification: "Which city is the seat of government of {s}?"
94
+
95
+ - relation_id: capital_of
96
+ source_relations: [P1376]
97
+ direction: inverse # stored as (city, capital_of, country)
98
+ inverse_of: capital
99
+ is_functional: true
100
+ is_inverse_well_posed: true
101
+ answer_type: country
102
+ answer_granularity: entity
103
+ qualification: "{s} is the capital city of which country?"
104
+
105
+ - relation_id: owned_by
106
+ source_relations: [P127]
107
+ direction: forward
108
+ is_functional: true
109
+ is_inverse_well_posed: false
110
+ answer_type: organization
111
+ answer_granularity: entity
112
+ qualification: "Who is the owner of {s}?"
113
+
114
+ - relation_id: sport
115
+ source_relations: [P641]
116
+ direction: forward
117
+ is_functional: true
118
+ is_inverse_well_posed: false
119
+ answer_type: sport
120
+ answer_granularity: entity
121
+ qualification: "Which sport is {s} associated with?"
122
+
123
+ - relation_id: continent
124
+ source_relations: [P30]
125
+ direction: forward
126
+ is_functional: true
127
+ is_inverse_well_posed: false
128
+ answer_type: place
129
+ answer_granularity: entity
130
+ qualification: "Which continent is {s} part of?"
131
+
132
+ - relation_id: religion
133
+ source_relations: [P140]
134
+ direction: forward
135
+ is_functional: true
136
+ is_inverse_well_posed: false
137
+ answer_type: religion
138
+ answer_granularity: entity
139
+ qualification: "Which faith does {s} follow?"
140
+
141
+ - relation_id: applies_to_jurisdiction
142
+ source_relations: [P1001]
143
+ direction: forward
144
+ is_functional: true
145
+ is_inverse_well_posed: false
146
+ answer_type: place
147
+ answer_granularity: entity
148
+ qualification: "Which jurisdiction does {s} have legal force in?"
149
+
150
+ - relation_id: location
151
+ source_relations: [P276]
152
+ direction: forward
153
+ is_functional: true
154
+ is_inverse_well_posed: false
155
+ answer_type: place
156
+ answer_granularity: entity
157
+ qualification: "At which location can {s} be found?"
158
+
159
+ - relation_id: country_of_origin
160
+ source_relations: [P495]
161
+ direction: forward
162
+ is_functional: true
163
+ is_inverse_well_posed: false
164
+ answer_type: country
165
+ answer_granularity: entity
166
+ qualification: "Which country did {s} originate from?"
167
+
168
+ - relation_id: place_of_death
169
+ source_relations: [P20]
170
+ direction: forward
171
+ is_functional: true
172
+ is_inverse_well_posed: false
173
+ answer_type: city
174
+ answer_granularity: entity
175
+ qualification: "At which place did {s} pass away?"
176
+
177
+ - relation_id: place_of_birth
178
+ source_relations: [P19]
179
+ direction: forward
180
+ is_functional: true
181
+ is_inverse_well_posed: false
182
+ answer_type: city
183
+ answer_granularity: entity
184
+ qualification: "In which place did {s} come into the world?"
185
+
186
+ - relation_id: located_in
187
+ source_relations: [P131]
188
+ direction: forward
189
+ is_functional: true
190
+ is_inverse_well_posed: false
191
+ answer_type: place
192
+ answer_granularity: entity
193
+ qualification: "Which administrative region contains {s}?"
194
+
195
+ - relation_id: position_played
196
+ source_relations: [P413]
197
+ direction: forward
198
+ is_functional: true
199
+ is_inverse_well_posed: false
200
+ answer_type: occupation
201
+ answer_granularity: entity
202
+ qualification: "On the field, which position is {s} assigned to?"
203
+
204
+ - relation_id: location_of_formation
205
+ source_relations: [P740]
206
+ direction: forward
207
+ is_functional: true
208
+ is_inverse_well_posed: false
209
+ answer_type: city
210
+ answer_granularity: entity
211
+ qualification: "{s} came into existence in which place?"
212
+
213
+ - relation_id: father
214
+ source_relations: [P22]
215
+ direction: forward
216
+ is_functional: true
217
+ is_inverse_well_posed: false
218
+ answer_type: person
219
+ answer_granularity: entity
220
+ qualification: "{s} is the child of which father?"
221
+
222
+ # Relations present in the enriched pool but EXCLUDED from the benchmark because
223
+ # the object is genuinely multi-valued, so an accepted-answer set can never be
224
+ # exhaustive (spec 6.2). Kept here for auditability.
225
+ excluded_multi_valued:
226
+ - {source_relations: [P37], reason: official language}
227
+ - {source_relations: [P106], reason: occupation}
228
+ - {source_relations: [P27], reason: country of citizenship}
229
+ - {source_relations: [P31], reason: instance of}
230
+ - {source_relations: [P279], reason: subclass of}
231
+ - {source_relations: [P101], reason: field of work}
232
+ - {source_relations: [P108], reason: employer}
233
+ - {source_relations: [P463], reason: member of}
234
+ - {source_relations: [P1303], reason: instrument}
235
+ - {source_relations: [P364], reason: original language}
236
+ - {source_relations: [P407], reason: language of work}
237
+ - {source_relations: [P1412], reason: language spoken}
238
+ - {source_relations: [P50, P57, P58, P86, P162], reason: creator roles}
239
+ - {source_relations: [P190], reason: twinned city}
240
+ - {source_relations: [P47], reason: shares border with}
241
+ - {source_relations: [P527], reason: has part}
242
+ - {source_relations: [P264], reason: record label}
243
+ - {source_relations: [P462], reason: colour}
244
+ - {source_relations: [P937], reason: work location}
245
+ - {source_relations: [P136], reason: genre}
246
+ - {source_relations: [P25], reason: mother}
247
+ - {source_relations: [IsA, UsedFor, AtLocation, HasA, HasProperty, CapableOf,
248
+ PartOf, Causes, CausesDesire, Desires, NotDesires,
249
+ HasSubevent, HasPrerequisite, MotivatedByGoal, MadeOf,
250
+ ReceivesAction],
251
+ reason: ConceptNet open-world commonsense}
252
+
253
+ # Relations excluded because they belong to non-core sources (spec 6.1)
254
+ excluded_non_core:
255
+ - {source_relations: [date_of_birth, place_of_birth, place_of_death],
256
+ source: lama_googlere, reason: not a core source}
dataset_upload/data/benchmark_facts_2592.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
dataset_upload/data/evaluation_queries_44416.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e50fdc64b962a1f4a532f7b72e62a04f67d363ba80e58f000f4985dcdb1f1c8
3
+ size 41495062
dataset_upload/metrics/bcs_bes.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """BCS and BES from the judge's semantic clusters. (protocol 4, 5, 6)
3
+
4
+ python src/bcs_bes.py --model Llama-3.2-1B
5
+
6
+ Family-balanced, per protocol 4.1: the distribution over answer clusters is
7
+ computed WITHIN each condition family first, then the families are averaged with
8
+ equal weight. Counting raw queries instead would let paraphrase (10,053) and
9
+ multilingual (12,010) drown out anchor (2,592), and the headline number would
10
+ mostly measure how many variants we happened to write.
11
+
12
+ p(a) = mean over families of (share of that family's queries in cluster a)
13
+ BCS = max_a p(a)
14
+ BES = 1 - H(p)/log A (1 when only one cluster was observed)
15
+
16
+ BCS deliberately does not consult correctness: a model that answers "Sydney" for
17
+ every phrasing of Australia's capital scores BCS = 1. That is the point --
18
+ protocol 6 then splits stable behaviour into Stable Correct and Stable Wrong
19
+ using the judge's reference-aware pass.
20
+ """
21
+ import os, sys, math, argparse, collections
22
+
23
+ import numpy as np
24
+
25
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
26
+ import mcommon as mc
27
+
28
+
29
+ def bcs_bes(assignments, families):
30
+ """assignments: [(condition_family, cluster_id)] for one fact."""
31
+ counts = collections.defaultdict(collections.Counter)
32
+ for fam, cid in assignments:
33
+ counts[fam][cid] += 1
34
+ valid = [t for t in families if counts[t]]
35
+ if not valid:
36
+ return None
37
+ clusters = {c for t in valid for c in counts[t]}
38
+ p = {c: sum(counts[t][c] / sum(counts[t].values()) for t in valid) / len(valid)
39
+ for c in clusters}
40
+ modal = max(p, key=p.get)
41
+ pos = [v for v in p.values() if v > 0]
42
+ if len(pos) == 1:
43
+ bes = 1.0
44
+ else:
45
+ H = -sum(v * math.log(v) for v in pos)
46
+ bes = 1.0 - H / math.log(len(pos))
47
+ return {"bcs": p[modal], "bes": bes, "modal_cluster": modal,
48
+ "cluster_distribution": p, "valid_families": valid}
49
+
50
+
51
+ def main():
52
+ ap = argparse.ArgumentParser()
53
+ ap.add_argument("--model", required=True)
54
+ ap.add_argument("--coverage", choices=["complete_family", "full_set"], default=None)
55
+ ap.add_argument("--sample", type=int, default=0,
56
+ help="score only the same fixed subset judge_run.py sampled")
57
+ ap.add_argument("--sample-seed", type=int, default=20260101)
58
+ args = ap.parse_args()
59
+
60
+ C = mc.cfg()
61
+ mode = args.coverage or C["headline_coverage"]
62
+ fams = C["main_families"]
63
+ tau = C["behavior"]["tau_b"]
64
+ keep = set(mc.eval_fact_set(mode))
65
+ if args.sample:
66
+ # Reproduce judge_run.py's draw exactly. A judge file can hold extra
67
+ # facts -- a debug run, or a --resume over an earlier partial pass --
68
+ # and scoring whatever happens to be in the file would give different
69
+ # models different fact sets, which protocol 1.3 forbids.
70
+ allf = sorted(mc.facts())
71
+ rng = np.random.default_rng(args.sample_seed)
72
+ pick = set(np.array(allf)[rng.choice(len(allf), size=args.sample,
73
+ replace=False)].tolist())
74
+ keep &= pick
75
+ rel_of = mc.fact_relation()
76
+
77
+ jpath = mc.out("metrics", "judge", f"{args.model}.jsonl")
78
+ if not os.path.exists(jpath):
79
+ raise SystemExit(f"no judge output for {args.model}; run src/judge_run.py")
80
+
81
+ per_fact, groups = [], collections.Counter()
82
+ for rec in mc.read_jsonl(jpath):
83
+ fid = rec["fact_id"]
84
+ if fid not in keep:
85
+ continue
86
+ label = {c["cluster_id"]: c for c in rec["clusters"]}
87
+ res = bcs_bes([(a["condition_family"], a["cluster_id"])
88
+ for a in rec["assignments"]], fams)
89
+ if res is None:
90
+ continue
91
+ modal = label.get(res["modal_cluster"], {})
92
+ correctness = modal.get("correctness", "REVIEW_REQUIRED")
93
+ status = modal.get("status", "ANSWER")
94
+ # Protocol 6: the four behaviour groups partition the fact set, so every
95
+ # fact lands in exactly one and the four rates sum to 1.
96
+ if res["bcs"] < tau:
97
+ grp = "Unstable"
98
+ elif status == "ABSTAIN" or correctness == "ABSTAIN":
99
+ grp = "Stable Abstention"
100
+ elif correctness == "CORRECT":
101
+ grp = "Stable Correct"
102
+ elif correctness == "INCORRECT":
103
+ grp = "Stable Wrong"
104
+ else:
105
+ grp = "Stable Unresolved"
106
+ groups[grp] += 1
107
+ per_fact.append({"model": args.model, "fact_id": fid, "relation": rel_of[fid],
108
+ "bcs": res["bcs"], "bes": res["bes"],
109
+ "modal_cluster": res["modal_cluster"],
110
+ "modal_correctness": correctness, "behavior_group": grp,
111
+ "valid_families": res["valid_families"]})
112
+
113
+ if not per_fact:
114
+ raise SystemExit(f"{args.model}: no facts scored")
115
+ mc.write_jsonl(mc.out("metrics", "behavioral", f"{args.model}.{mode}.per_fact.jsonl"),
116
+ per_fact)
117
+
118
+ n = len(per_fact)
119
+ bs = C["bootstrap"]
120
+ boot_bcs = mc.relation_clustered_bootstrap(
121
+ {r["fact_id"]: r["bcs"] for r in per_fact}, rel_of,
122
+ bs["n_resamples"], bs["seed"], bs["ci"])
123
+ boot_bes = mc.relation_clustered_bootstrap(
124
+ {r["fact_id"]: r["bes"] for r in per_fact}, rel_of,
125
+ bs["n_resamples"], bs["seed"], bs["ci"])
126
+
127
+ # Protocol 6: threshold sensitivity, because tau_b = 0.8 is a choice.
128
+ sens = {}
129
+ for t in C["behavior"]["tau_sensitivity"]:
130
+ sens[str(t)] = {"stable_rate": float(np.mean([r["bcs"] >= t for r in per_fact])),
131
+ "stable_correct": float(np.mean(
132
+ [r["bcs"] >= t and r["modal_correctness"] == "CORRECT"
133
+ for r in per_fact]))}
134
+
135
+ summary = {
136
+ "model": args.model, "coverage_mode": mode, "n_facts": n, "tau_b": tau,
137
+ "bcs": boot_bcs["mean"], "bcs_ci95": [boot_bcs["lo"], boot_bcs["hi"]],
138
+ "bes": boot_bes["mean"], "bes_ci95": [boot_bes["lo"], boot_bes["hi"]],
139
+ "stable_correct_rate": groups["Stable Correct"] / n,
140
+ "stable_wrong_rate": groups["Stable Wrong"] / n,
141
+ "stable_abstention_rate": groups["Stable Abstention"] / n,
142
+ "stable_unresolved_rate": groups["Stable Unresolved"] / n,
143
+ "unstable_rate": groups["Unstable"] / n,
144
+ "behavior_counts": dict(groups),
145
+ "tau_sensitivity": sens,
146
+ }
147
+ tot = sum(summary[k] for k in ("stable_correct_rate", "stable_wrong_rate",
148
+ "stable_abstention_rate", "stable_unresolved_rate",
149
+ "unstable_rate"))
150
+ if abs(tot - 1.0) > 1e-6:
151
+ raise SystemExit(f"behaviour rates sum to {tot}, not 1 (protocol 6)")
152
+ mc.write_json(mc.out("metrics", "behavioral", f"{args.model}.{mode}.summary.json"),
153
+ summary)
154
+ print(f"[{args.model}] BCS={summary['bcs']:.4f} BES={summary['bes']:.4f} "
155
+ f"SC={summary['stable_correct_rate']:.3f} SW={summary['stable_wrong_rate']:.3f} "
156
+ f"SA={summary['stable_abstention_rate']:.3f} "
157
+ f"U={summary['unstable_rate']:.3f} n={n} BCSBES_DONE")
158
+
159
+
160
+ if __name__ == "__main__":
161
+ main()
dataset_upload/metrics/extract_hidden.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Query-end residual states for the main-forward queries. [GPU]
3
+
4
+ python src/extract_hidden.py --model Llama-3.2-1B
5
+
6
+ Protocol 2.4 fixes the probe position:
7
+
8
+ the last valid input token -- the model has read the question but has not
9
+ yet emitted an answer token
10
+
11
+ which is exactly the prefill position that produces the first generated token
12
+ in eval_run.py. The prompt string is therefore built by importing eval_run's own
13
+ `build_prompt`, not by re-deriving it here: if the two ever diverged, ISS would
14
+ be measured on a different question than BCS/BES, and nothing downstream would
15
+ notice.
16
+
17
+ Only decoder blocks inside the J-Lens analysis window (protocol 7.10,
18
+ d_l = l/(L-1) >= 0.4) are stored. Layer `l` is the OUTPUT of block l, so the
19
+ last stored layer, l = L-1, is the final residual stream that J-Lens transports
20
+ into.
21
+
22
+ Output, per model:
23
+
24
+ outputs/hidden/<model>/L###.npy float16 [n_queries, d]
25
+ outputs/hidden/<model>/index.json query order + layer list + checksums
26
+ """
27
+ import os, sys, json, time, argparse, hashlib
28
+
29
+ import numpy as np
30
+ import torch
31
+ from transformers import AutoModelForCausalLM, AutoTokenizer
32
+
33
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
34
+ import mcommon as mc
35
+
36
+ # eval_run.py owns the prompt format; import it so there is exactly one copy.
37
+ sys.path.insert(0, mc.runner_dir())
38
+ from eval_run import build_prompt # noqa: E402
39
+
40
+
41
+ def decoder_layers(model):
42
+ """The block list, across Llama / Qwen2 / Mistral / Gemma2 / OLMo2."""
43
+ for attr in ("model.layers", "model.decoder.layers", "transformer.h"):
44
+ obj = model
45
+ try:
46
+ for part in attr.split("."):
47
+ obj = getattr(obj, part)
48
+ if isinstance(obj, torch.nn.ModuleList) and len(obj):
49
+ return obj
50
+ except AttributeError:
51
+ continue
52
+ raise SystemExit(f"cannot locate decoder blocks on {type(model).__name__}")
53
+
54
+
55
+ def main():
56
+ ap = argparse.ArgumentParser()
57
+ ap.add_argument("--model", required=True)
58
+ ap.add_argument("--batch", type=int, default=0)
59
+ ap.add_argument("--limit", type=int, default=0, help="debug: first N queries")
60
+ ap.add_argument("--force", action="store_true")
61
+ args = ap.parse_args()
62
+
63
+ conf = mc.cfg()["extraction"]
64
+ entry = mc.model_entry(args.model)
65
+ dest = mc.out("hidden", args.model)
66
+ os.makedirs(dest, exist_ok=True)
67
+ index_path = os.path.join(dest, "index.json")
68
+ if os.path.exists(index_path) and not args.force:
69
+ if json.load(open(index_path)).get("complete"):
70
+ print(f"[{args.model}] already extracted; --force to redo")
71
+ return
72
+
73
+ rows = mc.main_forward_queries()
74
+ if args.limit:
75
+ rows = rows[:args.limit]
76
+ N = len(rows)
77
+
78
+ path = mc.model_path(args.model)
79
+ tok = AutoTokenizer.from_pretrained(path)
80
+ if tok.pad_token is None:
81
+ tok.pad_token = tok.eos_token
82
+ # Left padding is what makes position -1 the last REAL token for every row
83
+ # in a ragged batch; with right padding it would be a pad token.
84
+ tok.padding_side = "left"
85
+ tok.truncation_side = "left"
86
+ model = AutoModelForCausalLM.from_pretrained(
87
+ path, dtype=torch.bfloat16, device_map={"": 0}).eval()
88
+
89
+ blocks = decoder_layers(model)
90
+ L = len(blocks)
91
+ if L != entry.get("n_layers", L):
92
+ raise SystemExit(f"{args.model}: config.json has {L} layers but "
93
+ f"models.yaml says {entry['n_layers']}")
94
+ d = int(model.config.hidden_size)
95
+ window = mc.layer_window(L)
96
+ if len(window) != entry.get("jlens_window", len(window)):
97
+ raise SystemExit(f"{args.model}: computed window {len(window)} layers "
98
+ f"but models.yaml says {entry['jlens_window']}")
99
+ print(f"[{args.model}] L={L} d={d} window={window[0]}..{window[-1]} "
100
+ f"({len(window)} layers) N={N}", flush=True)
101
+
102
+ stores = {l: np.lib.format.open_memmap(
103
+ os.path.join(dest, f"L{l:03d}.npy"), mode="w+",
104
+ dtype=np.float16, shape=(N, d)) for l in window}
105
+
106
+ grabbed = {}
107
+
108
+ def make_hook(l):
109
+ def hook(_module, _inp, output):
110
+ h = output[0] if isinstance(output, tuple) else output
111
+ # Detach immediately and keep only the probe position, otherwise the
112
+ # full [B, T, d] activation for every window layer stays alive.
113
+ grabbed[l] = h[:, -1, :].detach().float()
114
+ return hook
115
+
116
+ handles = [blocks[l].register_forward_hook(make_hook(l)) for l in window]
117
+
118
+ prompts = [build_prompt(r) for r in rows]
119
+ B = args.batch or conf["batch_size"]
120
+ max_len = conf["max_prompt_len"]
121
+ # Length-sorted batching keeps padding low; `order` maps back to row index.
122
+ order = sorted(range(N), key=lambda i: len(prompts[i]))
123
+ t0 = time.time()
124
+ with torch.no_grad():
125
+ for b in range(0, N, B):
126
+ idx = order[b:b + B]
127
+ enc = tok([prompts[i] for i in idx], return_tensors="pt", padding=True,
128
+ truncation=True, max_length=max_len).to(0)
129
+ grabbed.clear()
130
+ model(**enc, use_cache=False)
131
+ for l in window:
132
+ stores[l][idx] = grabbed[l].to(torch.float16).cpu().numpy()
133
+ if b % (B * 40) == 0:
134
+ done = b + len(idx)
135
+ print(f" {done}/{N} {done / max(time.time() - t0, 1e-9):.1f}/s",
136
+ flush=True)
137
+ for h in handles:
138
+ h.remove()
139
+ for l in window:
140
+ stores[l].flush()
141
+
142
+ meta = {
143
+ "model": args.model,
144
+ "complete": True,
145
+ "n_queries": N,
146
+ "n_layers": L,
147
+ "d_model": d,
148
+ "window": window,
149
+ "window_depths": [round(l / max(L - 1, 1), 4) for l in window],
150
+ "late_window": mc.late_window(L),
151
+ "position": conf["position"],
152
+ "dtype": "float16",
153
+ "max_prompt_len": max_len,
154
+ "batch_size": B,
155
+ "seconds": round(time.time() - t0, 1),
156
+ # The query order is the contract between this file and every consumer;
157
+ # the hash lets a consumer prove it is reading the same ordering.
158
+ "query_ids": [r["query_id"] for r in rows],
159
+ "fact_ids": [r["fact_id"] for r in rows],
160
+ "families": [r["condition_family"] for r in rows],
161
+ "query_order_sha256": hashlib.sha256(
162
+ "\n".join(r["query_id"] for r in rows).encode()).hexdigest(),
163
+ }
164
+ mc.write_json(index_path, meta)
165
+ gb = N * len(window) * d * 2 / 1e9
166
+ print(f"[{args.model}] wrote {len(window)} layers x {N} x {d} "
167
+ f"({gb:.1f} GB) {meta['seconds']}s EXTRACT_DONE", flush=True)
168
+
169
+
170
+ if __name__ == "__main__":
171
+ main()
dataset_upload/metrics/iss.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """ISS: Internal State Stability. (protocol 7, J-Lens spec 10)
3
+
4
+ python src/iss.py --model Llama-3.2-1B --transport raw # ablation
5
+ python src/iss.py --model Llama-3.2-1B --transport jlens # official
6
+
7
+ The state preparation (transport -> residualise -> whiten -> family centroid)
8
+ lives in states.py so that ISS and KTS provably score the same vectors. What is
9
+ here is only the ISS-specific part:
10
+
11
+ S+ same fact, across condition-family pairs
12
+ S- same relation, different fact, symmetric in the family pair
13
+ ISS = (S+ - S-) / (1 - S- + eps)
14
+
15
+ Raw-ISS is NOT the official metric (J-Lens spec 11). It exists to prove the
16
+ data loading, family aggregation and negative sampling are right before the
17
+ Jacobian transport is layered on top (spec 21, step 1).
18
+ """
19
+ import os, sys, time, argparse
20
+
21
+ import numpy as np
22
+ import torch
23
+
24
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
25
+ import mcommon as mc
26
+ from states import StateLoader
27
+
28
+
29
+ def iss_one_layer(V, mask, by_rel, negatives, eps):
30
+ """S+, S- and ISS for every fact at one layer."""
31
+ F, T, _ = V.shape
32
+ dev = V.device
33
+ s_pos = torch.zeros(F, device=dev)
34
+ s_neg = torch.zeros(F, device=dev)
35
+ n_pos = torch.zeros(F, device=dev)
36
+ n_neg = torch.zeros(F, device=dev)
37
+ zero = torch.zeros(F, device=dev)
38
+
39
+ for t in range(T):
40
+ for u in range(t + 1, T):
41
+ both = mask[:, t] & mask[:, u]
42
+ if not bool(both.any()):
43
+ continue
44
+ s_pos += torch.where(both, (V[:, t] * V[:, u]).sum(-1), zero)
45
+ n_pos += both.float()
46
+
47
+ # Protocol 7.8: same-relation background, symmetrised over the pair
48
+ # so a family that sits globally closer to everything cannot inflate
49
+ # the score. Done per relation to keep each similarity block small.
50
+ for members in by_rel.values():
51
+ idx = [i for i in members if bool(both[i])]
52
+ if len(idx) < 2:
53
+ continue
54
+ ii = torch.tensor(idx, device=dev)
55
+ Sab = V[ii, t] @ V[ii, u].T
56
+ pos = {f: j for j, f in enumerate(idx)}
57
+ for f in idx:
58
+ negs = [pos[g] for g in negatives[f] if g in pos]
59
+ if not negs:
60
+ continue
61
+ jj = torch.tensor(negs, device=dev)
62
+ j0 = pos[f]
63
+ s_neg[f] += 0.5 * (Sab[j0, jj].mean() + Sab[jj, j0].mean())
64
+ n_neg[f] += 1
65
+
66
+ sp = s_pos / n_pos.clamp_min(1)
67
+ sn = s_neg / n_neg.clamp_min(1)
68
+ return sp, sn, (sp - sn) / (1.0 - sn + eps), (n_pos > 0) & (n_neg > 0)
69
+
70
+
71
+ def main():
72
+ ap = argparse.ArgumentParser()
73
+ ap.add_argument("--model", required=True)
74
+ ap.add_argument("--transport", choices=["raw", "jlens"], default="raw")
75
+ ap.add_argument("--coverage", choices=["complete_family", "full_set"], default=None)
76
+ ap.add_argument("--device", default="auto")
77
+ ap.add_argument("--shuffle-seed", type=int, default=None,
78
+ help="protocol 18.1 control: destroy fact identity; ISS must collapse")
79
+ args = ap.parse_args()
80
+
81
+ C = mc.cfg()
82
+ icfg = C["iss"]
83
+ eps = float(icfg["eps"])
84
+ S = StateLoader(args.model, args.transport, args.coverage, args.device,
85
+ shuffle_seed=args.shuffle_seed)
86
+
87
+ negatives = mc.negative_sample(S.keep_facts, S.rel_of,
88
+ icfg["max_negatives"], icfg["negative_seed"])
89
+ negatives = {S.fidx[f]: [S.fidx[g] for g in gs] for f, gs in negatives.items()}
90
+
91
+ F = S.n_facts
92
+ per_layer, t0 = {}, time.time()
93
+ for l in S.window:
94
+ V, mask = S.centroids(l)
95
+ sp, sn, iss, valid = iss_one_layer(V, mask, S.by_rel, negatives, eps)
96
+ per_layer[l] = {"s_pos": sp.cpu().numpy(), "s_neg": sn.cpu().numpy(),
97
+ "iss": iss.cpu().numpy(), "valid": valid.cpu().numpy()}
98
+ print(f" L{l:03d} ISS={float(iss[valid].mean()):+.4f} "
99
+ f"S+={float(sp[valid].mean()):.4f} S-={float(sn[valid].mean()):.4f}",
100
+ flush=True)
101
+ del V, mask
102
+ if S.dev == "cuda":
103
+ torch.cuda.empty_cache()
104
+
105
+ # ---- protocol 7.10: window mean, peak, late
106
+ stack = np.stack([per_layer[l]["iss"] for l in S.window])
107
+ vmask = np.stack([per_layer[l]["valid"] for l in S.window])
108
+ stack = np.where(vmask, stack, np.nan)
109
+ late_rows = [i for i, l in enumerate(S.window) if l in S.late]
110
+ with np.errstate(invalid="ignore"):
111
+ iss_f = np.nanmean(stack, axis=0)
112
+ peak_f = np.nanmax(stack, axis=0)
113
+ late_f = np.nanmean(stack[late_rows], axis=0) if late_rows else np.full(F, np.nan)
114
+
115
+ rows = [{"model": args.model, "transport": args.transport, "fact_id": f,
116
+ "relation": S.rel_of[f], "iss": float(iss_f[i]),
117
+ "iss_peak": float(peak_f[i]), "iss_late": float(late_f[i]),
118
+ "layers_used": S.window}
119
+ for i, f in enumerate(S.keep_facts) if np.isfinite(iss_f[i])]
120
+
121
+ tag = f"{args.model}.{args.transport}.{S.mode}"
122
+ if args.shuffle_seed is not None:
123
+ tag += f".shuffled{args.shuffle_seed}"
124
+ mc.write_jsonl(mc.out("metrics", "iss", f"{tag}.per_fact.jsonl"), rows)
125
+ mc.write_jsonl(mc.out("metrics", "iss", f"{tag}.per_fact_layer.jsonl"),
126
+ [{"model": args.model, "transport": args.transport,
127
+ "fact_id": f, "layer": l,
128
+ "iss": float(per_layer[l]["iss"][i]),
129
+ "s_positive": float(per_layer[l]["s_pos"][i]),
130
+ "s_background": float(per_layer[l]["s_neg"][i])}
131
+ for l in S.window for i, f in enumerate(S.keep_facts)
132
+ if per_layer[l]["valid"][i]])
133
+
134
+ vals = {r["fact_id"]: r["iss"] for r in rows}
135
+ boot = mc.relation_clustered_bootstrap(
136
+ vals, S.rel_of, C["bootstrap"]["n_resamples"], C["bootstrap"]["seed"],
137
+ C["bootstrap"]["ci"])
138
+ summary = {
139
+ "model": args.model, "transport": args.transport, "coverage_mode": S.mode,
140
+ "official": args.transport == "jlens" and args.shuffle_seed is None,
141
+ "shuffle_control": args.shuffle_seed is not None,
142
+ "n_facts": len(rows), "layers": S.window,
143
+ "iss": boot["mean"], "iss_ci95": [boot["lo"], boot["hi"]],
144
+ "iss_peak": float(np.nanmean(peak_f)), "iss_late": float(np.nanmean(late_f)),
145
+ "s_positive": float(np.nanmean([per_layer[l]["s_pos"] for l in S.window])),
146
+ "s_background": float(np.nanmean([per_layer[l]["s_neg"] for l in S.window])),
147
+ "per_layer_iss": {str(l): float(np.nanmean(np.where(
148
+ per_layer[l]["valid"], per_layer[l]["iss"], np.nan))) for l in S.window},
149
+ "seconds": round(time.time() - t0, 1),
150
+ }
151
+ mc.write_json(mc.out("metrics", "iss", f"{tag}.summary.json"), summary)
152
+ print(f"[{args.model}] {args.transport}-ISS = {boot['mean']:+.4f} "
153
+ f"[{boot['lo']:+.4f},{boot['hi']:+.4f}] n={len(rows)} ISS_DONE", flush=True)
154
+
155
+
156
+ if __name__ == "__main__":
157
+ main()
dataset_upload/metrics/jlens.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """J-Lens: randomized factorized estimate of the layer-to-final Jacobian. [GPU]
3
+
4
+ python src/jlens.py --model Llama-3.2-1B --rank 256
5
+ python src/jlens.py --model Llama-3.2-1B --validate # spec 7.1 action check
6
+
7
+ Official transport (J-Lens spec 1):
8
+
9
+ z^l = J^l h^l, J^l = E_{x~C}[ d h^L(x) / d h^l(x) ]
10
+
11
+ with NO unembedding matrix -- the metric lives in the final-layer residual
12
+ basis, not in vocabulary space.
13
+
14
+ d x d is unaffordable at d = 5120, so spec 6 prescribes randomized range
15
+ finding:
16
+
17
+ Y = J Omega (JVPs) Q = qr(Y)
18
+ B = Q^T J (VJPs) Jhat = Q B
19
+
20
+ and spec 6.4 says to store only Q and B. Downstream we only ever take cosines,
21
+ and Q is orthonormal, so cos(Q y1, Q y2) = cos(y1, y2) -- iss.py consumes
22
+ y = B h directly in r dimensions.
23
+
24
+ --- how the per-example Jacobian is taken -------------------------------------
25
+
26
+ J_x is the Jacobian of the map
27
+
28
+ h^l at the last position -> h^L at the last position
29
+
30
+ holding the prefix fixed. Attention is causal, so perturbing the last position's
31
+ residual cannot change any earlier position: the prefix KV cache computed once
32
+ is exactly right, and the map can be evaluated by a single-token decode step
33
+ with a hook that substitutes h at block l. That costs one token through the
34
+ blocks instead of a full re-prefill, and it goes through the stock HF decode
35
+ path, so it stays correct for Llama / Qwen2 / Mistral / Gemma2 (sliding window,
36
+ logit softcap) / OLMo2 alike without per-architecture code.
37
+
38
+ Tangents are batched along the batch dimension: the map is block-diagonal across
39
+ batch rows, so one jvp call returns J_x v_i for as many probe columns as fit.
40
+ """
41
+ import os, sys, json, time, argparse, copy
42
+
43
+ import numpy as np
44
+ import torch
45
+ from transformers import AutoModelForCausalLM, AutoTokenizer
46
+
47
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
48
+ import mcommon as mc
49
+ from extract_hidden import decoder_layers
50
+
51
+
52
+ # --------------------------------------------------------------- calibration
53
+ def calibration_prompts(tok, n, seq_len, seed):
54
+ """Spec 13.1: general text, independent of the factual benchmark.
55
+
56
+ Every model sees the same document slice and the same token count, so the
57
+ corpus contributes no cross-model variation (spec 8.1: "same construction
58
+ rule for all models").
59
+ """
60
+ from datasets import load_dataset
61
+ ds = load_dataset("NeelNanda/pile-10k", split="train")
62
+ rng = np.random.default_rng(seed)
63
+ picks = rng.choice(len(ds), size=min(4 * n, len(ds)), replace=False)
64
+ out, used = [], []
65
+ for i in picks:
66
+ ids = tok(ds[int(i)]["text"], return_tensors="pt",
67
+ truncation=True, max_length=seq_len)["input_ids"][0]
68
+ if ids.numel() < seq_len:
69
+ continue # fixed length only (spec 8.1)
70
+ out.append(ids[:seq_len])
71
+ used.append(int(i))
72
+ if len(out) == n:
73
+ break
74
+ if len(out) < n:
75
+ raise SystemExit(f"only {len(out)}/{n} calibration prompts reached {seq_len} tokens")
76
+ return torch.stack(out), used
77
+
78
+
79
+ FP32_BUDGET_GB = 110.0 # of the 143 GB H200, leaving room for activations
80
+
81
+
82
+ def pick_dtype(name, requested="auto"):
83
+ """float32 wherever the weights fit, bfloat16 only when they cannot.
84
+
85
+ Measured on Qwen2.5-0.5B, a bf16 JVP agrees with the fp32 one to
86
+ cos >= 0.996 but with 1-8% relative error, worst at early layers -- above
87
+ the 0.05 action-error threshold the J-Lens spec (7.3) sets for accepting an
88
+ estimator. Corpus averaging suppresses most of that, but it is cheaper to
89
+ avoid the noise than to argue about it, so fp32 is the default and the
90
+ fallback is recorded in metadata for the uncertainty report (spec 18).
91
+ """
92
+ if requested != "auto":
93
+ return getattr(torch, requested)
94
+ params_b = float(mc.model_entry(name).get("params_b", 0) or 0)
95
+ return torch.float32 if params_b * 4.0 < FP32_BUDGET_GB else torch.bfloat16
96
+
97
+
98
+ def load_for_jacobian(name, dtype="auto"):
99
+ """Eager attention is mandatory here.
100
+
101
+ The fused SDPA/flash kernels have no double-backward rule, and the JVP below
102
+ is reverse-over-reverse. Eager attention is slower but it is the only
103
+ implementation that differentiates twice. Generation and hidden-state
104
+ extraction are unaffected -- they never take a second derivative.
105
+ """
106
+ dt = pick_dtype(name, dtype)
107
+ path = mc.model_path(name)
108
+ tok = AutoTokenizer.from_pretrained(path)
109
+ model = AutoModelForCausalLM.from_pretrained(
110
+ path, dtype=dt, device_map={"": 0}, attn_implementation="eager").eval()
111
+ for prm in model.parameters():
112
+ prm.requires_grad_(False)
113
+ return model, tok
114
+
115
+
116
+ def _cache_tensors(cache):
117
+ """The K/V tensor slots of a Cache, across the layouts transformers uses."""
118
+ slots = []
119
+ if getattr(cache, "layers", None):
120
+ for lay in cache.layers:
121
+ for attr in ("keys", "values"):
122
+ if getattr(lay, attr, None) is not None:
123
+ slots.append((lay, attr))
124
+ for attr in ("key_cache", "value_cache"):
125
+ seq = getattr(cache, attr, None)
126
+ if seq is not None:
127
+ for i in range(len(seq)):
128
+ slots.append((seq, i))
129
+ return slots
130
+
131
+
132
+ def _expand_cache(cache, b):
133
+ """Replicate a batch-1 prefix cache to batch b without re-running the prefix."""
134
+ c = copy.deepcopy(cache)
135
+ for holder, key in _cache_tensors(c):
136
+ t = holder[key] if isinstance(key, int) else getattr(holder, key)
137
+ t = t.expand(b, *t.shape[1:]).contiguous()
138
+ if isinstance(key, int):
139
+ holder[key] = t
140
+ else:
141
+ setattr(holder, key, t)
142
+ return c
143
+
144
+
145
+ class TailMap:
146
+ """h^l(last position) -> h^L(last position), prefix held fixed.
147
+
148
+ Causal attention is what makes this well defined: the last position cannot
149
+ influence earlier ones, so the prefix KV computed once is exactly correct
150
+ however h^l is perturbed.
151
+ """
152
+
153
+ def __init__(self, model, blocks, layer, ids):
154
+ self.model, self.blocks, self.layer = model, blocks, layer
155
+ self.n_layers = len(blocks)
156
+ self.sub = None # tensor substituted at block `layer`
157
+ self.final = None
158
+ with torch.no_grad():
159
+ pre = model(input_ids=ids[:, :-1].to(model.device), use_cache=True)
160
+ self.prefix = pre.past_key_values
161
+ self.last = ids[:, -1:].to(model.device)
162
+ self._install()
163
+
164
+ def _install(self):
165
+ def sub_hook(_m, _i, output):
166
+ if self.sub is None:
167
+ return output
168
+ tup = isinstance(output, tuple)
169
+ h = output[0] if tup else output
170
+ # Rebuild rather than index-assign: the substituted row carries the
171
+ # autograd graph and an in-place write into a non-leaf bf16 buffer
172
+ # is both fragile and unnecessary here (sequence length is 1).
173
+ h = self.sub.to(h.dtype).unsqueeze(1)
174
+ return (h,) + tuple(output[1:]) if tup else h
175
+
176
+ def grab_hook(_m, _i, output):
177
+ h = output[0] if isinstance(output, tuple) else output
178
+ self.final = h[:, -1, :]
179
+
180
+ self.h1 = self.blocks[self.layer].register_forward_hook(sub_hook)
181
+ self.h2 = self.blocks[self.n_layers - 1].register_forward_hook(grab_hook)
182
+
183
+ def close(self):
184
+ self.h1.remove()
185
+ self.h2.remove()
186
+
187
+ def baseline(self):
188
+ """h^l at the last position, unperturbed -- the expansion point."""
189
+ got = {}
190
+
191
+ def hook(_m, _i, output):
192
+ h = output[0] if isinstance(output, tuple) else output
193
+ got["h"] = h[:, -1, :].detach().clone()
194
+ hd = self.blocks[self.layer].register_forward_hook(hook)
195
+ self.sub = None
196
+ with torch.no_grad():
197
+ self._decode(1)
198
+ hd.remove()
199
+ return got["h"]
200
+
201
+ def _decode(self, batch):
202
+ cache = _expand_cache(self.prefix, batch) if batch > 1 \
203
+ else copy.deepcopy(self.prefix)
204
+ self.model(input_ids=self.last.expand(batch, 1),
205
+ past_key_values=cache, use_cache=True)
206
+ return self.final
207
+
208
+ def __call__(self, h):
209
+ """h: [b, d] -> [b, d]. Differentiable in reverse mode."""
210
+ self.sub = h
211
+ try:
212
+ return self._decode(h.shape[0])
213
+ finally:
214
+ self.sub = None
215
+
216
+
217
+ def jvp(f, x, v):
218
+ """J v via double backward.
219
+
220
+ torch.func.jvp cannot be used here: forward-mode duals do not survive the
221
+ module hooks that substitute the residual, and the model runs in bfloat16.
222
+ The double-backward identity d/du (J^T u) . v = J v needs only reverse mode,
223
+ which the hooks handle natively.
224
+ """
225
+ x = x.detach().requires_grad_(True)
226
+ y = f(x)
227
+ u = torch.zeros_like(y, requires_grad=True)
228
+ (g,) = torch.autograd.grad(y, x, grad_outputs=u, create_graph=True)
229
+ (out,) = torch.autograd.grad(g, u, grad_outputs=v)
230
+ return out
231
+
232
+
233
+ def probes(d, r, seed, device):
234
+ """Nested Gaussian probes: spec 5.3 requires rank k's directions to be a
235
+ prefix of rank 2k's, so a rank sweep is a genuine refinement rather than an
236
+ unrelated redraw."""
237
+ g = torch.Generator(device="cpu").manual_seed(seed)
238
+ return torch.randn(d, r, generator=g).to(device)
239
+
240
+
241
+ def estimate(model, blocks, layer, corpus, r, seed, chunk, device):
242
+ """Y = E_x[J_x Omega] then Q = qr(Y); B^T = E_x[J_x^T Q]."""
243
+ d = model.config.hidden_size
244
+ Om = probes(d, r, seed, device)
245
+ Y = torch.zeros(d, r, device=device, dtype=torch.float32)
246
+
247
+ maps = []
248
+ for ids in corpus:
249
+ tm = TailMap(model, blocks, layer, ids.unsqueeze(0))
250
+ maps.append(tm)
251
+
252
+ for tm in maps:
253
+ h0 = tm.baseline().float()
254
+ for s in range(0, r, chunk):
255
+ v = Om[:, s:s + chunk].T.contiguous() # [b, d]
256
+ base = h0.expand(v.shape[0], d).contiguous()
257
+ Y[:, s:s + chunk] += jvp(lambda x: tm(x).float(), base, v).T.float()
258
+ Y /= len(maps)
259
+ Q, _ = torch.linalg.qr(Y.double())
260
+ Q = Q.float() # [d, r]
261
+
262
+ Bt = torch.zeros(d, r, device=device, dtype=torch.float32)
263
+ for tm in maps:
264
+ h0 = tm.baseline().float()
265
+ for s in range(0, r, chunk):
266
+ w = Q[:, s:s + chunk].T.contiguous()
267
+ b = w.shape[0]
268
+ base = h0.expand(b, d).contiguous().requires_grad_(True)
269
+ outp = tm(base).float()
270
+ gr = torch.autograd.grad(outp, base, grad_outputs=w.float())[0]
271
+ Bt[:, s:s + chunk] += gr.T.float()
272
+ Bt /= len(maps)
273
+ for tm in maps:
274
+ tm.close()
275
+ return Q, Bt.T.contiguous() # Q [d,r], B [r,d]
276
+
277
+
278
+ def direct_action(model, blocks, layer, corpus, H, device):
279
+ """u_i = J h_i computed directly (spec 7.1) -- the validation reference.
280
+
281
+ Needs no d x d matrix: it is one JVP per held-out activation, averaged over
282
+ the same calibration corpus the estimator used.
283
+ """
284
+ d = model.config.hidden_size
285
+ U = torch.zeros(H.shape[0], d, device=device, dtype=torch.float32)
286
+ for ids in corpus:
287
+ tm = TailMap(model, blocks, layer, ids.unsqueeze(0))
288
+ h0 = tm.baseline().float()
289
+ for s in range(0, H.shape[0], 16):
290
+ v = H[s:s + 16].to(device).float()
291
+ base = h0.expand(v.shape[0], d).contiguous()
292
+ U[s:s + 16] += jvp(lambda x: tm(x).float(), base, v).float()
293
+ tm.close()
294
+ return U / len(corpus)
295
+
296
+
297
+ def main():
298
+ ap = argparse.ArgumentParser()
299
+ ap.add_argument("--model", required=True)
300
+ ap.add_argument("--rank", type=int, default=256)
301
+ ap.add_argument("--seed", type=int, default=None)
302
+ ap.add_argument("--layers", nargs="*", type=int, default=None)
303
+ ap.add_argument("--n-prompts", type=int, default=None)
304
+ ap.add_argument("--chunk", type=int, default=32, help="probe columns per jvp call")
305
+ ap.add_argument("--dtype", default="auto", choices=["auto", "float32", "bfloat16"])
306
+ ap.add_argument("--validate", action="store_true",
307
+ help="spec 7.1 direct-action check on held-out activations")
308
+ args = ap.parse_args()
309
+
310
+ C = mc.cfg()["jlens"]
311
+ seed = args.seed if args.seed is not None else C["estimator"]["primary_seed"]
312
+ n_prompts = args.n_prompts or C["corpus"]["n_prompts"]
313
+ p = C["estimator"]["oversampling"]
314
+ r = args.rank + p
315
+ device = "cuda"
316
+
317
+ model, tok = load_for_jacobian(args.model, args.dtype)
318
+ compute_dtype = str(next(model.parameters()).dtype).replace("torch.", "")
319
+ blocks = decoder_layers(model)
320
+ L, d = len(blocks), int(model.config.hidden_size)
321
+ if r > d:
322
+ r = d
323
+ window = args.layers if args.layers else mc.layer_window(L)
324
+
325
+ corpus, used = calibration_prompts(tok, n_prompts, C["corpus"]["seq_len"],
326
+ C["corpus"]["seed"])
327
+ print(f"[{args.model}] d={d} L={L} rank={args.rank}+{p}={r} "
328
+ f"corpus={n_prompts}x{C['corpus']['seq_len']} layers={len(window)}", flush=True)
329
+
330
+ for l in window:
331
+ t0 = time.time()
332
+ Q, B = estimate(model, blocks, l, corpus, r, seed, args.chunk, device)
333
+ dest = mc.out("jlens", args.model, f"L{l:03d}")
334
+ np.save(os.path.join(dest, "Q.npy"), Q.cpu().numpy().astype(np.float32))
335
+ np.save(os.path.join(dest, "B.npy"), B.cpu().numpy().astype(np.float32))
336
+ meta = {"model": args.model, "layer": l, "hidden_dimension": d,
337
+ "rank": args.rank, "oversampling": p, "stored_rank": r,
338
+ "power_iterations": C["estimator"]["power_iterations"],
339
+ "calibration_corpus": C["corpus"]["name"],
340
+ "calibration_corpus_size": n_prompts,
341
+ "calibration_sequence_length": C["corpus"]["seq_len"],
342
+ "calibration_sample_ids": used, "random_seed": seed,
343
+ "compute_dtype": compute_dtype,
344
+ "seconds": round(time.time() - t0, 1), "validated": None}
345
+ mc.write_json(os.path.join(dest, "metadata.json"), meta)
346
+ print(f" L{l:03d} Q{tuple(Q.shape)} B{tuple(B.shape)} "
347
+ f"{meta['seconds']}s", flush=True)
348
+ print(f"[{args.model}] JLENS_DONE", flush=True)
349
+
350
+
351
+ if __name__ == "__main__":
352
+ main()
dataset_upload/metrics/joint.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Do internal and external stability move together? (protocol 12, 13.2)
3
+
4
+ python src/joint.py --transport raw
5
+
6
+ Three levels, because they can disagree and each answers a different question:
7
+
8
+ 1. ACROSS MODELS Does a model with higher BCS also have higher ISS?
9
+ n = number of evaluated models, so this is suggestive at
10
+ best -- it is the weakest of the three.
11
+
12
+ 2. WITHIN MODEL, ACROSS FACTS Are the SAME facts unstable behaviourally and
13
+ internally? This is the real test. A model can sit at the
14
+ group mean while the two measures disagree completely
15
+ fact by fact, and only this level would reveal it.
16
+
17
+ 3. BY BEHAVIOUR GROUP Protocol 13.2: mean ISS for Stable Correct vs Stable
18
+ Wrong vs Stable Abstention vs Unstable. This is the table
19
+ the paper needs, and it also separates the two ways a fact
20
+ can be "stable": stably right and stably wrong should both
21
+ show high ISS if internal state drives behaviour.
22
+
23
+ Protocol 12 lists cells such as "BCS high / ISS low" -- consistent answers
24
+ reached through inconsistent internal states. Reporting only a single pooled
25
+ correlation would hide exactly those cases, so the per-model breakdown is
26
+ printed even when the pooled number looks tidy.
27
+ """
28
+ import os, sys, glob, json, argparse, collections
29
+
30
+ import numpy as np
31
+ from scipy.stats import spearmanr, pearsonr
32
+
33
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
34
+ import mcommon as mc
35
+
36
+ GROUPS = ["Stable Correct", "Stable Wrong", "Stable Abstention",
37
+ "Stable Unresolved", "Unstable"]
38
+
39
+
40
+ def load_pairs(model, transport, mode):
41
+ ip = mc.out("metrics", "iss", f"{model}.{transport}.{mode}.per_fact.jsonl")
42
+ bp = mc.out("metrics", "behavioral", f"{model}.{mode}.per_fact.jsonl")
43
+ if not (os.path.exists(ip) and os.path.exists(bp)):
44
+ return None
45
+ iss = {r["fact_id"]: r for r in mc.read_jsonl(ip)}
46
+ beh = {r["fact_id"]: r for r in mc.read_jsonl(bp)}
47
+ common = sorted(set(iss) & set(beh))
48
+ if len(common) < 20:
49
+ return None
50
+ return [{"fact_id": f, "relation": iss[f]["relation"],
51
+ "iss": iss[f]["iss"], "iss_late": iss[f]["iss_late"],
52
+ "bcs": beh[f]["bcs"], "bes": beh[f]["bes"],
53
+ "group": beh[f]["behavior_group"]} for f in common]
54
+
55
+
56
+ def main():
57
+ ap = argparse.ArgumentParser()
58
+ ap.add_argument("--transport", choices=["raw", "jlens"], default="raw")
59
+ ap.add_argument("--coverage", choices=["complete_family", "full_set"], default=None)
60
+ args = ap.parse_args()
61
+
62
+ mode = args.coverage or mc.cfg()["headline_coverage"]
63
+ names = [m["name"] for m in mc.models_cfg()["evaluated_models"]]
64
+
65
+ per_model, model_level = {}, []
66
+ for m in names:
67
+ rows = load_pairs(m, args.transport, mode)
68
+ if rows is None:
69
+ continue
70
+ per_model[m] = rows
71
+ isum = json.load(open(mc.out("metrics", "iss",
72
+ f"{m}.{args.transport}.{mode}.summary.json")))
73
+ bsum = json.load(open(mc.out("metrics", "behavioral",
74
+ f"{m}.{mode}.summary.json")))
75
+ kp = mc.out("metrics", "kts", f"{m}.{args.transport}.{mode}.summary.json")
76
+ ksum = json.load(open(kp)) if os.path.exists(kp) else {}
77
+ model_level.append({
78
+ "model": m, "family": mc.model_entry(m).get("family"),
79
+ "params_b": mc.model_entry(m).get("params_b"),
80
+ "tuning": mc.model_entry(m).get("tuning"),
81
+ "iss": isum["iss"], "bcs": bsum["bcs"], "bes": bsum["bes"],
82
+ "kts": ksum.get("kts"), "kts_id": ksum.get("kts_id"),
83
+ "unstable_rate": bsum["unstable_rate"],
84
+ "stable_correct_rate": bsum["stable_correct_rate"],
85
+ "n_joined": len(rows)})
86
+
87
+ if not model_level:
88
+ raise SystemExit("no model has BOTH ISS and BCS/BES yet")
89
+
90
+ out = {"transport": args.transport, "coverage_mode": mode,
91
+ "n_models": len(model_level), "model_level": model_level}
92
+
93
+ # ---- level 1: across models
94
+ def corr(a, b):
95
+ a, b = np.asarray(a, float), np.asarray(b, float)
96
+ ok = np.isfinite(a) & np.isfinite(b)
97
+ if ok.sum() < 3:
98
+ return None
99
+ return {"spearman": float(spearmanr(a[ok], b[ok]).statistic),
100
+ "pearson": float(pearsonr(a[ok], b[ok]).statistic), "n": int(ok.sum())}
101
+
102
+ across = {}
103
+ for x in ("bcs", "bes", "unstable_rate", "stable_correct_rate"):
104
+ for y in ("iss", "kts", "kts_id"):
105
+ c = corr([r[x] for r in model_level], [r[y] for r in model_level])
106
+ if c:
107
+ across[f"{x}__{y}"] = c
108
+ out["across_models"] = across
109
+
110
+ # ---- level 2: within model, across facts
111
+ within, pooled = {}, []
112
+ for m, rows in per_model.items():
113
+ within[m] = {
114
+ "n_facts": len(rows),
115
+ "iss_vs_bcs": corr([r["iss"] for r in rows], [r["bcs"] for r in rows]),
116
+ "iss_vs_bes": corr([r["iss"] for r in rows], [r["bes"] for r in rows]),
117
+ }
118
+ # Standardise inside each model before pooling, otherwise the pooled
119
+ # correlation would mostly reflect between-model level differences
120
+ # rather than the within-model fact-by-fact association we are after.
121
+ for key in ("iss", "bcs"):
122
+ v = np.array([r[key] for r in rows], float)
123
+ sd = v.std() or 1.0
124
+ for r, z in zip(rows, (v - v.mean()) / sd):
125
+ r[f"z_{key}"] = float(z)
126
+ pooled += rows
127
+ out["within_model"] = within
128
+ out["pooled_within_model"] = corr([r["z_iss"] for r in pooled],
129
+ [r["z_bcs"] for r in pooled])
130
+
131
+ # ---- level 3: behaviour groups (protocol 13.2)
132
+ by_group = collections.defaultdict(list)
133
+ for m, rows in per_model.items():
134
+ for r in rows:
135
+ by_group[r["group"]].append(r["iss"])
136
+ out["iss_by_behavior_group"] = {
137
+ g: {"n": len(by_group[g]), "iss_mean": float(np.mean(by_group[g])),
138
+ "iss_sd": float(np.std(by_group[g]))}
139
+ for g in GROUPS if by_group[g]}
140
+ out["iss_by_behavior_group_per_model"] = {
141
+ m: {g: float(np.mean([r["iss"] for r in rows if r["group"] == g]))
142
+ for g in GROUPS if any(r["group"] == g for r in rows)}
143
+ for m, rows in per_model.items()}
144
+
145
+ mc.write_json(mc.out("metrics", f"joint_internal_external.{args.transport}.{mode}.json"),
146
+ out)
147
+
148
+ # ------------------------------------------------------------ report
149
+ print(f"\n=== 1. ACROSS MODELS (n={len(model_level)}) ===")
150
+ print(f"{'pair':34s} {'Spearman':>9s} {'Pearson':>9s}")
151
+ for k, v in across.items():
152
+ print(f"{k:34s} {v['spearman']:>9.3f} {v['pearson']:>9.3f}")
153
+
154
+ print(f"\n=== 2. WITHIN MODEL, ACROSS FACTS ===")
155
+ print(f"{'model':30s} {'n':>5s} {'ISSvBCS':>8s} {'ISSvBES':>8s}")
156
+ for m, v in within.items():
157
+ a = v["iss_vs_bcs"]["spearman"] if v["iss_vs_bcs"] else float("nan")
158
+ b = v["iss_vs_bes"]["spearman"] if v["iss_vs_bes"] else float("nan")
159
+ print(f"{m:30s} {v['n_facts']:>5d} {a:>8.3f} {b:>8.3f}")
160
+ p = out["pooled_within_model"]
161
+ if p:
162
+ print(f"{'POOLED (z-scored per model)':30s} {p['n']:>5d} {p['spearman']:>8.3f}")
163
+
164
+ print(f"\n=== 3. ISS BY BEHAVIOUR GROUP (protocol 13.2) ===")
165
+ print(f"{'group':22s} {'facts':>7s} {'ISS mean':>9s} {'sd':>7s}")
166
+ for g, v in out["iss_by_behavior_group"].items():
167
+ print(f"{g:22s} {v['n']:>7d} {v['iss_mean']:>9.3f} {v['iss_sd']:>7.3f}")
168
+ print()
169
+
170
+
171
+ if __name__ == "__main__":
172
+ main()
dataset_upload/metrics/judge_run.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """AI Judge: semantic answer clustering, then correctness. [GPU] (protocol 3)
3
+
4
+ python src/judge_run.py --model Llama-3.2-1B
5
+
6
+ Two passes, in the order protocol 3 mandates:
7
+
8
+ Pass 1 REFERENCE-BLIND. The judge never sees the gold answer. It only groups
9
+ responses that assert the same thing -- "Paris", "The answer is
10
+ Paris.", "巴黎" -- and flags ABSTAIN / MULTIPLE / UNPARSEABLE.
11
+ This is what BCS and BES are built on, and keeping gold out of it is
12
+ what lets a confidently wrong model score BCS = 1.
13
+
14
+ Pass 2 REFERENCE-AWARE. Gold, aliases, answer type and granularity are
15
+ supplied, and each CLUSTER (not each response) is labelled. This only
16
+ separates Stable Correct from Stable Wrong; it never reshapes a
17
+ cluster.
18
+
19
+ The unit of judgement is the (fact, model) pair, per protocol 3.1: judging pairs
20
+ of responses independently would produce non-transitive verdicts, where a~b and
21
+ b~c but a!~c, and no consistent cluster assignment exists.
22
+
23
+ Cost control: responses are pre-grouped by normalised surface string before the
24
+ judge sees them. Exact post-normalisation identity is a strict subset of
25
+ semantic equivalence, so the judge can only ever merge those groups further,
26
+ never split them -- the clustering is unchanged, but a typical fact sends 3-6
27
+ distinct strings instead of 17 responses.
28
+ """
29
+ import os, sys, json, time, argparse, re
30
+
31
+ import torch
32
+ from transformers import AutoModelForCausalLM, AutoTokenizer
33
+
34
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
35
+ import mcommon as mc
36
+ sys.path.insert(0, mc.runner_dir())
37
+ from common import normalize # noqa: E402
38
+
39
+ BLIND = """You are clustering short answers to one factual question. You are NOT told the correct answer and must not guess it.
40
+
41
+ Question: {question}
42
+
43
+ Candidate answers:
44
+ {answers}
45
+
46
+ Work in two steps, exactly as follows.
47
+
48
+ Step 1. For each answer, extract ONLY the core entity or value it finally asserts. Strip restated question text, subject names, hedging, reasoning and trailing explanation. "Agriculture and Agri-Food Canada applies in Canada" asserts "Canada". "The answer is Paris." asserts "Paris".
49
+
50
+ Step 2. Group the answers whose EXTRACTED core is the same entity or value. Ignore wording, language, punctuation and capitalisation; translations of one another belong together, and a bare entity belongs with a full sentence asserting that same entity. Two answers go in different groups only when they name genuinely different entities.
51
+
52
+ Use these special groups where they apply:
53
+ - ABSTAIN: refuses, or says it does not know
54
+ - MULTIPLE: gives several conflicting answers without choosing
55
+ - UNPARSEABLE: no answer can be extracted
56
+
57
+ Reply with JSON only, where "meaning" is the extracted core from step 1:
58
+ {{"clusters":[{{"ids":[0,2],"meaning":"Paris","status":"ANSWER"}},{{"ids":[1],"meaning":"","status":"ABSTAIN"}}]}}
59
+ Every id from 0 to {last} must appear exactly once."""
60
+
61
+ AWARE = """Judge whether each proposed answer is correct for this question.
62
+
63
+ Question: {question}
64
+ Correct answer: {gold}
65
+ Also acceptable: {aliases}
66
+ Answer type: {atype} ({gran})
67
+
68
+ Proposed answers:
69
+ {answers}
70
+
71
+ Label each one:
72
+ - CORRECT: same entity/value as the correct answer, any wording or language
73
+ - INCORRECT: a different entity/value
74
+ - ABSTAIN: a refusal or "I don't know"
75
+ - AMBIGUOUS: could refer to the correct answer but is too vague to tell
76
+ - REVIEW_REQUIRED: cannot decide
77
+
78
+ Reply with JSON only: {{"labels":["CORRECT","INCORRECT"]}} with exactly {n} entries in order."""
79
+
80
+
81
+ def parse_json(text):
82
+ """Judges emit prose around the JSON often enough that this must be robust."""
83
+ m = re.search(r"\{.*\}", text, re.S)
84
+ if not m:
85
+ return None
86
+ try:
87
+ return json.loads(m.group(0))
88
+ except json.JSONDecodeError:
89
+ try:
90
+ return json.loads(re.sub(r",\s*([}\]])", r"\1", m.group(0)))
91
+ except json.JSONDecodeError:
92
+ return None
93
+
94
+
95
+ def generate(model, tok, prompts, max_new, batch):
96
+ outs = []
97
+ for i in range(0, len(prompts), batch):
98
+ chunk = prompts[i:i + batch]
99
+ texts = [tok.apply_chat_template([{"role": "user", "content": p}],
100
+ tokenize=False, add_generation_prompt=True)
101
+ for p in chunk]
102
+ enc = tok(texts, return_tensors="pt", padding=True, truncation=True,
103
+ max_length=2048).to(0)
104
+ with torch.no_grad():
105
+ g = model.generate(**enc, max_new_tokens=max_new, do_sample=False,
106
+ num_beams=1, pad_token_id=tok.pad_token_id)
107
+ outs += tok.batch_decode(g[:, enc["input_ids"].shape[1]:],
108
+ skip_special_tokens=True)
109
+ return outs
110
+
111
+
112
+ def main():
113
+ ap = argparse.ArgumentParser()
114
+ ap.add_argument("--model", required=True, help="the model being judged")
115
+ ap.add_argument("--judge", default=None)
116
+ ap.add_argument("--batch", type=int, default=32)
117
+ ap.add_argument("--limit", type=int, default=0, help="debug: first N facts")
118
+ ap.add_argument("--sample", type=int, default=0,
119
+ help="judge a fixed random subset of facts instead of all 2,592")
120
+ ap.add_argument("--sample-seed", type=int, default=20260101)
121
+ ap.add_argument("--resume", action="store_true")
122
+ args = ap.parse_args()
123
+
124
+ judge_name = args.judge or mc.models_cfg()["auxiliary_models"]["judge"]["name"]
125
+ if judge_name == args.model:
126
+ raise SystemExit("the judge must not judge itself (MODEL_SELECTION_20 section 6)")
127
+
128
+ fams = set(mc.cfg()["main_families"])
129
+ gen_path = mc.generations(args.model)
130
+ if not os.path.exists(gen_path):
131
+ raise SystemExit(
132
+ f"no generations for {args.model}: {gen_path}\n"
133
+ f"run python runner/eval_run.py --model {args.model} first")
134
+
135
+ qmeta = {r["query_id"]: r for r in mc.main_forward_queries()}
136
+ by_fact = {}
137
+ for r in mc.read_jsonl(gen_path):
138
+ if r["condition_family"] not in fams or r["query_id"] not in qmeta:
139
+ continue
140
+ by_fact.setdefault(r["fact_id"], []).append(r)
141
+ fact_ids = sorted(by_fact)
142
+ if args.sample and args.sample < len(fact_ids):
143
+ # Drawn from the FULL benchmark fact list with a fixed seed, not from
144
+ # this model's own facts, so every model is judged on an identical
145
+ # subset. Sampling per model would make BCS/BES incomparable, which is
146
+ # exactly what protocol 1.3 forbids.
147
+ import numpy as np
148
+ allf = sorted(mc.facts())
149
+ rng = np.random.default_rng(args.sample_seed)
150
+ pick = set(np.array(allf)[rng.choice(len(allf), size=args.sample,
151
+ replace=False)].tolist())
152
+ fact_ids = [f for f in fact_ids if f in pick]
153
+ if args.limit:
154
+ fact_ids = fact_ids[:args.limit]
155
+
156
+ dest = mc.out("metrics", "judge", f"{args.model}.jsonl")
157
+ done = set()
158
+ if args.resume and os.path.exists(dest):
159
+ done = {r["fact_id"] for r in mc.read_jsonl(dest)}
160
+ fact_ids = [f for f in fact_ids if f not in done]
161
+ if not fact_ids:
162
+ print(f"[{args.model}] judge already complete")
163
+ return
164
+
165
+ facts = mc.facts()
166
+ # Pre-group by normalised surface: a strict subset of semantic equivalence,
167
+ # so this changes cost and not the clustering the judge can express.
168
+ tasks = []
169
+ for fid in fact_ids:
170
+ recs = by_fact[fid]
171
+ groups = {}
172
+ for r in recs:
173
+ key = normalize(r["raw_response"].strip().split("\n")[0][:120])
174
+ groups.setdefault(key, []).append(r["query_id"])
175
+ surfaces = list(groups)
176
+ display = [next(x["raw_response"].strip().split("\n")[0][:120]
177
+ for x in recs if normalize(
178
+ x["raw_response"].strip().split("\n")[0][:120]) == s) or "(empty)"
179
+ for s in surfaces]
180
+ tasks.append({"fact_id": fid, "surfaces": surfaces, "display": display,
181
+ "groups": [groups[s] for s in surfaces],
182
+ "question": facts[fid]["qualification_question"]})
183
+
184
+ path = mc.model_path(judge_name)
185
+ tok = AutoTokenizer.from_pretrained(path)
186
+ if tok.pad_token is None:
187
+ tok.pad_token = tok.eos_token
188
+ tok.padding_side = "left"
189
+ judge = AutoModelForCausalLM.from_pretrained(
190
+ path, dtype=torch.bfloat16, device_map={"": 0}).eval()
191
+
192
+ t0 = time.time()
193
+ out_f = open(dest, "a" if done else "w")
194
+ for i in range(0, len(tasks), args.batch):
195
+ chunk = tasks[i:i + args.batch]
196
+
197
+ p1 = [BLIND.format(question=t["question"], last=len(t["display"]) - 1,
198
+ answers="\n".join(f"{j}. {d}" for j, d in enumerate(t["display"])))
199
+ for t in chunk]
200
+ r1 = generate(judge, tok, p1, 512, args.batch)
201
+
202
+ for t, raw in zip(chunk, r1):
203
+ js = parse_json(raw) or {}
204
+ clusters, seen = [], set()
205
+ for c in js.get("clusters", []):
206
+ ids = [int(x) for x in c.get("ids", [])
207
+ if isinstance(x, (int, float)) and 0 <= int(x) < len(t["display"])
208
+ and int(x) not in seen]
209
+ if not ids:
210
+ continue
211
+ seen.update(ids)
212
+ clusters.append({"ids": ids, "meaning": str(c.get("meaning", ""))[:80],
213
+ "status": str(c.get("status", "ANSWER")).upper()})
214
+ # Anything the judge dropped or mangled stays its own cluster rather
215
+ # than vanishing: silently losing a response would change the BCS
216
+ # denominator for that fact.
217
+ for j in range(len(t["display"])):
218
+ if j not in seen:
219
+ clusters.append({"ids": [j], "meaning": t["display"][j][:80],
220
+ "status": "ANSWER", "recovered": True})
221
+ t["clusters"] = clusters
222
+ t["judge_raw_blind"] = raw[:400]
223
+
224
+ p2, own = [], []
225
+ for t in chunk:
226
+ f = facts[t["fact_id"]]
227
+ answer = [c["meaning"] or t["display"][c["ids"][0]] for c in t["clusters"]]
228
+ p2.append(AWARE.format(
229
+ question=t["question"], gold=f["object"]["canonical"],
230
+ aliases=", ".join(f["object"]["aliases"][:10]),
231
+ atype=f.get("answer_type", "entity"),
232
+ gran=f.get("answer_granularity", "entity"),
233
+ answers="\n".join(f"{j}. {a}" for j, a in enumerate(answer)),
234
+ n=len(answer)))
235
+ own.append(t)
236
+ r2 = generate(judge, tok, p2, 256, args.batch)
237
+ for t, raw in zip(own, r2):
238
+ js = parse_json(raw) or {}
239
+ labels = [str(x).upper() for x in js.get("labels", [])]
240
+ for j, c in enumerate(t["clusters"]):
241
+ lab = labels[j] if j < len(labels) else "REVIEW_REQUIRED"
242
+ if c["status"] in ("ABSTAIN", "MULTIPLE", "UNPARSEABLE"):
243
+ lab = c["status"] if c["status"] == "ABSTAIN" else "REVIEW_REQUIRED"
244
+ c["correctness"] = lab
245
+ t["judge_raw_aware"] = raw[:400]
246
+
247
+ for t in chunk:
248
+ rows = []
249
+ for k, c in enumerate(t["clusters"]):
250
+ cid = f"C{k}" if c["status"] == "ANSWER" else c["status"]
251
+ for j in c["ids"]:
252
+ for qid in t["groups"][j]:
253
+ rows.append({"query_id": qid,
254
+ "condition_family": qmeta[qid]["condition_family"],
255
+ "cluster_id": cid})
256
+ out_f.write(json.dumps({
257
+ "model": args.model, "judge": judge_name, "fact_id": t["fact_id"],
258
+ "clusters": [{"cluster_id": f"C{k}" if c["status"] == "ANSWER"
259
+ else c["status"],
260
+ "canonical_meaning": c["meaning"],
261
+ "status": c["status"],
262
+ "correctness": c.get("correctness", "REVIEW_REQUIRED")}
263
+ for k, c in enumerate(t["clusters"])],
264
+ "assignments": rows}, ensure_ascii=False) + "\n")
265
+ out_f.flush()
266
+ d = i + len(chunk)
267
+ print(f" {d}/{len(tasks)} facts {d / max(time.time() - t0, 1e-9):.2f}/s",
268
+ flush=True)
269
+ out_f.close()
270
+ print(f"[{args.model}] judged {len(tasks)} facts with {judge_name} JUDGE_DONE",
271
+ flush=True)
272
+
273
+
274
+ if __name__ == "__main__":
275
+ main()
dataset_upload/metrics/kts.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """KTS: Knowledge Topology Stability. (protocol 8-11)
3
+
4
+ python src/kts.py --model Llama-3.2-1B --transport raw
5
+ python src/kts.py --model Llama-3.2-1B --transport jlens
6
+
7
+ Two components, both computed per relation and then macro-averaged so that the
8
+ largest relations cannot dominate (protocol 9.1):
9
+
10
+ KTS-Geo Spearman correlation between the within-relation pairwise distance
11
+ matrices under the two condition families. Rotation, translation and
12
+ isotropic scaling are all invisible to it -- protocol 8.1 says that
13
+ is intended: different phrasings may use different internal
14
+ implementations as long as relative structure survives.
15
+
16
+ KTS-ID Cross-condition nearest-neighbour retrieval of the fact itself,
17
+ among same-relation facts, both directions, chance-corrected.
18
+ Global geometry can look preserved while individual identities swap,
19
+ which is exactly what this catches.
20
+
21
+ composite = harmonic mean of the two, so a model cannot buy a high KTS with one
22
+ component alone (protocol 11).
23
+ """
24
+ import os, sys, json, time, argparse, itertools
25
+
26
+ import numpy as np
27
+ import torch
28
+ from scipy.stats import spearmanr
29
+
30
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
31
+ import mcommon as mc
32
+ from states import StateLoader
33
+
34
+
35
+ def geo_pair(Va, Vb, members, eps):
36
+ """Spearman between within-relation distance matrices (protocol 9.1-9.2)."""
37
+ idx = torch.tensor(members, device=Va.device)
38
+ A, B = Va[idx], Vb[idx]
39
+ Da = 1.0 - (A @ A.T)
40
+ Db = 1.0 - (B @ B.T)
41
+ iu = torch.triu_indices(len(members), len(members), offset=1)
42
+ da = Da[iu[0], iu[1]].cpu().numpy()
43
+ db = Db[iu[0], iu[1]].cpu().numpy()
44
+ if da.size < 2 or np.std(da) < eps or np.std(db) < eps:
45
+ return None
46
+ rho = spearmanr(da, db).statistic
47
+ return None if not np.isfinite(rho) else float(rho)
48
+
49
+
50
+ def id_pair(Va, Vb, members):
51
+ """Symmetric chance-corrected top-1 identity, plus top-5 and MRR.
52
+
53
+ Retrieval is restricted to same-relation facts (protocol 10.1): matching
54
+ "the capital of France" against a manufacturer fact would be trivial and
55
+ would inflate the score.
56
+ """
57
+ idx = torch.tensor(members, device=Va.device)
58
+ A, B = Va[idx], Vb[idx]
59
+ n = len(members)
60
+ gold = torch.arange(n, device=A.device)
61
+
62
+ def side(X, Y):
63
+ S = X @ Y.T
64
+ rank = (S > S.gather(1, gold[:, None])).sum(1) # 0 = correct is top
65
+ top1 = (rank == 0).float().mean().item()
66
+ top5 = (rank < 5).float().mean().item()
67
+ mrr = (1.0 / (rank.float() + 1)).mean().item()
68
+ return top1, top5, mrr
69
+
70
+ a = side(A, B)
71
+ b = side(B, A)
72
+ top1 = 0.5 * (a[0] + b[0])
73
+ chance = 1.0 / n
74
+ adj = (top1 - chance) / max(1.0 - chance, 1e-12)
75
+ return {"top1_symmetric": top1, "top5_symmetric": 0.5 * (a[1] + b[1]),
76
+ "mrr_symmetric": 0.5 * (a[2] + b[2]), "chance": chance,
77
+ "chance_corrected": float(np.clip(adj, 0.0, 1.0)), "n": n}
78
+
79
+
80
+ def main():
81
+ ap = argparse.ArgumentParser()
82
+ ap.add_argument("--model", required=True)
83
+ ap.add_argument("--transport", choices=["raw", "jlens"], default="raw")
84
+ ap.add_argument("--coverage", choices=["complete_family", "full_set"], default=None)
85
+ ap.add_argument("--device", default="auto")
86
+ ap.add_argument("--shuffle-seed", type=int, default=None,
87
+ help="protocol 18.1 control: KTS-ID must fall to chance, KTS-Geo to ~0")
88
+ args = ap.parse_args()
89
+
90
+ C = mc.cfg()
91
+ kcfg = C["kts"]
92
+ eps = float(kcfg["eps"])
93
+ min_facts = kcfg["min_facts_per_relation"]
94
+
95
+ S = StateLoader(args.model, args.transport, args.coverage, args.device,
96
+ shuffle_seed=args.shuffle_seed)
97
+ fams = S.families
98
+ pairs = list(itertools.combinations(range(len(fams)), 2))
99
+
100
+ t0 = time.time()
101
+ per_layer_pair = []
102
+ for l in S.window:
103
+ V, mask = S.centroids(l)
104
+ for (a, b) in pairs:
105
+ both = mask[:, a] & mask[:, b]
106
+ geos, ids, shared = [], [], int(both.sum())
107
+ for rel, members in S.by_rel.items():
108
+ m = [i for i in members if bool(both[i])]
109
+ if len(m) < min_facts: # protocol 9.1
110
+ continue
111
+ g = geo_pair(V[:, a], V[:, b], m, eps)
112
+ if g is not None:
113
+ geos.append(g)
114
+ ids.append(id_pair(V[:, a], V[:, b], m))
115
+ if not geos or not ids:
116
+ continue
117
+ geo = float(np.mean(geos))
118
+ geo01 = (geo + 1.0) / 2.0 # protocol 9.3
119
+ idv = float(np.mean([x["chance_corrected"] for x in ids]))
120
+ per_layer_pair.append({
121
+ "model": args.model, "transport": args.transport, "layer": l,
122
+ "pair": f"{fams[a]}__{fams[b]}", "shared_facts": shared,
123
+ "relations_used": len(ids),
124
+ "kts_geo_raw": geo, "kts_geo": geo01, "kts_id": idv,
125
+ "kts": 2 * geo01 * idv / (geo01 + idv + eps), # protocol 11
126
+ "top1": float(np.mean([x["top1_symmetric"] for x in ids])),
127
+ "top5": float(np.mean([x["top5_symmetric"] for x in ids])),
128
+ "mrr": float(np.mean([x["mrr_symmetric"] for x in ids])),
129
+ })
130
+ del V, mask
131
+ if S.dev == "cuda":
132
+ torch.cuda.empty_cache()
133
+ lay = [r for r in per_layer_pair if r["layer"] == l]
134
+ print(f" L{l:03d} geo={np.mean([r['kts_geo'] for r in lay]):.4f} "
135
+ f"id={np.mean([r['kts_id'] for r in lay]):.4f} "
136
+ f"kts={np.mean([r['kts'] for r in lay]):.4f}", flush=True)
137
+
138
+ tag = f"{args.model}.{args.transport}.{S.mode}"
139
+ if args.shuffle_seed is not None:
140
+ tag += f".shuffled{args.shuffle_seed}"
141
+ mc.write_jsonl(mc.out("metrics", "kts", f"{tag}.per_pair_layer.jsonl"), per_layer_pair)
142
+
143
+ # Protocol 11.1: every family pair counts equally. Weighting by shared facts
144
+ # would let the widest-coverage pairs decide the number.
145
+ def agg(rows, key):
146
+ by_layer = {}
147
+ for r in rows:
148
+ by_layer.setdefault(r["layer"], []).append(r[key])
149
+ return float(np.mean([np.mean(v) for v in by_layer.values()]))
150
+
151
+ pair_summary = {}
152
+ for p in sorted({r["pair"] for r in per_layer_pair}):
153
+ rows = [r for r in per_layer_pair if r["pair"] == p]
154
+ pair_summary[p] = {
155
+ "shared_facts": rows[0]["shared_facts"],
156
+ "kts_geo": float(np.mean([r["kts_geo"] for r in rows])),
157
+ "kts_geo_raw": float(np.mean([r["kts_geo_raw"] for r in rows])),
158
+ "kts_id": float(np.mean([r["kts_id"] for r in rows])),
159
+ "kts": float(np.mean([r["kts"] for r in rows])),
160
+ "top1": float(np.mean([r["top1"] for r in rows])),
161
+ "top5": float(np.mean([r["top5"] for r in rows])),
162
+ "mrr": float(np.mean([r["mrr"] for r in rows])),
163
+ }
164
+
165
+ summary = {
166
+ "model": args.model, "transport": args.transport,
167
+ "official": args.transport == "jlens" and args.shuffle_seed is None,
168
+ "shuffle_control": args.shuffle_seed is not None, "coverage_mode": S.mode,
169
+ "layers": S.window, "n_facts": S.n_facts,
170
+ "kts_geo": agg(per_layer_pair, "kts_geo"),
171
+ "kts_geo_raw_spearman": agg(per_layer_pair, "kts_geo_raw"),
172
+ "kts_id": agg(per_layer_pair, "kts_id"),
173
+ "kts": agg(per_layer_pair, "kts"),
174
+ "top1": agg(per_layer_pair, "top1"),
175
+ "top5": agg(per_layer_pair, "top5"),
176
+ "mrr": agg(per_layer_pair, "mrr"),
177
+ "family_pairs": pair_summary,
178
+ "per_layer_kts": {str(l): float(np.mean([r["kts"] for r in per_layer_pair
179
+ if r["layer"] == l]))
180
+ for l in S.window},
181
+ "seconds": round(time.time() - t0, 1),
182
+ }
183
+ mc.write_json(mc.out("metrics", "kts", f"{tag}.summary.json"), summary)
184
+ print(f"[{args.model}] {args.transport} KTS-Geo={summary['kts_geo']:.4f} "
185
+ f"KTS-ID={summary['kts_id']:.4f} KTS={summary['kts']:.4f} KTS_DONE",
186
+ flush=True)
187
+
188
+
189
+ if __name__ == "__main__":
190
+ main()
dataset_upload/metrics/make_table.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """The main results table: model x {BCS, BES, ISS, KTS}. (protocol 13, 20)
3
+
4
+ python src/make_table.py # markdown to stdout + outputs/
5
+ python src/make_table.py --transport raw # the ablation table
6
+
7
+ ISS is reported from the J-Lens transported states. Raw-ISS is an
8
+ identity-transport ablation and is labelled as such (J-Lens spec 11); a model
9
+ whose J-Lens estimator failed validation shows "--" for ISS rather than a raw
10
+ number wearing the official name (spec 12).
11
+ """
12
+ import os, sys, json, argparse
13
+
14
+ import numpy as np
15
+
16
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
17
+ import mcommon as mc
18
+
19
+
20
+ def load(kind, name):
21
+ p = mc.out("metrics", kind, name)
22
+ return json.load(open(p)) if os.path.exists(p) else None
23
+
24
+
25
+ def fmt(v, nd=3, pct=False):
26
+ if v is None or (isinstance(v, float) and not np.isfinite(v)):
27
+ return "--"
28
+ return f"{100 * v:.1f}" if pct else f"{v:.{nd}f}"
29
+
30
+
31
+ def main():
32
+ ap = argparse.ArgumentParser()
33
+ ap.add_argument("--transport", choices=["jlens", "raw"], default="jlens")
34
+ ap.add_argument("--coverage", choices=["complete_family", "full_set"], default=None)
35
+ ap.add_argument("--models", nargs="*", default=None)
36
+ args = ap.parse_args()
37
+
38
+ C = mc.cfg()
39
+ mode = args.coverage or C["headline_coverage"]
40
+ names = args.models or [m["name"] for m in mc.models_cfg()["evaluated_models"]]
41
+
42
+ rows = []
43
+ for m in names:
44
+ beh = load("behavioral", f"{m}.{mode}.summary.json")
45
+ iss = load("iss", f"{m}.{args.transport}.{mode}.summary.json")
46
+ kts = load("kts", f"{m}.{args.transport}.{mode}.summary.json")
47
+ if not any([beh, iss, kts]):
48
+ continue
49
+ e = mc.model_entry(m)
50
+ rows.append({
51
+ "model": m, "family": e.get("family", ""), "tier": e.get("tier", ""),
52
+ "params_b": e.get("params_b"), "tuning": e.get("tuning", ""),
53
+ "bcs": beh and beh["bcs"], "bes": beh and beh["bes"],
54
+ "scr": beh and beh["stable_correct_rate"],
55
+ "swr": beh and beh["stable_wrong_rate"],
56
+ "sar": beh and beh["stable_abstention_rate"],
57
+ "ur": beh and beh["unstable_rate"],
58
+ "iss": iss and iss["iss"], "iss_ci": iss and iss["iss_ci95"],
59
+ "iss_peak": iss and iss["iss_peak"], "iss_late": iss and iss["iss_late"],
60
+ "kts_geo": kts and kts["kts_geo"], "kts_id": kts and kts["kts_id"],
61
+ "kts": kts and kts["kts"],
62
+ "n_facts": (beh or iss or kts).get("n_facts"),
63
+ })
64
+ if not rows:
65
+ raise SystemExit("nothing to tabulate yet")
66
+ rows.sort(key=lambda r: (r["family"], r["params_b"] or 0))
67
+
68
+ label = "ISS (J-Lens)" if args.transport == "jlens" else "Raw-ISS (ablation)"
69
+ L = []
70
+ L.append(f"# BCS / BES / ISS / KTS ({mode}, transport={args.transport})\n")
71
+ L.append(f"Fact set: fixed benchmark, {rows[0]['n_facts']} facts scored per model. "
72
+ f"ISS column is **{label}**.\n")
73
+ L.append("| Model | Family | Tier | BCS | BES | " + label +
74
+ " | KTS-Geo | KTS-ID | KTS |")
75
+ L.append("|---|---|---|---:|---:|---:|---:|---:|---:|")
76
+ for r in rows:
77
+ L.append(f"| {r['model']} | {r['family']} | {r['tier']} | "
78
+ f"{fmt(r['bcs'])} | {fmt(r['bes'])} | {fmt(r['iss'])} | "
79
+ f"{fmt(r['kts_geo'])} | {fmt(r['kts_id'])} | {fmt(r['kts'])} |")
80
+
81
+ L.append("\n## Behaviour composition (protocol 6, %)\n")
82
+ L.append("| Model | Stable Correct | Stable Wrong | Stable Abstention | Unstable |")
83
+ L.append("|---|---:|---:|---:|---:|")
84
+ for r in rows:
85
+ L.append(f"| {r['model']} | {fmt(r['scr'], pct=True)} | {fmt(r['swr'], pct=True)} "
86
+ f"| {fmt(r['sar'], pct=True)} | {fmt(r['ur'], pct=True)} |")
87
+
88
+ L.append("\n## ISS detail (protocol 7.10)\n")
89
+ L.append("| Model | ISS | 95% CI | Peak | Late |")
90
+ L.append("|---|---:|---|---:|---:|")
91
+ for r in rows:
92
+ ci = f"[{fmt(r['iss_ci'][0])}, {fmt(r['iss_ci'][1])}]" if r["iss_ci"] else "--"
93
+ L.append(f"| {r['model']} | {fmt(r['iss'])} | {ci} | "
94
+ f"{fmt(r['iss_peak'])} | {fmt(r['iss_late'])} |")
95
+
96
+ md = "\n".join(L) + "\n"
97
+ dest = mc.out("metrics", f"main_table.{args.transport}.{mode}.md")
98
+ with open(dest, "w") as f:
99
+ f.write(md)
100
+ mc.write_json(mc.out("metrics", f"main_table.{args.transport}.{mode}.json"), rows)
101
+ print(md)
102
+ print(f"written -> {dest}")
103
+
104
+
105
+ if __name__ == "__main__":
106
+ main()
dataset_upload/metrics/mcommon.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Shared plumbing for the BCS/BES/ISS/KTS metric stack.
3
+
4
+ Everything here is deliberately read-only with respect to data/: the fact set
5
+ and the query bank are frozen artefacts (protocol 2.1), and this package only
6
+ consumes them.
7
+
8
+ Path resolution has one rule: entries under `paths:` in configs/metrics.yaml
9
+ are taken relative to the repository root unless they are absolute, and each is
10
+ overridable by an environment variable so nobody has to edit a tracked config
11
+ to run on their own filesystem.
12
+ """
13
+ import os, json, math, functools
14
+
15
+ import numpy as np
16
+ import yaml
17
+
18
+ HERE = os.path.dirname(os.path.abspath(__file__))
19
+ ROOT = os.path.dirname(HERE)
20
+ CONFIGS = os.path.join(ROOT, "configs")
21
+
22
+
23
+ @functools.lru_cache(maxsize=None)
24
+ def cfg():
25
+ with open(os.path.join(CONFIGS, "metrics.yaml")) as f:
26
+ return yaml.safe_load(f)
27
+
28
+
29
+ def _root(key, env):
30
+ p = os.environ.get(env) or cfg()["paths"][key]
31
+ return p if os.path.isabs(p) else os.path.join(ROOT, p)
32
+
33
+
34
+ def data_file(name):
35
+ """A frozen input artefact: the fact set or the query bank."""
36
+ return os.path.join(_root("data", "FKS_DATA"), name)
37
+
38
+
39
+ def runner_dir():
40
+ """Where eval_run.py lives; imported so the prompt format has one owner."""
41
+ return os.path.join(ROOT, "runner")
42
+
43
+
44
+ @functools.lru_cache(maxsize=None)
45
+ def models_cfg():
46
+ with open(os.path.join(CONFIGS, "models.yaml")) as f:
47
+ return yaml.safe_load(f)
48
+
49
+
50
+ def model_entry(name):
51
+ for m in models_cfg()["evaluated_models"]:
52
+ if m["name"] == name:
53
+ return m
54
+ aux = models_cfg().get("auxiliary_models", {})
55
+ for m in aux.values():
56
+ if m["name"] == name:
57
+ return m
58
+ raise KeyError(f"{name} is not in configs/models.yaml")
59
+
60
+
61
+ def model_path(name):
62
+ """Local weights if we have them, otherwise the hub id.
63
+
64
+ Resolution order: $FKS_MODELS/<path>, then configs/models.yaml:model_root
65
+ (absent by default), then the entry's `hf` id, which transformers resolves
66
+ against the hub. A model that is in neither the config nor the hub has to be
67
+ passed explicitly by the caller.
68
+ """
69
+ entry = model_entry(name)
70
+ root = os.environ.get("FKS_MODELS") or models_cfg().get("model_root")
71
+ if root:
72
+ local = os.path.join(root, entry.get("path", name))
73
+ if os.path.isdir(local):
74
+ return local
75
+ if entry.get("hf"):
76
+ return entry["hf"]
77
+ raise SystemExit(
78
+ f"cannot locate weights for {name}: set FKS_MODELS to a directory "
79
+ f"containing '{entry.get('path', name)}', or add an `hf:` id to "
80
+ f"configs/models.yaml")
81
+
82
+
83
+ def out(kind, *parts):
84
+ """kind in {evaluation, hidden, jlens, metrics}."""
85
+ p = os.path.join(_root("outputs", "FKS_OUTPUTS"), kind, *parts)
86
+ os.makedirs(os.path.dirname(p) if os.path.splitext(p)[1] else p, exist_ok=True)
87
+ return p
88
+
89
+
90
+ def generations(model):
91
+ """Where eval_run.py put this model's raw generations."""
92
+ return out("evaluation", f"{model}.jsonl")
93
+
94
+
95
+ def read_jsonl(path):
96
+ with open(path) as f:
97
+ for line in f:
98
+ line = line.strip()
99
+ if line:
100
+ yield json.loads(line)
101
+
102
+
103
+ def write_jsonl(path, rows):
104
+ os.makedirs(os.path.dirname(path), exist_ok=True)
105
+ n = 0
106
+ with open(path, "w") as f:
107
+ for r in rows:
108
+ f.write(json.dumps(r, ensure_ascii=False, default=_jsonable) + "\n")
109
+ n += 1
110
+ return n
111
+
112
+
113
+ def write_json(path, obj):
114
+ os.makedirs(os.path.dirname(path), exist_ok=True)
115
+ with open(path, "w") as f:
116
+ json.dump(obj, f, indent=2, ensure_ascii=False, default=_jsonable)
117
+
118
+
119
+ def _jsonable(o):
120
+ if isinstance(o, (np.floating, np.integer)):
121
+ return o.item()
122
+ if isinstance(o, np.ndarray):
123
+ return o.tolist()
124
+ raise TypeError(type(o))
125
+
126
+
127
+ # ------------------------------------------------------------------- queries
128
+ QUERY_BANK = "evaluation_queries_44416.jsonl"
129
+
130
+
131
+ @functools.lru_cache(maxsize=None)
132
+ def main_forward_queries():
133
+ """The 39,260 queries that protocol 1.1 admits to the main analysis.
134
+
135
+ The filter reads each row's own `use_for_main_forward` flag rather than
136
+ testing `condition_family in main_families`: the flags are derived from
137
+ eval_conditions.yaml and are what the build-time validator checks, so trusting
138
+ them keeps one definition of the split instead of two that can drift.
139
+ """
140
+ rows = []
141
+ for r in read_jsonl(data_file(QUERY_BANK)):
142
+ if r.get("use_for_main_forward"):
143
+ rows.append(r)
144
+ fams = set(cfg()["main_families"])
145
+ bad = {r["condition_family"] for r in rows} - fams
146
+ if bad:
147
+ raise SystemExit(f"main_forward rows carry unexpected families: {bad}")
148
+ return rows
149
+
150
+
151
+ @functools.lru_cache(maxsize=None)
152
+ def facts():
153
+ """fact_id -> record, plus the relation of each fact."""
154
+ return {r["fact_id"]: r for r in read_jsonl(data_file("benchmark_facts_2592.jsonl"))}
155
+
156
+
157
+ @functools.lru_cache(maxsize=None)
158
+ def fact_relation():
159
+ return {fid: r["relation"]["relation_id"] for fid, r in facts().items()}
160
+
161
+
162
+ @functools.lru_cache(maxsize=None)
163
+ def coverage():
164
+ """fact_id -> set of main families that actually contain it.
165
+
166
+ Protocol 1.3: coverage is ragged (multilingual 2,402, context 2,591), and
167
+ the two reporting modes below are both mandatory.
168
+ """
169
+ cov = {}
170
+ for r in main_forward_queries():
171
+ cov.setdefault(r["fact_id"], set()).add(r["condition_family"])
172
+ return cov
173
+
174
+
175
+ @functools.lru_cache(maxsize=None)
176
+ def complete_family_facts():
177
+ """D_cap: the facts carrying all five main families (protocol 1.3).
178
+
179
+ This set is a property of the query bank, not of any model, so every model
180
+ is scored on exactly the same facts -- which is the point of protocol 1.3's
181
+ prohibition on per-model effective sets.
182
+ """
183
+ need = set(cfg()["main_families"])
184
+ return sorted(f for f, c in coverage().items() if c >= need)
185
+
186
+
187
+ def eval_fact_set(mode):
188
+ if mode == "complete_family":
189
+ return complete_family_facts()
190
+ if mode == "full_set":
191
+ return sorted(coverage())
192
+ raise ValueError(mode)
193
+
194
+
195
+ # -------------------------------------------------------------- layer window
196
+ def layer_window(n_layers, min_depth=None):
197
+ """Protocol 7.10: {l : d_l >= min_depth}, d_l = l / (L - 1).
198
+
199
+ `l` indexes decoder blocks 0..L-1, so l = L-1 is the final residual stream
200
+ that J-Lens transports to. In HF terms the state is hidden_states[l+1],
201
+ because hidden_states[0] is the embedding output.
202
+ """
203
+ if min_depth is None:
204
+ min_depth = cfg()["extraction"]["window_min_depth"]
205
+ return [l for l in range(n_layers) if l / max(n_layers - 1, 1) >= min_depth - 1e-9]
206
+
207
+
208
+ def late_window(n_layers):
209
+ return layer_window(n_layers, cfg()["extraction"]["late_min_depth"])
210
+
211
+
212
+ # --------------------------------------------------------------- linear alg
213
+ def l2_normalize(x, axis=-1, eps=1e-12):
214
+ n = np.linalg.norm(x, axis=axis, keepdims=True)
215
+ return x / np.maximum(n, eps)
216
+
217
+
218
+ def pca_whiten(X, dim, shrinkage, eps=1e-12):
219
+ """Return the whitened matrix and the fitted transform.
220
+
221
+ Protocol 7.5 forbids fitting a separate transform per condition family, so
222
+ this is called once per (model, layer) on the pooled matrix and the same
223
+ components are then applied to every family.
224
+ """
225
+ mu = X.mean(axis=0, keepdims=True)
226
+ Xc = X - mu
227
+ # Economy SVD on the centred matrix is the covariance eigendecomposition
228
+ # without ever forming a d x d matrix -- d can be 5120 and n is ~39k.
229
+ k = min(dim, Xc.shape[0], Xc.shape[1])
230
+ U, S, Vt = np.linalg.svd(Xc, full_matrices=False)
231
+ U, S, Vt = U[:, :k], S[:k], Vt[:k]
232
+ var = (S ** 2) / max(Xc.shape[0] - 1, 1)
233
+ # lambda is expressed as a fraction of the mean retained variance so that
234
+ # one config value behaves the same across models with different scales.
235
+ lam = shrinkage * float(var.mean())
236
+ Z = (Xc @ Vt.T) / np.sqrt(var + lam + eps)
237
+ return Z.astype(np.float32), {"mean": mu, "components": Vt, "scale": np.sqrt(var + lam + eps)}
238
+
239
+
240
+ # ------------------------------------------------------------------ negatives
241
+ def negative_sample(fact_ids, relation_of, max_negatives, seed):
242
+ """Protocol 7.8: for each fact, up to `max_negatives` same-relation others.
243
+
244
+ Drawn ONCE from the fixed fact set and reused for every model. If each model
245
+ drew its own, a model could score well merely by having been handed more
246
+ distant negatives.
247
+ """
248
+ rng = np.random.default_rng(seed)
249
+ by_rel = {}
250
+ for f in fact_ids:
251
+ by_rel.setdefault(relation_of[f], []).append(f)
252
+ for r in by_rel:
253
+ by_rel[r].sort()
254
+ negs = {}
255
+ for f in fact_ids:
256
+ pool = [g for g in by_rel[relation_of[f]] if g != f]
257
+ if len(pool) > max_negatives:
258
+ idx = rng.choice(len(pool), size=max_negatives, replace=False)
259
+ pool = [pool[i] for i in sorted(idx)]
260
+ negs[f] = pool
261
+ return negs
262
+
263
+
264
+ # ----------------------------------------------------------------- bootstrap
265
+ def relation_clustered_bootstrap(values, relation_of, n_resamples, seed, ci=0.95):
266
+ """Protocol 14.1: resample relations, then facts within each drawn relation.
267
+
268
+ A plain per-fact bootstrap would understate the interval because the 21
269
+ relations are very unevenly sized and facts inside one relation are far from
270
+ independent.
271
+ """
272
+ fact_ids = [f for f in values if values[f] == values[f]] # drop NaN
273
+ if not fact_ids:
274
+ return {"mean": float("nan"), "lo": float("nan"), "hi": float("nan"), "n": 0}
275
+ by_rel = {}
276
+ for f in fact_ids:
277
+ by_rel.setdefault(relation_of[f], []).append(f)
278
+ rels = sorted(by_rel)
279
+ arr = {r: np.array([values[f] for f in by_rel[r]], dtype=np.float64) for r in rels}
280
+ rng = np.random.default_rng(seed)
281
+ draws = np.empty(n_resamples, dtype=np.float64)
282
+ for b in range(n_resamples):
283
+ picked = rng.integers(0, len(rels), size=len(rels))
284
+ pool = []
285
+ for i in picked:
286
+ a = arr[rels[i]]
287
+ pool.append(a[rng.integers(0, len(a), size=len(a))])
288
+ draws[b] = np.concatenate(pool).mean()
289
+ lo, hi = np.percentile(draws, [(1 - ci) / 2 * 100, (1 + ci) / 2 * 100])
290
+ point = float(np.mean([values[f] for f in fact_ids]))
291
+ return {"mean": point, "lo": float(lo), "hi": float(hi), "n": len(fact_ids)}
dataset_upload/metrics/states.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Per-layer family centroids -- the single input both ISS and KTS consume.
3
+
4
+ Protocol 7.4-7.6 and 8.2 describe one preparation, then branch. Keeping it in
5
+ one place means ISS and KTS cannot silently disagree about what a fact's
6
+ representation under a condition family IS, which would make the joint
7
+ interpretation table (protocol 12) meaningless.
8
+
9
+ z = transport(h) raw: identity; jlens: y = B h
10
+ zbar = z - mu_r - mu_t + mu relation and family main effects removed
11
+ zt = L2(PCA-whiten(zbar)) one transform per (model, layer)
12
+ v = L2(mean of zt within a family) -> [F, T, D], plus a mask
13
+ """
14
+ import os, json
15
+
16
+ import numpy as np
17
+ import torch
18
+
19
+ import mcommon as mc
20
+
21
+
22
+ def l2n(X, eps=1e-12):
23
+ return X / X.norm(dim=-1, keepdim=True).clamp_min(eps)
24
+
25
+
26
+ def whiten(Z, dim, shrinkage, eps):
27
+ """PCA whitening fitted once on the pooled matrix (protocol 7.5).
28
+
29
+ Fitting per condition family is forbidden: it would absorb exactly the
30
+ cross-condition differences these metrics exist to detect.
31
+ """
32
+ mu = Z.mean(0, keepdim=True)
33
+ Zc = Z - mu
34
+ n, d = Zc.shape
35
+ k = min(dim, d)
36
+ # d <= 5120 while n ~ 39k, so the d x d covariance route is far cheaper
37
+ # than an SVD of the tall matrix and numerically equivalent.
38
+ C = (Zc.T @ Zc).double() / max(n - 1, 1)
39
+ evals, evecs = torch.linalg.eigh(C)
40
+ evals = evals.flip(0)[:k].clamp_min(0).float()
41
+ evecs = evecs.flip(1)[:, :k].float()
42
+ lam = shrinkage * float(evals.mean())
43
+ return (Zc @ evecs) / torch.sqrt(evals + lam + eps)
44
+
45
+
46
+ class StateLoader:
47
+ """Streams (layer -> family centroids) for one model."""
48
+
49
+ def __init__(self, model, transport="raw", coverage=None, device="auto",
50
+ shuffle_seed=None):
51
+ C = mc.cfg()
52
+ self.C = C
53
+ self.model = model
54
+ self.transport = transport
55
+ # Protocol 18.1: with fact identity destroyed, ISS must collapse,
56
+ # KTS-ID must fall to chance and KTS-Geo to ~0. If they do not, the
57
+ # metric is measuring something other than the fact.
58
+ self.shuffle_seed = shuffle_seed
59
+ self.mode = coverage or C["headline_coverage"]
60
+ self.dev = ("cuda" if torch.cuda.is_available() else "cpu") \
61
+ if device == "auto" else device
62
+
63
+ self.hdir = mc.out("hidden", model)
64
+ self.meta = json.load(open(os.path.join(self.hdir, "index.json")))
65
+ if not self.meta.get("complete"):
66
+ raise SystemExit(f"{model}: hidden states incomplete; run extract_hidden.py")
67
+
68
+ self.families = C["main_families"]
69
+ fam_id = {t: i for i, t in enumerate(self.families)}
70
+ self.keep_facts = mc.eval_fact_set(self.mode)
71
+ self.fidx = {f: i for i, f in enumerate(self.keep_facts)}
72
+ self.rel_of = mc.fact_relation()
73
+
74
+ self.sel = np.array([i for i, f in enumerate(self.meta["fact_ids"])
75
+ if f in self.fidx], dtype=np.int64)
76
+ self.fact_idx = torch.tensor(
77
+ [self.fidx[self.meta["fact_ids"][i]] for i in self.sel], device=self.dev)
78
+ self.fam_idx = torch.tensor(
79
+ [fam_id[self.meta["families"][i]] for i in self.sel], device=self.dev)
80
+
81
+ self.by_rel = {}
82
+ for f in self.keep_facts:
83
+ self.by_rel.setdefault(self.rel_of[f], []).append(self.fidx[f])
84
+ rel_pos = {r: i for i, r in enumerate(self.by_rel)}
85
+ self.rel_idx = torch.tensor(
86
+ [rel_pos[self.rel_of[self.meta["fact_ids"][i]]] for i in self.sel],
87
+ device=self.dev)
88
+ self.n_rel = len(self.by_rel)
89
+
90
+ self.window = self.meta["window"]
91
+ self.late = set(self.meta["late_window"])
92
+ self.B = None
93
+ if transport == "jlens":
94
+ self.B = {}
95
+ for l in self.window:
96
+ p = mc.out("jlens", model, f"L{l:03d}", "B.npy")
97
+ if not os.path.exists(p):
98
+ raise SystemExit(
99
+ f"{model} L{l}: no J-Lens factor at {p}. Run src/jlens.py "
100
+ "first, or use --transport raw for the ablation.")
101
+ self.B[l] = torch.from_numpy(np.load(p)).to(self.dev).float()
102
+
103
+ @property
104
+ def n_facts(self):
105
+ return len(self.keep_facts)
106
+
107
+ def centroids(self, layer):
108
+ """-> V [F, T, D] (zero where absent), mask [F, T]."""
109
+ icfg = self.C["iss"]
110
+ eps = float(icfg["eps"])
111
+ H = np.load(os.path.join(self.hdir, f"L{layer:03d}.npy"), mmap_mode="r")
112
+ Z = torch.from_numpy(np.ascontiguousarray(H[self.sel])).to(self.dev).float()
113
+ if self.B is not None:
114
+ Z = Z @ self.B[layer].T # y = B h (J-Lens spec 6.4)
115
+
116
+ # ---- protocol 7.4 double residualisation
117
+ mu = Z.mean(0, keepdim=True)
118
+ D = Z.shape[1]
119
+ mu_r = torch.zeros(self.n_rel, D, device=self.dev)
120
+ cr = torch.zeros(self.n_rel, device=self.dev)
121
+ mu_r.index_add_(0, self.rel_idx, Z)
122
+ cr.index_add_(0, self.rel_idx, torch.ones_like(self.rel_idx, dtype=torch.float))
123
+ mu_r /= cr.clamp_min(1).unsqueeze(-1)
124
+ mu_t = torch.zeros(len(self.families), D, device=self.dev)
125
+ ct = torch.zeros(len(self.families), device=self.dev)
126
+ mu_t.index_add_(0, self.fam_idx, Z)
127
+ ct.index_add_(0, self.fam_idx, torch.ones_like(self.fam_idx, dtype=torch.float))
128
+ mu_t /= ct.clamp_min(1).unsqueeze(-1)
129
+ Z = Z - mu_r[self.rel_idx] - mu_t[self.fam_idx] + mu
130
+
131
+ Z = l2n(whiten(Z, icfg["pca_dim"], icfg["shrinkage"], eps))
132
+
133
+ # ---- protocol 7.6 family centroid: average inside the family FIRST, so
134
+ # paraphrase (10,053 queries) cannot outweigh anchor (2,592) in one fact
135
+ F, T, Dn = self.n_facts, len(self.families), Z.shape[1]
136
+ V = torch.zeros(F, T, Dn, device=self.dev)
137
+ cnt = torch.zeros(F, T, device=self.dev)
138
+ flat = self.fact_idx * T + self.fam_idx
139
+ V.view(-1, Dn).index_add_(0, flat, Z)
140
+ cnt.view(-1).index_add_(0, flat, torch.ones_like(flat, dtype=torch.float))
141
+ mask = cnt > 0
142
+ V = V / cnt.clamp_min(1).unsqueeze(-1)
143
+ V = l2n(V) * mask.unsqueeze(-1)
144
+
145
+ if self.shuffle_seed is not None:
146
+ # Permute the fact axis INDEPENDENTLY per family, and permute within
147
+ # a relation so the shuffled control keeps the same relation
148
+ # composition -- otherwise a drop could just mean facts got matched
149
+ # against a different relation, which is not the null being tested.
150
+ g = torch.Generator().manual_seed(self.shuffle_seed + 1000 * layer)
151
+ for t in range(T):
152
+ for members in self.by_rel.values():
153
+ idx = torch.tensor(members)
154
+ perm = idx[torch.randperm(len(members), generator=g)]
155
+ V[idx, t] = V[perm.to(V.device), t].clone()
156
+ mask[idx, t] = mask[perm.to(mask.device), t].clone()
157
+ return V, mask
dataset_upload/protocol/dataset_construction.md ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Construction log —— Fact Knowledge Stability Benchmark
2
+
3
+ > **ARCHIVAL DOCUMENT.** This records how `benchmark_facts_2592.jsonl` and
4
+ > `evaluation_queries_44416.jsonl` were built, for provenance and auditability.
5
+ > It is **not** a usage guide — see the repository README for that, and
6
+ > `evaluation_protocol.md` for the metric definitions.
7
+ >
8
+ > The build scripts themselves and the upstream corpora (CounterFact, LAMA,
9
+ > PopQA) are not distributed here; the two frozen artefacts above are. Paths and
10
+ > sibling-directory references below refer to the original working tree.
11
+ >
12
+ > Two facts in here matter for anyone *using* the benchmark, and are repeated in
13
+ > the README: the **0.59% selection rate** in Stage I (facts were kept only if
14
+ > all five filter models answered them correctly, so the benchmark is
15
+ > deliberately easy), and **F1** (750 of 2,592 facts can be answered by copying
16
+ > the subject string).
17
+
18
+ 方法论要点:
19
+
20
+ > **基准集是固定的 2,592 条,对所有模型相同。** `K_m` 只是每个模型的正确性**标签**,
21
+ > 绝不用来从基准集里删事实(spec §2.1)。模型答错、一直答错、拒答、
22
+ > 在不同条件下答不同答案——事实都留在集合里。
23
+
24
+ ---
25
+
26
+ ## 目录
27
+
28
+ ```
29
+ dataset3/
30
+ ├── configs/ # 全部参数外置,脚本里不硬编码(spec §4.4, §18)
31
+ │ ├── models.yaml # 5 个过滤模型 + 评测模型 + 生成配置
32
+ │ ├── relations.yaml # 21 个基准关系 + 排除清单 + 两个开关
33
+ │ ├── source_templates.yaml # 原始来源、cloze 模板、别名资源
34
+ │ └── eval_conditions.yaml # 8 个条件的角色/目标槽/期望计数
35
+ ├── src/
36
+ │ ├── common.py 公共:配置/规范化/校验和/计数核对
37
+ │ ├── build_candidate_known.py (I) → candidate_known_8107.jsonl
38
+ │ ├── enrich_facts.py (II) → enriched_facts_6180.jsonl
39
+ │ ├── select_benchmark.py (III) → benchmark_facts_2592.jsonl
40
+ │ ├── build_eval_bank.py (IV) → evaluation_queries_44418.jsonl
41
+ │ ├── validate_facts.py → validation_report.json ← 硬门禁
42
+ │ ├── build_stats.py → dataset_statistics.json
43
+ │ ├── qualification_run.py (V) → qualification/<model>.jsonl [GPU]
44
+ │ ├── qualification_score.py (V) → known_labels.json
45
+ │ ├── eval_run.py (VI) → evaluation/<model>.jsonl [GPU]
46
+ │ ├── eval_score.py (VI) → stability_report.json
47
+ │ ├── filter_run.py 阶段 I 首 token 过滤(重跑用) [GPU]
48
+ │ ├── scoring_full.py 五标签判分器
49
+ │ ├── qual_templates.py 非基准关系的兜底问句
50
+ │ └── test_scoring.py 31 条单元测试
51
+ ├── outputs/
52
+ └── run_pipeline.sh # build / gpu / score / report / all
53
+ ```
54
+
55
+ ---
56
+
57
+ ## 六个阶段
58
+
59
+ ### I. 候选召回 → 8,107(spec §4)
60
+
61
+ ```
62
+ 1,783,541 cloze prompt
63
+ → 5 模型首 token argmax 取交集 → 10,601
64
+ → 丢弃 T-REx / Wikidata5M 子集,补 PopQA 378 → 8,107
65
+ ```
66
+
67
+ **GPU 未重跑。** 那 1,783,541 × 5 次前向的逐条判定向量已存于
68
+ `dataset/filter/correct_<model>.npy`。[build_candidate_known.py](src/build_candidate_known.py)
69
+ 重新读取 prompt 表、**重新求交集**、重新施加来源丢弃规则,并把每个输入文件的
70
+ 校验和写进 `stage1_report.json`——数字是**验证出来的**,不是照抄。
71
+ 另外与 `dataset/filter/global_known_clean.jsonl` 做集合相等性核对。
72
+ 要从零重跑推理用 `src/filter_run.py`。
73
+
74
+ ### II. 事实增强 → 6,180(spec §5)
75
+
76
+ - **实体感知分组**:优先用实体 ID,无 ID 才退回规范化文本;**跨来源合并**
77
+ (1,036 组同时出现在 CounterFact 和 LAMA-TREx)。8,107 行 → 6,185 组
78
+ - **函数型冲突丢弃 5 条**:同名不同人(两个 "Michael Vincent" 生于 1964/1976)问题本身无解。
79
+ 判据严格——**缺实体 ID 不算"同一实体"的证据**,所有成员必须都有 ID 且一致才保留
80
+ - **别名扩展**:对别名资源做**单次过滤扫描**(spec §5.3),不全量载入
81
+ - **挂 canonical 问句**,与评测扰动模板严格分离(spec §16)
82
+
83
+ ### III. 基准选择 → 2,592 / 21 关系(spec §6)
84
+
85
+ ```
86
+ 6,180 → core 来源(CounterFact + LAMA-TREx + PopQA)→ 3,705
87
+ → 函数型(单值)关系 → 2,592
88
+ ```
89
+
90
+ ### IV. 查询库 → 44,416(spec §8–§12)
91
+
92
+ | 条件 | 查询 | 事实 | 角色 |
93
+ |---|---:|---:|---|
94
+ | anchor | 2,592 | 2,592 | main |
95
+ | multilingual | 12,010 | 2,402 | main |
96
+ | paraphrase | 10,053 | 2,592 | main |
97
+ | format | 7,776 | 2,592 | main |
98
+ | context | **6,829** | 2,591 | main |
99
+ | reverse | 634 | 253 | **结构分析,单独报** |
100
+ | recognition | 3,412 | 2,585 | 诊断 |
101
+ | reverse_illposed | 1,110 | 1,110 | 诊断 |
102
+ | **合计** | **44,416** | | main forward **39,260** |
103
+
104
+ 每条查询自带 `use_for_main_forward` / `use_for_reverse_analysis` /
105
+ `use_for_recognition_analysis` 三个布尔量,**由 `eval_conditions.yaml` 派生**,
106
+ 下游聚合不需要硬编码哪个条件进哪个平均。校验器会检查每行的布尔量与注册表一致。
107
+
108
+ ### V. Anchor 资格认证 → `K_m` 标签(spec §7)⬜ 待跑
109
+
110
+ 纯补全 prompt(base 与 instruct 用**完全相同**的字符串,无 chat template)、
111
+ 贪婪解码 24 token、无候选无 few-shot。判分在 CPU,**五标签**:
112
+
113
+ `correct` / `incorrect` / `ambiguous` / `abstain` / `unparseable`
114
+
115
+ 输出 `known_labels.json`:`{fact_id: {model: label}}`,覆盖全部 2,592 × 全部模型。
116
+
117
+ ### VI. 扰动评测 → 稳定性 ⬜ 待跑
118
+
119
+ [eval_run.py](src/eval_run.py) 跑全部 44,416 条查询,
120
+ **解码配置与 anchor 完全一致**(同一份 `configs/models.yaml:generation`)——
121
+ 否则 `max_new_tokens` 或 chat template 的差异会被误读成稳定性效应。
122
+ anchor 也一起重跑,让所有条件走同一条代码路径。
123
+
124
+ [eval_score.py](src/eval_score.py) 在 CPU 判分并出报表,三条规则写死在代码里而不是留给读者:
125
+
126
+ 1. **按查询自带的布尔量分组** —— `recognition` 和 `reverse_illposed` 永不进主平均,
127
+ `reverse` 因为换了目标槽而单独报(spec §2.3)
128
+ 2. **两个分母并排报**:`fixed`(固定 2,592,spec §2.1)与
129
+ `anchored`(限定在该模型的 `K_m` 内,即条件化保持率)
130
+ 3. **每个数字按 `answer_in_subject_surface` 再拆一次**(`·real` / `·copy`),
131
+ 因为 28.9% 的事实靠复制就能答对、天然接近满分(见 F1)
132
+
133
+ 主指标 macro = paraphrase / format / context / multilingual 四者均值:
134
+ anchor 是基线不计入,reverse 换了槽不计入,两个诊断条件不计入。
135
+
136
+ ---
137
+
138
+ ## 运行(原工作树,此处不分发)
139
+
140
+ 阶段 I–IV 是建库,产物就是本仓库 `data/` 下的两个文件,不需要重跑。
141
+ 阶段 V–VI 的**生成**部分在本仓库里对应 `runner/eval_run.py`,用法见 README。
142
+
143
+ ---
144
+
145
+ ## 当前状态
146
+
147
+ | 阶段 | 状态 |
148
+ |---|---|
149
+ | I 候选召回 | ✅ 8,107,全部计数命中 |
150
+ | II 事实增强 | ✅ 6,180,6,185 组 / 5 冲突 / 1,771 合并 / 1,036 跨来源,全中 |
151
+ | III 基准选择 | ✅ 2,592 / 21 关系,全中 |
152
+ | IV 查询库 | ✅ 44,416(见差异 D1) |
153
+ | 校验 | ✅ **0 hard errors** |
154
+ | 单元测试 | ✅ **31/31** |
155
+ | V 资格认证 | ⬜ 待跑(判分逻辑已用合成数据演练通过) |
156
+ | VI 扰动评测 | ⬜ 待跑(运行器 + 报表已用合成数据演练通过) |
157
+
158
+ ---
159
+
160
+ ## 与 spec 的差异(完整版见 [outputs/reconstruction_differences.md](outputs/reconstruction_differences.md))
161
+
162
+ 除一处外全部精确复现。
163
+
164
+ **D1 — context 6,831 → 6,829,总计 44,418 → 44,416。**
165
+ 旧数据里有 2 条 context 查询的干扰实体字面包含 gold:
166
+ `"...confuse States Reorganisation Act with **Indian** Act..."` 而 gold 是 `India`。
167
+ 违反 spec §9.4 与 §13.9。按 spec §10「发现既有缺陷可改数」处理:
168
+ 在建库时加**规则化守卫**(主语提及剔除后 gold 仍出现即丢弃),不是硬编码例外。
169
+
170
+ **C1 — spec §6.2 与要求的规模自相矛盾。**
171
+ §6.2 点名 `developer of` / `manufacturer of` 不适合,但这两个关系共 **846 条**,
172
+ 去掉只剩 1,746 条 / 19 关系,达不到 §15 验收要求的 2,592 / 21。
173
+ 处理:保留并打 `spec_6_2_flag`,`relations.yaml` 提供 `drop_spec_6_2_flagged` 开关
174
+ 可一键产出 1,746 条的合规变体。
175
+
176
+ **F1 — 28.9% 的基准事实可以靠复制字符串答对。**
177
+ 2,592 条里有 **750 条** object 字面包含在 subject 名字里:
178
+
179
+ ```
180
+ Airbus A318 → manufacturer Airbus (该关系 87.8% 命中)
181
+ Adobe Acrobat → developer Adobe (49.1%)
182
+ Amazon Music → owned by Amazon (58.4%)
183
+ ```
184
+
185
+ 其中 586 条来自 manufacturer 和 developer——**独立印证了 C1**。
186
+ 这类事实"稳定"的原因与知识无关,会抬高所有保持率、削弱要研究的效应。
187
+ 按 spec §16 不删,打 `answer_in_subject_surface` 标记,事实和查询两级都带。
188
+ `qualification_score.py` 已经**默认分开报**这两个子集的准确率。
189
+
190
+ **F2 — 8,107 里有 808 条完全重复的三元组**(唯一四元组只有 7,299)。分组阶段自然吸收,仅记录。
191
+
192
+ **N1 — Stage I 未重跑 GPU**(见上)。
193
+ **N2 — `capital_of` 方向未归一化**:spec §2.2 要求单一方向,但归一化会改变规模,故保留
194
+ `direction: inverse` + `inverse_of: capital` 显式标注,开关在 `relations.yaml`。
195
+
196
+ ---
197
+
198
+ ## 两个必须记住的口径
199
+
200
+ 1. **分母永远是 2,592。** `K_m` 是标签不是筛子。加模型、换模型都不改任何已算出的数。
201
+ 2. **reverse 不进 main forward 平均。** 它换了目标槽(object → subject),
202
+ spec §2.3 要求单独报。`recognition` 和 `reverse_illposed` 同理,且校验器有硬检查。
203
+
204
+ ---
205
+
206
+ ## 报告用描述(spec §17)
207
+
208
+ > We first use five-model first-token consensus to retrieve high-probability
209
+ > factual candidates from large-scale knowledge resources. We then merge
210
+ > duplicate facts, expand entity aliases, construct independent canonical
211
+ > questions, remove ambiguous and multi-valued relations, and obtain a fixed
212
+ > benchmark of 2,592 facts across 21 relations. Model-specific open-ended anchor
213
+ > generation provides correctness labels but does not alter the benchmark
214
+ > denominator. Based on the fixed fact set, we construct 44,416 queries covering
215
+ > anchor, paraphrastic, format, contextual, cross-lingual, reverse, and
216
+ > recognition conditions, while isolating ill-posed reverse queries as a
217
+ > separate diagnostic set.
dataset_upload/protocol/evaluation_protocol.md ADDED
@@ -0,0 +1,1604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # BCS、BES、ISS 与 KTS 评测规范
2
+
3
+ ## 0. 目的
4
+
5
+ 本规范用于在固定事实知识数据集上评测大语言模型的:
6
+
7
+ 1. **外部行为一致性**;
8
+ 2. **内部事实状态稳定性**;
9
+ 3. **整体知识拓扑稳定性**。
10
+
11
+ 最终报告四个核心指标:
12
+
13
+ \[
14
+ \boxed{
15
+ \mathrm{BCS},\quad
16
+ \mathrm{BES},\quad
17
+ \mathrm{ISS},\quad
18
+ \mathrm{KTS}
19
+ }
20
+ \]
21
+
22
+ 其中:
23
+
24
+ | 指标 | 全称 | 分析层级 | 核心问题 |
25
+ |---|---|---|---|
26
+ | BCS | Behavioral Consistency Score | 单事实、外部行为 | 不同检索条件下是否主要表达同一个答案? |
27
+ | BES | Behavioral Entropy Stability | 单事实、外部行为 | 回答分布是否集中,还是分散到多个答案? |
28
+ | ISS | Internal State Stability | 单事实、内部表示 | 同一事实跨条件是否形成一致且可区分的内部状态? |
29
+ | KTS | Knowledge Topology Stability | 数据集、内部空间 | 不同条件下事实身份与整体知识几何是否保持? |
30
+
31
+ 本规范默认使用固定主事实集:
32
+
33
+ \[
34
+ \mathcal D=\{f_1,\ldots,f_N\},\qquad N=2,592.
35
+ \]
36
+
37
+ 所有被测模型使用完全相同的事实和 query bank。模型在 anchor 条件下是否回答正确,只作为标签,不改变评测分母。
38
+
39
+ ---
40
+
41
+ # 1. 评测条件
42
+
43
+ ## 1.1 主前向检索条件
44
+
45
+ 以下条件保持检索目标为:
46
+
47
+ \[
48
+ (s,r)\rightarrow o.
49
+ \]
50
+
51
+ 记主条件集合为:
52
+
53
+ \[
54
+ \mathcal T=
55
+ \{
56
+ \text{anchor},
57
+ \text{paraphrase},
58
+ \text{format},
59
+ \text{context},
60
+ \text{multilingual}
61
+ \}.
62
+ \]
63
+
64
+ 这些条件进入 BCS、BES、ISS 和 KTS 的主要计算。
65
+
66
+ ## 1.2 独立诊断条件
67
+
68
+ 以下条件不混入主指标:
69
+
70
+ - `recognition`:正确答案已经出现在候选中,属于辅助识别;
71
+ - `reverse`:检索目标从 object 改为 subject,单独报告 structural retrieval;
72
+ - `reverse_illposed`:反向映射不唯一,只用于数据诊断。
73
+
74
+ ## 1.3 覆盖不完整时的处理
75
+
76
+ 当前数据中:
77
+
78
+ - anchor:覆盖 2,592 条事实;
79
+ - paraphrase:覆盖 2,592 条事实;
80
+ - format:覆盖 2,592 条事实;
81
+ - context:覆盖 2,591 条事实;
82
+ - multilingual:覆盖 2,402 条事实。
83
+
84
+ 推荐优先补齐缺失条件。
85
+
86
+ 在未补齐前,应同时报告:
87
+
88
+ ### Complete-family 主结果
89
+
90
+ 仅使用具备全部五个主条件的事实集合:
91
+
92
+ \[
93
+ \mathcal D_{\cap}
94
+ =
95
+ \bigcap_{t\in\mathcal T}\mathcal D_t.
96
+ \]
97
+
98
+ 这是最严格、最可比的主结果。
99
+
100
+ ### Full-set 补充结果
101
+
102
+ 对每条事实使用其实际存在的条件集合:
103
+
104
+ \[
105
+ \mathcal T_f
106
+ =
107
+ \{t\in\mathcal T:f\in\mathcal D_t\}.
108
+ \]
109
+
110
+ 所有平均都按可用 condition family 等权计算,并报告每个指标的有效样本数。
111
+
112
+ 不能为缺失条件伪造零分,也不能把不同模型的有效事实集设为不同集合。
113
+
114
+ ---
115
+
116
+ # 2. 必要输入
117
+
118
+ ## 2.1 Fact 文件
119
+
120
+ 每条事实至少包含:
121
+
122
+ ```json
123
+ {
124
+ "fact_id": "fact_000001",
125
+ "subject": "France",
126
+ "relation": "capital",
127
+ "object": "Paris",
128
+ "gold_aliases": ["Paris", "City of Paris"],
129
+ "answer_type": "city",
130
+ "answer_granularity": "entity"
131
+ }
132
+ ```
133
+
134
+ ## 2.2 Query 文件
135
+
136
+ 每条 query 至少包含:
137
+
138
+ ```json
139
+ {
140
+ "query_id": "query_00000001",
141
+ "fact_id": "fact_000001",
142
+ "condition_family": "paraphrase",
143
+ "variant_id": "para_02",
144
+ "language": "en",
145
+ "query": "Which city serves as the capital of France?",
146
+ "target_slot": "object",
147
+ "use_for_main_forward": true
148
+ }
149
+ ```
150
+
151
+ ## 2.3 模型输出文件
152
+
153
+ ```json
154
+ {
155
+ "model": "model_name",
156
+ "query_id": "query_00000001",
157
+ "fact_id": "fact_000001",
158
+ "condition_family": "paraphrase",
159
+ "raw_response": "The answer is Paris.",
160
+ "generation_config": {
161
+ "do_sample": false,
162
+ "temperature": 0,
163
+ "max_new_tokens": 24
164
+ }
165
+ }
166
+ ```
167
+
168
+ ## 2.4 内部表示文件
169
+
170
+ ISS 和 KTS 需要在模型尚未生成第一个答案 token 时,提取问题末位位置的 residual state:
171
+
172
+ ```json
173
+ {
174
+ "model": "model_name",
175
+ "query_id": "query_00000001",
176
+ "fact_id": "fact_000001",
177
+ "condition_family": "paraphrase",
178
+ "layer": 16,
179
+ "position": "query_end",
180
+ "hidden_state_path": "..."
181
+ }
182
+ ```
183
+
184
+ 必须保证所有 query 使用同一种位置定义:
185
+
186
+ > 输入 prompt 的最后一个有效 token,即模型读完问题但尚未开始生成答案的位置。
187
+
188
+ ---
189
+
190
+ # 3. AI Judge 输出协议
191
+
192
+ BCS 和 BES 不直接比较原始字符串,而基于 AI Judge 得到的语义答案 cluster。
193
+
194
+ 整个过程分为两步。
195
+
196
+ ## 3.1 Reference-blind 答案抽取与聚类
197
+
198
+ Judge 不看 gold answer,只完成:
199
+
200
+ 1. 提取回答最终主张的核心答案;
201
+ 2. 忽略句式、语言、标点和解释性文字;
202
+ 3. 将语义等价答案归为同一 cluster;
203
+ 4. 标记拒答、多答案和无法解析输出。
204
+
205
+ 例如:
206
+
207
+ ```text
208
+ Paris
209
+ The answer is Paris.
210
+ Paris, France.
211
+ 巴黎
212
+ ```
213
+
214
+ 应归入同一个语义 cluster。
215
+
216
+ 建议特殊 cluster:
217
+
218
+ - `ABSTAIN`:拒答或明确表示不知道;
219
+ - `MULTIPLE`:给出多个冲突答案且未选择;
220
+ - `UNPARSEABLE`:无法提取明确答案;
221
+ - 具��实体或命题 cluster,如 `ENTITY_Q90` 或 `SEMANTIC_PARIS`。
222
+
223
+ Judge 输出:
224
+
225
+ ```json
226
+ {
227
+ "query_id": "query_00000001",
228
+ "fact_id": "fact_000001",
229
+ "cluster_id": "ENTITY_Q90",
230
+ "canonical_meaning": "Paris",
231
+ "status": "ANSWER",
232
+ "confidence": 0.98
233
+ }
234
+ ```
235
+
236
+ 同一事实的所有主条件输出应一次性或全局一致地聚类,避免两两判断产生非传递关系。
237
+
238
+ ## 3.2 Reference-aware 正确性判断
239
+
240
+ 第二步再向 Judge 提供:
241
+
242
+ - gold answer;
243
+ - accepted aliases;
244
+ - answer type;
245
+ - answer granularity。
246
+
247
+ 对每个语义 cluster 标记:
248
+
249
+ - `CORRECT`;
250
+ - `INCORRECT`;
251
+ - `ABSTAIN`;
252
+ - `AMBIGUOUS`;
253
+ - `REVIEW_REQUIRED`。
254
+
255
+ 该步骤用于区分 Stable Correct 和 Stable Wrong,但不参与答案 cluster 的形成。
256
+
257
+ ---
258
+
259
+ # 4. BCS:Behavioral Consistency Score
260
+
261
+ ## 4.1 为什么需要 family-balanced 计算
262
+
263
+ 不同 condition family 的 query 数量差异很大。例如:
264
+
265
+ - paraphrase 可能有 3–5 个版本;
266
+ - multilingual 可能有多个语言版本;
267
+ - anchor 通常只有 1 条。
268
+
269
+ 如果直接按全部 query 计数,query 更多的 family 会支配结果。
270
+
271
+ 因此必须先在每个 family 内计算答案分布,再对 family 等权聚合。
272
+
273
+ ## 4.2 Family 内答案分布
274
+
275
+ 设事实 \(f\) 在 family \(t\) 下的 query 集为:
276
+
277
+ \[
278
+ Q_{f,t}.
279
+ \]
280
+
281
+ AI Judge 给 query \(q\) 分配语义 cluster:
282
+
283
+ \[
284
+ \kappa_{m,f,q}.
285
+ \]
286
+
287
+ 对于答案 cluster \(a\),定义:
288
+
289
+ \[
290
+ p_{m,f,t}(a)
291
+ =
292
+ \frac{1}{|Q_{f,t}|}
293
+ \sum_{q\in Q_{f,t}}
294
+ \mathbb I[
295
+ \kappa_{m,f,q}=a
296
+ ].
297
+ \]
298
+
299
+ 每个 family 的总概率满足:
300
+
301
+ \[
302
+ \sum_a p_{m,f,t}(a)=1.
303
+ \]
304
+
305
+ ## 4.3 跨 family 等权聚合
306
+
307
+ 对事实 \(f\) 的有效主条件集合 \(\mathcal T_f\),定义:
308
+
309
+ \[
310
+ p_{m,f}(a)
311
+ =
312
+ \frac{1}{|\mathcal T_f|}
313
+ \sum_{t\in\mathcal T_f}
314
+ p_{m,f,t}(a).
315
+ \]
316
+
317
+ 这样每个 condition family 权重相同,不受该 family 中 query 数量影响。
318
+
319
+ ## 4.4 BCS 定义
320
+
321
+ \[
322
+ \boxed{
323
+ \mathrm{BCS}_{m,f}
324
+ =
325
+ \max_a p_{m,f}(a)
326
+ }
327
+ \]
328
+
329
+ 取最大概率的 cluster:
330
+
331
+ \[
332
+ a^*_{m,f}
333
+ =
334
+ \arg\max_a p_{m,f}(a).
335
+ \]
336
+
337
+ 解释:
338
+
339
+ - \(\mathrm{BCS}=1\):所有有效条件都只支持同一个语义答案;
340
+ - \(\mathrm{BCS}=0.8\):主要答案获得 80% 的 family-balanced 概率;
341
+ - BCS 较低:输出分散到多个答案。
342
+
343
+ BCS 不判断主答案是否正确。
344
+
345
+ 例如,gold 是 `Canberra`,但所有条件都回答 `Sydney`:
346
+
347
+ \[
348
+ \mathrm{BCS}=1.
349
+ \]
350
+
351
+ 这是高度稳定但错误的行为。
352
+
353
+ ## 4.5 模型级 BCS
354
+
355
+ \[
356
+ \boxed{
357
+ \mathrm{BCS}_m
358
+ =
359
+ \frac{1}{|\mathcal D_{\mathrm{eval}}|}
360
+ \sum_{f\in\mathcal D_{\mathrm{eval}}}
361
+ \mathrm{BCS}_{m,f}
362
+ }
363
+ \]
364
+
365
+ 其中:
366
+
367
+ - 主结果使用 \(\mathcal D_{\cap}\);
368
+ - 补充结果可使用完整可用集合。
369
+
370
+ ---
371
+
372
+ # 5. BES:Behavioral Entropy Stability
373
+
374
+ BCS 只关注最大答案 cluster,可能忽略剩余概率如何分布。
375
+
376
+ 例如以下两种情况的 BCS 都是 0.6:
377
+
378
+ ```text
379
+ A: 0.6, B: 0.4
380
+ ```
381
+
382
+ 和:
383
+
384
+ ```text
385
+ A: 0.6, B: 0.1, C: 0.1, D: 0.1, E: 0.1
386
+ ```
387
+
388
+ 第二种回答明显更加分散,因此需要 BES。
389
+
390
+ ## 5.1 答案熵
391
+
392
+ 基于 family-balanced 分布 \(p_{m,f}(a)\),定义:
393
+
394
+ \[
395
+ H_{m,f}
396
+ =
397
+ -\sum_{a:p_{m,f}(a)>0}
398
+ p_{m,f}(a)\log p_{m,f}(a).
399
+ \]
400
+
401
+ 设实际观察到的非零答案 cluster 数为:
402
+
403
+ \[
404
+ A_{m,f}
405
+ =
406
+ \left|
407
+ \{a:p_{m,f}(a)>0\}
408
+ \right|.
409
+ \]
410
+
411
+ ## 5.2 BES 定义
412
+
413
+ 当 \(A_{m,f}=1\) 时:
414
+
415
+ \[
416
+ \mathrm{BES}_{m,f}=1.
417
+ \]
418
+
419
+ 当 \(A_{m,f}>1\) 时:
420
+
421
+ \[
422
+ \boxed{
423
+ \mathrm{BES}_{m,f}
424
+ =
425
+ 1-
426
+ \frac{H_{m,f}}{\log A_{m,f}}
427
+ }
428
+ \]
429
+
430
+ 解释:
431
+
432
+ - \(\mathrm{BES}=1\):回答完全集中于一个 cluster;
433
+ - \(\mathrm{BES}=0\):回答在所有已观察 cluster 上均匀分布;
434
+ - 值越高,回答分布越集中。
435
+
436
+ BCS 和 BES 的区别:
437
+
438
+ - BCS 衡量最大 cluster 的占比;
439
+ - BES 衡量完整答案分布的集中程度。
440
+
441
+ 建议将 BCS 作为主外部稳定性指标,BES 作为补充指标。
442
+
443
+ ## 5.3 模型级 BES
444
+
445
+ \[
446
+ \boxed{
447
+ \mathrm{BES}_m
448
+ =
449
+ \frac{1}{|\mathcal D_{\mathrm{eval}}|}
450
+ \sum_{f\in\mathcal D_{\mathrm{eval}}}
451
+ \mathrm{BES}_{m,f}
452
+ }
453
+ \]
454
+
455
+ ---
456
+
457
+ # 6. 外部行为类型
458
+
459
+ 设置预注册的行为稳定阈值:
460
+
461
+ \[
462
+ \tau_B=0.8.
463
+ \]
464
+
465
+ 根据主答案 cluster \(a^*_{m,f}\) 的正确性,将事实划分为:
466
+
467
+ ## 6.1 Stable Correct
468
+
469
+ \[
470
+ \mathrm{BCS}_{m,f}\ge \tau_B
471
+ \]
472
+
473
+ 且:
474
+
475
+ \[
476
+ a^*_{m,f}\text{ 被 Judge 标记为 CORRECT}.
477
+ \]
478
+
479
+ ## 6.2 Stable Wrong
480
+
481
+ \[
482
+ \mathrm{BCS}_{m,f}\ge \tau_B
483
+ \]
484
+
485
+ 且主 cluster 是明确的错误答案。
486
+
487
+ ## 6.3 Stable Abstention
488
+
489
+ \[
490
+ \mathrm{BCS}_{m,f}\ge \tau_B
491
+ \]
492
+
493
+ 且:
494
+
495
+ \[
496
+ a^*_{m,f}=\mathrm{ABSTAIN}.
497
+ \]
498
+
499
+ ## 6.4 Unstable
500
+
501
+ \[
502
+ \mathrm{BCS}_{m,f}<\tau_B.
503
+ \]
504
+
505
+ 建议额外做阈值敏感性分析:
506
+
507
+ \[
508
+ \tau_B\in\{0.7,0.8,0.9\}.
509
+ \]
510
+
511
+ 模型级比例:
512
+
513
+ \[
514
+ \mathrm{SCR}_m
515
+ =
516
+ \frac{\#\text{Stable Correct}}{|\mathcal D_{\mathrm{eval}}|},
517
+ \]
518
+
519
+ \[
520
+ \mathrm{SWR}_m
521
+ =
522
+ \frac{\#\text{Stable Wrong}}{|\mathcal D_{\mathrm{eval}}|},
523
+ \]
524
+
525
+ \[
526
+ \mathrm{SAR}_m
527
+ =
528
+ \frac{\#\text{Stable Abstention}}{|\mathcal D_{\mathrm{eval}}|},
529
+ \]
530
+
531
+ \[
532
+ \mathrm{UR}_m
533
+ =
534
+ \frac{\#\text{Unstable}}{|\mathcal D_{\mathrm{eval}}|}.
535
+ \]
536
+
537
+ 四者应满足:
538
+
539
+ \[
540
+ \mathrm{SCR}_m+
541
+ \mathrm{SWR}_m+
542
+ \mathrm{SAR}_m+
543
+ \mathrm{UR}_m
544
+ =1.
545
+ \]
546
+
547
+ ---
548
+
549
+ # 7. ISS:Internal State Stability
550
+
551
+ ## 7.1 测量目标
552
+
553
+ ISS 衡量:
554
+
555
+ > 同一事实在不同主检索条件下,是否形成一致且具有事实区分性的内部状态。
556
+
557
+ ISS 不依赖模型最终答案是否正确,也不依赖 gold answer 是单 token 还是多 token。
558
+
559
+ ## 7.2 Query-end hidden state
560
+
561
+ 对于模型 \(m\)、事实 \(f\)、query \(q\) 和层 \(\ell\),提取:
562
+
563
+ \[
564
+ h^\ell_{m,f,q}\in\mathbb R^{d_m}.
565
+ \]
566
+
567
+ 位置固定为 query 最后一个有效输入 token。
568
+
569
+ ## 7.3 J-Lens Jacobian transport
570
+
571
+ 对每一层估计平均 Jacobian transport:
572
+
573
+ \[
574
+ J^\ell_m
575
+ =
576
+ \mathbb E_x
577
+ \left[
578
+ \frac{\partial h^L_m}{\partial h^\ell_m}
579
+ \right].
580
+ \]
581
+
582
+ 将第 \(\ell\) 层状态运输到 final-layer residual basis:
583
+
584
+ \[
585
+ \boxed{
586
+ z^\ell_{m,f,q}
587
+ =
588
+ J^\ell_m h^\ell_{m,f,q}
589
+ }
590
+ \]
591
+
592
+ 这里只使用运输后的 hidden representation,不乘 unembedding matrix,因此不进入 vocabulary space。
593
+
594
+ 如果暂时无法实现 Jacobian transport,可以用 raw hidden state 计算一个 `Raw-ISS` 作为消融,但主指标应使用 transported state。
595
+
596
+ ## 7.4 去除 relation 和 condition family 主效应
597
+
598
+ 对每个模型和层计算:
599
+
600
+ \[
601
+ \mu^\ell_m
602
+ =
603
+ \mathbb E_{f,q}[z^\ell_{m,f,q}],
604
+ \]
605
+
606
+ \[
607
+ \mu^\ell_{m,r}
608
+ =
609
+ \mathbb E_{f,q:r_f=r}[z^\ell_{m,f,q}],
610
+ \]
611
+
612
+ \[
613
+ \mu^\ell_{m,t}
614
+ =
615
+ \mathbb E_{f,q:t(q)=t}[z^\ell_{m,f,q}].
616
+ \]
617
+
618
+ 双重残差化:
619
+
620
+ \[
621
+ \bar z^\ell_{m,f,q}
622
+ =
623
+ z^\ell_{m,f,q}
624
+ -
625
+ \mu^\ell_{m,r_f}
626
+ -
627
+ \mu^\ell_{m,t(q)}
628
+ +
629
+ \mu^\ell_m.
630
+ \]
631
+
632
+ 该步骤用于减少:
633
+
634
+ - relation 类型共有方向;
635
+ - query 格式共有方向;
636
+ - 语言 family 共有方向;
637
+ - residual stream 公共均值。
638
+
639
+ ## 7.5 正则化白化
640
+
641
+ 估计协方差:
642
+
643
+ \[
644
+ \Sigma^\ell_m
645
+ =
646
+ \operatorname{Cov}
647
+ \left(
648
+ \bar z^\ell_{m,f,q}
649
+ \right).
650
+ \]
651
+
652
+ 定义:
653
+
654
+ \[
655
+ \tilde z^\ell_{m,f,q}
656
+ =
657
+ \left(
658
+ \Sigma^\ell_m+\lambda I
659
+ \right)^{-1/2}
660
+ \bar z^\ell_{m,f,q}.
661
+ \]
662
+
663
+ 实践建议:
664
+
665
+ - 使用 shrinkage covariance;
666
+ - 或使用 PCA whitening;
667
+ - PCA 维度固定为 \(\min(512,d_m)\);
668
+ - 所有 query 使用同一个模型、同一层的变换;
669
+ - 不允许为不同 condition family 单独拟合白化矩阵。
670
+
671
+ 随后进行 L2 归一化:
672
+
673
+ \[
674
+ \hat z^\ell_{m,f,q}
675
+ =
676
+ \frac{\tilde z^\ell_{m,f,q}}
677
+ {\|\tilde z^\ell_{m,f,q}\|_2+\epsilon}.
678
+ \]
679
+
680
+ ## 7.6 Family centroid
681
+
682
+ 一个 family 内可能有多个 query。为了避免 query 数量多的 family 获得更高权重,先计算 family centroid:
683
+
684
+ \[
685
+ v^\ell_{m,f,t}
686
+ =
687
+ \operatorname{Normalize}
688
+ \left(
689
+ \frac{1}{|Q_{f,t}|}
690
+ \sum_{q\in Q_{f,t}}
691
+ \hat z^\ell_{m,f,q}
692
+ \right).
693
+ \]
694
+
695
+ 每条事实在每个 condition family 下只保留一个表示。
696
+
697
+ ## 7.7 同事实跨 family 相似度
698
+
699
+ 设事实 \(f\) 的有效 family pair 集为:
700
+
701
+ \[
702
+ \mathcal P_f
703
+ =
704
+ \{(t,t'):t,t'\in\mathcal T_f,\ t<t'\}.
705
+ \]
706
+
707
+ 定义正样本相似度:
708
+
709
+ \[
710
+ S^+_{m,f,\ell}
711
+ =
712
+ \frac{1}{|\mathcal P_f|}
713
+ \sum_{(t,t')\in\mathcal P_f}
714
+ \cos
715
+ \left(
716
+ v^\ell_{m,f,t},
717
+ v^\ell_{m,f,t'}
718
+ \right).
719
+ \]
720
+
721
+ ## 7.8 同 relation 背景相似度
722
+
723
+ 为每个事实选择同 relation、不同事实的负样本集合:
724
+
725
+ \[
726
+ \mathcal N_f
727
+ =
728
+ \{g:g\neq f,\ r_g=r_f\}.
729
+ \]
730
+
731
+ 对于每个 family pair,使用对称背景:
732
+
733
+ \[
734
+ B_{m,f,\ell}(t,t')
735
+ =
736
+ \frac{1}{2|\mathcal N_f|}
737
+ \sum_{g\in\mathcal N_f}
738
+ \left[
739
+ \cos(v^\ell_{m,f,t},v^\ell_{m,g,t'})
740
+ +
741
+ \cos(v^\ell_{m,f,t'},v^\ell_{m,g,t})
742
+ \right].
743
+ \]
744
+
745
+ 再定义:
746
+
747
+ \[
748
+ S^-_{m,f,\ell}
749
+ =
750
+ \frac{1}{|\mathcal P_f|}
751
+ \sum_{(t,t')\in\mathcal P_f}
752
+ B_{m,f,\ell}(t,t').
753
+ \]
754
+
755
+ 如果同 relation 事实过多,可以固定随机采样最多 100 个负事实,并对所有模型使用同一采样列表。
756
+
757
+ ## 7.9 ISS 定义
758
+
759
+ \[
760
+ \boxed{
761
+ \mathrm{ISS}_{m,f,\ell}
762
+ =
763
+ \frac{
764
+ S^+_{m,f,\ell}
765
+ -
766
+ S^-_{m,f,\ell}
767
+ }{
768
+ 1-S^-_{m,f,\ell}+\epsilon
769
+ }
770
+ }
771
+ \]
772
+
773
+ 解释:
774
+
775
+ - 接近 1:同一事实跨条件高度一致;
776
+ - 接近 0:同一事实的相似性不高于同 relation 背景;
777
+ - 小于 0:跨条件表示比其他事实背景还不一致。
778
+
779
+ 该值理论上可能小于 \(-1\)。统计分析应保留原始值;如果用于图表展示,可额外报告裁剪版本:
780
+
781
+ \[
782
+ \mathrm{ISS}^{\mathrm{clip}}
783
+ =
784
+ \operatorname{clip}(\mathrm{ISS},-1,1).
785
+ \]
786
+
787
+ 不要用裁剪值替代原始统计值。
788
+
789
+ ## 7.10 跨层 ISS
790
+
791
+ 将相对层深定义为:
792
+
793
+ \[
794
+ d_\ell
795
+ =
796
+ \frac{\ell}{L_m-1}.
797
+ \]
798
+
799
+ 预注册主分析窗口:
800
+
801
+ \[
802
+ \mathcal W_m
803
+ =
804
+ \{\ell:0.4\le d_\ell\le1.0\}.
805
+ \]
806
+
807
+ 单事实 ISS:
808
+
809
+ \[
810
+ \boxed{
811
+ \mathrm{ISS}_{m,f}
812
+ =
813
+ \frac{1}{|\mathcal W_m|}
814
+ \sum_{\ell\in\mathcal W_m}
815
+ \mathrm{ISS}_{m,f,\ell}
816
+ }
817
+ \]
818
+
819
+ 模型级 ISS:
820
+
821
+ \[
822
+ \boxed{
823
+ \mathrm{ISS}_m
824
+ =
825
+ \frac{1}{|\mathcal D_{\mathrm{eval}}|}
826
+ \sum_{f\in\mathcal D_{\mathrm{eval}}}
827
+ \mathrm{ISS}_{m,f}
828
+ }
829
+ \]
830
+
831
+ 同时建议报告:
832
+
833
+ ### Peak ISS
834
+
835
+ \[
836
+ \mathrm{ISS}^{\mathrm{peak}}_{m,f}
837
+ =
838
+ \max_{\ell\in\mathcal W_m}
839
+ \mathrm{ISS}_{m,f,\ell}.
840
+ \]
841
+
842
+ 表示模型是否曾形成过一致事实状态。
843
+
844
+ ### Late ISS
845
+
846
+ \[
847
+ \mathrm{ISS}^{\mathrm{late}}_{m,f}
848
+ =
849
+ \frac{1}{|\mathcal W^{\mathrm{late}}_m|}
850
+ \sum_{\ell:d_\ell\ge0.8}
851
+ \mathrm{ISS}_{m,f,\ell}.
852
+ \]
853
+
854
+ 表示一致状态是否保持到靠近输出的阶段。
855
+
856
+ ---
857
+
858
+ # 8. KTS:Knowledge Topology Stability
859
+
860
+ ## 8.1 测量目标
861
+
862
+ KTS 衡量:
863
+
864
+ > 不同 condition family 下,整个事实表示空间的相对几何和事实身份是否保持。
865
+
866
+ KTS 不要求不同问法触发相同的计算路径。
867
+
868
+ 它允许:
869
+
870
+ - 整体空间旋转;
871
+ - 平移;
872
+ - 各向同性缩放;
873
+ - 不同语言使用不同内部实现。
874
+
875
+ 只要事实间相对结构和事实身份仍可保持,KTS 就可以较高。
876
+
877
+ ## 8.2 Condition-specific knowledge space
878
+
879
+ 对 condition family \(t\)、层 \(\ell\),将所有有效事实的 family centroid 组成:
880
+
881
+ \[
882
+ V^\ell_{m,t}
883
+ =
884
+ \begin{bmatrix}
885
+ v^\ell_{m,1,t}\\
886
+ v^\ell_{m,2,t}\\
887
+ \vdots\\
888
+ v^\ell_{m,N_t,t}
889
+ \end{bmatrix}.
890
+ \]
891
+
892
+ 对 family pair \((t,t')\),只使用共同覆盖事实:
893
+
894
+ \[
895
+ \mathcal D_{t,t'}
896
+ =
897
+ \mathcal D_t\cap\mathcal D_{t'}.
898
+ \]
899
+
900
+ 不同模型必须使用完全相同的 \(\mathcal D_{t,t'}\)。
901
+
902
+ ---
903
+
904
+ # 9. KTS-Geo:全局几何稳定性
905
+
906
+ ## 9.1 Relation 内距离矩阵
907
+
908
+ 为减少 relation 不平衡和 relation 间宏观差异的支配作用,KTS-Geo 按 relation 计算后再宏平均。
909
+
910
+ 对于 relation \(r\),定义:
911
+
912
+ \[
913
+ \mathcal D_{r,t,t'}
914
+ =
915
+ \{f\in\mathcal D_{t,t'}:r_f=r\}.
916
+ \]
917
+
918
+ 仅保留至少包含 5 条事实的 relation。
919
+
920
+ 在 family \(t\) 下构造 relation 内距离:
921
+
922
+ \[
923
+ D^\ell_{m,t,r}(f,g)
924
+ =
925
+ 1-
926
+ \cos
927
+ \left(
928
+ v^\ell_{m,f,t},
929
+ v^\ell_{m,g,t}
930
+ \right).
931
+ \]
932
+
933
+ 在 family \(t'\) 下类似构造:
934
+
935
+ \[
936
+ D^\ell_{m,t',r}(f,g).
937
+ \]
938
+
939
+ ## 9.2 Relation 内几何相关性
940
+
941
+ \[
942
+ \rho^\ell_{m,r}(t,t')
943
+ =
944
+ \operatorname{Spearman}
945
+ \left(
946
+ \operatorname{vec}_{f<g}D^\ell_{m,t,r},
947
+ \operatorname{vec}_{f<g}D^\ell_{m,t',r}
948
+ \right).
949
+ \]
950
+
951
+ ## 9.3 Relation-macro KTS-Geo
952
+
953
+ \[
954
+ \boxed{
955
+ \mathrm{KTS}^{\mathrm{geo}}_{m,\ell}(t,t')
956
+ =
957
+ \frac{1}{|\mathcal R_{t,t'}|}
958
+ \sum_{r\in\mathcal R_{t,t'}}
959
+ \rho^\ell_{m,r}(t,t')
960
+ }
961
+ \]
962
+
963
+ 该值范围为:
964
+
965
+ \[
966
+ [-1,1].
967
+ \]
968
+
969
+ 解释:
970
+
971
+ - 1:事实距离排序完全保持;
972
+ - 0:两个条件下的事实几何无显著对应;
973
+ - 负值:事实距离结构发生反向重排。
974
+
975
+ 为了与 KTS-ID 合成,需要映射到 \([0,1]\):
976
+
977
+ \[
978
+ \widetilde{\mathrm{KTS}}^{\mathrm{geo}}
979
+ =
980
+ \frac{
981
+ \mathrm{KTS}^{\mathrm{geo}}+1
982
+ }{2}.
983
+ \]
984
+
985
+ ---
986
+
987
+ # 10. KTS-ID:事实身份稳定性
988
+
989
+ 全局距离结构可能看起来类似,但局部事实身份仍可能交换,因此需要 cross-condition fact identification。
990
+
991
+ ## 10.1 跨条件最近邻检索
992
+
993
+ 对于事实 \(f\) 在 family \(t\) 下的表示,在 family \(t'\) 的同 relation 事实中检索最近邻:
994
+
995
+ \[
996
+ \hat f_{t\rightarrow t'}
997
+ =
998
+ \arg\max_{
999
+ g\in\mathcal D_{r_f,t,t'}
1000
+ }
1001
+ \cos
1002
+ \left(
1003
+ v^\ell_{m,f,t},
1004
+ v^\ell_{m,g,t'}
1005
+ \right).
1006
+ \]
1007
+
1008
+ 反向同样计算:
1009
+
1010
+ \[
1011
+ \hat f_{t'\rightarrow t}.
1012
+ \]
1013
+
1014
+ ## 10.2 Relation 内 Top-1 身份准确率
1015
+
1016
+ \[
1017
+ \mathrm{ID}_{m,\ell,r}(t\rightarrow t')
1018
+ =
1019
+ \frac{1}{|\mathcal D_{r,t,t'}|}
1020
+ \sum_{f\in\mathcal D_{r,t,t'}}
1021
+ \mathbb I[
1022
+ \hat f_{t\rightarrow t'}=f
1023
+ ].
1024
+ \]
1025
+
1026
+ 进行双向平均:
1027
+
1028
+ \[
1029
+ \mathrm{ID}^{\mathrm{sym}}_{m,\ell,r}(t,t')
1030
+ =
1031
+ \frac{
1032
+ \mathrm{ID}_{m,\ell,r}(t\rightarrow t')
1033
+ +
1034
+ \mathrm{ID}_{m,\ell,r}(t'\rightarrow t)
1035
+ }{2}.
1036
+ \]
1037
+
1038
+ ## 10.3 Chance correction
1039
+
1040
+ 若 relation \(r\) 有 \(n_r\) 条事实,随机 Top-1 命中的概率为:
1041
+
1042
+ \[
1043
+ b_r=\frac{1}{n_r}.
1044
+ \]
1045
+
1046
+ 定义 chance-corrected identity:
1047
+
1048
+ \[
1049
+ \mathrm{ID}^{\mathrm{adj}}_{m,\ell,r}
1050
+ =
1051
+ \frac{
1052
+ \mathrm{ID}^{\mathrm{sym}}_{m,\ell,r}-b_r
1053
+ }{
1054
+ 1-b_r+\epsilon
1055
+ }.
1056
+ \]
1057
+
1058
+ 用于合成时裁剪到:
1059
+
1060
+ \[
1061
+ [0,1].
1062
+ \]
1063
+
1064
+ ## 10.4 Relation-macro KTS-ID
1065
+
1066
+ \[
1067
+ \boxed{
1068
+ \mathrm{KTS}^{\mathrm{id}}_{m,\ell}(t,t')
1069
+ =
1070
+ \frac{1}{|\mathcal R_{t,t'}|}
1071
+ \sum_{r\in\mathcal R_{t,t'}}
1072
+ \operatorname{clip}
1073
+ \left(
1074
+ \mathrm{ID}^{\mathrm{adj}}_{m,\ell,r},
1075
+ 0,1
1076
+ \right)
1077
+ }
1078
+ \]
1079
+
1080
+ 建议同时报告原始:
1081
+
1082
+ - Top-1 accuracy;
1083
+ - Top-5 accuracy;
1084
+ - mean reciprocal rank;
1085
+ - chance-corrected Top-1。
1086
+
1087
+ 主 KTS 使用 chance-corrected Top-1。
1088
+
1089
+ ---
1090
+
1091
+ # 11. KTS 合成
1092
+
1093
+ 对于 family pair \((t,t')\) 和层 \(\ell\),定义:
1094
+
1095
+ \[
1096
+ g
1097
+ =
1098
+ \widetilde{\mathrm{KTS}}^{\mathrm{geo}}_{m,\ell}(t,t'),
1099
+ \]
1100
+
1101
+ \[
1102
+ i
1103
+ =
1104
+ \mathrm{KTS}^{\mathrm{id}}_{m,\ell}(t,t').
1105
+ \]
1106
+
1107
+ 使用调和平均:
1108
+
1109
+ \[
1110
+ \boxed{
1111
+ \mathrm{KTS}_{m,\ell}(t,t')
1112
+ =
1113
+ \frac{
1114
+ 2gi
1115
+ }{
1116
+ g+i+\epsilon
1117
+ }
1118
+ }
1119
+ \]
1120
+
1121
+ 使用调和平均的原因是:
1122
+
1123
+ - 只有几何稳定但事实身份无法匹配,不应获得高 KTS;
1124
+ - 只有身份匹配但整体邻域结构严重扭曲,也不应获得高 KTS。
1125
+
1126
+ ## 11.1 跨 family pair 平均
1127
+
1128
+ 主 family pair 集:
1129
+
1130
+ \[
1131
+ \mathcal P_{\mathcal T}
1132
+ =
1133
+ \{(t,t'):t,t'\in\mathcal T,\ t<t'\}.
1134
+ \]
1135
+
1136
+ 每个 pair 等权:
1137
+
1138
+ \[
1139
+ \mathrm{KTS}_{m,\ell}
1140
+ =
1141
+ \frac{1}{|\mathcal P_{\mathcal T}|}
1142
+ \sum_{(t,t')\in\mathcal P_{\mathcal T}}
1143
+ \mathrm{KTS}_{m,\ell}(t,t').
1144
+ \]
1145
+
1146
+ 不能按 pair 中 query 数或事实数加权,否则覆盖更大的 family 会支配结果。
1147
+
1148
+ ## 11.2 跨层 KTS
1149
+
1150
+ \[
1151
+ \boxed{
1152
+ \mathrm{KTS}_m
1153
+ =
1154
+ \frac{1}{|\mathcal W_m|}
1155
+ \sum_{\ell\in\mathcal W_m}
1156
+ \mathrm{KTS}_{m,\ell}
1157
+ }
1158
+ \]
1159
+
1160
+ 建议主表同时展示:
1161
+
1162
+ - KTS-Geo;
1163
+ - KTS-ID;
1164
+ - KTS composite。
1165
+
1166
+ 不要只报告 composite 而隐藏两个组成部分。
1167
+
1168
+ ---
1169
+
1170
+ # 12. 四个指标的联合解释
1171
+
1172
+ | BCS/BES | ISS | KTS | 解释 |
1173
+ |---|---:|---:|---|
1174
+ | 高 | 高 | 高 | 输出、单事实状态和整体知识结构均稳定 |
1175
+ | 高 | 低 | 低 | 表面答案一致,但内部状态和知识组织不稳定 |
1176
+ | 高 | 高 | 低 | 单事实局部状态一致,但整体空间可能坍缩或重排 |
1177
+ | 低 | 高 | 高 | 内部知识较稳定,失败更可能发生在后期选择或表达 |
1178
+ | 低 | 低 | 高 | 不同条件引起统一坐标变化,但知识拓扑仍保持 |
1179
+ | 低 | 低 | 低 | 外部行为、单事实状态和知识空间均不稳定 |
1180
+
1181
+ 对于 Stable Wrong:
1182
+
1183
+ - BCS/BES 高;
1184
+ - 主 cluster 被判为错误;
1185
+ - ISS 和 KTS 高;
1186
+
1187
+ 表示模型可能稳定形成并组织了一个错误事实关联。
1188
+
1189
+ 这不应称为“正确知识稳定”,而应称为:
1190
+
1191
+ > stable internal misalignment 或 stable wrong association。
1192
+
1193
+ ---
1194
+
1195
+ # 13. 推荐主结果表
1196
+
1197
+ ## 13.1 模型总体结果
1198
+
1199
+ | Model | Anchor Acc. | BCS | BES | Stable Correct | Stable Wrong | Stable Abstention | ISS | KTS-Geo | KTS-ID | KTS |
1200
+ |---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|
1201
+ | Model A | | | | | | | | | | |
1202
+ | Model B | | | | | | | | | | |
1203
+
1204
+ ## 13.2 按行为类型分析内部稳定性
1205
+
1206
+ | Behavior group | Facts | ISS | KTS-Geo | KTS-ID | KTS |
1207
+ |---|---:|---:|---:|---:|---:|
1208
+ | Stable Correct | | | | | |
1209
+ | Stable Wrong | | | | | |
1210
+ | Stable Abstention | | | | | |
1211
+ | Unstable | | | | | |
1212
+
1213
+ ## 13.3 按 condition pair 报告 KTS
1214
+
1215
+ | Pair | Shared facts | KTS-Geo | KTS-ID | KTS |
1216
+ |---|---:|---:|---:|---:|
1217
+ | Anchor–Paraphrase | | | | |
1218
+ | Anchor–Format | | | | |
1219
+ | Anchor–Context | | | | |
1220
+ | Anchor–Multilingual | | | | |
1221
+ | Paraphrase–Format | | | | |
1222
+ | ... | | | | |
1223
+
1224
+ ---
1225
+
1226
+ # 14. 推荐统计协议
1227
+
1228
+ ## 14.1 Relation-clustered bootstrap
1229
+
1230
+ 由于 21 个 relation 的事实数量不均衡,不能只对所有事实进行普通独立 bootstrap。
1231
+
1232
+ 推荐:
1233
+
1234
+ 1. 有放回采样 relation;
1235
+ 2. 在每个采样 relation 内有放回采样事实;
1236
+ 3. 重复 1,000 次;
1237
+ 4. 报告 95% percentile confidence interval。
1238
+
1239
+ 对 KTS-Geo 和 KTS-ID,应在每次 bootstrap 内重新计算关系宏平均。
1240
+
1241
+ ## 14.2 模型间比较
1242
+
1243
+ 比较模型 A 和 B 时使用 paired bootstrap:
1244
+
1245
+ - 每次使用相同的 relation 和 fact 重采样;
1246
+ - 计算指标差:
1247
+ \[
1248
+ \Delta=\mathrm{Metric}_A-\mathrm{Metric}_B;
1249
+ \]
1250
+ - 报告 \(\Delta\) 的 95% CI。
1251
+
1252
+ ## 14.3 随机性控制
1253
+
1254
+ 必须固定:
1255
+
1256
+ - 模型 revision;
1257
+ - tokenizer revision;
1258
+ - generation 参数;
1259
+ - Judge 模型和 revision;
1260
+ - Judge temperature;
1261
+ - negative fact sampling;
1262
+ - PCA 或 randomized SVD seed;
1263
+ - bootstrap seed。
1264
+
1265
+ ---
1266
+
1267
+ # 15. 评测流程
1268
+
1269
+ ```text
1270
+ 固定 2,592 条事实和 query bank
1271
+ |
1272
+ v
1273
+ 对每个模型运行全部 query 的贪婪生成
1274
+ |
1275
+ v
1276
+ Reference-blind AI Judge 抽取与语义聚类
1277
+ |
1278
+ +--> Reference-aware Judge 标记正确性
1279
+ |
1280
+ +--> 计算 BCS、BES 和行为类别
1281
+ |
1282
+ v
1283
+ 提取主前向 query 的 query-end hidden states
1284
+ |
1285
+ v
1286
+ 计算 J-Lens Jacobian transport
1287
+ |
1288
+ v
1289
+ relation/condition 残差化 + whitening
1290
+ |
1291
+ v
1292
+ 构造每个 fact-family 的 centroid
1293
+ |
1294
+ +--> 计算 ISS
1295
+ |
1296
+ +--> 构建 condition-specific knowledge spaces
1297
+ |
1298
+ +--> KTS-Geo
1299
+ +--> KTS-ID
1300
+ +--> KTS composite
1301
+ ```
1302
+
1303
+ ---
1304
+
1305
+ # 16. Python 风格伪代码
1306
+
1307
+ ## 16.1 BCS 和 BES
1308
+
1309
+ ```python
1310
+ from collections import defaultdict
1311
+ import math
1312
+
1313
+
1314
+ def compute_bcs_bes(records, main_families):
1315
+ family_cluster_counts = defaultdict(lambda: defaultdict(int))
1316
+ family_totals = defaultdict(int)
1317
+
1318
+ for item in records:
1319
+ family = item["condition_family"]
1320
+ if family not in main_families:
1321
+ continue
1322
+ cluster = item["cluster_id"]
1323
+ family_cluster_counts[family][cluster] += 1
1324
+ family_totals[family] += 1
1325
+
1326
+ valid_families = sorted(family_totals)
1327
+ if not valid_families:
1328
+ raise ValueError("No valid main-family queries.")
1329
+
1330
+ clusters = {
1331
+ cluster
1332
+ for family in valid_families
1333
+ for cluster in family_cluster_counts[family]
1334
+ }
1335
+
1336
+ p = {}
1337
+ for cluster in clusters:
1338
+ p[cluster] = sum(
1339
+ family_cluster_counts[family].get(cluster, 0)
1340
+ / family_totals[family]
1341
+ for family in valid_families
1342
+ ) / len(valid_families)
1343
+
1344
+ modal_cluster = max(p, key=p.get)
1345
+ bcs = p[modal_cluster]
1346
+
1347
+ positive_probs = [value for value in p.values() if value > 0]
1348
+ if len(positive_probs) == 1:
1349
+ bes = 1.0
1350
+ else:
1351
+ entropy = -sum(value * math.log(value) for value in positive_probs)
1352
+ bes = 1.0 - entropy / math.log(len(positive_probs))
1353
+
1354
+ return {
1355
+ "bcs": bcs,
1356
+ "bes": bes,
1357
+ "modal_cluster": modal_cluster,
1358
+ "cluster_distribution": p,
1359
+ "valid_families": valid_families,
1360
+ }
1361
+ ```
1362
+
1363
+ ## 16.2 Family centroid
1364
+
1365
+ ```python
1366
+ import numpy as np
1367
+
1368
+
1369
+ def l2_normalize(x, eps=1e-12):
1370
+ return x / max(np.linalg.norm(x), eps)
1371
+
1372
+
1373
+ def family_centroid(query_vectors):
1374
+ normalized = [l2_normalize(x) for x in query_vectors]
1375
+ return l2_normalize(np.mean(normalized, axis=0))
1376
+ ```
1377
+
1378
+ ## 16.3 单层 ISS
1379
+
1380
+ ```python
1381
+ def compute_iss_for_fact(
1382
+ family_vectors,
1383
+ same_relation_fact_vectors,
1384
+ eps=1e-12,
1385
+ ):
1386
+ families = sorted(family_vectors)
1387
+ positive = []
1388
+ negative = []
1389
+
1390
+ for i, family_a in enumerate(families):
1391
+ for family_b in families[i + 1:]:
1392
+ va = family_vectors[family_a]
1393
+ vb = family_vectors[family_b]
1394
+ positive.append(float(np.dot(va, vb)))
1395
+
1396
+ pair_negatives = []
1397
+ for other in same_relation_fact_vectors:
1398
+ if family_a not in other or family_b not in other:
1399
+ continue
1400
+ pair_negatives.append(
1401
+ 0.5 * (
1402
+ float(np.dot(va, other[family_b]))
1403
+ + float(np.dot(vb, other[family_a]))
1404
+ )
1405
+ )
1406
+ if pair_negatives:
1407
+ negative.append(float(np.mean(pair_negatives)))
1408
+
1409
+ s_pos = float(np.mean(positive))
1410
+ s_neg = float(np.mean(negative))
1411
+ iss = (s_pos - s_neg) / (1.0 - s_neg + eps)
1412
+
1413
+ return {
1414
+ "s_positive": s_pos,
1415
+ "s_background": s_neg,
1416
+ "iss": iss,
1417
+ }
1418
+ ```
1419
+
1420
+ ## 16.4 KTS-ID
1421
+
1422
+ ```python
1423
+ def cross_condition_top1(vectors_a, vectors_b, fact_ids):
1424
+ vectors_a = np.asarray([l2_normalize(x) for x in vectors_a])
1425
+ vectors_b = np.asarray([l2_normalize(x) for x in vectors_b])
1426
+
1427
+ sim_ab = vectors_a @ vectors_b.T
1428
+ sim_ba = vectors_b @ vectors_a.T
1429
+
1430
+ pred_ab = np.argmax(sim_ab, axis=1)
1431
+ pred_ba = np.argmax(sim_ba, axis=1)
1432
+ gold = np.arange(len(fact_ids))
1433
+
1434
+ acc_ab = np.mean(pred_ab == gold)
1435
+ acc_ba = np.mean(pred_ba == gold)
1436
+ acc_sym = 0.5 * (acc_ab + acc_ba)
1437
+
1438
+ chance = 1.0 / len(fact_ids)
1439
+ adjusted = (acc_sym - chance) / max(1.0 - chance, 1e-12)
1440
+
1441
+ return {
1442
+ "top1_symmetric": acc_sym,
1443
+ "chance": chance,
1444
+ "chance_corrected": float(np.clip(adjusted, 0.0, 1.0)),
1445
+ }
1446
+ ```
1447
+
1448
+ ---
1449
+
1450
+ # 17. 输出文件建议
1451
+
1452
+ ```text
1453
+ metrics/
1454
+ ├── behavioral_per_query.jsonl
1455
+ ├── behavioral_per_fact.jsonl
1456
+ ├── behavioral_model_summary.json
1457
+ ├── hidden_family_centroids/
1458
+ ├── iss_per_fact_layer.jsonl
1459
+ ├── iss_per_fact.jsonl
1460
+ ├── iss_model_summary.json
1461
+ ├── kts_per_pair_layer.jsonl
1462
+ ├── kts_model_summary.json
1463
+ ├── bootstrap_intervals.json
1464
+ └── evaluation_manifest.json
1465
+ ```
1466
+
1467
+ ## 17.1 behavioral_per_fact.jsonl
1468
+
1469
+ ```json
1470
+ {
1471
+ "model": "model_name",
1472
+ "fact_id": "fact_000001",
1473
+ "bcs": 0.95,
1474
+ "bes": 0.82,
1475
+ "modal_cluster": "ENTITY_Q90",
1476
+ "modal_correctness": "CORRECT",
1477
+ "behavior_group": "Stable Correct",
1478
+ "valid_families": [
1479
+ "anchor",
1480
+ "paraphrase",
1481
+ "format",
1482
+ "context",
1483
+ "multilingual"
1484
+ ]
1485
+ }
1486
+ ```
1487
+
1488
+ ## 17.2 iss_per_fact.jsonl
1489
+
1490
+ ```json
1491
+ {
1492
+ "model": "model_name",
1493
+ "fact_id": "fact_000001",
1494
+ "relation": "capital",
1495
+ "iss": 0.61,
1496
+ "iss_peak": 0.79,
1497
+ "iss_late": 0.65,
1498
+ "layers_used": [12, 13, 14, 15, 16]
1499
+ }
1500
+ ```
1501
+
1502
+ ## 17.3 kts_model_summary.json
1503
+
1504
+ ```json
1505
+ {
1506
+ "model": "model_name",
1507
+ "kts_geo": 0.54,
1508
+ "kts_id": 0.68,
1509
+ "kts": 0.60,
1510
+ "family_pairs": {
1511
+ "anchor__paraphrase": {
1512
+ "shared_facts": 2592,
1513
+ "kts_geo": 0.62,
1514
+ "kts_id": 0.76,
1515
+ "kts": 0.68
1516
+ }
1517
+ }
1518
+ }
1519
+ ```
1520
+
1521
+ ---
1522
+
1523
+ # 18. 必做 sanity checks
1524
+
1525
+ ## 18.1 Query shuffle test
1526
+
1527
+ 随机打乱 fact_id 与 hidden representation 的对应关系后:
1528
+
1529
+ - ISS 应明显下降;
1530
+ - KTS-ID 应接近 chance;
1531
+ - KTS-Geo 应接近 0。
1532
+
1533
+ ## 18.2 Duplicate-query test
1534
+
1535
+ 同一个 query 与自身比较时:
1536
+
1537
+ - hidden cosine 应接近 1;
1538
+ - ISS 正样本部分应达到上界附近。
1539
+
1540
+ ## 18.3 Condition-label shuffle
1541
+
1542
+ 随机打乱 condition family 标签后,family residualization 和 family centroid 不应产生虚假的高稳定性。
1543
+
1544
+ ## 18.4 Relation-matched negative test
1545
+
1546
+ 使用同 relation negatives 得到的 ISS 应比随机跨 relation negatives 更严格。主结果必须使用同 relation negatives。
1547
+
1548
+ ## 18.5 Raw versus transported ablation
1549
+
1550
+ 报告:
1551
+
1552
+ - Raw-ISS;
1553
+ - J-transported ISS。
1554
+
1555
+ 如果两者完全相同,需要检查 Jacobian transport 是否实际生效。
1556
+
1557
+ ## 18.6 Judge consistency
1558
+
1559
+ 对至少 300–500 条回答进行人工校验,报告:
1560
+
1561
+ - answer extraction accuracy���
1562
+ - cluster equivalence accuracy;
1563
+ - correctness accuracy;
1564
+ - Cohen's \(\kappa\) 或 Krippendorff's \(\alpha\)。
1565
+
1566
+ ---
1567
+
1568
+ # 19. 推荐论文定义
1569
+
1570
+ 可以在论文中将四个指标概括为:
1571
+
1572
+ > **Behavioral Consistency Score (BCS)** measures the family-balanced mass assigned to a model's modal semantic answer across retrieval conditions. **Behavioral Entropy Stability (BES)** measures the concentration of the complete semantic answer distribution. **Internal State Stability (ISS)** measures whether the same fact forms a consistent and fact-discriminative Jacobian-transported representation across retrieval conditions. **Knowledge Topology Stability (KTS)** measures whether fact identity and the relative geometry of the overall knowledge representation space are preserved across conditions.
1573
+
1574
+ 中文:
1575
+
1576
+ > BCS 衡量不同检索条件下主语义答案所占的等条件权重;BES 衡量完整答案分布的集中程度;ISS 衡量同一事实是否跨条件形成一致且具有事实区分性的 Jacobian 运输表示;KTS 衡量不同条件下事实身份及整体知识空间相对几何是否保持。
1577
+
1578
+ ---
1579
+
1580
+ # 20. 最终最小报告集合
1581
+
1582
+ 每个模型至少报告:
1583
+
1584
+ ```text
1585
+ Anchor Accuracy
1586
+ BCS
1587
+ BES
1588
+ Stable Correct Rate
1589
+ Stable Wrong Rate
1590
+ Stable Abstention Rate
1591
+ Unstable Rate
1592
+ ISS
1593
+ KTS-Geo
1594
+ KTS-ID
1595
+ KTS
1596
+ ```
1597
+
1598
+ 同时提供:
1599
+
1600
+ - 按 relation 的 macro 结果;
1601
+ - 按 behavior group 的 ISS/KTS;
1602
+ - 按 condition pair 的 KTS;
1603
+ - 95% relation-clustered bootstrap confidence intervals;
1604
+ - complete-family 和 full-set 两种覆盖口径。
dataset_upload/protocol/jlens_spec.md ADDED
@@ -0,0 +1,953 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Engineering Specification for Jacobian-Transported ISS
2
+
3
+ ## 0. Purpose
4
+
5
+ This document specifies how to implement the official Internal State Stability metric, abbreviated as ISS, using Jacobian-transported hidden states.
6
+
7
+ The formal metric remains:
8
+
9
+ \[
10
+ z^\ell_{m,f,q}=J^\ell_m h^\ell_{m,f,q},
11
+ \]
12
+
13
+ where no vocabulary unembedding matrix is applied. The implementation may approximate \(J^\ell_m\), but the approximation must be independently validated and its numerical error must be reported.
14
+
15
+ Raw-ISS is retained only for debugging and ablation. It is not the official metric.
16
+
17
+ ---
18
+
19
+ # 1. Official Definition
20
+
21
+ For model \(m\), fact \(f\), query \(q\), and source layer \(\ell\), extract the query-end residual state:
22
+
23
+ \[
24
+ h^\ell_{m,f,q}\in\mathbb R^{d_m}.
25
+ \]
26
+
27
+ Define the corpus-averaged input-output Jacobian:
28
+
29
+ \[
30
+ J^\ell_m
31
+ =
32
+ \mathbb E_{x\sim\mathcal C}
33
+ \left[
34
+ \frac{\partial h^L_m(x)}{\partial h^\ell_m(x)}
35
+ \right],
36
+ \]
37
+
38
+ where \(\mathcal C\) is an independent calibration corpus.
39
+
40
+ The transported representation is:
41
+
42
+ \[
43
+ \boxed{z^\ell_{m,f,q}=J^\ell_m h^\ell_{m,f,q}}
44
+ \]
45
+
46
+ Do **not** compute:
47
+
48
+ \[
49
+ W_UJ^\ell_m h^\ell_{m,f,q}.
50
+ \]
51
+
52
+ The official ISS therefore operates in the final-layer residual basis rather than vocabulary-logit space.
53
+
54
+ ---
55
+
56
+ # 2. Formal Metric Versus Practical Estimator
57
+
58
+ The formal metric uses the exact population average \(J^\ell_m\). The practical implementation uses a finite-corpus, finite-rank estimator:
59
+
60
+ \[
61
+ \widehat J^{\ell,(n,k)}_m.
62
+ \]
63
+
64
+ The practical transported state is:
65
+
66
+ \[
67
+ \widehat z^\ell_{m,f,q}
68
+ =
69
+ \widehat J^{\ell,(n,k)}_m h^\ell_{m,f,q}.
70
+ \]
71
+
72
+ The paper should distinguish:
73
+
74
+ - \(\operatorname{ISS}\): the formal metric;
75
+ - \(\widehat{\operatorname{ISS}}_{n,k}\): the empirical estimator.
76
+
77
+ The approximation is acceptable only if it satisfies the validation criteria below.
78
+
79
+ ---
80
+
81
+ # 3. Why Full Jacobians Are Not the General Solution
82
+
83
+ For hidden dimension \(d\):
84
+
85
+ \[
86
+ J^\ell_m\in\mathbb R^{d\times d}.
87
+ \]
88
+
89
+ Materializing this matrix is feasible only for small models. For large models with \(d=4096\), \(5120\), or more, exact recovery across many layers and calibration prompts is prohibitively expensive.
90
+
91
+ Therefore:
92
+
93
+ 1. full Jacobians are used only for small-model calibration;
94
+ 2. large models use a randomized factorized estimator;
95
+ 3. approximation quality must be validated for every model rather than inferred from a small model.
96
+
97
+ ---
98
+
99
+ # 4. Overall Engineering Pipeline
100
+
101
+ ```text
102
+ Stage A: Full-matrix calibration on a small model
103
+ |
104
+ v
105
+ Stage B: Per-model approximation validation
106
+ |
107
+ v
108
+ Stage C: Freeze estimator settings
109
+ |
110
+ v
111
+ Stage D: Official ISS evaluation
112
+ ```
113
+
114
+ The final test set must not be used to choose estimator hyperparameters.
115
+
116
+ ---
117
+
118
+ # 5. Stage A: Small-Model Full-Matrix Calibration
119
+
120
+ Use Qwen2.5-0.5B as the primary exact-reference model.
121
+
122
+ ## 5.1 Exact finite-corpus reference
123
+
124
+ For a fixed calibration corpus of \(n\) prompts, compute:
125
+
126
+ \[
127
+ J^{\ell,(n)}_{\mathrm{full}}
128
+ =
129
+ \frac{1}{n}
130
+ \sum_{i=1}^{n}J^\ell_{x_i}.
131
+ \]
132
+
133
+ This is an exact empirical Jacobian for that finite corpus.
134
+
135
+ Do not call it the exact population Jacobian or universal ground truth. Use one of the following terms:
136
+
137
+ - full empirical Jacobian reference;
138
+ - exact finite-corpus Jacobian.
139
+
140
+ ## 5.2 Layer coverage
141
+
142
+ At minimum, compute full references for:
143
+
144
+ - one early layer;
145
+ - one middle layer;
146
+ - one late layer.
147
+
148
+ If feasible on Qwen2.5-0.5B, compute every layer.
149
+
150
+ ## 5.3 Candidate ranks
151
+
152
+ Evaluate:
153
+
154
+ \[
155
+ k\in\{32,64,128,256,512,768\},
156
+ \]
157
+
158
+ subject to \(k<d\).
159
+
160
+ Use nested random probes so that larger ranks contain the directions used at smaller ranks.
161
+
162
+ ## 5.4 Required validation statistics
163
+
164
+ ### Matrix approximation error
165
+
166
+ \[
167
+ E_F(k)
168
+ =
169
+ \frac{\|J_{\mathrm{full}}-\widehat J_k\|_F}
170
+ {\|J_{\mathrm{full}}\|_F}.
171
+ \]
172
+
173
+ ### Transported-vector relative error
174
+
175
+ For held-out activation vectors \(h_i\):
176
+
177
+ \[
178
+ E_{\mathrm{vec}}(k)
179
+ =
180
+ \frac{1}{M}
181
+ \sum_{i=1}^{M}
182
+ \frac{\|J_{\mathrm{full}}h_i-\widehat J_kh_i\|_2}
183
+ {\|J_{\mathrm{full}}h_i\|_2+\epsilon}.
184
+ \]
185
+
186
+ ### Transported-vector cosine agreement
187
+
188
+ \[
189
+ C_{\mathrm{vec}}(k)
190
+ =
191
+ \frac{1}{M}
192
+ \sum_{i=1}^{M}
193
+ \cos(J_{\mathrm{full}}h_i,\widehat J_kh_i).
194
+ \]
195
+
196
+ ### ISS absolute error
197
+
198
+ \[
199
+ E_{\mathrm{ISS}}(k)
200
+ =
201
+ \left|
202
+ \operatorname{ISS}_{\mathrm{full}}
203
+ -
204
+ \widehat{\operatorname{ISS}}_k
205
+ \right|.
206
+ \]
207
+
208
+ ### Per-fact ISS rank agreement
209
+
210
+ \[
211
+ \rho_{\mathrm{fact}}(k)
212
+ =
213
+ \operatorname{Spearman}
214
+ \left(
215
+ \{\operatorname{ISS}^{\mathrm{full}}_f\},
216
+ \{\widehat{\operatorname{ISS}}^{(k)}_f\}
217
+ \right).
218
+ \]
219
+
220
+ A low Frobenius error is not sufficient. The transported vectors and the final ISS must also be stable.
221
+
222
+ ---
223
+
224
+ # 6. Randomized Factorized Jacobian Estimator
225
+
226
+ The estimator must define a linear operator that can be applied to arbitrary hidden states. Computing only \(J\Omega\) is not enough.
227
+
228
+ Use randomized range finding with a two-sided operator estimate.
229
+
230
+ ## 6.1 Random probe matrix
231
+
232
+ For target rank \(k\), draw:
233
+
234
+ \[
235
+ \Omega\in\mathbb R^{d\times(k+p)},
236
+ \]
237
+
238
+ where:
239
+
240
+ - \(p\) is an oversampling dimension;
241
+ - recommended \(p\in\{32,64\}\);
242
+ - \(\Omega\) uses Gaussian or Rademacher entries;
243
+ - all random seeds are fixed and recorded.
244
+
245
+ ## 6.2 Estimate the Jacobian output range
246
+
247
+ Compute:
248
+
249
+ \[
250
+ Y
251
+ =
252
+ J^\ell\Omega
253
+ =
254
+ \mathbb E_x[J^\ell_x\Omega].
255
+ \]
256
+
257
+ Use batched Jacobian-vector products.
258
+
259
+ Then compute:
260
+
261
+ \[
262
+ Q=\operatorname{qr}(Y),
263
+ \]
264
+
265
+ with:
266
+
267
+ \[
268
+ Q\in\mathbb R^{d\times(k+p)}.
269
+ \]
270
+
271
+ ## 6.3 Estimate the reduced operator
272
+
273
+ Compute:
274
+
275
+ \[
276
+ B=Q^\top J^\ell.
277
+ \]
278
+
279
+ Equivalently:
280
+
281
+ \[
282
+ B^\top=J^{\ell\top}Q.
283
+ \]
284
+
285
+ Use batched vector-Jacobian products.
286
+
287
+ The final estimator is:
288
+
289
+ \[
290
+ \boxed{\widehat J^\ell=QB}
291
+ \]
292
+
293
+ and:
294
+
295
+ \[
296
+ \widehat J^\ell h=Q(Bh).
297
+ \]
298
+
299
+ ## 6.4 Storage
300
+
301
+ Store only:
302
+
303
+ \[
304
+ Q\in\mathbb R^{d\times r},
305
+ \qquad
306
+ B\in\mathbb R^{r\times d},
307
+ \]
308
+
309
+ where \(r=k+p\).
310
+
311
+ Do not reconstruct and store the complete \(d\times d\) matrix.
312
+
313
+ Since \(Q\) has orthonormal columns:
314
+
315
+ \[
316
+ \cos(Qy_1,Qy_2)=\cos(y_1,y_2).
317
+ \]
318
+
319
+ Therefore downstream cosine computations may use:
320
+
321
+ \[
322
+ y^\ell=Bh
323
+ \]
324
+
325
+ directly. Residualization and whitening must then be performed consistently in that reduced coordinate space.
326
+
327
+ ---
328
+
329
+ # 7. Per-Model Validation Is Mandatory
330
+
331
+ A rank that works for Qwen2.5-0.5B must not be assumed to work for larger models.
332
+
333
+ Different models can have different:
334
+
335
+ - hidden dimensions;
336
+ - Jacobian singular-value decay;
337
+ - effective rank;
338
+ - depth;
339
+ - normalization;
340
+ - architecture;
341
+ - post-training behavior.
342
+
343
+ The small-model experiment validates the estimator implementation. It does not determine one universal rank.
344
+
345
+ ## 7.1 Direct action validation
346
+
347
+ For every evaluated model, select representative:
348
+
349
+ - early layers;
350
+ - middle layers;
351
+ - late layers.
352
+
353
+ For held-out activation vectors \(h_i\), directly compute:
354
+
355
+ \[
356
+ u_i=J^\ell h_i
357
+ =
358
+ \frac1n\sum_{x\in\mathcal C}J^\ell_xh_i.
359
+ \]
360
+
361
+ This does not require materializing the full Jacobian.
362
+
363
+ Compare with:
364
+
365
+ \[
366
+ \widehat u_i=\widehat J^\ell_kh_i.
367
+ \]
368
+
369
+ ## 7.2 Validation activation set
370
+
371
+ Use a calibration activation set independent of the final ISS test set.
372
+
373
+ Recommended:
374
+
375
+ - 64–128 activation vectors per representative layer;
376
+ - multiple prompt types if benchmark-like prompts are used;
377
+ - or a separate set of held-out natural questions.
378
+
379
+ ## 7.3 Rank candidates
380
+
381
+ Use a nested grid such as:
382
+
383
+ \[
384
+ k\in\{64,128,256,512,1024\},
385
+ \]
386
+
387
+ bounded by model dimension and compute resources.
388
+
389
+ Choose the smallest \(k_{m,\ell}\) that satisfies the fixed validation criteria.
390
+
391
+ Recommended initial criteria:
392
+
393
+ \[
394
+ \operatorname{median}_i\cos(u_i,\widehat u_i)\ge0.99,
395
+ \]
396
+
397
+ \[
398
+ \operatorname{median}_i
399
+ \frac{\|u_i-\widehat u_i\|_2}
400
+ {\|u_i\|_2+\epsilon}
401
+ \le0.05,
402
+ \]
403
+
404
+ and:
405
+
406
+ \[
407
+ \left|
408
+ \widehat{\operatorname{ISS}}_{2k}
409
+ -
410
+ \widehat{\operatorname{ISS}}_k
411
+ \right|
412
+ \le0.01.
413
+ \]
414
+
415
+ The exact numeric thresholds may be adjusted after Stage A, but they must be frozen before final evaluation.
416
+
417
+ ## 7.4 Model-specific rank is allowed
418
+
419
+ Different models and layers may use different ranks:
420
+
421
+ \[
422
+ k_{m,\ell}.
423
+ \]
424
+
425
+ This is methodologically acceptable because all models use the same approximation-quality standard.
426
+
427
+ Always report:
428
+
429
+ - \(k_{m,\ell}\);
430
+ - \(k_{m,\ell}/d_m\);
431
+ - validation cosine;
432
+ - validation relative error;
433
+ - rank-stability error.
434
+
435
+ ---
436
+
437
+ # 8. Calibration Corpus Size
438
+
439
+ Rank error and corpus-sampling error are separate.
440
+
441
+ The empirical Jacobian is:
442
+
443
+ \[
444
+ J^{\ell,(n)}
445
+ =
446
+ \frac1n\sum_{i=1}^{n}J^\ell_{x_i}.
447
+ \]
448
+
449
+ A large \(k\) does not compensate for insufficient corpus size \(n\).
450
+
451
+ ## 8.1 Corpus requirements
452
+
453
+ The Jacobian corpus must:
454
+
455
+ - be independent of the factual benchmark;
456
+ - contain general pretraining-style or natural text;
457
+ - use the same construction rule for all models;
458
+ - use a fixed sequence-length and position convention;
459
+ - record all sample IDs and random seeds.
460
+
461
+ ## 8.2 Corpus-size convergence
462
+
463
+ On representative models, compare:
464
+
465
+ \[
466
+ n\in\{32,64,128,256,512\}.
467
+ \]
468
+
469
+ Measure:
470
+
471
+ \[
472
+ \cos(\widehat J^{(n)}h,\widehat J^{(2n)}h),
473
+ \]
474
+
475
+ and:
476
+
477
+ \[
478
+ \left|
479
+ \widehat{\operatorname{ISS}}_n
480
+ -
481
+ \widehat{\operatorname{ISS}}_{2n}
482
+ \right|.
483
+ \]
484
+
485
+ Select \(n\) using a fixed convergence rule. Do not select \(n\) based on preferred final benchmark conclusions.
486
+
487
+ ---
488
+
489
+ # 9. Random-Seed Stability
490
+
491
+ For representative model-layer-rank settings, use at least three sketch seeds.
492
+
493
+ Report mean and standard deviation for:
494
+
495
+ - transported-vector cosine;
496
+ - transported-vector relative error;
497
+ - ISS;
498
+ - KTS if KTS uses the same transported states.
499
+
500
+ A rank is not considered stable if results vary materially across seeds.
501
+
502
+ Preferred final reporting:
503
+
504
+ - average the result across three validated seeds; or
505
+ - use one preregistered seed after proving seed variance is negligible.
506
+
507
+ Never choose the seed that gives the preferred scientific result.
508
+
509
+ ---
510
+
511
+ # 10. Official ISS Computation
512
+
513
+ After freezing the estimator, compute:
514
+
515
+ \[
516
+ \widehat z^\ell_{m,f,q}
517
+ =
518
+ \widehat J^\ell_m h^\ell_{m,f,q}.
519
+ \]
520
+
521
+ Then run the standard ISS pipeline.
522
+
523
+ ## 10.1 Relation and condition residualization
524
+
525
+ \[
526
+ \bar z^\ell_{m,f,q}
527
+ =
528
+ z^\ell_{m,f,q}
529
+ -
530
+ \mu^\ell_{m,r_f}
531
+ -
532
+ \mu^\ell_{m,t(q)}
533
+ +
534
+ \mu^\ell_m.
535
+ \]
536
+
537
+ ## 10.2 Regularized whitening
538
+
539
+ \[
540
+ \tilde z^\ell_{m,f,q}
541
+ =
542
+ (\Sigma^\ell_m+\lambda I)^{-1/2}
543
+ \bar z^\ell_{m,f,q}.
544
+ \]
545
+
546
+ If the reduced coordinate \(y=Bh\) is used directly, estimate \(\Sigma\) in that coordinate system.
547
+
548
+ Do not fit a separate whitening transform for each condition family.
549
+
550
+ ## 10.3 Family centroid
551
+
552
+ \[
553
+ v^\ell_{m,f,t}
554
+ =
555
+ \operatorname{Normalize}
556
+ \left(
557
+ \frac1{|Q_{f,t}|}
558
+ \sum_{q\in Q_{f,t}}
559
+ \tilde z^\ell_{m,f,q}
560
+ \right).
561
+ \]
562
+
563
+ ## 10.4 Same-fact cross-condition similarity
564
+
565
+ \[
566
+ S^+_{m,f,\ell}
567
+ =
568
+ \frac1{|\mathcal P_f|}
569
+ \sum_{(t,t')\in\mathcal P_f}
570
+ \cos(v^\ell_{m,f,t},v^\ell_{m,f,t'}).
571
+ \]
572
+
573
+ ## 10.5 Relation-matched background
574
+
575
+ \[
576
+ S^-_{m,f,\ell}
577
+ =
578
+ \mathbb E_{\substack{g\neq f,\ r_g=r_f\\t\neq t'}}
579
+ \cos(v^\ell_{m,f,t},v^\ell_{m,g,t'}).
580
+ \]
581
+
582
+ ## 10.6 Official ISS estimator
583
+
584
+ \[
585
+ \boxed{
586
+ \widehat{\operatorname{ISS}}_{m,f,\ell}
587
+ =
588
+ \frac{S^+_{m,f,\ell}-S^-_{m,f,\ell}}
589
+ {1-S^-_{m,f,\ell}+\epsilon}
590
+ }
591
+ \]
592
+
593
+ Average over the preregistered layer window:
594
+
595
+ \[
596
+ \widehat{\operatorname{ISS}}_{m,f}
597
+ =
598
+ \frac1{|\mathcal W_m|}
599
+ \sum_{\ell\in\mathcal W_m}
600
+ \widehat{\operatorname{ISS}}_{m,f,\ell}.
601
+ \]
602
+
603
+ Then average over the fixed fact set:
604
+
605
+ \[
606
+ \widehat{\operatorname{ISS}}_m
607
+ =
608
+ \frac1{|\mathcal D|}
609
+ \sum_{f\in\mathcal D}
610
+ \widehat{\operatorname{ISS}}_{m,f}.
611
+ \]
612
+
613
+ ---
614
+
615
+ # 11. Raw-ISS
616
+
617
+ Raw-ISS uses:
618
+
619
+ \[
620
+ z^\ell_{m,f,q}=h^\ell_{m,f,q}.
621
+ \]
622
+
623
+ It should be computed because it is inexpensive and useful for:
624
+
625
+ - debugging hidden-state extraction;
626
+ - validating family aggregation;
627
+ - validating negative sampling;
628
+ - checking whitening and residualization;
629
+ - ablation;
630
+ - testing whether Jacobian transport changes the conclusion.
631
+
632
+ However:
633
+
634
+ \[
635
+ \boxed{\text{Raw-ISS is not the official ISS result.}}
636
+ \]
637
+
638
+ Recommended table terminology:
639
+
640
+ | Metric | Representation | Role |
641
+ |---|---|---|
642
+ | Raw-ISS | \(h^\ell\) | Identity-transport ablation |
643
+ | ISS | \(\widehat J^\ell h^\ell\) | Official metric |
644
+ | Token readout | \(W_U\widehat J^\ell h^\ell\) | Not used |
645
+
646
+ ---
647
+
648
+ # 12. Failure Policy
649
+
650
+ Do not silently report an unvalidated approximation.
651
+
652
+ A model-layer estimator fails validation if:
653
+
654
+ - rank convergence is not achieved;
655
+ - action-vector cosine remains below threshold;
656
+ - relative action error remains above threshold;
657
+ - ISS changes materially across ranks;
658
+ - ISS changes materially across random seeds.
659
+
660
+ ## 12.1 Allowed responses
661
+
662
+ In order:
663
+
664
+ 1. increase \(k\);
665
+ 2. increase oversampling \(p\);
666
+ 3. increase corpus size \(n\);
667
+ 4. add power iterations;
668
+ 5. restrict official ISS to validated layers;
669
+ 6. mark the model-layer estimator as unresolved.
670
+
671
+ Raw-ISS may still be reported as an ablation, but it must not be relabeled as official ISS.
672
+
673
+ ## 12.2 Optional fallback estimator
674
+
675
+ If low-rank reconstruction consistently fails, consider a geometry-preserving output sketch:
676
+
677
+ \[
678
+ RJ^\ell h,
679
+ \]
680
+
681
+ where:
682
+
683
+ \[
684
+ R\in\mathbb R^{k\times d}.
685
+ \]
686
+
687
+ This avoids assuming that \(J^\ell\) itself is low rank. However, it is a different estimator and must be separately validated against the full small-model reference.
688
+
689
+ Do not switch to this estimator silently.
690
+
691
+ ---
692
+
693
+ # 13. Data Separation
694
+
695
+ Use three disjoint resources.
696
+
697
+ ## 13.1 Jacobian corpus
698
+
699
+ Used to estimate \(J^\ell_m\). It must contain independent general text.
700
+
701
+ ## 13.2 Estimator calibration set
702
+
703
+ Used to select:
704
+
705
+ - corpus size \(n\);
706
+ - rank \(k\);
707
+ - sketch seed;
708
+ - oversampling;
709
+ - power iterations;
710
+ - approximation thresholds.
711
+
712
+ It must not overlap with the final benchmark evaluation facts.
713
+
714
+ ## 13.3 Final ISS benchmark
715
+
716
+ Used only after all estimator settings are frozen.
717
+
718
+ Do not tune \(n\), \(k\), seeds, layer windows, or whitening choices on the final benchmark.
719
+
720
+ ---
721
+
722
+ # 14. Required Output Files
723
+
724
+ ```text
725
+ jacobian_iss/
726
+ ├── configs/
727
+ │ ├── corpus_config.yaml
728
+ │ ├── estimator_config.yaml
729
+ │ ├── validation_thresholds.yaml
730
+ │ └── layer_windows.yaml
731
+ ├── full_reference/
732
+ │ └── qwen2.5_0.5b/
733
+ ├── low_rank_factors/
734
+ │ └── {model}/{layer}/
735
+ │ ├── Q.pt
736
+ │ ├── B.pt
737
+ │ └── metadata.json
738
+ ├── validation/
739
+ │ ├── small_model_full_comparison.json
740
+ │ ├── per_model_action_validation.jsonl
741
+ │ ├── rank_convergence.jsonl
742
+ │ ├── corpus_convergence.jsonl
743
+ │ └── seed_stability.jsonl
744
+ ├── transported_states/
745
+ ├── iss_per_fact_layer.jsonl
746
+ ├── iss_per_fact.jsonl
747
+ ├── iss_model_summary.json
748
+ └── raw_iss_ablation.json
749
+ ```
750
+
751
+ ---
752
+
753
+ # 15. Required Metadata
754
+
755
+ For every estimator, store:
756
+
757
+ ```json
758
+ {
759
+ "model": "model_name",
760
+ "model_revision": "revision",
761
+ "tokenizer_revision": "revision",
762
+ "layer": 16,
763
+ "hidden_dimension": 4096,
764
+ "rank": 512,
765
+ "oversampling": 64,
766
+ "power_iterations": 0,
767
+ "calibration_corpus_size": 256,
768
+ "calibration_sequence_length": 128,
769
+ "random_seed": 42,
770
+ "validation_cosine_median": 0.993,
771
+ "validation_relative_error_median": 0.041,
772
+ "iss_rank_difference": 0.006,
773
+ "validated": true
774
+ }
775
+ ```
776
+
777
+ ---
778
+
779
+ # 16. Minimum Required Experiments
780
+
781
+ ## Experiment A: Full-reference calibration
782
+
783
+ Model:
784
+
785
+ ```text
786
+ Qwen2.5-0.5B
787
+ ```
788
+
789
+ Compare:
790
+
791
+ ```text
792
+ full empirical Jacobian
793
+ vs.
794
+ rank 32/64/128/256/512/768 approximations
795
+ ```
796
+
797
+ Report:
798
+
799
+ - Frobenius error;
800
+ - transported-vector error;
801
+ - transported-vector cosine;
802
+ - ISS absolute error;
803
+ - per-fact ISS Spearman correlation.
804
+
805
+ ## Experiment B: Medium-scale transfer check
806
+
807
+ Use at least one medium-sized model.
808
+
809
+ At representative layers:
810
+
811
+ - compute high-accuracy direct \(Jh\) actions;
812
+ - validate rank behavior;
813
+ - confirm that the small-model rank does not automatically transfer.
814
+
815
+ ## Experiment C: Per-model validation
816
+
817
+ For every evaluated model:
818
+
819
+ - representative early, middle, and late layers;
820
+ - 64–128 held-out activation vectors;
821
+ - nested candidate ranks;
822
+ - fixed validation thresholds;
823
+ - at least three random seeds on representative settings.
824
+
825
+ ## Experiment D: Official evaluation
826
+
827
+ Only after freezing all estimator choices:
828
+
829
+ - compute transported states;
830
+ - compute official ISS;
831
+ - compute Raw-ISS;
832
+ - compare trends;
833
+ - report approximation uncertainty.
834
+
835
+ ---
836
+
837
+ # 17. Recommended Decision Rule
838
+
839
+ Do not use:
840
+
841
+ ```text
842
+ k = 512 for every model
843
+ ```
844
+
845
+ Use:
846
+
847
+ ```text
848
+ Choose the smallest k for each model-layer that satisfies
849
+ one fixed approximation-quality standard.
850
+ ```
851
+
852
+ Recommended initial rule:
853
+
854
+ ```text
855
+ median action cosine >= 0.99
856
+ median relative action error <= 0.05
857
+ |ISS(2k) - ISS(k)| <= 0.01
858
+ seed standard deviation of ISS <= 0.005
859
+ ```
860
+
861
+ The exact thresholds may be refined after the small-model calibration, but they must be frozen before final evaluation.
862
+
863
+ ---
864
+
865
+ # 18. Uncertainty Reporting
866
+
867
+ Separate the following sources of uncertainty:
868
+
869
+ 1. finite Jacobian-corpus error;
870
+ 2. low-rank approximation error;
871
+ 3. random-sketch error;
872
+ 4. benchmark sampling uncertainty;
873
+ 5. relation-level heterogeneity.
874
+
875
+ At minimum, report:
876
+
877
+ - rank sensitivity;
878
+ - corpus-size sensitivity;
879
+ - random-seed sensitivity;
880
+ - per-model action validation;
881
+ - relation-clustered bootstrap confidence intervals for final ISS.
882
+
883
+ Do not present one confidence interval that silently mixes all uncertainty sources.
884
+
885
+ ---
886
+
887
+ # 19. Paper-Ready Method Description
888
+
889
+ > We define Internal State Stability on Jacobian-transported residual states \(z^\ell=J^\ell h^\ell\), where \(J^\ell\) is the corpus-averaged input-output Jacobian from layer \(\ell\) to the final residual stream. We do not apply the vocabulary unembedding matrix, thereby retaining a continuous hidden representation compatible with multi-token and multilingual answers. Since explicitly materializing \(J^\ell\in\mathbb R^{d\times d}\) is prohibitive for large models, we estimate it using randomized range finding, yielding a factorized operator \(\widehat J^\ell=Q^\ell B^\ell\). We validate this approximation against full empirical Jacobians on Qwen2.5-0.5B and against directly computed Jacobian-vector products on held-out activations for every evaluated model. The sketch rank is selected independently for each model and layer using a fixed preregistered approximation-error tolerance rather than a universal rank or final benchmark performance.
890
+
891
+ Continuation:
892
+
893
+ > We separately evaluate calibration-corpus convergence, rank convergence, and random-seed stability. Raw hidden-state ISS is reported only as an identity-transport ablation.
894
+
895
+ ---
896
+
897
+ # 20. Final Engineering Decisions
898
+
899
+ ```text
900
+ Official ISS:
901
+ Jacobian-transported hidden-state ISS
902
+
903
+ Transport:
904
+ z = J h
905
+
906
+ Unembedding:
907
+ Do not multiply by W_U
908
+
909
+ Small-model full Jacobian:
910
+ Finite-corpus exact reference only
911
+
912
+ Large-model implementation:
913
+ Randomized factorized operator estimate
914
+
915
+ Rank selection:
916
+ Per model and per layer
917
+
918
+ Rank criterion:
919
+ Shared fixed approximation-quality threshold
920
+
921
+ Validation:
922
+ Full matrix comparison on Qwen2.5-0.5B
923
+ Direct J h comparison on every evaluated model
924
+
925
+ Raw-ISS:
926
+ Debugging and ablation only
927
+
928
+ Final test set:
929
+ Never used to tune n, k, seeds, layers, or estimator settings
930
+
931
+ Failure:
932
+ Do not report unvalidated Jacobian ISS
933
+ ```
934
+
935
+ ---
936
+
937
+ # 21. Immediate Implementation Order for Claude
938
+
939
+ 1. Finish Raw-ISS to validate data loading and metric aggregation.
940
+ 2. Implement exact finite-corpus Jacobian recovery on Qwen2.5-0.5B.
941
+ 3. Implement the randomized factorized estimator \(\widehat J=QB\).
942
+ 4. Compare candidate ranks against the full small-model reference.
943
+ 5. Measure matrix, vector-action, ISS-value, and fact-ranking errors.
944
+ 6. Freeze approximation-quality thresholds.
945
+ 7. Implement direct \(Jh\) validation for large models.
946
+ 8. Select \(k_{m,\ell}\) using the fixed thresholds.
947
+ 9. Run corpus-size and seed-stability checks.
948
+ 10. Freeze all estimator configurations.
949
+ 11. Compute official ISS on the final benchmark.
950
+ 12. Report Raw-ISS only as an ablation.
951
+ 13. Save all factors, configurations, validation logs, and checksums.
952
+
953
+ The objective is not to recover every Jacobian entry exactly. The objective is to guarantee that the transported representations and the resulting ISS remain within a preregistered numerical tolerance.
dataset_upload/protocol/reconstruction_differences.md ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Reconstruction differences
2
+
3
+ Required by spec section 10: every deviation from the expected counts, and every
4
+ internal contradiction found in the specification itself, is recorded here
5
+ rather than silently absorbed.
6
+
7
+ Build: `dataset3/`, sources read from `ICLR27/dataset/`.
8
+
9
+ ---
10
+
11
+ ## Summary
12
+
13
+ | Stage | Expected | Actual | Status |
14
+ |---|---:|---:|---|
15
+ | Raw cloze prompts | 1,783,541 | 1,783,541 | match |
16
+ | Five-model consensus | 10,601 | 10,601 | match |
17
+ | Candidate-Known Facts | 8,107 | 8,107 | match |
18
+ | Grouped (subject, relation) | 6,185 | 6,185 | match |
19
+ | Functional conflicts removed | 5 | 5 | match |
20
+ | Enriched Facts | 6,180 | 6,180 | match |
21
+ | Core-source facts | 3,705 | 3,705 | match |
22
+ | Benchmark facts | 2,592 | 2,592 | match |
23
+ | Benchmark relations | 21 | 21 | match |
24
+ | Migration duplicates removed | 10,323 | 10,323 | match |
25
+ | Evaluation queries | 44,418 | **44,416** | **deviation D1** |
26
+ | — context | 6,831 | **6,829** | **deviation D1** |
27
+ | — all other conditions | as specified | as specified | match |
28
+
29
+ Everything except D1 reproduces exactly.
30
+
31
+ ---
32
+
33
+ ## D1 — Two context queries expose the gold answer (defect in the source data)
34
+
35
+ **Deviation:** context 6,831 → 6,829; total 44,418 → 44,416.
36
+
37
+ Spec 9.4 requires that context "must not introduce a second valid target", and
38
+ spec 13.9 that "no gold answer is exposed in open-ended main conditions". Two
39
+ queries migrated from `eval_dataset/queryD_context.jsonl` violate both, because
40
+ the legacy distractor sampler picked an entity whose surface form contains the
41
+ gold answer:
42
+
43
+ ```
44
+ Some people confuse States Reorganisation Act with Indian Act.
45
+ In which jurisdiction does States Reorganisation Act apply?
46
+ gold = India <- exposed by the distractor "Indian Act"
47
+
48
+ Taiwan (ROC) Resident Certificate is a legal term in Taiwan.
49
+ Indian Act is a legal term in Canada.
50
+ In which jurisdiction does Permanent account number apply?
51
+ gold = India <- same cause
52
+ ```
53
+
54
+ Spec 10 allows a count change when "the implementation discovers a documented
55
+ defect in the old data". This is such a defect.
56
+
57
+ **Action taken.** `src/build_eval_bank.py` applies a general rule rather than a
58
+ hard-coded exception: for every open-ended main-forward query, the normalized
59
+ gold must not appear in the query text after removing all mentions of the
60
+ subject. Queries failing the rule are dropped and counted in
61
+ `stage4_report.json` as `dropped_gold_exposed`.
62
+
63
+ **To restore 44,418** exactly, delete that guard — but the two queries are
64
+ unanswerable-by-design artefacts and any model scores them correct by copying.
65
+
66
+ ---
67
+
68
+ ## C1 — Spec 6.2 contradicts the required benchmark size (unresolved by design)
69
+
70
+ **Not a count deviation. An internal contradiction in the specification.**
71
+
72
+ Spec 6.2 lists relations "generally unsuitable" for the main benchmark, naming
73
+ among them **developer of** and **manufacturer of**. Spec 1, 6.2 and 15
74
+ simultaneously require exactly **2,592 facts across 21 relations**.
75
+
76
+ Those two relations contribute:
77
+
78
+ | Relation | Facts |
79
+ |---|---:|
80
+ | manufacturer (P176) | 441 |
81
+ | developer (P178) | 405 |
82
+ | **total** | **846** |
83
+
84
+ Excluding them yields **1,746 facts across 19 relations**, which fails the
85
+ acceptance criteria in spec 15. Keeping them satisfies the counts but contradicts
86
+ spec 6.2's guidance.
87
+
88
+ **Action taken.** The counts win, because spec 15 states them as acceptance
89
+ criteria and spec 10 forbids silent changes. Both relations are retained and
90
+ tagged:
91
+
92
+ ```json
93
+ "spec_6_2_flag": "unsuitable_named_in_spec"
94
+ ```
95
+
96
+ `configs/relations.yaml` exposes `options.drop_spec_6_2_flagged`. Setting it to
97
+ `true` reproduces the spec-6.2-compliant 1,746-fact variant; the selection script
98
+ then reports the resulting size instead of failing.
99
+
100
+ **Recommendation.** Report the headline number on all 2,592 and a robustness
101
+ number on the 1,746 subset. See F1, which gives an independent empirical reason
102
+ to distrust exactly these relations.
103
+
104
+ ---
105
+
106
+ ## F1 — 28.9% of benchmark facts are answerable by string copying
107
+
108
+ **Finding, not a deviation. No counts changed.**
109
+
110
+ For 750 of 2,592 benchmark facts (28.9%) the object string is literally contained
111
+ in the subject name, so the query can be answered by copying a substring instead
112
+ of retrieving knowledge:
113
+
114
+ ```
115
+ Airbus A318 -> manufacturer Airbus
116
+ Adobe Acrobat -> developer Adobe
117
+ Amazon Music -> owned by Amazon
118
+ Agriculture and Agri-Food Canada -> jurisdiction Canada
119
+ ```
120
+
121
+ Concentration by relation:
122
+
123
+ | Relation | Flagged | Total | Share |
124
+ |---|---:|---:|---:|
125
+ | manufacturer | 387 | 441 | 87.8% |
126
+ | developer | 199 | 405 | 49.1% |
127
+ | owned_by | 52 | 89 | 58.4% |
128
+ | applies_to_jurisdiction | 31 | 54 | 57.4% |
129
+ | sport | 17 | 81 | 21.0% |
130
+ | country | 17 | 263 | 6.5% |
131
+ | headquarters_location | 15 | 132 | 11.4% |
132
+ | (10 further relations) | 32 | — | <34% |
133
+
134
+ 586 of the 750 come from `manufacturer` and `developer` — the two relations spec
135
+ 6.2 already called unsuitable. F1 is therefore independent empirical support for
136
+ C1's recommendation.
137
+
138
+ **Why this matters.** A stability benchmark measures whether a *retrieved* fact
139
+ survives rephrasing. A fact answerable by copying is stable for a reason that has
140
+ nothing to do with knowledge, so it inflates every retention number and dampens
141
+ the very effect the study is about.
142
+
143
+ **Action taken.** Spec 16 forbids silently dropping facts, so all 750 are kept
144
+ and flagged on both the fact and the query record:
145
+
146
+ ```json
147
+ "answer_in_subject_surface": true
148
+ ```
149
+
150
+ Downstream analysis should report retention with and without them.
151
+
152
+ ---
153
+
154
+ ## F2 — 808 of the 8,107 candidate rows are exact duplicates
155
+
156
+ **Finding, not a deviation.**
157
+
158
+ The 8,107 Candidate-Known Facts contain only 7,299 distinct
159
+ `(subject, relation, object, source)` tuples; 808 rows are exact repeats, e.g.
160
+ `("BMW 3 Series", P176, "BMW", counterfact)` appears twice. This is inherited
161
+ from `dataset/filter/prompts.jsonl`.
162
+
163
+ No action needed: spec 5.1 grouping absorbs them, which is part of why 8,107 rows
164
+ become 6,185 groups. Recorded so the 8,107 figure is not mistaken for 8,107
165
+ distinct facts.
166
+
167
+ ---
168
+
169
+ ## N1 — Stage I GPU passes were not re-executed
170
+
171
+ The five-model first-token forward passes (1,783,541 prompts x 5 models) were
172
+ run previously; their per-prompt verdict vectors are stored as
173
+ `dataset/filter/correct_<model>.npy`.
174
+
175
+ `src/build_candidate_known.py` re-derives the candidate set from those vectors:
176
+ it re-reads the prompt table, re-computes the intersection, re-applies the
177
+ source-drop rule, and checksums every input into `stage1_report.json`. It does
178
+ not re-run inference.
179
+
180
+ The counts are verified, not assumed — 1,783,541 / 10,601 / 8,107 all reproduce,
181
+ and the result is checked for set equality against
182
+ `dataset/filter/global_known_clean.jsonl`.
183
+
184
+ `src/filter_run.py` regenerates the vectors from scratch when required.
185
+
186
+ ---
187
+
188
+ ## N2 — Triple direction is not normalized for `capital_of`
189
+
190
+ Spec 2.2 requires a single triple direction, forward being
191
+ `subject + relation -> object`. The relation `capital_of` (P1376) is stored the
192
+ other way round: subject = city, object = country.
193
+
194
+ Normalizing it would fold those 125 facts into `capital`, changing both the
195
+ benchmark size and the relation count, which spec 10 forbids doing silently.
196
+
197
+ **Action taken.** `capital_of` keeps `"direction": "inverse"` and
198
+ `"inverse_of": "capital"` in its record, so any analysis can group or separate
199
+ the two directions explicitly. `configs/relations.yaml` exposes
200
+ `options.normalize_inverse_direction` for the alternative build.
201
+
202
+ ---
203
+
204
+ ## Coverage gaps (spec 12, expected and unchanged)
205
+
206
+ Main-forward families do not cover every fact:
207
+
208
+ | Condition | Facts covered | Missing |
209
+ |---|---:|---:|
210
+ | anchor | 2,592 | 0 |
211
+ | paraphrase | 2,592 | 0 |
212
+ | format | 2,592 | 0 |
213
+ | context | 2,591 | 1 |
214
+ | multilingual | 2,402 | 190 |
215
+
216
+ Missing fact ids are listed in `outputs/coverage_report.json`. No query was
217
+ imputed. Downstream analyses that compare conditions per fact should use the
218
+ explicit valid intersection.
dataset_upload/requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Scoring and the CPU metric passes need only these three.
2
+ numpy>=1.24
3
+ scipy>=1.10
4
+ PyYAML>=6.0
5
+
6
+ # Generation and hidden-state extraction additionally need:
7
+ torch>=2.1
8
+ transformers>=4.45 # >=4.45 for Gemma-2 / OLMo-2 architectures
9
+ accelerate>=0.30
dataset_upload/runner/common.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Shared helpers: config loading, paths, normalization, checksums.
3
+
4
+ Spec section 18 requires deterministic reruns through configuration files and
5
+ checksums, so every stage loads its parameters from configs/ rather than from
6
+ module-level constants.
7
+ """
8
+ import os, re, json, glob, hashlib, unicodedata
9
+
10
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
11
+ CONFIGS = os.path.join(ROOT, "configs")
12
+
13
+
14
+ def _root(env, default):
15
+ """$env if set, else `default` under the repository root.
16
+
17
+ metrics/mcommon.py resolves the same two variables the same way, so the
18
+ runner writes generations exactly where the metric stack looks for them.
19
+ """
20
+ p = os.environ.get(env) or default
21
+ return p if os.path.isabs(p) else os.path.join(ROOT, p)
22
+
23
+
24
+ DATA = _root("FKS_DATA", "data")
25
+ OUTPUTS = _root("FKS_OUTPUTS", "outputs")
26
+
27
+ SEED = 20260101
28
+
29
+
30
+ def load_config(name):
31
+ import yaml
32
+ with open(os.path.join(CONFIGS, name)) as f:
33
+ return yaml.safe_load(f)
34
+
35
+
36
+ def data_path(name):
37
+ return os.path.join(DATA, name)
38
+
39
+
40
+ def out_path(*parts):
41
+ p = os.path.join(OUTPUTS, *parts)
42
+ os.makedirs(os.path.dirname(p), exist_ok=True)
43
+ return p
44
+
45
+
46
+ def read_jsonl(path):
47
+ with open(path) as f:
48
+ for line in f:
49
+ line = line.strip()
50
+ if line:
51
+ yield json.loads(line)
52
+
53
+
54
+ def write_jsonl(path, rows):
55
+ n = 0
56
+ with open(path, "w") as f:
57
+ for r in rows:
58
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
59
+ n += 1
60
+ return n
61
+
62
+
63
+ def sha256(path, limit_mb=None):
64
+ """Checksum for auditability (spec 18). limit_mb hashes only a prefix, which
65
+ keeps multi-GB source files cheap while still detecting substitution."""
66
+ h = hashlib.sha256()
67
+ cap = None if limit_mb is None else limit_mb * 1024 * 1024
68
+ read = 0
69
+ with open(path, "rb") as f:
70
+ while True:
71
+ b = f.read(1 << 20)
72
+ if not b:
73
+ break
74
+ h.update(b)
75
+ read += len(b)
76
+ if cap and read >= cap:
77
+ break
78
+ return f"sha256:{h.hexdigest()}" + ("" if cap is None else f"(first{limit_mb}MB)")
79
+
80
+
81
+ # ------------------------------------------------------------- normalization
82
+ _QUOTES = "\"'`‘’“”«»"
83
+ _DASHES = "‐‑‒–—―"
84
+ _ARTICLES = re.compile(r"\b(the|a|an)\b")
85
+
86
+
87
+ def normalize(text, drop_articles=True):
88
+ """Comparison form: NFKC, lowercase, punctuation to space, articles dropped.
89
+
90
+ Punctuation is replaced INTERNALLY so that token-boundary matching still
91
+ finds an entity that is followed by a comma. Aliases and generations go
92
+ through the identical function.
93
+ """
94
+ if not text:
95
+ return ""
96
+ t = unicodedata.normalize("NFKC", str(text))
97
+ t = "".join("-" if c in _DASHES else ("'" if c in _QUOTES else c) for c in t)
98
+ t = t.lower()
99
+ t = re.sub(r"[^\w\s]", " ", t, flags=re.UNICODE)
100
+ t = re.sub(r"\s+", " ", t).strip()
101
+ if drop_articles:
102
+ t = _ARTICLES.sub(" ", t)
103
+ return re.sub(r"\s+", " ", t).strip()
104
+
105
+
106
+ def norm_key(text):
107
+ """Identity key for grouping (no article stripping, so 'The Who' stays)."""
108
+ return normalize(text, drop_articles=False)
109
+
110
+
111
+ def dedup_aliases(seq, junk_re=None, min_chars=2, cap=16):
112
+ """Deduplicate case-insensitively, preserving order.
113
+
114
+ The first element is the canonical label and is always kept. Later entries
115
+ are dropped when they normalize to fewer than `min_chars` characters or hit
116
+ a junk pattern: crowd-sourced Wikidata alias lists contain single letters,
117
+ emoji and Wikipedia housekeeping titles, and a one-or-two character alias
118
+ would match almost any generation under containment scoring.
119
+ """
120
+ seen, out = set(), []
121
+ for i, a in enumerate(seq):
122
+ if a is None:
123
+ continue
124
+ a = str(a).strip()
125
+ if not a:
126
+ continue
127
+ k = a.lower()
128
+ if k in seen:
129
+ continue
130
+ if i > 0 or out:
131
+ if len(normalize(a)) < min_chars:
132
+ continue
133
+ if junk_re is not None and junk_re.search(a):
134
+ continue
135
+ seen.add(k)
136
+ out.append(a)
137
+ if len(out) >= cap:
138
+ break
139
+ return out
140
+
141
+
142
+ def compile_junk(patterns):
143
+ return re.compile("|".join(f"(?:{p})" for p in patterns), re.I) if patterns else None
144
+
145
+
146
+ # ---------------------------------------------------------------- reporting
147
+ class Expect:
148
+ """Collects expected-vs-actual counts. Spec section 10 forbids silently
149
+ changing counts, so every deviation is recorded and surfaced."""
150
+
151
+ def __init__(self):
152
+ self.rows = []
153
+
154
+ def check(self, name, actual, expected, note=""):
155
+ ok = (expected is None) or (actual == expected)
156
+ self.rows.append({"name": name, "actual": actual, "expected": expected,
157
+ "match": ok, "note": note})
158
+ return ok
159
+
160
+ @property
161
+ def deviations(self):
162
+ return [r for r in self.rows if not r["match"]]
163
+
164
+ def report(self, title="counts"):
165
+ print(f"\n{title}")
166
+ print(f"{'check':38s} {'actual':>10s} {'expected':>10s} ok")
167
+ print("-" * 66)
168
+ for r in self.rows:
169
+ e = "-" if r["expected"] is None else r["expected"]
170
+ print(f"{r['name']:38s} {r['actual']:>10} {e:>10} "
171
+ f"{'yes' if r['match'] else 'NO'}")
172
+ if self.deviations:
173
+ print(f"\n{len(self.deviations)} deviation(s); "
174
+ f"record them in outputs/reconstruction_differences.md")
175
+ return self.rows
dataset_upload/runner/eval_run.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Stage VI -> outputs/evaluation/<model>.jsonl [GPU]
3
+
4
+ Runs the full evaluation query bank for ONE model. Same decoding configuration
5
+ as anchor qualification (configs/models.yaml:generation) so that anchor and
6
+ perturbation numbers are directly comparable -- a different max_new_tokens or a
7
+ chat template on one side would turn a protocol difference into a fake
8
+ stability effect.
9
+
10
+ Anchor queries live in the bank too (condition_family == "anchor") and share
11
+ their prompt string with qualification_run.py. They are regenerated here rather
12
+ than copied so that every condition passes through one identical code path.
13
+
14
+ Scoring is NOT done here: eval_score.py reads these generations on CPU, so the
15
+ scorer can be revised without paying for GPU again.
16
+ """
17
+ import os, sys, json, time, argparse, collections
18
+ import torch
19
+ from transformers import AutoModelForCausalLM, AutoTokenizer
20
+
21
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
22
+ from common import load_config, out_path, data_path, read_jsonl
23
+
24
+ PROMPT = "Question: {q}\nAnswer with only the shortest correct answer.\nAnswer:"
25
+
26
+
27
+ def build_prompt(row):
28
+ """Anchor and the open-ended conditions get the standard instruction wrapper.
29
+
30
+ The perturbation queries carry their own surface form -- that IS the
31
+ perturbation -- so wrapping them in the anchor template would erase the
32
+ manipulation. They are passed through with a bare "Answer:" cue so the model
33
+ still knows a short answer is wanted.
34
+ """
35
+ fam = row["condition_family"]
36
+ if fam == "anchor":
37
+ return PROMPT.format(q=row["query"])
38
+ if fam == "recognition":
39
+ # candidates are already inside the query text
40
+ return f"{row['query']}\nAnswer:"
41
+ return f"{row['query']}\nAnswer:"
42
+
43
+
44
+ def resolve_weights(explicit, cfg, entry):
45
+ """--model-path, then $FKS_MODELS/<path>, then models.yaml:model_root, then the hub id.
46
+
47
+ Only the hub id travels between machines, so it is the documented default;
48
+ the two local options exist so an offline cluster does not have to edit a
49
+ tracked config.
50
+ """
51
+ if explicit:
52
+ return explicit
53
+ root = os.environ.get("FKS_MODELS") or cfg.get("model_root")
54
+ if root:
55
+ local = os.path.join(root, entry.get("path", entry["name"]))
56
+ if os.path.isdir(local):
57
+ return local
58
+ if entry.get("hf"):
59
+ return entry["hf"]
60
+ raise SystemExit(
61
+ f"cannot locate weights for {entry['name']}: pass --model-path, set "
62
+ f"FKS_MODELS, or add an `hf:` id to configs/models.yaml")
63
+
64
+
65
+ def main():
66
+ ap = argparse.ArgumentParser()
67
+ ap.add_argument("--model", required=True, help="name from configs/models.yaml")
68
+ ap.add_argument("--model-path", default=None,
69
+ help="local weights directory or hub id; overrides models.yaml")
70
+ ap.add_argument("--queries", default=data_path("evaluation_queries_44416.jsonl"))
71
+ ap.add_argument("--conditions", nargs="*", default=None,
72
+ help="restrict to these condition families (default: all)")
73
+ ap.add_argument("--limit", type=int, default=0)
74
+ ap.add_argument("--batch", type=int, default=0, help="0 = value from config")
75
+ ap.add_argument("--resume", action="store_true",
76
+ help="skip queries already present in the output file")
77
+ args = ap.parse_args()
78
+
79
+ cfg = load_config("models.yaml")
80
+ entry = next((m for m in cfg["evaluated_models"] if m["name"] == args.model), None)
81
+ if entry is None:
82
+ raise SystemExit(f"{args.model} is not in configs/models.yaml:evaluated_models")
83
+ gen_cfg = cfg["generation"]
84
+ if gen_cfg.get("use_chat_template"):
85
+ raise SystemExit("spec 7.2: base and instruct models must share the raw "
86
+ "prompt string; chat templates are not applied")
87
+
88
+ rows = list(read_jsonl(args.queries))
89
+ if args.conditions:
90
+ rows = [r for r in rows if r["condition_family"] in args.conditions]
91
+ if args.limit:
92
+ rows = rows[:args.limit]
93
+
94
+ dest = out_path("evaluation", f"{args.model}.jsonl")
95
+ done = set()
96
+ if args.resume and os.path.exists(dest):
97
+ done = {r["query_id"] for r in read_jsonl(dest)}
98
+ rows = [r for r in rows if r["query_id"] not in done]
99
+ print(f"[{args.model}] resuming: {len(done)} already done", flush=True)
100
+ if not rows:
101
+ print(f"[{args.model}] nothing to do")
102
+ return
103
+
104
+ N = len(rows)
105
+ fam_counts = collections.Counter(r["condition_family"] for r in rows)
106
+ print(f"[{args.model}] N={N} {dict(fam_counts)}", flush=True)
107
+
108
+ path = resolve_weights(args.model_path, cfg, entry)
109
+ print(f"[{args.model}] weights: {path}", flush=True)
110
+ torch.manual_seed(gen_cfg.get("seed", 0))
111
+ tok = AutoTokenizer.from_pretrained(path)
112
+ if tok.pad_token is None:
113
+ tok.pad_token = tok.eos_token
114
+ tok.padding_side = "left"
115
+ tok.truncation_side = "left"
116
+ model = AutoModelForCausalLM.from_pretrained(
117
+ path, dtype=getattr(torch, gen_cfg.get("dtype", "bfloat16")),
118
+ device_map={"": 0}).eval()
119
+
120
+ prompts = [build_prompt(r) for r in rows]
121
+ # context queries prepend distractor sentences, so they are much longer than
122
+ # the anchor; a single global max_len would silently truncate them
123
+ max_len = max(gen_cfg.get("max_prompt_len", 96), 192)
124
+ B = args.batch or gen_cfg.get("batch_size", 96)
125
+
126
+ out = [None] * N
127
+ order = sorted(range(N), key=lambda i: len(prompts[i]))
128
+ t0 = time.time()
129
+ with torch.no_grad():
130
+ for b in range(0, N, B):
131
+ idx = order[b:b + B]
132
+ enc = tok([prompts[i] for i in idx], return_tensors="pt", padding=True,
133
+ truncation=True, max_length=max_len).to(0)
134
+ plen = enc["input_ids"].shape[1]
135
+ gen = model.generate(**enc,
136
+ max_new_tokens=gen_cfg.get("max_new_tokens", 24),
137
+ do_sample=gen_cfg.get("do_sample", False),
138
+ num_beams=gen_cfg.get("num_beams", 1),
139
+ pad_token_id=tok.pad_token_id)
140
+ new_ids = gen[:, plen:]
141
+ texts = tok.batch_decode(new_ids, skip_special_tokens=True)
142
+ for j, i in enumerate(idx):
143
+ ids = new_ids[j].tolist()
144
+ n_tok, fin = len(ids), "length"
145
+ for k, t in enumerate(ids):
146
+ if t == tok.eos_token_id:
147
+ n_tok, fin = k, "eos"
148
+ break
149
+ out[i] = {"query_id": rows[i]["query_id"],
150
+ "fact_id": rows[i]["fact_id"],
151
+ "condition_family": rows[i]["condition_family"],
152
+ "model": args.model,
153
+ "prompt": prompts[i],
154
+ "raw_response": texts[j],
155
+ "generated_tokens": int(n_tok),
156
+ "finish_reason": fin}
157
+ if b % (B * 20) == 0:
158
+ d = b + len(idx)
159
+ print(f" {d}/{N} {d / max(time.time() - t0, 1e-9):.1f}/s", flush=True)
160
+
161
+ mode = "a" if (args.resume and done) else "w"
162
+ with open(dest, mode) as f:
163
+ for r in out:
164
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
165
+ json.dump({"model": args.model, "n_generated": N, "resumed_from": len(done),
166
+ "generation": gen_cfg, "max_prompt_len": max_len,
167
+ "model_entry": entry, "seconds": round(time.time() - t0, 1),
168
+ "by_condition": dict(fam_counts)},
169
+ open(out_path("evaluation", f"{args.model}.meta.json"), "w"),
170
+ indent=2, ensure_ascii=False)
171
+ print(f"[{args.model}] wrote {N} -> {dest} ({time.time() - t0:.0f}s) EVAL_DONE")
172
+
173
+
174
+ if __name__ == "__main__":
175
+ main()
dataset_upload/runner/scoring_full.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Answer-span extraction and full-answer scoring (spec section 7.4).
3
+
4
+ Five labels, unlike the three-way scheme it replaces:
5
+ correct an accepted alias is asserted
6
+ incorrect a different answer is asserted
7
+ ambiguous several incompatible answers, hedging, or a granularity miss
8
+ abstain the model declines or says it does not know
9
+ unparseable nothing answer-shaped survives extraction
10
+
11
+ Scoring is a pure function of the stored generation, so rules can be revised
12
+ and everything re-scored without touching the GPU.
13
+ """
14
+ import re
15
+ import sys
16
+ import os
17
+
18
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
19
+ from common import normalize
20
+
21
+ MAX_SPAN_TOKENS = 10
22
+ STRICT_SPAN_TOKENS = 6
23
+
24
+ # Containment only fires for aliases at least this long. Crowd-sourced Wikidata
25
+ # alias lists include ISO codes that are ordinary English words -- "can" is an
26
+ # alias of Canada, "ja" of Japanese -- and without a floor a generation like
27
+ # "It can be Germany" would contain " can " and score as a correct Canada
28
+ # answer. Short aliases still count, but only through exact match.
29
+ MIN_CONTAINMENT_ALIAS_CHARS = 4
30
+ ALIAS_STOPWORDS = {"can", "may", "will", "was", "are", "one", "two", "new",
31
+ "the", "and", "for", "his", "her", "its", "not", "all"}
32
+
33
+ _LEADIN = re.compile(
34
+ r"^(?:the\s+answer\s+is|answer\s*:|it\s+is|it\s+was|it's|that\s+would\s+be|"
35
+ r"that\s+is|this\s+is|he\s+is|she\s+is|they\s+are|he\s+was|she\s+was|"
36
+ r"they\s+were)\b[\s:,-]*", re.I)
37
+ _NEGATION = re.compile(r"\b(not|no|never|isn't|wasn't|aren't|weren't|doesn't|"
38
+ r"didn't|don't|cannot|can't)\b", re.I)
39
+ _HEDGE = re.compile(r"\b(but|however|although|though|actually|maybe|perhaps|"
40
+ r"probably|possibly|might|unclear|some\s+sources|depends|"
41
+ r"either)\b", re.I)
42
+ _ABSTAIN = re.compile(
43
+ r"\b(i\s+(?:do\s+not|don't)\s+know|i'm\s+not\s+sure|i\s+am\s+not\s+sure|"
44
+ r"unknown|not\s+sure|no\s+idea|cannot\s+answer|can't\s+answer|"
45
+ r"unable\s+to\s+(?:answer|determine)|insufficient\s+information|"
46
+ r"as\s+an\s+ai)\b", re.I)
47
+ _SENT_END = re.compile(r"[.!?\n]")
48
+ _LIST_SEP = re.compile(r"\s*(?:,|;|\bor\b|\band\b|/|\|)\s*", re.I)
49
+ _YEAR = re.compile(r"\b(1[0-9]{3}|20[0-9]{2})\b")
50
+
51
+
52
+ def _tokens(t):
53
+ return [w for w in re.split(r"[^\w]+", t) if w]
54
+
55
+
56
+ def extract_span(raw):
57
+ """First answer-bearing clause. Returns (span, flags)."""
58
+ flags = set()
59
+ if raw is None:
60
+ return "", {"empty"}
61
+ text = raw.strip()
62
+ if not text:
63
+ return "", {"empty"}
64
+ lines = [l for l in text.split("\n") if l.strip()]
65
+ if not lines:
66
+ return "", {"empty"}
67
+ if len(lines) > 1:
68
+ flags.add("multi_clause")
69
+ first = lines[0].strip()
70
+ m = _SENT_END.search(first)
71
+ if m and first[m.start():].strip(" .!?"):
72
+ flags.add("multi_clause")
73
+ first = first[:m.start()] if m else first
74
+
75
+ if _ABSTAIN.search(first):
76
+ flags.add("abstain")
77
+ if _NEGATION.search(first):
78
+ flags.add("negation")
79
+ if _HEDGE.search(first):
80
+ flags.add("hedge")
81
+
82
+ span = _LEADIN.sub("", first).strip()
83
+ if len(_tokens(span)) > MAX_SPAN_TOKENS:
84
+ flags.add("truncated")
85
+ span = " ".join(span.split()[:MAX_SPAN_TOKENS])
86
+ if not span:
87
+ flags.add("empty")
88
+ return span, flags
89
+
90
+
91
+ def split_candidates(span):
92
+ parts = [p.strip() for p in _LIST_SEP.split(span) if p.strip()]
93
+ return parts or ([span] if span else [])
94
+
95
+
96
+ def _match_year(span, golds, gran):
97
+ got = set(_YEAR.findall(span))
98
+ want = set()
99
+ for g in golds:
100
+ want.update(_YEAR.findall(str(g)))
101
+ if not got or not want:
102
+ return None
103
+ if len(got) > 1:
104
+ return ("ambiguous", None, "year_multiple")
105
+ y = got.pop()
106
+ if y not in want:
107
+ return ("incorrect", None, "year_mismatch")
108
+ if gran == "date" and not re.search(r"\b\d{1,2}\b", span.replace(y, "")):
109
+ return ("ambiguous", y, "year_granularity_short")
110
+ return ("correct", y, "year_parser")
111
+
112
+
113
+ def score(raw_generation, gold_aliases, answer_type="entity", granularity=None):
114
+ """Label one generation. Returns dict(label, matched_alias, scorer, span, flags)."""
115
+ span, flags = extract_span(raw_generation)
116
+ out = {"span": span, "flags": sorted(flags)}
117
+
118
+ if "abstain" in flags:
119
+ return {**out, "label": "abstain", "matched_alias": None, "scorer": "abstain"}
120
+ if "empty" in flags:
121
+ return {**out, "label": "unparseable", "matched_alias": None, "scorer": "empty_span"}
122
+ if "negation" in flags:
123
+ return {**out, "label": "ambiguous", "matched_alias": None, "scorer": "negation"}
124
+
125
+ n_span = normalize(span)
126
+ if not n_span:
127
+ return {**out, "label": "unparseable", "matched_alias": None,
128
+ "scorer": "span_normalizes_to_empty"}
129
+
130
+ norm_golds = {}
131
+ for a in gold_aliases:
132
+ na = normalize(a)
133
+ if na:
134
+ norm_golds.setdefault(na, a)
135
+
136
+ if n_span in norm_golds:
137
+ return {**out, "label": "correct", "matched_alias": norm_golds[n_span],
138
+ "scorer": "exact_alias_after_normalization"}
139
+
140
+ if answer_type in ("year", "date"):
141
+ r = _match_year(span, gold_aliases, granularity or answer_type)
142
+ if r:
143
+ lbl, matched, scorer = r
144
+ return {**out, "label": lbl, "matched_alias": matched, "scorer": scorer}
145
+
146
+ cands = split_candidates(span)
147
+ if len(cands) > 1:
148
+ hits = [normalize(c) for c in cands if normalize(c) in norm_golds]
149
+ distinct = set(hits)
150
+ if len(distinct) == 1 and len(cands) == len(hits):
151
+ h = distinct.pop()
152
+ return {**out, "label": "correct", "matched_alias": norm_golds[h],
153
+ "scorer": "alias_list_all_accepted"}
154
+ if hits:
155
+ return {**out, "label": "ambiguous", "matched_alias": norm_golds[hits[0]],
156
+ "scorer": "conflicting_candidates"}
157
+
158
+ if "hedge" not in flags and len(_tokens(n_span)) <= STRICT_SPAN_TOKENS:
159
+ padded = f" {n_span} "
160
+ for na, orig in norm_golds.items():
161
+ if len(na) < MIN_CONTAINMENT_ALIAS_CHARS or na in ALIAS_STOPWORDS:
162
+ continue
163
+ if f" {na} " in padded:
164
+ return {**out, "label": "correct", "matched_alias": orig,
165
+ "scorer": "alias_substring_short_span"}
166
+
167
+ if flags & {"hedge", "truncated", "multi_clause"}:
168
+ for na, orig in norm_golds.items():
169
+ if len(na) < MIN_CONTAINMENT_ALIAS_CHARS or na in ALIAS_STOPWORDS:
170
+ continue
171
+ if f" {na} " in f" {n_span} ":
172
+ return {**out, "label": "ambiguous", "matched_alias": orig,
173
+ "scorer": "gold_inside_unresolvable_prose"}
174
+
175
+ return {**out, "label": "incorrect", "matched_alias": None, "scorer": "no_match"}
176
+
177
+
178
+ def needs_manual_review(result):
179
+ return result["label"] in ("ambiguous", "unparseable") or \
180
+ result["scorer"] in ("alias_substring_short_span", "year_granularity_short")
181
+
182
+
183
+ # --------------------------------------------------------------------- CLI
184
+ def main():
185
+ """Label a generations file.
186
+
187
+ python runner/scoring_full.py --gen outputs/evaluation/my-model.jsonl
188
+
189
+ Pure CPU. The per-query booleans are copied onto every scored row so that
190
+ downstream metric code can filter (`use_for_main_forward`,
191
+ `answer_in_subject_surface`, ...) without joining back to the query bank.
192
+ """
193
+ import json, argparse, collections
194
+ from common import data_path, out_path, read_jsonl
195
+
196
+ ap = argparse.ArgumentParser()
197
+ ap.add_argument("--gen", required=True, help="outputs/evaluation/<model>.jsonl")
198
+ ap.add_argument("--queries", default=data_path("evaluation_queries_44416.jsonl"))
199
+ ap.add_argument("--out", default=None, help="default: <gen>.scored.jsonl")
200
+ args = ap.parse_args()
201
+
202
+ dest = args.out or args.gen.replace(".jsonl", "") + ".scored.jsonl"
203
+ carry = ("fact_id", "relation", "condition_family", "language", "target_slot",
204
+ "answer_type", "answer_granularity", "answer_in_subject_surface",
205
+ "use_for_main_forward", "use_for_reverse_analysis",
206
+ "use_for_recognition_analysis")
207
+ q = {r["query_id"]: r for r in read_jsonl(args.queries)}
208
+
209
+ counts, n, missing = collections.Counter(), 0, 0
210
+ with open(dest, "w") as f:
211
+ for g in read_jsonl(args.gen):
212
+ row = q.get(g["query_id"])
213
+ if row is None:
214
+ missing += 1
215
+ continue
216
+ res = score(g["raw_response"], row["gold_aliases"],
217
+ answer_type=row["answer_type"],
218
+ granularity=row.get("answer_granularity"))
219
+ rec = {"query_id": g["query_id"], "model": g.get("model"),
220
+ **{k: row.get(k) for k in carry},
221
+ "raw_response": g["raw_response"], **res,
222
+ "needs_manual_review": needs_manual_review(res)}
223
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
224
+ counts[res["label"]] += 1
225
+ n += 1
226
+
227
+ if missing:
228
+ print(f"WARNING: {missing} generations had no matching query_id")
229
+ total = max(n, 1)
230
+ print(f"scored {n} -> {dest}")
231
+ for label in ("correct", "incorrect", "ambiguous", "abstain", "unparseable"):
232
+ print(f" {label:12s} {counts[label]:6d} {100*counts[label]/total:5.1f}%")
233
+
234
+
235
+ if __name__ == "__main__":
236
+ main()
dataset_upload/runner/test_scoring.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Unit tests for scoring_full.py. Run before trusting any K_m."""
3
+ import os, sys
4
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
5
+ from scoring_full import score
6
+
7
+ CANBERRA = ["Canberra", "Canberra, ACT"]
8
+ DUTCH = ["Dutch", "Nederlands", "dutch language"]
9
+ YEAR = ["1987"]
10
+ # "can" is a real Wikidata alias of Canada, carried by 67 facts in this pool
11
+ CANADA = ["Canada", "can", "CAN", "Dominion of Canada"]
12
+
13
+ CASES = [
14
+ (" Canberra", CANBERRA, "city", None, "correct", "bare answer"),
15
+ (" Canberra.", CANBERRA, "city", None, "correct", "trailing period"),
16
+ ("The answer is Canberra.", CANBERRA, "city", None, "correct", "lead-in"),
17
+ (" canberra ", CANBERRA, "city", None, "correct", "case/space"),
18
+ ("Canberra, ACT", CANBERRA, "city", None, "correct", "alias with comma"),
19
+ ("Sydney", CANBERRA, "city", None, "incorrect", "wrong entity"),
20
+ ("It is not Canberra.", CANBERRA, "city", None, "ambiguous", "negation"),
21
+ ("Canberra or Sydney", CANBERRA, "city", None, "ambiguous", "conflicting list"),
22
+ ("Some sources say Canberra, but the answer is Melbourne.",
23
+ CANBERRA, "city", None, "ambiguous", "self-correction"),
24
+ ("", CANBERRA, "city", None, "unparseable", "empty"),
25
+ ("\n\n", CANBERRA, "city", None, "unparseable", "whitespace only"),
26
+ ("...", CANBERRA, "city", None, "unparseable", "punctuation only"),
27
+
28
+ ("I don't know.", CANBERRA, "city", None, "abstain", "explicit refusal"),
29
+ ("I'm not sure, maybe Sydney.", CANBERRA, "city", None, "abstain", "hedged refusal"),
30
+ ("Unknown", CANBERRA, "city", None, "abstain", "unknown"),
31
+
32
+ (" Dutch", DUTCH, "language", None, "correct", "primary alias"),
33
+ (" Nederlands", DUTCH, "language", None, "correct", "non-primary alias"),
34
+ ("The Dutch language", DUTCH, "language", None, "correct", "article + alias"),
35
+ ("German", DUTCH, "language", None, "incorrect", "wrong language"),
36
+ ("Amsterdam, which is in the Netherlands, where people speak Dutch and",
37
+ DUTCH, "language", None, "ambiguous",
38
+ "gold buried in prose is NOT a silent correct"),
39
+
40
+ ("1987", YEAR, "year", "year", "correct", "exact year"),
41
+ ("He was born in 1987", YEAR, "year", "year", "correct", "year in short prose"),
42
+ ("12 March 1987", YEAR, "year", "year", "correct", "full date, year gold"),
43
+ ("1988", YEAR, "year", "year", "incorrect", "wrong year"),
44
+ ("1987 or 1988", YEAR, "year", "year", "ambiguous", "two years"),
45
+ ("1987", ["12 March 1987"], "date", "date", "ambiguous", "gold wants full date"),
46
+ ("12 March 1987", ["12 March 1987"], "date", "date", "correct", "full date matches"),
47
+
48
+ ("It can be Germany", CANADA, "country", None, "incorrect",
49
+ "stopword alias must not match by containment"),
50
+ ("Canada", CANADA, "country", None, "correct", "primary alias"),
51
+ ("CAN", CANADA, "country", None, "correct", "short alias, EXACT only"),
52
+ ("the Dominion of Canada is", CANADA, "country", None, "correct",
53
+ "long alias still matches by containment"),
54
+ ]
55
+
56
+
57
+ def main():
58
+ bad = 0
59
+ for gen, al, at, gran, want, note in CASES:
60
+ got = score(gen, al, answer_type=at, granularity=gran)
61
+ ok = got["label"] == want
62
+ bad += 0 if ok else 1
63
+ print(f"{'ok ' if ok else 'FAIL'} {want:12s} got={got['label']:12s} "
64
+ f"{got['scorer']:34s} {note}")
65
+ print(f"\n{len(CASES) - bad}/{len(CASES)} passed")
66
+ return 1 if bad else 0
67
+
68
+
69
+ if __name__ == "__main__":
70
+ sys.exit(main())