LucasLoading commited on
Commit
db8bf2d
·
verified ·
1 Parent(s): 414bb5e

Upload 43 files

Browse files
Files changed (44) hide show
  1. .gitattributes +1 -0
  2. ICLR dataset/README.md +216 -0
  3. ICLR dataset/benchmark_facts_2592.jsonl +0 -0
  4. ICLR dataset/configs/eval_conditions.yaml +162 -0
  5. ICLR dataset/configs/models.yaml +178 -0
  6. ICLR dataset/configs/relations.yaml +256 -0
  7. ICLR dataset/configs/source_templates.yaml +117 -0
  8. ICLR dataset/evaluation_queries_44416.jsonl +3 -0
  9. ICLR dataset/metrics/__pycache__/extract_hidden.cpython-313.pyc +0 -0
  10. ICLR dataset/metrics/__pycache__/jlens.cpython-313.pyc +0 -0
  11. ICLR dataset/metrics/__pycache__/mcommon.cpython-313.pyc +0 -0
  12. ICLR dataset/metrics/__pycache__/states.cpython-313.pyc +0 -0
  13. ICLR dataset/metrics/bcs_bes.py +161 -0
  14. ICLR dataset/metrics/extract_hidden.py +171 -0
  15. ICLR dataset/metrics/iss.py +157 -0
  16. ICLR dataset/metrics/jlens.py +352 -0
  17. ICLR dataset/metrics/joint.py +172 -0
  18. ICLR dataset/metrics/judge_run.py +273 -0
  19. ICLR dataset/metrics/kts.py +190 -0
  20. ICLR dataset/metrics/make_table.py +106 -0
  21. ICLR dataset/metrics/mcommon.py +252 -0
  22. ICLR dataset/metrics/states.py +157 -0
  23. ICLR dataset/protocol/bcs_bes_iss_kts_evaluation_protocol (1).md +1604 -0
  24. ICLR dataset/protocol/jacobian_transported_iss_engineering_spec (1).md +953 -0
  25. ICLR dataset/protocol/reconstruction_differences.md +218 -0
  26. ICLR dataset/runner/__pycache__/common.cpython-313.pyc +0 -0
  27. ICLR dataset/runner/__pycache__/eval_run.cpython-313.pyc +0 -0
  28. ICLR dataset/runner/__pycache__/qual_templates.cpython-313.pyc +0 -0
  29. ICLR dataset/runner/__pycache__/scoring_full.cpython-313.pyc +0 -0
  30. ICLR dataset/runner/build_candidate_known.py +168 -0
  31. ICLR dataset/runner/build_eval_bank.py +253 -0
  32. ICLR dataset/runner/build_stats.py +142 -0
  33. ICLR dataset/runner/common.py +159 -0
  34. ICLR dataset/runner/enrich_facts.py +305 -0
  35. ICLR dataset/runner/eval_run.py +151 -0
  36. ICLR dataset/runner/eval_score.py +207 -0
  37. ICLR dataset/runner/filter_run.py +109 -0
  38. ICLR dataset/runner/qual_templates.py +122 -0
  39. ICLR dataset/runner/qualification_run.py +135 -0
  40. ICLR dataset/runner/qualification_score.py +145 -0
  41. ICLR dataset/runner/scoring_full.py +180 -0
  42. ICLR dataset/runner/select_benchmark.py +97 -0
  43. ICLR dataset/runner/test_scoring.py +70 -0
  44. ICLR dataset/runner/validate_facts.py +208 -0
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
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
ICLR dataset/README.md ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `dataset3/` —— Fact Knowledge Stability Benchmark
2
+
3
+ 按 [`../dataset/fact_knowledge_stability_dataset_reconstruction.md`](../dataset/fact_knowledge_stability_dataset_reconstruction.md)
4
+ 从 `../dataset/` 的数据重建。**不改动 `../dataset/` 和 `../dataset2/`。**
5
+
6
+ 与 `dataset2` 的根本区别在方法论,不在数字:
7
+
8
+ > **基准集是固定的 2,592 条,对所有模型相同。** `K_m` 只是每个模型的正确性**标签**,
9
+ > 绝不用来从基准集里删事实(spec §2.1)。模型答错、一直答错、拒答、
10
+ > 在不同条件下答不同答案——事实都留在集合里。
11
+
12
+ ---
13
+
14
+ ## 目录
15
+
16
+ ```
17
+ dataset3/
18
+ ├── configs/ # 全部参数外置,脚本里不硬编码(spec §4.4, §18)
19
+ │ ├── models.yaml # 5 个过滤模型 + 评测模型 + 生成配置
20
+ │ ├── relations.yaml # 21 个基准关系 + 排除清单 + 两个开关
21
+ │ ├── source_templates.yaml # 原始来源、cloze 模板、别名资源
22
+ │ └── eval_conditions.yaml # 8 个条件的角色/目标槽/期望计数
23
+ ├── src/
24
+ │ ├── common.py 公共:配置/规范化/校验和/计数核对
25
+ │ ├── build_candidate_known.py (I) → candidate_known_8107.jsonl
26
+ │ ├── enrich_facts.py (II) → enriched_facts_6180.jsonl
27
+ │ ├── select_benchmark.py (III) → benchmark_facts_2592.jsonl
28
+ │ ├── build_eval_bank.py (IV) → evaluation_queries_44418.jsonl
29
+ │ ├── validate_facts.py → validation_report.json ← 硬门禁
30
+ │ ├── build_stats.py → dataset_statistics.json
31
+ │ ├── qualification_run.py (V) → qualification/<model>.jsonl [GPU]
32
+ │ ├── qualification_score.py (V) → known_labels.json
33
+ │ ├── eval_run.py (VI) → evaluation/<model>.jsonl [GPU]
34
+ │ ├── eval_score.py (VI) → stability_report.json
35
+ │ ├── filter_run.py 阶段 I 首 token 过滤(重跑用) [GPU]
36
+ │ ├── scoring_full.py 五标签判分器
37
+ │ ├── qual_templates.py 非基准关系的兜底问句
38
+ │ └── test_scoring.py 31 条单元测试
39
+ ├── outputs/
40
+ └── run_pipeline.sh # build / gpu / score / report / all
41
+ ```
42
+
43
+ ---
44
+
45
+ ## 六个阶段
46
+
47
+ ### I. 候选召回 → 8,107(spec §4)
48
+
49
+ ```
50
+ 1,783,541 cloze prompt
51
+ → 5 模型首 token argmax 取交集 → 10,601
52
+ → 丢弃 T-REx / Wikidata5M 子集,补 PopQA 378 → 8,107
53
+ ```
54
+
55
+ **GPU 未重跑。** 那 1,783,541 × 5 次前向的逐条判定向量已存于
56
+ `dataset/filter/correct_<model>.npy`。[build_candidate_known.py](src/build_candidate_known.py)
57
+ 重新读取 prompt 表、**重新求交集**、重新施加来源丢弃规则,并把每个输入文件的
58
+ 校验和写进 `stage1_report.json`——数字是**验证出来的**,不是照抄。
59
+ 另外与 `dataset/filter/global_known_clean.jsonl` 做集合相等性核对。
60
+ 要从零重跑推理用 `src/filter_run.py`。
61
+
62
+ ### II. 事实增强 → 6,180(spec §5)
63
+
64
+ - **实体感知分组**:优先用实体 ID,无 ID 才退回规范化文本;**跨来源合并**
65
+ (1,036 组同时出现在 CounterFact 和 LAMA-TREx)。8,107 行 → 6,185 组
66
+ - **函数型冲突丢弃 5 条**:同名不同人(两个 "Michael Vincent" 生于 1964/1976)问题本身无解。
67
+ 判据严格——**缺实体 ID 不算"同一实体"的证据**,所有成员必须都有 ID 且一致才保留
68
+ - **别名扩展**:对别名资源做**单次过滤扫描**(spec §5.3),不全量载入
69
+ - **挂 canonical 问句**,与评测扰动模板严格分离(spec §16)
70
+
71
+ ### III. 基准选择 → 2,592 / 21 关系(spec §6)
72
+
73
+ ```
74
+ 6,180 → core 来源(CounterFact + LAMA-TREx + PopQA)→ 3,705
75
+ → 函数型(单值)关系 → 2,592
76
+ ```
77
+
78
+ ### IV. 查询库 → 44,416(spec §8–§12)
79
+
80
+ | 条件 | 查询 | 事实 | 角色 |
81
+ |---|---:|---:|---|
82
+ | anchor | 2,592 | 2,592 | main |
83
+ | multilingual | 12,010 | 2,402 | main |
84
+ | paraphrase | 10,053 | 2,592 | main |
85
+ | format | 7,776 | 2,592 | main |
86
+ | context | **6,829** | 2,591 | main |
87
+ | reverse | 634 | 253 | **结构分析,单独报** |
88
+ | recognition | 3,412 | 2,585 | 诊断 |
89
+ | reverse_illposed | 1,110 | 1,110 | 诊断 |
90
+ | **合计** | **44,416** | | main forward **39,260** |
91
+
92
+ 每条查询自带 `use_for_main_forward` / `use_for_reverse_analysis` /
93
+ `use_for_recognition_analysis` 三个布尔量,**由 `eval_conditions.yaml` 派生**,
94
+ 下游聚合不需要硬编码哪个条件进哪个平均。校验器会检查每行的布尔量与注册表一致。
95
+
96
+ ### V. Anchor 资格认证 → `K_m` 标签(spec §7)⬜ 待跑
97
+
98
+ 纯补全 prompt(base 与 instruct 用**完全相同**的字符串,无 chat template)、
99
+ 贪婪解码 24 token、无候选无 few-shot。判分在 CPU,**五标签**:
100
+
101
+ `correct` / `incorrect` / `ambiguous` / `abstain` / `unparseable`
102
+
103
+ 输出 `known_labels.json`:`{fact_id: {model: label}}`,覆盖全部 2,592 × 全部模型。
104
+
105
+ ### VI. 扰动评测 → 稳定性 ⬜ 待跑
106
+
107
+ [eval_run.py](src/eval_run.py) 跑全部 44,416 条查询,
108
+ **解码配置与 anchor 完全一致**(同一份 `configs/models.yaml:generation`)——
109
+ 否则 `max_new_tokens` 或 chat template 的差异会被误读成稳定性效应。
110
+ anchor 也一起重跑,让所有条件走同一条代码路径。
111
+
112
+ [eval_score.py](src/eval_score.py) 在 CPU 判分并出报表,三条规则写死在代码里而不是留给读者:
113
+
114
+ 1. **按查询自带的布尔量分组** —— `recognition` 和 `reverse_illposed` 永不进主平均,
115
+ `reverse` 因为换了目标槽而单独报(spec §2.3)
116
+ 2. **两个分母并排报**:`fixed`(固定 2,592,spec §2.1)与
117
+ `anchored`(限定在该模型的 `K_m` 内,即条件化保持率)
118
+ 3. **每个数字按 `answer_in_subject_surface` 再拆一次**(`·real` / `·copy`),
119
+ 因为 28.9% 的事实靠复制就能答对、天然接近满分(见 F1)
120
+
121
+ 主指标 macro = paraphrase / format / context / multilingual 四者均值:
122
+ anchor 是基线不计入,reverse 换了槽不计入,两个诊断条件不计入。
123
+
124
+ ---
125
+
126
+ ## 运行
127
+
128
+ ```bash
129
+ cd /scratch/rds-fei-rsfm-rw/cshi0459/ICLR27/dataset3
130
+ bash run_pipeline.sh build # 阶段 I-IV + 校验 + 统计,CPU 约 1 分钟(已跑完)
131
+ bash run_pipeline.sh gpu # 阶段 V+VI 生成,每个模型只加载一次权重
132
+ bash run_pipeline.sh score # 阶段 V 判分 → K_m 标签
133
+ bash run_pipeline.sh report # 阶段 VI 判分 → stability_report.json
134
+ ```
135
+
136
+ `gpu` 把 anchor 和扰动两趟生成合在一起跑,权重只载入一次。
137
+ 两个生成阶段都幂等:anchor 已存在会跳过,`eval_run.py --resume` 会跳过已完成的查询。
138
+
139
+ **顺序要求**:`score` 必须在 `report` 之前跑,否则没有 `known_labels.json`,
140
+ `anchored` 那一列会缺失(脚本会警告并只报 `fixed`)。
141
+
142
+ ---
143
+
144
+ ## 当前状态
145
+
146
+ | 阶段 | 状态 |
147
+ |---|---|
148
+ | I 候选召回 | ✅ 8,107,全部计数命中 |
149
+ | II 事实增强 | ✅ 6,180,6,185 组 / 5 冲突 / 1,771 合并 / 1,036 跨来源,全中 |
150
+ | III 基准选择 | ✅ 2,592 / 21 关系,全中 |
151
+ | IV 查询库 | ✅ 44,416(见差异 D1) |
152
+ | 校验 | ✅ **0 hard errors** |
153
+ | 单元测试 | ✅ **31/31** |
154
+ | V 资格认证 | ⬜ 待跑(判分逻辑已用合成数据演练通过) |
155
+ | VI 扰动评测 | ⬜ 待跑(运行器 + 报表已用合成数据演练通过) |
156
+
157
+ ---
158
+
159
+ ## 与 spec 的差异(完整版见 [outputs/reconstruction_differences.md](outputs/reconstruction_differences.md))
160
+
161
+ 除一处外全部精确复现。
162
+
163
+ **D1 — context 6,831 → 6,829,总计 44,418 → 44,416。**
164
+ 旧数据里有 2 条 context 查询的干扰实体字面包含 gold:
165
+ `"...confuse States Reorganisation Act with **Indian** Act..."` 而 gold 是 `India`。
166
+ 违反 spec §9.4 与 §13.9。按 spec §10「发现既有缺陷可改数」处理:
167
+ 在建库时加**规则化守卫**(主语提及剔除后 gold 仍出现即丢弃),不是硬编码例外。
168
+
169
+ **C1 — spec §6.2 与要求的规模自相矛盾。**
170
+ §6.2 点名 `developer of` / `manufacturer of` 不适合,但这两个关系共 **846 条**,
171
+ 去掉只剩 1,746 条 / 19 关系,达不到 §15 验收要求的 2,592 / 21。
172
+ 处理:保留并打 `spec_6_2_flag`,`relations.yaml` 提供 `drop_spec_6_2_flagged` 开关
173
+ 可一键产出 1,746 条的合规变体。
174
+
175
+ **F1 — 28.9% 的基准事实可以靠复制字符串答对。**
176
+ 2,592 条里有 **750 条** object 字面包含在 subject 名字里:
177
+
178
+ ```
179
+ Airbus A318 → manufacturer Airbus (该关系 87.8% 命中)
180
+ Adobe Acrobat → developer Adobe (49.1%)
181
+ Amazon Music → owned by Amazon (58.4%)
182
+ ```
183
+
184
+ 其中 586 条来自 manufacturer 和 developer——**独立印证了 C1**。
185
+ 这类事实"稳定"的原因与知识无关,会抬高所有保持率、削弱要研究的效应。
186
+ 按 spec §16 不删,打 `answer_in_subject_surface` 标记,事实和查询两级都带。
187
+ `qualification_score.py` 已经**默认分开报**这两个子集的准确率。
188
+
189
+ **F2 — 8,107 里有 808 条完全重复的三元组**(唯一四元组只有 7,299)。分组阶段自然吸收,仅记录。
190
+
191
+ **N1 — Stage I 未重跑 GPU**(见上)。
192
+ **N2 — `capital_of` 方向未归一化**:spec §2.2 要求单一方向,但归一化会改变规模,故保留
193
+ `direction: inverse` + `inverse_of: capital` 显式标注,开关在 `relations.yaml`。
194
+
195
+ ---
196
+
197
+ ## 两个必须记住的口径
198
+
199
+ 1. **分母永远是 2,592。** `K_m` 是标签不是筛子。加模型、换模型都不改任何已算出的数。
200
+ 2. **reverse 不进 main forward 平均。** 它换了目标槽(object → subject),
201
+ spec §2.3 要求单独报。`recognition` 和 `reverse_illposed` 同理,且校验器有硬检查。
202
+
203
+ ---
204
+
205
+ ## 报告用描述(spec §17)
206
+
207
+ > We first use five-model first-token consensus to retrieve high-probability
208
+ > factual candidates from large-scale knowledge resources. We then merge
209
+ > duplicate facts, expand entity aliases, construct independent canonical
210
+ > questions, remove ambiguous and multi-valued relations, and obtain a fixed
211
+ > benchmark of 2,592 facts across 21 relations. Model-specific open-ended anchor
212
+ > generation provides correctness labels but does not alter the benchmark
213
+ > denominator. Based on the fixed fact set, we construct 44,416 queries covering
214
+ > anchor, paraphrastic, format, contextual, cross-lingual, reverse, and
215
+ > recognition conditions, while isolating ill-posed reverse queries as a
216
+ > separate diagnostic set.
ICLR dataset/benchmark_facts_2592.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
ICLR dataset/configs/eval_conditions.yaml ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ totals:
134
+ expected_total_queries: 44418
135
+ # anchor 2592 + paraphrase 10053 + format 7776 + context 6831 + multilingual 12010
136
+ expected_main_forward_queries: 39262
137
+ expected_benchmark_facts: 2592
138
+ expected_relations: 21
139
+
140
+ # Spec 11: a query is a duplicate when fact_id + normalized text + target slot +
141
+ # condition family all coincide.
142
+ deduplication:
143
+ key: [fact_id, normalized_query, target_slot, condition_family]
144
+ expected_removed_during_migration: 10323
145
+
146
+ # Deviations from the spec counts that have been investigated and written up in
147
+ # outputs/reconstruction_differences.md. Listing one here stops the build from
148
+ # failing on it; an UNLISTED deviation still fails, so a new regression cannot
149
+ # hide behind a documented one.
150
+ accepted_deviations:
151
+ - check: context.queries
152
+ actual: 6829
153
+ expected: 6831
154
+ ref: D1
155
+ - check: total_queries
156
+ actual: 44416
157
+ expected: 44418
158
+ ref: D1
159
+ - check: main_forward_queries
160
+ actual: 39260
161
+ expected: 39262
162
+ ref: D1
ICLR dataset/configs/models.yaml ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 follows Model/MODEL_SELECTION_20.md: 5 families x 4 models,
5
+ # four size tiers, and four clean base<->instruct pairs spread across four
6
+ # different families.
7
+ #
8
+ # revision: "local" means the snapshot under Model/ is authoritative. Record the
9
+ # real commit hash once weights are re-pulled from the hub.
10
+
11
+ model_root: /scratch/rds-fei-rsfm-rw/cshi0459/ICLR27/Model
12
+
13
+ # ---- Stage I: five-model first-token candidate recall -----------------------
14
+ # FROZEN. These five defined the 8,107-fact candidate pool that everything
15
+ # downstream rests on. Changing this list invalidates
16
+ # candidate_known_8107.jsonl and every artefact derived from it, so it must stay
17
+ # fixed even as the evaluated set grows.
18
+ filter_models:
19
+ - {name: Gemma-2-2B-it, path: Gemma-2-2B-it, revision: local}
20
+ - {name: Qwen2.5-7B, path: Qwen2.5-7B, revision: local}
21
+ - {name: Mistral-7B-v0.3, path: Mistral-7B-v0.3, revision: local}
22
+ - {name: Llama-3.1-8B, path: Llama-3.1-8B, revision: local}
23
+ - {name: Gemma-2-9B-it, path: Gemma-2-9B-it, revision: local}
24
+
25
+ # ---- Stage V/VI: the 20 evaluated models ------------------------------------
26
+ # Spec 7.1: qualification produces K_m LABELS only. Adding or removing a model
27
+ # here never changes the benchmark denominator (fixed at 2,592), so this list is
28
+ # safe to extend at any time without invalidating earlier results.
29
+ #
30
+ # n_layers / d_model / jlens_window come from MODEL_SELECTION_20.md, where
31
+ # window = number of layers with normalized depth >= 0.4.
32
+ evaluated_models:
33
+ # ---------------- Llama-3.x ----------------
34
+ - {name: Llama-3.2-1B, path: Llama-3.2-1B, hf: meta-llama/Llama-3.2-1B,
35
+ family: llama-3.x, tier: 1-5B, params_b: 1.24, tuning: base,
36
+ n_layers: 16, d_model: 2048, jlens_window: 10, revision: main}
37
+ - {name: Llama-3.2-3B, path: Llama-3.2-3B, hf: meta-llama/Llama-3.2-3B,
38
+ family: llama-3.x, tier: 1-5B, params_b: 3.21, tuning: base,
39
+ n_layers: 28, d_model: 3072, jlens_window: 17, revision: main}
40
+ - {name: Llama-3.1-8B, path: Llama-3.1-8B, hf: meta-llama/Llama-3.1-8B,
41
+ family: llama-3.x, tier: 5-9B, params_b: 8.03, tuning: base,
42
+ n_layers: 32, d_model: 4096, jlens_window: 19, revision: local,
43
+ pair: llama_8b}
44
+ - {name: Llama-3.1-8B-Instruct, path: Llama-3.1-8B-Instruct,
45
+ hf: meta-llama/Llama-3.1-8B-Instruct,
46
+ family: llama-3.x, tier: 5-9B, params_b: 8.03, tuning: instruct,
47
+ n_layers: 32, d_model: 4096, jlens_window: 19, revision: main,
48
+ pair: llama_8b}
49
+
50
+ # ---------------- Qwen2.5 ----------------
51
+ - {name: Qwen2.5-3B, path: Qwen2.5-3B, hf: Qwen/Qwen2.5-3B,
52
+ family: qwen2.5, tier: 1-5B, params_b: 3.09, tuning: base,
53
+ n_layers: 36, d_model: 2048, jlens_window: 22, revision: main}
54
+ - {name: Qwen2.5-7B, path: Qwen2.5-7B, hf: Qwen/Qwen2.5-7B,
55
+ family: qwen2.5, tier: 5-9B, params_b: 7.62, tuning: base,
56
+ n_layers: 28, d_model: 3584, jlens_window: 17, revision: local,
57
+ pair: qwen_7b}
58
+ - {name: Qwen2.5-7B-Instruct, path: Qwen2.5-7B-Instruct,
59
+ hf: Qwen/Qwen2.5-7B-Instruct,
60
+ family: qwen2.5, tier: 5-9B, params_b: 7.62, tuning: instruct,
61
+ n_layers: 28, d_model: 3584, jlens_window: 17, revision: main,
62
+ pair: qwen_7b}
63
+ - {name: Qwen2.5-32B, path: Qwen2.5-32B, hf: Qwen/Qwen2.5-32B,
64
+ family: qwen2.5, tier: 20B+, params_b: 32.76, tuning: base,
65
+ n_layers: 64, d_model: 5120, jlens_window: 38, revision: local}
66
+
67
+ # ---------------- Mistral ----------------
68
+ - {name: Mistral-7B-v0.3, path: Mistral-7B-v0.3, hf: mistralai/Mistral-7B-v0.3,
69
+ family: mistral, tier: 5-9B, params_b: 7.25, tuning: base,
70
+ n_layers: 32, d_model: 4096, jlens_window: 19, revision: local,
71
+ pair: mistral_7b}
72
+ - {name: Mistral-7B-Instruct-v0.3, path: Mistral-7B-Instruct-v0.3,
73
+ hf: mistralai/Mistral-7B-Instruct-v0.3,
74
+ family: mistral, tier: 5-9B, params_b: 7.25, tuning: instruct,
75
+ n_layers: 32, d_model: 4096, jlens_window: 19, revision: main,
76
+ pair: mistral_7b}
77
+ - {name: Mistral-Nemo-Base-2407, path: Mistral-Nemo-Base-2407,
78
+ hf: mistralai/Mistral-Nemo-Base-2407,
79
+ family: mistral, tier: 9-20B, params_b: 12.25, tuning: base,
80
+ n_layers: 40, d_model: 5120, jlens_window: 24, revision: main}
81
+ - {name: Mistral-Small-24B-Base-2501, path: Mistral-Small-24B-Base-2501,
82
+ hf: mistralai/Mistral-Small-24B-Base-2501,
83
+ family: mistral, tier: 20B+, params_b: 23.57, tuning: base,
84
+ n_layers: 40, d_model: 5120, jlens_window: 24, revision: main}
85
+
86
+ # ---------------- Gemma-2 ----------------
87
+ # Gemma-2 and OLMo-2 publish fp32 safetensors only; they are loaded with
88
+ # dtype=bfloat16, so on-disk size is ~2x the bf16 figure.
89
+ - {name: gemma-2-2b, path: gemma-2-2b, hf: google/gemma-2-2b,
90
+ family: gemma-2, tier: 1-5B, params_b: 2.61, tuning: base,
91
+ n_layers: 26, d_model: 2304, jlens_window: 16, revision: main}
92
+ - {name: gemma-2-9b, path: gemma-2-9b, hf: google/gemma-2-9b,
93
+ family: gemma-2, tier: 9-20B, params_b: 9.24, tuning: base,
94
+ n_layers: 42, d_model: 3584, jlens_window: 25, revision: main,
95
+ pair: gemma_9b}
96
+ - {name: Gemma-2-9B-it, path: Gemma-2-9B-it, hf: google/gemma-2-9b-it,
97
+ family: gemma-2, tier: 9-20B, params_b: 9.24, tuning: instruct,
98
+ n_layers: 42, d_model: 3584, jlens_window: 25, revision: local,
99
+ pair: gemma_9b}
100
+ - {name: gemma-2-27b, path: gemma-2-27b, hf: google/gemma-2-27b,
101
+ family: gemma-2, tier: 20B+, params_b: 27.23, tuning: base,
102
+ n_layers: 46, d_model: 4608, jlens_window: 28, revision: main}
103
+
104
+ # ---------------- OLMo-2 ----------------
105
+ # The only family with all four tiers AND fully public pretraining data, which
106
+ # is what makes "the model never saw this fact" separable from "the model
107
+ # cannot retrieve it".
108
+ - {name: OLMo-2-0425-1B, path: OLMo-2-0425-1B, hf: allenai/OLMo-2-0425-1B,
109
+ family: olmo-2, tier: 1-5B, params_b: 1.48, tuning: base,
110
+ n_layers: 16, d_model: 2048, jlens_window: 10, revision: main}
111
+ - {name: OLMo-2-1124-7B, path: OLMo-2-1124-7B, hf: allenai/OLMo-2-1124-7B,
112
+ family: olmo-2, tier: 5-9B, params_b: 7.30, tuning: base,
113
+ n_layers: 32, d_model: 4096, jlens_window: 19, revision: main}
114
+ - {name: OLMo-2-1124-13B, path: OLMo-2-1124-13B, hf: allenai/OLMo-2-1124-13B,
115
+ family: olmo-2, tier: 9-20B, params_b: 13.72, tuning: base,
116
+ n_layers: 40, d_model: 5120, jlens_window: 24, revision: main}
117
+ - {name: OLMo-2-0325-32B, path: OLMo-2-0325-32B, hf: allenai/OLMo-2-0325-32B,
118
+ family: olmo-2, tier: 20B+, params_b: 32.23, tuning: base,
119
+ n_layers: 64, d_model: 5120, jlens_window: 38, revision: main}
120
+
121
+ # ---- base <-> instruct pairs (MODEL_SELECTION_20.md section 4) --------------
122
+ # Same weights lineage, same tokenizer, same size; only post-training differs.
123
+ # If BES improves while ISS does not, instruction tuning stabilised EXPRESSION
124
+ # rather than KNOWLEDGE.
125
+ tuning_pairs:
126
+ llama_8b: {base: Llama-3.1-8B, instruct: Llama-3.1-8B-Instruct, family: llama-3.x, tier: 5-9B}
127
+ qwen_7b: {base: Qwen2.5-7B, instruct: Qwen2.5-7B-Instruct, family: qwen2.5, tier: 5-9B}
128
+ mistral_7b: {base: Mistral-7B-v0.3, instruct: Mistral-7B-Instruct-v0.3, family: mistral, tier: 5-9B}
129
+ gemma_9b: {base: gemma-2-9b, instruct: Gemma-2-9B-it, family: gemma-2, tier: 9-20B}
130
+
131
+ # ---- models that do NOT occupy an evaluated slot ----------------------------
132
+ auxiliary_models:
133
+ stage_a_calibration:
134
+ name: Qwen2.5-0.5B
135
+ path: Qwen2.5-0.5B
136
+ hf: Qwen/Qwen2.5-0.5B
137
+ params_b: 0.49
138
+ n_layers: 24
139
+ d_model: 896
140
+ reason: exact full-matrix reference for J-Lens (J-Lens spec section 5)
141
+ judge:
142
+ name: Qwen2.5-32B-Instruct
143
+ path: Qwen2.5-32B-Instruct
144
+ hf: Qwen/Qwen2.5-32B-Instruct
145
+ params_b: 32.76
146
+ n_layers: 64
147
+ d_model: 5120
148
+ reason: semantic clustering judge (evaluation protocol section 3)
149
+ # Must be instruct (structured JSON output) and multilingual-strong: 12,010
150
+ # of 44,416 queries are zh/fr/es/de/ru.
151
+ known_bias: >
152
+ shares pretraining lineage with the four evaluated Qwen models and may
153
+ systematically favour their phrasing. Mitigation: agreement check against
154
+ src/scoring_full.py on a stratified sample, and optionally a second judge
155
+ (gemma-2-27b-it) on a subsample. The judge is never itself evaluated.
156
+
157
+ # ---- excluded, with reasons (MODEL_SELECTION_20.md section 9) ---------------
158
+ excluded_models:
159
+ - {name: Llama-3.1-70B, reason: "bf16 weights 141 GB vs 143 GB H200; quantisation would alter hidden states and break ISS/KTS comparability"}
160
+ - {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."}
161
+ - {name: Llama-2-13B, reason: "different generation from Llama-3; mixing would break the family axis"}
162
+ - {name: Phi-3/Phi-4, reason: "heavily synthetic training data; atypical knowledge profile"}
163
+ - {name: Yi/InternLM/GLM, reason: "adds family breadth but no new scientific axis"}
164
+
165
+ # ---- Stage V/VI generation configuration (spec section 7.3) -----------------
166
+ generation:
167
+ do_sample: false
168
+ num_beams: 1
169
+ temperature: 0.0
170
+ max_new_tokens: 24
171
+ max_prompt_len: 96
172
+ batch_size: 96
173
+ dtype: bfloat16
174
+ # Spec 7.2: identical raw prompt string for base and instruct models, so no
175
+ # chat template is ever applied. This matters more with 4 instruct models in
176
+ # the set: giving only those a chat template would confound tuning with format.
177
+ use_chat_template: false
178
+ seed: 20260101
ICLR dataset/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}
ICLR dataset/configs/source_templates.yaml ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Raw source registry and Stage I cloze templates (spec sections 4.1 - 4.3).
2
+
3
+ raw_root: /scratch/rds-fei-rsfm-rw/cshi0459/ICLR27/dataset
4
+
5
+ sources:
6
+ counterfact:
7
+ path: counterfact/data/*.parquet
8
+ format: parquet
9
+ expected_triples: 21919
10
+ is_core: true
11
+ # spec 4.1: the TRUE object, never the counterfactual edit target
12
+ object_field: requested_rewrite.target_true.str
13
+ object_id_field: requested_rewrite.target_true.id
14
+ subject_field: requested_rewrite.subject
15
+ relation_field: requested_rewrite.relation_id
16
+ cloze: native # the dataset ships its own prompt template
17
+
18
+ lama_trex:
19
+ path: lama/data/TREx/*.jsonl
20
+ format: jsonl
21
+ expected_triples: 34039
22
+ is_core: true
23
+ subject_field: sub_label
24
+ subject_id_field: sub_uri
25
+ relation_field: predicate_id
26
+ object_field: obj_label
27
+ object_id_field: obj_uri
28
+ cloze: relations_jsonl_template # lama/data/relations.jsonl, cut at [Y]
29
+
30
+ lama_googlere:
31
+ path: lama/data/Google_RE/*.jsonl
32
+ format: jsonl
33
+ expected_triples: 5528
34
+ is_core: false
35
+ subject_field: sub_label
36
+ relation_field: pred # last path segment
37
+ object_field: obj_label
38
+ alias_fields: [sub_aliases, obj_aliases]
39
+ cloze: handwritten
40
+ templates:
41
+ place_of_birth: "{s} was born in"
42
+ place_of_death: "{s} died in"
43
+ date_of_birth: "{s} was born in the year"
44
+
45
+ lama_conceptnet:
46
+ path: lama/data/ConceptNet/*.jsonl
47
+ format: jsonl
48
+ expected_triples: 28914
49
+ is_core: false
50
+ subject_field: sub_label
51
+ relation_field: pred
52
+ object_field: obj_label
53
+ cloze: masked_sentence # masked_sentences[0], cut at [MASK]
54
+
55
+ t_rex:
56
+ path: trex/*.jsonl
57
+ format: jsonl
58
+ expected_triples: 1592952
59
+ is_core: false
60
+ subject_field: head
61
+ relation_field: relation # natural-language template with brackets
62
+ object_field: tail
63
+ cloze: bracket_template
64
+ # spec 4.5: dropped after consensus filtering (pass rate 0.17%)
65
+ drop_after_consensus: true
66
+
67
+ wikidata5m:
68
+ path: wikidata5m/extracted/wikidata5m_all_triplet.txt
69
+ format: tsv
70
+ expected_triples: 21354359
71
+ is_core: false
72
+ cloze: generic # "{subject} {relation}"
73
+ # spec 4.3: strided down to ~100k prompts before model filtering
74
+ sample:
75
+ method: stride
76
+ target_prompts: 100000
77
+ actual_prompts: 100189
78
+ drop_after_consensus: true
79
+
80
+ popqa:
81
+ path: hf_cache/hub/datasets--akariasai--PopQA/snapshots/*/test.tsv
82
+ format: tsv
83
+ is_core: true
84
+ # spec 4.1 / 4.5: added AFTER the initial consensus stage, then run through
85
+ # the identical five-model first-token protocol
86
+ added_after_consensus: true
87
+ expected_prompts: 14149
88
+ expected_passed: 378
89
+ alias_fields: [s_aliases, o_aliases, possible_answers]
90
+
91
+ # Aggregate expectations (spec section 1)
92
+ expected:
93
+ raw_triples_total: 23038571
94
+ cloze_prompts: 1783541
95
+ five_model_consensus: 10601
96
+ candidate_known: 8107
97
+
98
+ alias_resources:
99
+ wikidata_entity_aliases: wikidata5m/extracted/wikidata5m_alias/wikidata5m_entity.txt
100
+ # spec 5.3: scan once, keep only the QIDs the candidate set needs
101
+ scan_mode: filtered_single_pass
102
+ max_aliases_per_entity: 16
103
+ # crowd-sourced alias lists carry Wikipedia housekeeping titles and ISO codes
104
+ junk_patterns:
105
+ - "^list of "
106
+ - "^books?/"
107
+ - "^number of "
108
+ - "^category:"
109
+ - "^template:"
110
+ - "^wikipedia:"
111
+ - "^iso \\d"
112
+ - "^portal:"
113
+ - "^index of "
114
+ - "^outline of "
115
+ - "\\(disambiguation\\)"
116
+ - "/"
117
+ min_alias_chars: 2
ICLR dataset/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
ICLR dataset/metrics/__pycache__/extract_hidden.cpython-313.pyc ADDED
Binary file (11.1 kB). View file
 
ICLR dataset/metrics/__pycache__/jlens.cpython-313.pyc ADDED
Binary file (21.3 kB). View file
 
ICLR dataset/metrics/__pycache__/mcommon.cpython-313.pyc ADDED
Binary file (15.6 kB). View file
 
ICLR dataset/metrics/__pycache__/states.cpython-313.pyc ADDED
Binary file (11.9 kB). View file
 
ICLR dataset/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()
ICLR dataset/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.ds3("src"))
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()
ICLR dataset/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()
ICLR dataset/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()
ICLR dataset/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()
ICLR dataset/metrics/judge_run.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.ds3("src"))
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.ds3("outputs", "evaluation", f"{args.model}.jsonl")
130
+ if not os.path.exists(gen_path):
131
+ raise SystemExit(f"no generations for {args.model}: {gen_path}")
132
+
133
+ qmeta = {r["query_id"]: r for r in mc.main_forward_queries()}
134
+ by_fact = {}
135
+ for r in mc.read_jsonl(gen_path):
136
+ if r["condition_family"] not in fams or r["query_id"] not in qmeta:
137
+ continue
138
+ by_fact.setdefault(r["fact_id"], []).append(r)
139
+ fact_ids = sorted(by_fact)
140
+ if args.sample and args.sample < len(fact_ids):
141
+ # Drawn from the FULL benchmark fact list with a fixed seed, not from
142
+ # this model's own facts, so every model is judged on an identical
143
+ # subset. Sampling per model would make BCS/BES incomparable, which is
144
+ # exactly what protocol 1.3 forbids.
145
+ import numpy as np
146
+ allf = sorted(mc.facts())
147
+ rng = np.random.default_rng(args.sample_seed)
148
+ pick = set(np.array(allf)[rng.choice(len(allf), size=args.sample,
149
+ replace=False)].tolist())
150
+ fact_ids = [f for f in fact_ids if f in pick]
151
+ if args.limit:
152
+ fact_ids = fact_ids[:args.limit]
153
+
154
+ dest = mc.out("metrics", "judge", f"{args.model}.jsonl")
155
+ done = set()
156
+ if args.resume and os.path.exists(dest):
157
+ done = {r["fact_id"] for r in mc.read_jsonl(dest)}
158
+ fact_ids = [f for f in fact_ids if f not in done]
159
+ if not fact_ids:
160
+ print(f"[{args.model}] judge already complete")
161
+ return
162
+
163
+ facts = mc.facts()
164
+ # Pre-group by normalised surface: a strict subset of semantic equivalence,
165
+ # so this changes cost and not the clustering the judge can express.
166
+ tasks = []
167
+ for fid in fact_ids:
168
+ recs = by_fact[fid]
169
+ groups = {}
170
+ for r in recs:
171
+ key = normalize(r["raw_response"].strip().split("\n")[0][:120])
172
+ groups.setdefault(key, []).append(r["query_id"])
173
+ surfaces = list(groups)
174
+ display = [next(x["raw_response"].strip().split("\n")[0][:120]
175
+ for x in recs if normalize(
176
+ x["raw_response"].strip().split("\n")[0][:120]) == s) or "(empty)"
177
+ for s in surfaces]
178
+ tasks.append({"fact_id": fid, "surfaces": surfaces, "display": display,
179
+ "groups": [groups[s] for s in surfaces],
180
+ "question": facts[fid]["qualification_question"]})
181
+
182
+ path = mc.model_path(judge_name)
183
+ tok = AutoTokenizer.from_pretrained(path)
184
+ if tok.pad_token is None:
185
+ tok.pad_token = tok.eos_token
186
+ tok.padding_side = "left"
187
+ judge = AutoModelForCausalLM.from_pretrained(
188
+ path, dtype=torch.bfloat16, device_map={"": 0}).eval()
189
+
190
+ t0 = time.time()
191
+ out_f = open(dest, "a" if done else "w")
192
+ for i in range(0, len(tasks), args.batch):
193
+ chunk = tasks[i:i + args.batch]
194
+
195
+ p1 = [BLIND.format(question=t["question"], last=len(t["display"]) - 1,
196
+ answers="\n".join(f"{j}. {d}" for j, d in enumerate(t["display"])))
197
+ for t in chunk]
198
+ r1 = generate(judge, tok, p1, 512, args.batch)
199
+
200
+ for t, raw in zip(chunk, r1):
201
+ js = parse_json(raw) or {}
202
+ clusters, seen = [], set()
203
+ for c in js.get("clusters", []):
204
+ ids = [int(x) for x in c.get("ids", [])
205
+ if isinstance(x, (int, float)) and 0 <= int(x) < len(t["display"])
206
+ and int(x) not in seen]
207
+ if not ids:
208
+ continue
209
+ seen.update(ids)
210
+ clusters.append({"ids": ids, "meaning": str(c.get("meaning", ""))[:80],
211
+ "status": str(c.get("status", "ANSWER")).upper()})
212
+ # Anything the judge dropped or mangled stays its own cluster rather
213
+ # than vanishing: silently losing a response would change the BCS
214
+ # denominator for that fact.
215
+ for j in range(len(t["display"])):
216
+ if j not in seen:
217
+ clusters.append({"ids": [j], "meaning": t["display"][j][:80],
218
+ "status": "ANSWER", "recovered": True})
219
+ t["clusters"] = clusters
220
+ t["judge_raw_blind"] = raw[:400]
221
+
222
+ p2, own = [], []
223
+ for t in chunk:
224
+ f = facts[t["fact_id"]]
225
+ answer = [c["meaning"] or t["display"][c["ids"][0]] for c in t["clusters"]]
226
+ p2.append(AWARE.format(
227
+ question=t["question"], gold=f["object"]["canonical"],
228
+ aliases=", ".join(f["object"]["aliases"][:10]),
229
+ atype=f.get("answer_type", "entity"),
230
+ gran=f.get("answer_granularity", "entity"),
231
+ answers="\n".join(f"{j}. {a}" for j, a in enumerate(answer)),
232
+ n=len(answer)))
233
+ own.append(t)
234
+ r2 = generate(judge, tok, p2, 256, args.batch)
235
+ for t, raw in zip(own, r2):
236
+ js = parse_json(raw) or {}
237
+ labels = [str(x).upper() for x in js.get("labels", [])]
238
+ for j, c in enumerate(t["clusters"]):
239
+ lab = labels[j] if j < len(labels) else "REVIEW_REQUIRED"
240
+ if c["status"] in ("ABSTAIN", "MULTIPLE", "UNPARSEABLE"):
241
+ lab = c["status"] if c["status"] == "ABSTAIN" else "REVIEW_REQUIRED"
242
+ c["correctness"] = lab
243
+ t["judge_raw_aware"] = raw[:400]
244
+
245
+ for t in chunk:
246
+ rows = []
247
+ for k, c in enumerate(t["clusters"]):
248
+ cid = f"C{k}" if c["status"] == "ANSWER" else c["status"]
249
+ for j in c["ids"]:
250
+ for qid in t["groups"][j]:
251
+ rows.append({"query_id": qid,
252
+ "condition_family": qmeta[qid]["condition_family"],
253
+ "cluster_id": cid})
254
+ out_f.write(json.dumps({
255
+ "model": args.model, "judge": judge_name, "fact_id": t["fact_id"],
256
+ "clusters": [{"cluster_id": f"C{k}" if c["status"] == "ANSWER"
257
+ else c["status"],
258
+ "canonical_meaning": c["meaning"],
259
+ "status": c["status"],
260
+ "correctness": c.get("correctness", "REVIEW_REQUIRED")}
261
+ for k, c in enumerate(t["clusters"])],
262
+ "assignments": rows}, ensure_ascii=False) + "\n")
263
+ out_f.flush()
264
+ d = i + len(chunk)
265
+ print(f" {d}/{len(tasks)} facts {d / max(time.time() - t0, 1e-9):.2f}/s",
266
+ flush=True)
267
+ out_f.close()
268
+ print(f"[{args.model}] judged {len(tasks)} facts with {judge_name} JUDGE_DONE",
269
+ flush=True)
270
+
271
+
272
+ if __name__ == "__main__":
273
+ main()
ICLR dataset/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()
ICLR dataset/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()
ICLR dataset/metrics/mcommon.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 dataset3/: the fact
5
+ set and the query bank are frozen artefacts (protocol 2.1), and this package
6
+ only consumes them.
7
+ """
8
+ import os, json, math, functools
9
+
10
+ import numpy as np
11
+ import yaml
12
+
13
+ HERE = os.path.dirname(os.path.abspath(__file__))
14
+ ROOT = os.path.dirname(HERE)
15
+ CONFIGS = os.path.join(ROOT, "configs")
16
+
17
+
18
+ @functools.lru_cache(maxsize=None)
19
+ def cfg():
20
+ with open(os.path.join(CONFIGS, "metrics.yaml")) as f:
21
+ return yaml.safe_load(f)
22
+
23
+
24
+ @functools.lru_cache(maxsize=None)
25
+ def models_cfg():
26
+ with open(os.path.join(cfg()["paths"]["dataset3"], "configs", "models.yaml")) as f:
27
+ return yaml.safe_load(f)
28
+
29
+
30
+ def model_entry(name):
31
+ for m in models_cfg()["evaluated_models"]:
32
+ if m["name"] == name:
33
+ return m
34
+ aux = models_cfg().get("auxiliary_models", {})
35
+ for m in aux.values():
36
+ if m["name"] == name:
37
+ return m
38
+ raise KeyError(f"{name} is not in dataset3/configs/models.yaml")
39
+
40
+
41
+ def model_path(name):
42
+ return os.path.join(models_cfg()["model_root"], model_entry(name)["path"])
43
+
44
+
45
+ def ds3(*parts):
46
+ return os.path.join(cfg()["paths"]["dataset3"], *parts)
47
+
48
+
49
+ def out(kind, *parts):
50
+ """kind in {hidden, jlens, metrics}."""
51
+ p = os.path.join(cfg()["paths"][f"{kind}_root"], *parts)
52
+ os.makedirs(os.path.dirname(p) if os.path.splitext(p)[1] else p, exist_ok=True)
53
+ return p
54
+
55
+
56
+ def read_jsonl(path):
57
+ with open(path) as f:
58
+ for line in f:
59
+ line = line.strip()
60
+ if line:
61
+ yield json.loads(line)
62
+
63
+
64
+ def write_jsonl(path, rows):
65
+ os.makedirs(os.path.dirname(path), exist_ok=True)
66
+ n = 0
67
+ with open(path, "w") as f:
68
+ for r in rows:
69
+ f.write(json.dumps(r, ensure_ascii=False, default=_jsonable) + "\n")
70
+ n += 1
71
+ return n
72
+
73
+
74
+ def write_json(path, obj):
75
+ os.makedirs(os.path.dirname(path), exist_ok=True)
76
+ with open(path, "w") as f:
77
+ json.dump(obj, f, indent=2, ensure_ascii=False, default=_jsonable)
78
+
79
+
80
+ def _jsonable(o):
81
+ if isinstance(o, (np.floating, np.integer)):
82
+ return o.item()
83
+ if isinstance(o, np.ndarray):
84
+ return o.tolist()
85
+ raise TypeError(type(o))
86
+
87
+
88
+ # ------------------------------------------------------------------- queries
89
+ QUERY_BANK = "evaluation_queries_44418.jsonl" # 44,416 rows; see dataset3 D1
90
+
91
+
92
+ @functools.lru_cache(maxsize=None)
93
+ def main_forward_queries():
94
+ """The 39,260 queries that protocol 1.1 admits to the main analysis.
95
+
96
+ The filter reads each row's own `use_for_main_forward` flag rather than
97
+ testing `condition_family in main_families`: the flags are derived from
98
+ eval_conditions.yaml and are what dataset3's validator checks, so trusting
99
+ them keeps one definition of the split instead of two that can drift.
100
+ """
101
+ rows = []
102
+ for r in read_jsonl(ds3("outputs", QUERY_BANK)):
103
+ if r.get("use_for_main_forward"):
104
+ rows.append(r)
105
+ fams = set(cfg()["main_families"])
106
+ bad = {r["condition_family"] for r in rows} - fams
107
+ if bad:
108
+ raise SystemExit(f"main_forward rows carry unexpected families: {bad}")
109
+ return rows
110
+
111
+
112
+ @functools.lru_cache(maxsize=None)
113
+ def facts():
114
+ """fact_id -> record, plus the relation of each fact."""
115
+ return {r["fact_id"]: r for r in read_jsonl(ds3("outputs", "benchmark_facts_2592.jsonl"))}
116
+
117
+
118
+ @functools.lru_cache(maxsize=None)
119
+ def fact_relation():
120
+ return {fid: r["relation"]["relation_id"] for fid, r in facts().items()}
121
+
122
+
123
+ @functools.lru_cache(maxsize=None)
124
+ def coverage():
125
+ """fact_id -> set of main families that actually contain it.
126
+
127
+ Protocol 1.3: coverage is ragged (multilingual 2,402, context 2,591), and
128
+ the two reporting modes below are both mandatory.
129
+ """
130
+ cov = {}
131
+ for r in main_forward_queries():
132
+ cov.setdefault(r["fact_id"], set()).add(r["condition_family"])
133
+ return cov
134
+
135
+
136
+ @functools.lru_cache(maxsize=None)
137
+ def complete_family_facts():
138
+ """D_cap: the facts carrying all five main families (protocol 1.3).
139
+
140
+ This set is a property of the query bank, not of any model, so every model
141
+ is scored on exactly the same facts -- which is the point of protocol 1.3's
142
+ prohibition on per-model effective sets.
143
+ """
144
+ need = set(cfg()["main_families"])
145
+ return sorted(f for f, c in coverage().items() if c >= need)
146
+
147
+
148
+ def eval_fact_set(mode):
149
+ if mode == "complete_family":
150
+ return complete_family_facts()
151
+ if mode == "full_set":
152
+ return sorted(coverage())
153
+ raise ValueError(mode)
154
+
155
+
156
+ # -------------------------------------------------------------- layer window
157
+ def layer_window(n_layers, min_depth=None):
158
+ """Protocol 7.10: {l : d_l >= min_depth}, d_l = l / (L - 1).
159
+
160
+ `l` indexes decoder blocks 0..L-1, so l = L-1 is the final residual stream
161
+ that J-Lens transports to. In HF terms the state is hidden_states[l+1],
162
+ because hidden_states[0] is the embedding output.
163
+ """
164
+ if min_depth is None:
165
+ min_depth = cfg()["extraction"]["window_min_depth"]
166
+ return [l for l in range(n_layers) if l / max(n_layers - 1, 1) >= min_depth - 1e-9]
167
+
168
+
169
+ def late_window(n_layers):
170
+ return layer_window(n_layers, cfg()["extraction"]["late_min_depth"])
171
+
172
+
173
+ # --------------------------------------------------------------- linear alg
174
+ def l2_normalize(x, axis=-1, eps=1e-12):
175
+ n = np.linalg.norm(x, axis=axis, keepdims=True)
176
+ return x / np.maximum(n, eps)
177
+
178
+
179
+ def pca_whiten(X, dim, shrinkage, eps=1e-12):
180
+ """Return the whitened matrix and the fitted transform.
181
+
182
+ Protocol 7.5 forbids fitting a separate transform per condition family, so
183
+ this is called once per (model, layer) on the pooled matrix and the same
184
+ components are then applied to every family.
185
+ """
186
+ mu = X.mean(axis=0, keepdims=True)
187
+ Xc = X - mu
188
+ # Economy SVD on the centred matrix is the covariance eigendecomposition
189
+ # without ever forming a d x d matrix -- d can be 5120 and n is ~39k.
190
+ k = min(dim, Xc.shape[0], Xc.shape[1])
191
+ U, S, Vt = np.linalg.svd(Xc, full_matrices=False)
192
+ U, S, Vt = U[:, :k], S[:k], Vt[:k]
193
+ var = (S ** 2) / max(Xc.shape[0] - 1, 1)
194
+ # lambda is expressed as a fraction of the mean retained variance so that
195
+ # one config value behaves the same across models with different scales.
196
+ lam = shrinkage * float(var.mean())
197
+ Z = (Xc @ Vt.T) / np.sqrt(var + lam + eps)
198
+ return Z.astype(np.float32), {"mean": mu, "components": Vt, "scale": np.sqrt(var + lam + eps)}
199
+
200
+
201
+ # ------------------------------------------------------------------ negatives
202
+ def negative_sample(fact_ids, relation_of, max_negatives, seed):
203
+ """Protocol 7.8: for each fact, up to `max_negatives` same-relation others.
204
+
205
+ Drawn ONCE from the fixed fact set and reused for every model. If each model
206
+ drew its own, a model could score well merely by having been handed more
207
+ distant negatives.
208
+ """
209
+ rng = np.random.default_rng(seed)
210
+ by_rel = {}
211
+ for f in fact_ids:
212
+ by_rel.setdefault(relation_of[f], []).append(f)
213
+ for r in by_rel:
214
+ by_rel[r].sort()
215
+ negs = {}
216
+ for f in fact_ids:
217
+ pool = [g for g in by_rel[relation_of[f]] if g != f]
218
+ if len(pool) > max_negatives:
219
+ idx = rng.choice(len(pool), size=max_negatives, replace=False)
220
+ pool = [pool[i] for i in sorted(idx)]
221
+ negs[f] = pool
222
+ return negs
223
+
224
+
225
+ # ----------------------------------------------------------------- bootstrap
226
+ def relation_clustered_bootstrap(values, relation_of, n_resamples, seed, ci=0.95):
227
+ """Protocol 14.1: resample relations, then facts within each drawn relation.
228
+
229
+ A plain per-fact bootstrap would understate the interval because the 21
230
+ relations are very unevenly sized and facts inside one relation are far from
231
+ independent.
232
+ """
233
+ fact_ids = [f for f in values if values[f] == values[f]] # drop NaN
234
+ if not fact_ids:
235
+ return {"mean": float("nan"), "lo": float("nan"), "hi": float("nan"), "n": 0}
236
+ by_rel = {}
237
+ for f in fact_ids:
238
+ by_rel.setdefault(relation_of[f], []).append(f)
239
+ rels = sorted(by_rel)
240
+ arr = {r: np.array([values[f] for f in by_rel[r]], dtype=np.float64) for r in rels}
241
+ rng = np.random.default_rng(seed)
242
+ draws = np.empty(n_resamples, dtype=np.float64)
243
+ for b in range(n_resamples):
244
+ picked = rng.integers(0, len(rels), size=len(rels))
245
+ pool = []
246
+ for i in picked:
247
+ a = arr[rels[i]]
248
+ pool.append(a[rng.integers(0, len(a), size=len(a))])
249
+ draws[b] = np.concatenate(pool).mean()
250
+ lo, hi = np.percentile(draws, [(1 - ci) / 2 * 100, (1 + ci) / 2 * 100])
251
+ point = float(np.mean([values[f] for f in fact_ids]))
252
+ return {"mean": point, "lo": float(lo), "hi": float(hi), "n": len(fact_ids)}
ICLR dataset/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
ICLR dataset/protocol/bcs_bes_iss_kts_evaluation_protocol (1).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 两种覆盖口径。
ICLR dataset/protocol/jacobian_transported_iss_engineering_spec (1).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.
ICLR dataset/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.
ICLR dataset/runner/__pycache__/common.cpython-313.pyc ADDED
Binary file (9.23 kB). View file
 
ICLR dataset/runner/__pycache__/eval_run.cpython-313.pyc ADDED
Binary file (10.3 kB). View file
 
ICLR dataset/runner/__pycache__/qual_templates.cpython-313.pyc ADDED
Binary file (7.88 kB). View file
 
ICLR dataset/runner/__pycache__/scoring_full.cpython-313.pyc ADDED
Binary file (9.08 kB). View file
 
ICLR dataset/runner/build_candidate_known.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Stage I -> outputs/candidate_known_8107.jsonl (spec sections 4.1 - 4.5)
3
+
4
+ Stage I is the expensive part of the pipeline: 1,783,541 cloze prompts x 5
5
+ models of GPU forward passes. Those passes were already run and their outputs
6
+ live under dataset/filter/ as `correct_<model>.npy` vectors aligned to
7
+ `prompts.jsonl`. This script therefore RECONSTRUCTS the candidate set from
8
+ those stored per-model verdicts rather than re-running the GPU, while
9
+ re-deriving every count from raw data so the numbers are verified, not assumed:
10
+
11
+ * prompts.jsonl and prompts_popqa.jsonl are re-read and counted;
12
+ * the five per-model vectors are re-intersected here, not taken on trust;
13
+ * the source-drop rule (spec 4.5) is re-applied;
14
+ * every input file is checksummed into the output header.
15
+
16
+ Re-running the GPU stage from scratch is `src/filter_run.py`, which is kept
17
+ byte-compatible with the stored vectors; use --verify_only to check that this
18
+ reconstruction still matches dataset/filter/global_known_clean.jsonl.
19
+ """
20
+ import os, sys, json, argparse, collections
21
+ import numpy as np
22
+
23
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
24
+ from common import (DATASET, load_config, out_path, read_jsonl, write_jsonl,
25
+ sha256, Expect)
26
+
27
+
28
+ def main():
29
+ ap = argparse.ArgumentParser()
30
+ ap.add_argument("--verify_only", action="store_true")
31
+ args = ap.parse_args()
32
+
33
+ src_cfg = load_config("source_templates.yaml")
34
+ mdl_cfg = load_config("models.yaml")
35
+ filter_models = [m["name"] for m in mdl_cfg["filter_models"]]
36
+ exp = Expect()
37
+
38
+ fdir = os.path.join(DATASET, "filter")
39
+ prompts_path = os.path.join(fdir, "prompts.jsonl")
40
+ popqa_path = os.path.join(fdir, "prompts_popqa.jsonl")
41
+
42
+ # ---- 1. cloze prompt table (spec 4.3) ----
43
+ print("[1/4] reading cloze prompt table ...", flush=True)
44
+ prompts = list(read_jsonl(prompts_path))
45
+ exp.check("cloze_prompts", len(prompts), src_cfg["expected"]["cloze_prompts"])
46
+
47
+ by_source = collections.Counter(p["source"] for p in prompts)
48
+ for name, s in src_cfg["sources"].items():
49
+ if s.get("added_after_consensus"):
50
+ continue
51
+ key = {"t_rex": "trex"}.get(name, name)
52
+ if key in by_source and "expected_triples" in s:
53
+ exp.check(f"prompts[{name}]", by_source[key], None)
54
+
55
+ # ---- 2. five-model consensus (spec 4.4) ----
56
+ print(f"[2/4] intersecting {len(filter_models)} first-token verdict vectors ...",
57
+ flush=True)
58
+ inter = np.ones(len(prompts), dtype=bool)
59
+ per_model = {}
60
+ for m in filter_models:
61
+ v = np.load(os.path.join(fdir, f"correct_{m}.npy")).astype(bool)
62
+ if len(v) != len(prompts):
63
+ raise SystemExit(f"correct_{m}.npy has {len(v)} rows, "
64
+ f"prompts.jsonl has {len(prompts)}")
65
+ per_model[m] = float(v.mean())
66
+ inter &= v
67
+ exp.check("five_model_consensus", int(inter.sum()),
68
+ src_cfg["expected"]["five_model_consensus"])
69
+
70
+ # ---- 3. source filtering (spec 4.5) ----
71
+ drop = {name for name, s in src_cfg["sources"].items()
72
+ if s.get("drop_after_consensus")}
73
+ drop |= {"trex"} if "t_rex" in drop else set()
74
+ print(f"[3/4] dropping post-consensus sources: {sorted(drop)}", flush=True)
75
+
76
+ rows = []
77
+ for i, p in enumerate(prompts):
78
+ if not inter[i]:
79
+ continue
80
+ if p["source"] in drop:
81
+ continue
82
+ rows.append({
83
+ "raw_id": p["id"],
84
+ "prompt_id": f"p{i:07d}",
85
+ "source": p["source"],
86
+ "subject": p["subject"],
87
+ "relation": p["relation"],
88
+ "object": p["object"],
89
+ "cloze_prompt": p["prompt"],
90
+ "consensus": {"models": filter_models, "n_passed": len(filter_models)},
91
+ "legacy_ref": {"file": "prompts.jsonl", "row": i},
92
+ })
93
+
94
+ # ---- 4. PopQA supplement, same protocol (spec 4.5) ----
95
+ n_popqa = 0
96
+ if os.path.exists(popqa_path):
97
+ pq = list(read_jsonl(popqa_path))
98
+ exp.check("popqa_prompts", len(pq),
99
+ src_cfg["sources"]["popqa"].get("expected_prompts"))
100
+ pinter = np.ones(len(pq), dtype=bool)
101
+ for m in filter_models:
102
+ v = np.load(os.path.join(fdir, f"popqa_correct_{m}.npy")).astype(bool)
103
+ pinter &= v
104
+ for i, p in enumerate(pq):
105
+ if not pinter[i]:
106
+ continue
107
+ rows.append({
108
+ "raw_id": p["id"],
109
+ "prompt_id": f"q{i:07d}",
110
+ "source": "popqa",
111
+ "subject": p["subject"],
112
+ "relation": p["relation"],
113
+ "object": p["object"],
114
+ "cloze_prompt": p["prompt"],
115
+ "consensus": {"models": filter_models, "n_passed": len(filter_models)},
116
+ "legacy_ref": {"file": "prompts_popqa.jsonl", "row": i},
117
+ })
118
+ n_popqa += 1
119
+ exp.check("popqa_passed", n_popqa,
120
+ src_cfg["sources"]["popqa"].get("expected_passed"))
121
+
122
+ exp.check("candidate_known", len(rows), src_cfg["expected"]["candidate_known"])
123
+
124
+ # ---- cross-check against the legacy file ----
125
+ legacy = os.path.join(fdir, "global_known_clean.jsonl")
126
+ if os.path.exists(legacy):
127
+ want = {(d["subject"], d["relation"], d["object"], d["source"])
128
+ for d in read_jsonl(legacy)}
129
+ got = {(r["subject"], r["relation"], r["object"], r["source"]) for r in rows}
130
+ exp.check("matches_legacy_clean_set", len(got & want), len(want),
131
+ note="set equality against dataset/filter/global_known_clean.jsonl")
132
+ if got != want:
133
+ print(f" only-in-new: {len(got - want)} only-in-legacy: {len(want - got)}")
134
+
135
+ exp.report("Stage I counts")
136
+ if args.verify_only:
137
+ return 1 if exp.deviations else 0
138
+
139
+ path = out_path("candidate_known_8107.jsonl")
140
+ write_jsonl(path, rows)
141
+
142
+ meta = {
143
+ "stage": "I_candidate_recall",
144
+ "n_candidate_known": len(rows),
145
+ "per_source": dict(collections.Counter(r["source"] for r in rows)),
146
+ "filter_models": filter_models,
147
+ "filter_model_first_token_accuracy": per_model,
148
+ "dropped_sources_after_consensus": sorted(drop),
149
+ "checks": exp.rows,
150
+ "inputs": {
151
+ "prompts.jsonl": sha256(prompts_path, limit_mb=64),
152
+ "prompts_popqa.jsonl": sha256(popqa_path) if os.path.exists(popqa_path) else None,
153
+ **{f"correct_{m}.npy": sha256(os.path.join(fdir, f"correct_{m}.npy"))
154
+ for m in filter_models},
155
+ },
156
+ "note": "GPU forward passes were not re-run; the stored per-model "
157
+ "first-token verdict vectors were re-intersected here. Use "
158
+ "src/filter_run.py to regenerate them from scratch.",
159
+ }
160
+ json.dump(meta, open(out_path("stage1_report.json"), "w"),
161
+ indent=2, ensure_ascii=False)
162
+ print(f"\nwrote {len(rows)} candidate facts -> {path}")
163
+ print(f" per source: {meta['per_source']}")
164
+ return 1 if exp.deviations else 0
165
+
166
+
167
+ if __name__ == "__main__":
168
+ sys.exit(main())
ICLR dataset/runner/build_eval_bank.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Stage IV -> outputs/evaluation_queries_44418.jsonl (spec sections 8 - 12)
3
+
4
+ Builds the query bank on the FIXED 2,592-fact benchmark. Sources:
5
+ * anchor the qualification question itself
6
+ * everything else migrated from eval_dataset/query{A..E}_*.jsonl
7
+
8
+ Migration rules (spec 11):
9
+ * old `kid` -> `fact_id`, joined entity-aware; original ids preserved in
10
+ `legacy_query_refs`
11
+ * duplicates removed on (fact_id, normalized query, target slot, family)
12
+ * single-string gold replaced by an alias set from the enriched fact
13
+ * MCQ rows routed to `recognition`, never to `format`
14
+ * reverse rows with a non-unique inverse routed to `reverse_illposed`
15
+
16
+ Condition family names follow configs/eval_conditions.yaml rather than the old
17
+ file names, because those are a known trap: `queryA_canonical` holds surface
18
+ rewrites and was reported as paraphrase, `queryB_paraphrase` holds format
19
+ variants and was reported as format.
20
+ """
21
+ import os, sys, json, glob, argparse, collections
22
+
23
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
24
+ from common import (load_config, out_path, read_jsonl, write_jsonl,
25
+ normalize, norm_key, Expect)
26
+
27
+ EVAL_LEGACY = "/scratch/rds-fei-rsfm-rw/cshi0459/ICLR27/eval_dataset"
28
+ FILE_FAMILY = {"queryA_canonical": "paraphrase", "queryB_paraphrase": "format",
29
+ "queryC_reverse": "reverse", "queryD_context": "context",
30
+ "queryE_multilingual": "multilingual"}
31
+ ORDER = ["anchor", "paraphrase", "format", "context", "multilingual",
32
+ "reverse", "recognition", "reverse_illposed"]
33
+
34
+
35
+ def main():
36
+ ap = argparse.ArgumentParser()
37
+ ap.add_argument("--facts", default=out_path("benchmark_facts_2592.jsonl"))
38
+ args = ap.parse_args()
39
+
40
+ cond_cfg = load_config("eval_conditions.yaml")
41
+ CONDS = cond_cfg["conditions"]
42
+ exp = Expect()
43
+
44
+ facts = list(read_jsonl(args.facts))
45
+ by_id = {f["fact_id"]: f for f in facts}
46
+ exp.check("benchmark_facts", len(facts), cond_cfg["totals"]["expected_benchmark_facts"])
47
+
48
+ # ---- kid -> fact_id, joined on (subject identity, source relation) ----
49
+ key2fid = {}
50
+ for f in facts:
51
+ for pid in f["relation"]["source_relations"]:
52
+ key2fid[(norm_key(f["subject"]["canonical"]), pid)] = f["fact_id"]
53
+ if f["subject"].get("entity_id"):
54
+ for pid in f["relation"]["source_relations"]:
55
+ key2fid[(f["subject"]["entity_id"], pid)] = f["fact_id"]
56
+
57
+ kid2fid, unmapped = {}, []
58
+ for b in read_jsonl(f"{EVAL_LEGACY}/base.jsonl"):
59
+ fid = key2fid.get((norm_key(b["subject"]), b["relation_id"]))
60
+ if fid:
61
+ kid2fid[b["kid"]] = fid
62
+ else:
63
+ unmapped.append(b["kid"])
64
+ print(f"kid -> fact_id: {len(kid2fid)} mapped onto {len(set(kid2fid.values()))} "
65
+ f"benchmark facts ({len(unmapped)} legacy kids fall outside the benchmark)")
66
+
67
+ def emit(fid, family, text, variant_id, language="en", template_id=None,
68
+ legacy=None, extra=None):
69
+ f = by_id[fid]
70
+ c = CONDS[family]
71
+ slot = c["target_slot"]
72
+ node = f["subject"] if slot == "subject" else f["object"]
73
+ rec = {
74
+ "query_id": None, # assigned after ordering
75
+ "fact_id": fid,
76
+ "relation": f["relation"]["relation_id"],
77
+ "condition_family": family,
78
+ "variant_id": variant_id,
79
+ "language": language,
80
+ "query": text,
81
+ "target_slot": slot,
82
+ "gold_canonical": node["canonical"],
83
+ "gold_aliases": node["aliases"],
84
+ "answer_type": f["answer_type"],
85
+ "answer_granularity": f["answer_granularity"],
86
+ "is_assisted": bool(c["is_assisted"]),
87
+ "is_well_posed": bool(c["is_well_posed"]),
88
+ "use_for_main_forward": bool(c["use_for_main_forward"]),
89
+ "use_for_reverse_analysis": bool(c["use_for_reverse_analysis"]),
90
+ "use_for_recognition_analysis": bool(c["use_for_recognition_analysis"]),
91
+ "source_template_id": template_id,
92
+ "legacy_query_refs": legacy or [],
93
+ # propagated from the fact: the gold string is part of the subject
94
+ # name, so the query text contains it for reasons that have nothing
95
+ # to do with answer leakage introduced by the template
96
+ "answer_in_subject_surface": bool(f.get("answer_in_subject_surface")),
97
+ }
98
+ if extra:
99
+ rec.update(extra)
100
+ return rec
101
+
102
+ rows = collections.defaultdict(list)
103
+ seen = set() # spec 11 dedup key
104
+ stats = collections.Counter()
105
+
106
+ # ---- anchor (spec 9.1) ----
107
+ for f in facts:
108
+ rows["anchor"].append(
109
+ emit(f["fact_id"], "anchor", f["qualification_question"], "anchor",
110
+ template_id=f"{f['relation']['relation_id']}_anchor"))
111
+ seen.add((f["fact_id"], normalize(f["qualification_question"]),
112
+ "object", "anchor"))
113
+
114
+ # ---- migrated conditions ----
115
+ for path in sorted(glob.glob(f"{EVAL_LEGACY}/query*.jsonl")):
116
+ stem = os.path.basename(path)[:-len(".jsonl")]
117
+ base_family = FILE_FAMILY.get(stem)
118
+ if base_family is None:
119
+ continue
120
+ for q in read_jsonl(path):
121
+ stats["read"] += 1
122
+ fid = kid2fid.get(q["kid"])
123
+ if fid is None:
124
+ stats["out_of_benchmark"] += 1
125
+ continue
126
+ family = base_family
127
+ if q.get("fmt") == "mcq":
128
+ family = "recognition" # spec 9.3 / 9.7
129
+ elif family == "reverse" and not q.get("reverse_well_posed"):
130
+ family = "reverse_illposed" # spec 9.8
131
+
132
+ key = (fid, normalize(q["prompt"]), CONDS[family]["target_slot"], family)
133
+ if key in seen:
134
+ stats["duplicates_removed"] += 1
135
+ continue
136
+
137
+ # spec 9.4 / 13.9: an open-ended main query must not expose the gold.
138
+ # Two context queries in the legacy bank sampled a distractor entity
139
+ # that literally contains the answer ("... confuse X with Indian Act
140
+ # ..." where the gold is India). A gold occurrence that lies inside
141
+ # the SUBJECT mention is inherent to the fact and stays; anything
142
+ # surviving removal of the subject is a defect and is dropped.
143
+ if CONDS[family]["use_for_main_forward"] and not CONDS[family]["is_assisted"]:
144
+ f = by_id[fid]
145
+ nq = normalize(q["prompt"])
146
+ gold = normalize(f["object"]["canonical"])
147
+ subj = normalize(f["subject"]["canonical"])
148
+ if gold and gold in (nq.replace(subj, " ") if subj else nq):
149
+ stats["dropped_gold_exposed"] += 1
150
+ continue
151
+
152
+ seen.add(key)
153
+
154
+ extra = {}
155
+ if family == "recognition":
156
+ extra["options"] = q.get("options")
157
+ extra["correct_option"] = q.get("correct_option")
158
+ if q.get("dkind"):
159
+ extra["context_kind"] = q["dkind"]
160
+ rows[family].append(
161
+ emit(fid, family, q["prompt"],
162
+ variant_id=(q.get("qid") or "").split("_")[-1] or "01",
163
+ language=q.get("lang", "en"),
164
+ template_id=q.get("template_id"),
165
+ legacy=[{"kid": q["kid"], "qid": q.get("qid"), "file": stem}],
166
+ extra=extra))
167
+ stats["kept"] += 1
168
+
169
+ # ---- assign ids, write ----
170
+ flat = []
171
+ per_cond = {}
172
+ for fam in ORDER:
173
+ rs = rows.get(fam, [])
174
+ per_cond[fam] = {"queries": len(rs), "facts": len({r["fact_id"] for r in rs})}
175
+ flat += rs
176
+ for i, r in enumerate(flat, 1):
177
+ r["query_id"] = f"query_{i:08d}"
178
+
179
+ path = out_path("evaluation_queries_44418.jsonl")
180
+ write_jsonl(path, flat)
181
+
182
+ # ---- expected-count checks (spec 10) ----
183
+ for fam in ORDER:
184
+ c = CONDS[fam]
185
+ exp.check(f"{fam}.queries", per_cond[fam]["queries"], c["expected_queries"])
186
+ exp.check(f"{fam}.facts", per_cond[fam]["facts"], c["expected_facts"])
187
+ exp.check("total_queries", len(flat), cond_cfg["totals"]["expected_total_queries"])
188
+ main_n = sum(per_cond[f]["queries"] for f in ORDER
189
+ if CONDS[f]["use_for_main_forward"])
190
+ exp.check("main_forward_queries", main_n,
191
+ cond_cfg["totals"]["expected_main_forward_queries"])
192
+ exp.check("duplicates_removed", stats["duplicates_removed"],
193
+ cond_cfg["deduplication"]["expected_removed_during_migration"])
194
+
195
+ # ---- coverage report (spec 12) ----
196
+ all_ids = set(by_id)
197
+ coverage, missing = {}, {}
198
+ for fam in ORDER:
199
+ covered = {r["fact_id"] for r in rows.get(fam, [])}
200
+ coverage[fam] = len(covered)
201
+ if CONDS[fam]["use_for_main_forward"]:
202
+ miss = sorted(all_ids - covered)
203
+ if miss:
204
+ missing[fam] = miss
205
+ json.dump({"benchmark_facts": len(facts), **coverage,
206
+ "missing_by_condition": missing,
207
+ "note": "main-forward families should ideally cover all facts; "
208
+ "missing ids are listed rather than imputed (spec 12)"},
209
+ open(out_path("coverage_report.json"), "w"),
210
+ indent=2, ensure_ascii=False)
211
+
212
+ exp.report("Stage IV counts")
213
+ print(f"\n{'condition':20s} {'queries':>9s} {'facts':>7s} {'role':>12s}")
214
+ print("-" * 52)
215
+ for fam in ORDER:
216
+ print(f"{fam:20s} {per_cond[fam]['queries']:9d} "
217
+ f"{per_cond[fam]['facts']:7d} {CONDS[fam]['role']:>12s}")
218
+ print("-" * 52)
219
+ print(f"{'TOTAL':20s} {len(flat):9d}")
220
+ print(f"{'main forward':20s} {main_n:9d}")
221
+ print(f"\nmigration: {dict(stats)}")
222
+ print(f"wrote -> {path}")
223
+
224
+ # A deviation listed in configs/eval_conditions.yaml:accepted_deviations has
225
+ # been investigated and written up in reconstruction_differences.md, so it
226
+ # must not abort the pipeline. Anything NOT listed still fails, which keeps a
227
+ # fresh regression from hiding behind a documented one.
228
+ accepted = {(d["check"], d["actual"], d["expected"]): d.get("ref")
229
+ for d in cond_cfg.get("accepted_deviations", [])}
230
+ unexpected = [d for d in exp.deviations
231
+ if (d["name"], d["actual"], d["expected"]) not in accepted]
232
+ for d in exp.deviations:
233
+ ref = accepted.get((d["name"], d["actual"], d["expected"]))
234
+ if ref:
235
+ print(f" accepted deviation [{ref}]: {d['name']} "
236
+ f"{d['actual']} vs {d['expected']}")
237
+ if unexpected:
238
+ print(f"\nUNDOCUMENTED deviations: {[d['name'] for d in unexpected]}")
239
+ print("Investigate, then add them to configs/eval_conditions.yaml:"
240
+ "accepted_deviations and outputs/reconstruction_differences.md")
241
+
242
+ json.dump({"stage": "IV_query_bank", "per_condition": per_cond,
243
+ "total": len(flat), "main_forward": main_n,
244
+ "migration": dict(stats), "checks": exp.rows,
245
+ "accepted_deviations": [d for d in exp.deviations
246
+ if (d["name"], d["actual"], d["expected"]) in accepted],
247
+ "undocumented_deviations": unexpected},
248
+ open(out_path("stage4_report.json"), "w"), indent=2, ensure_ascii=False)
249
+ return 1 if unexpected else 0
250
+
251
+
252
+ if __name__ == "__main__":
253
+ sys.exit(main())
ICLR dataset/runner/build_stats.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """outputs/dataset_statistics.json (spec section 14.1)
3
+
4
+ Aggregates every stage report plus the fact and query files into the single
5
+ statistics document the specification asks for.
6
+ """
7
+ import os, sys, json, glob, collections, statistics
8
+
9
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
10
+ from common import load_config, out_path, read_jsonl, normalize
11
+
12
+
13
+ def load_report(name):
14
+ p = out_path(name)
15
+ return json.load(open(p)) if os.path.exists(p) else {}
16
+
17
+
18
+ def main():
19
+ facts = list(read_jsonl(out_path("benchmark_facts_2592.jsonl")))
20
+ enriched = list(read_jsonl(out_path("enriched_facts_6180.jsonl")))
21
+ cands = list(read_jsonl(out_path("candidate_known_8107.jsonl")))
22
+ queries = list(read_jsonl(out_path("evaluation_queries_44418.jsonl")))
23
+ cond_cfg = load_config("eval_conditions.yaml")
24
+ mdl_cfg = load_config("models.yaml")
25
+
26
+ by_id = {f["fact_id"]: f for f in facts}
27
+ per_fact_q = collections.Counter(q["fact_id"] for q in queries)
28
+ alias_counts = [len(f["object"]["aliases"]) for f in facts]
29
+ sub_alias_counts = [len(f["subject"]["aliases"]) for f in facts]
30
+
31
+ fam = collections.defaultdict(lambda: {"queries": 0, "facts": set()})
32
+ for q in queries:
33
+ fam[q["condition_family"]]["queries"] += 1
34
+ fam[q["condition_family"]]["facts"].add(q["fact_id"])
35
+
36
+ # recognition distractor statistics (spec 14.1)
37
+ rec = [q for q in queries if q["condition_family"] == "recognition"]
38
+ opt_sizes = collections.Counter(len(q.get("options") or []) for q in rec)
39
+ pos = collections.Counter(q.get("correct_option") for q in rec)
40
+
41
+ ml = [q for q in queries if q["condition_family"] == "multilingual"]
42
+
43
+ stats = {
44
+ "pipeline": {
45
+ "candidate_known": len(cands),
46
+ "enriched_facts": len(enriched),
47
+ "benchmark_facts": len(facts),
48
+ "evaluation_queries": len(queries),
49
+ "relations": len({f["relation"]["relation_id"] for f in facts}),
50
+ },
51
+ "counts_by_source": {
52
+ "candidates": dict(collections.Counter(c["source"] for c in cands)),
53
+ "enriched": dict(collections.Counter(e["sources"][0] for e in enriched)),
54
+ "benchmark": dict(collections.Counter(f["sources"][0] for f in facts)),
55
+ },
56
+ "counts_by_relation": dict(collections.Counter(
57
+ f["relation"]["relation_id"] for f in facts).most_common()),
58
+ "counts_by_answer_type": dict(collections.Counter(
59
+ f["answer_type"] for f in facts).most_common()),
60
+ "counts_by_condition_family": {
61
+ k: {"queries": v["queries"], "facts": len(v["facts"]),
62
+ "role": cond_cfg["conditions"][k]["role"]}
63
+ for k, v in sorted(fam.items())},
64
+ "query_variants_per_fact": {
65
+ "min": min(per_fact_q.values()), "max": max(per_fact_q.values()),
66
+ "median": statistics.median(per_fact_q.values()),
67
+ "mean": round(statistics.mean(per_fact_q.values()), 2)},
68
+ "alias_counts": {
69
+ "object": {"total": sum(alias_counts),
70
+ "median": statistics.median(alias_counts),
71
+ "mean": round(statistics.mean(alias_counts), 2),
72
+ "facts_with_one_alias": sum(1 for a in alias_counts if a == 1)},
73
+ "subject": {"total": sum(sub_alias_counts),
74
+ "median": statistics.median(sub_alias_counts)}},
75
+ "duplicates": {
76
+ "candidate_rows_that_are_exact_duplicates":
77
+ len(cands) - len({(c["subject"], c["relation"], c["object"], c["source"])
78
+ for c in cands}),
79
+ "groups_merged_during_enrichment":
80
+ load_report("stage2_report.json").get("merged_groups"),
81
+ "cross_source_groups":
82
+ load_report("stage2_report.json").get("cross_source_groups"),
83
+ "queries_removed_during_migration":
84
+ load_report("stage4_report.json").get("migration", {})
85
+ .get("duplicates_removed")},
86
+ "conflicts": {
87
+ "functional_conflicts_removed":
88
+ load_report("stage2_report.json").get("conflicts_removed", {}),
89
+ "queries_dropped_gold_exposed":
90
+ load_report("stage4_report.json").get("migration", {})
91
+ .get("dropped_gold_exposed", 0)},
92
+ "coverage": json.load(open(out_path("coverage_report.json")))
93
+ if os.path.exists(out_path("coverage_report.json")) else {},
94
+ "reverse": {
95
+ "well_posed_queries": fam["reverse"]["queries"],
96
+ "well_posed_facts": len(fam["reverse"]["facts"]),
97
+ "ill_posed_queries": fam["reverse_illposed"]["queries"],
98
+ "ill_posed_facts": len(fam["reverse_illposed"]["facts"]),
99
+ "benchmark_facts_flagged_inverse_well_posed":
100
+ sum(1 for f in facts if f["is_inverse_well_posed"])},
101
+ "recognition_distractors": {
102
+ "queries": len(rec),
103
+ "option_count_distribution": {str(k): v for k, v in opt_sizes.items()},
104
+ "correct_option_position": {str(k): v for k, v in sorted(pos.items())}},
105
+ "multilingual": {
106
+ "queries": len(ml),
107
+ "by_language": dict(collections.Counter(q["language"] for q in ml))},
108
+ "validity_flags": {
109
+ "answer_in_subject_surface": {
110
+ "facts": sum(1 for f in facts if f.get("answer_in_subject_surface")),
111
+ "share": round(sum(1 for f in facts
112
+ if f.get("answer_in_subject_surface")) / len(facts), 4),
113
+ "by_relation": dict(collections.Counter(
114
+ f["relation"]["relation_id"] for f in facts
115
+ if f.get("answer_in_subject_surface")).most_common()),
116
+ "note": "object string is literally contained in the subject name, "
117
+ "so the query can be answered by copying rather than by "
118
+ "retrieval; kept in the benchmark but flagged"},
119
+ "spec_6_2_flagged": {
120
+ "facts": sum(1 for f in facts if f.get("spec_6_2_flag")),
121
+ "by_relation": dict(collections.Counter(
122
+ f["relation"]["relation_id"] for f in facts
123
+ if f.get("spec_6_2_flag")).most_common())}},
124
+ "configuration": {
125
+ "filter_models": [m["name"] for m in mdl_cfg["filter_models"]],
126
+ "evaluated_models": [m["name"] for m in mdl_cfg["evaluated_models"]],
127
+ "generation": mdl_cfg["generation"]},
128
+ "stage_reports": {n: load_report(f"stage{n}_report.json")
129
+ for n in ["1", "2", "3", "4"]},
130
+ }
131
+
132
+ json.dump(stats, open(out_path("dataset_statistics.json"), "w"),
133
+ indent=2, ensure_ascii=False)
134
+ print(json.dumps(stats["pipeline"], indent=2))
135
+ print("\nvalidity flags:")
136
+ print(json.dumps(stats["validity_flags"]["answer_in_subject_surface"],
137
+ indent=2, ensure_ascii=False)[:600])
138
+ print(f"\nwrote -> {out_path('dataset_statistics.json')}")
139
+
140
+
141
+ if __name__ == "__main__":
142
+ main()
ICLR dataset/runner/common.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ OUTPUTS = os.path.join(ROOT, "outputs")
13
+ DATASET = "/scratch/rds-fei-rsfm-rw/cshi0459/ICLR27/dataset"
14
+
15
+ SEED = 20260101
16
+
17
+
18
+ def load_config(name):
19
+ import yaml
20
+ with open(os.path.join(CONFIGS, name)) as f:
21
+ return yaml.safe_load(f)
22
+
23
+
24
+ def out_path(*parts):
25
+ p = os.path.join(OUTPUTS, *parts)
26
+ os.makedirs(os.path.dirname(p), exist_ok=True)
27
+ return p
28
+
29
+
30
+ def read_jsonl(path):
31
+ with open(path) as f:
32
+ for line in f:
33
+ line = line.strip()
34
+ if line:
35
+ yield json.loads(line)
36
+
37
+
38
+ def write_jsonl(path, rows):
39
+ n = 0
40
+ with open(path, "w") as f:
41
+ for r in rows:
42
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
43
+ n += 1
44
+ return n
45
+
46
+
47
+ def sha256(path, limit_mb=None):
48
+ """Checksum for auditability (spec 18). limit_mb hashes only a prefix, which
49
+ keeps multi-GB source files cheap while still detecting substitution."""
50
+ h = hashlib.sha256()
51
+ cap = None if limit_mb is None else limit_mb * 1024 * 1024
52
+ read = 0
53
+ with open(path, "rb") as f:
54
+ while True:
55
+ b = f.read(1 << 20)
56
+ if not b:
57
+ break
58
+ h.update(b)
59
+ read += len(b)
60
+ if cap and read >= cap:
61
+ break
62
+ return f"sha256:{h.hexdigest()}" + ("" if cap is None else f"(first{limit_mb}MB)")
63
+
64
+
65
+ # ------------------------------------------------------------- normalization
66
+ _QUOTES = "\"'`‘’“”«»"
67
+ _DASHES = "‐‑‒–—―"
68
+ _ARTICLES = re.compile(r"\b(the|a|an)\b")
69
+
70
+
71
+ def normalize(text, drop_articles=True):
72
+ """Comparison form: NFKC, lowercase, punctuation to space, articles dropped.
73
+
74
+ Punctuation is replaced INTERNALLY so that token-boundary matching still
75
+ finds an entity that is followed by a comma. Aliases and generations go
76
+ through the identical function.
77
+ """
78
+ if not text:
79
+ return ""
80
+ t = unicodedata.normalize("NFKC", str(text))
81
+ t = "".join("-" if c in _DASHES else ("'" if c in _QUOTES else c) for c in t)
82
+ t = t.lower()
83
+ t = re.sub(r"[^\w\s]", " ", t, flags=re.UNICODE)
84
+ t = re.sub(r"\s+", " ", t).strip()
85
+ if drop_articles:
86
+ t = _ARTICLES.sub(" ", t)
87
+ return re.sub(r"\s+", " ", t).strip()
88
+
89
+
90
+ def norm_key(text):
91
+ """Identity key for grouping (no article stripping, so 'The Who' stays)."""
92
+ return normalize(text, drop_articles=False)
93
+
94
+
95
+ def dedup_aliases(seq, junk_re=None, min_chars=2, cap=16):
96
+ """Deduplicate case-insensitively, preserving order.
97
+
98
+ The first element is the canonical label and is always kept. Later entries
99
+ are dropped when they normalize to fewer than `min_chars` characters or hit
100
+ a junk pattern: crowd-sourced Wikidata alias lists contain single letters,
101
+ emoji and Wikipedia housekeeping titles, and a one-or-two character alias
102
+ would match almost any generation under containment scoring.
103
+ """
104
+ seen, out = set(), []
105
+ for i, a in enumerate(seq):
106
+ if a is None:
107
+ continue
108
+ a = str(a).strip()
109
+ if not a:
110
+ continue
111
+ k = a.lower()
112
+ if k in seen:
113
+ continue
114
+ if i > 0 or out:
115
+ if len(normalize(a)) < min_chars:
116
+ continue
117
+ if junk_re is not None and junk_re.search(a):
118
+ continue
119
+ seen.add(k)
120
+ out.append(a)
121
+ if len(out) >= cap:
122
+ break
123
+ return out
124
+
125
+
126
+ def compile_junk(patterns):
127
+ return re.compile("|".join(f"(?:{p})" for p in patterns), re.I) if patterns else None
128
+
129
+
130
+ # ---------------------------------------------------------------- reporting
131
+ class Expect:
132
+ """Collects expected-vs-actual counts. Spec section 10 forbids silently
133
+ changing counts, so every deviation is recorded and surfaced."""
134
+
135
+ def __init__(self):
136
+ self.rows = []
137
+
138
+ def check(self, name, actual, expected, note=""):
139
+ ok = (expected is None) or (actual == expected)
140
+ self.rows.append({"name": name, "actual": actual, "expected": expected,
141
+ "match": ok, "note": note})
142
+ return ok
143
+
144
+ @property
145
+ def deviations(self):
146
+ return [r for r in self.rows if not r["match"]]
147
+
148
+ def report(self, title="counts"):
149
+ print(f"\n{title}")
150
+ print(f"{'check':38s} {'actual':>10s} {'expected':>10s} ok")
151
+ print("-" * 66)
152
+ for r in self.rows:
153
+ e = "-" if r["expected"] is None else r["expected"]
154
+ print(f"{r['name']:38s} {r['actual']:>10} {e:>10} "
155
+ f"{'yes' if r['match'] else 'NO'}")
156
+ if self.deviations:
157
+ print(f"\n{len(self.deviations)} deviation(s); "
158
+ f"record them in outputs/reconstruction_differences.md")
159
+ return self.rows
ICLR dataset/runner/enrich_facts.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Stage II -> outputs/enriched_facts_6180.jsonl (spec section 5)
3
+
4
+ 8,107 candidate rows
5
+ -> group by entity-aware (subject identity, relation) spec 5.1
6
+ -> merge object identities, discard functional conflicts spec 5.2
7
+ -> expand accepted-answer aliases spec 5.3
8
+ -> attach a canonical qualification question spec 5.4
9
+ -> emit the nested enriched schema spec 5.5
10
+
11
+ Grouping is deliberately CROSS-SOURCE: 1,036 (subject, relation) pairs appear in
12
+ both CounterFact and LAMA-TREx. Kept apart they would put the identical
13
+ qualification question into the benchmark twice, double-counting the fact and
14
+ breaking sample independence.
15
+ """
16
+ import os, re, sys, json, glob, argparse, collections
17
+
18
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
19
+ from common import (DATASET, load_config, out_path, read_jsonl, write_jsonl,
20
+ normalize, norm_key, dedup_aliases, compile_junk, Expect)
21
+ import qual_templates as QT
22
+
23
+ try:
24
+ import pandas as pd
25
+ except ImportError:
26
+ pd = None
27
+
28
+ EXPECTED_GROUPS = 6185
29
+ EXPECTED_CONFLICTS = 5
30
+ EXPECTED_ENRICHED = 6180
31
+
32
+
33
+ # ------------------------------------------------------- source metadata maps
34
+ def load_source_metadata(allow_missing_parquet=False):
35
+ """Entity ids and native alias lists, keyed by (source, subject, rel, object)."""
36
+ print("[1/5] loading entity ids and source-native aliases ...", flush=True)
37
+ obj_qid, sub_qid = {}, {}
38
+ gre_obj, gre_sub, pq_meta = {}, {}, {}
39
+ degraded = False
40
+
41
+ if pd is None:
42
+ if not allow_missing_parquet:
43
+ raise SystemExit(
44
+ "pandas is required to read the CounterFact parquet files "
45
+ "(spec 5.3 needs target_true.id). Activate the project venv.")
46
+ print(" WARNING: pandas missing -> CounterFact entity ids SKIPPED",
47
+ flush=True)
48
+ degraded = True
49
+ else:
50
+ for p in glob.glob(f"{DATASET}/counterfact/data/*.parquet"):
51
+ for rr in pd.read_parquet(p, columns=["requested_rewrite"])["requested_rewrite"]:
52
+ k = ("counterfact", rr["subject"], rr["relation_id"],
53
+ rr["target_true"]["str"])
54
+ obj_qid[k] = rr["target_true"]["id"]
55
+
56
+ for f in glob.glob(f"{DATASET}/lama/data/TREx/*.jsonl"):
57
+ for d in read_jsonl(f):
58
+ k = ("lama_trex", d.get("sub_label"), d.get("predicate_id"),
59
+ d.get("obj_label"))
60
+ obj_qid[k] = d.get("obj_uri")
61
+ sub_qid[k] = d.get("sub_uri")
62
+
63
+ for f in glob.glob(f"{DATASET}/lama/data/Google_RE/*.jsonl"):
64
+ for d in read_jsonl(f):
65
+ rid = (d.get("pred") or "").rstrip("/").split("/")[-1]
66
+ k = (d.get("sub_label") or d.get("sub"), rid,
67
+ d.get("obj_label") or d.get("obj"))
68
+ gre_obj[k] = d.get("obj_aliases") or []
69
+ gre_sub[k] = d.get("sub_aliases") or []
70
+
71
+ p = f"{DATASET}/filter/popqa_meta.jsonl"
72
+ if os.path.exists(p):
73
+ for d in read_jsonl(p):
74
+ pq_meta[(d["subject"], d["relation"], d["object"])] = d
75
+
76
+ return obj_qid, sub_qid, gre_obj, gre_sub, pq_meta, degraded
77
+
78
+
79
+ def load_wikidata_aliases(needed, path, cap):
80
+ """Spec 5.3: single filtered pass over the alias resource, never a full load."""
81
+ print(f"[2/5] single-pass scan of the alias resource for {len(needed)} qids ...",
82
+ flush=True)
83
+ out = {}
84
+ with open(path) as f:
85
+ for line in f:
86
+ i = line.find("\t")
87
+ if i < 0:
88
+ continue
89
+ q = line[:i]
90
+ if q in needed:
91
+ out[q] = line[i + 1:].rstrip("\n").split("\t")[:cap]
92
+ print(f" resolved {len(out)}/{len(needed)}", flush=True)
93
+ return out
94
+
95
+
96
+ # -------------------------------------------------------------------- main
97
+ def main():
98
+ ap = argparse.ArgumentParser()
99
+ ap.add_argument("--candidates", default=out_path("candidate_known_8107.jsonl"))
100
+ ap.add_argument("--allow_missing_parquet", action="store_true")
101
+ args = ap.parse_args()
102
+
103
+ rel_cfg = load_config("relations.yaml")
104
+ src_cfg = load_config("source_templates.yaml")
105
+ alias_cfg = src_cfg["alias_resources"]
106
+ junk_re = compile_junk(alias_cfg.get("junk_patterns"))
107
+ cap = alias_cfg.get("max_aliases_per_entity", 16)
108
+ min_chars = alias_cfg.get("min_alias_chars", 2)
109
+
110
+ # relation metadata: relations.yaml is authoritative for benchmark relations,
111
+ # qual_templates.py supplies the rest so that every enriched fact has a
112
+ # question (spec 5.4)
113
+ rel_meta = {}
114
+ for r in rel_cfg["relations"]:
115
+ for pid in r["source_relations"]:
116
+ rel_meta[pid] = r
117
+ exp = Expect()
118
+
119
+ obj_qid, sub_qid, gre_obj, gre_sub, pq_meta, degraded = \
120
+ load_source_metadata(args.allow_missing_parquet)
121
+
122
+ rows = list(read_jsonl(args.candidates))
123
+ needed = set()
124
+ for d in rows:
125
+ k = (d["source"], d["subject"], d["relation"], d["object"])
126
+ for m in (obj_qid, sub_qid):
127
+ if m.get(k):
128
+ needed.add(m[k])
129
+ qid_alias = load_wikidata_aliases(
130
+ needed, os.path.join(DATASET, alias_cfg["wikidata_entity_aliases"]), cap)
131
+
132
+ def obj_alias_raw(d):
133
+ src, s, rid, o = d["source"], d["subject"], d["relation"], d["object"]
134
+ al = [o]
135
+ if src == "lama_googlere":
136
+ al += gre_obj.get((s, rid, o), [])
137
+ elif src == "popqa":
138
+ m = pq_meta.get((s, rid, o), {})
139
+ al += m.get("possible_answers", []) + m.get("o_aliases", [])
140
+ q = obj_qid.get((src, s, rid, o))
141
+ if q:
142
+ al += qid_alias.get(q, [])
143
+ return al
144
+
145
+ def sub_alias_raw(d):
146
+ src, s, rid, o = d["source"], d["subject"], d["relation"], d["object"]
147
+ al = [s]
148
+ if src == "lama_googlere":
149
+ al += gre_sub.get((s, rid, o), [])
150
+ elif src == "popqa":
151
+ al += pq_meta.get((s, rid, o), {}).get("s_aliases", [])
152
+ q = sub_qid.get((src, s, rid, o))
153
+ if q:
154
+ al += qid_alias.get(q, [])
155
+ return al
156
+
157
+ # ---- spec 5.1: entity-aware grouping ----
158
+ print("[3/5] grouping by (subject identity, relation) across sources ...",
159
+ flush=True)
160
+ groups = collections.OrderedDict()
161
+ for d in rows:
162
+ # prefer the entity id when the source provides one, else normalized text
163
+ sq = sub_qid.get((d["source"], d["subject"], d["relation"], d["object"]))
164
+ ident = sq or norm_key(d["subject"])
165
+ groups.setdefault((ident, d["relation"]), []).append(d)
166
+ # a subject with an id in one source and no id in another must not split into
167
+ # two groups: fold text-keyed groups into the id-keyed one where possible
168
+ text_to_id = {}
169
+ for (ident, rid), members in groups.items():
170
+ if str(ident).startswith("Q"):
171
+ for m in members:
172
+ text_to_id[(norm_key(m["subject"]), rid)] = (ident, rid)
173
+ merged = collections.OrderedDict()
174
+ for key, members in groups.items():
175
+ ident, rid = key
176
+ if not str(ident).startswith("Q"):
177
+ key = text_to_id.get((ident, rid), key)
178
+ merged.setdefault(key, []).extend(members)
179
+ groups = merged
180
+ exp.check("grouped_facts", len(groups), EXPECTED_GROUPS)
181
+
182
+ # ---- spec 5.2 / 5.3 / 5.4 ----
183
+ print("[4/5] merging objects, expanding aliases, attaching questions ...",
184
+ flush=True)
185
+ SRC_PRIORITY = ["lama_trex", "counterfact", "popqa",
186
+ "lama_googlere", "lama_conceptnet"]
187
+ rep = {"conflicts": collections.Counter(), "no_template": collections.Counter(),
188
+ "cross_source_groups": 0, "merged_groups": 0}
189
+
190
+ facts = []
191
+ for (ident, rid), members in groups.items():
192
+ cfg = rel_meta.get(rid)
193
+ spec = QT.resolve(rid)
194
+ if cfg is None and spec is None:
195
+ rep["no_template"][rid] += len(members)
196
+ continue
197
+
198
+ is_functional = bool(cfg["is_functional"]) if cfg else (not spec["multi"])
199
+ srcs = sorted({m["source"] for m in members},
200
+ key=lambda s: SRC_PRIORITY.index(s) if s in SRC_PRIORITY else 99)
201
+ primary = next(m for m in members if m["source"] == srcs[0])
202
+
203
+ objects, obj_ids = [], []
204
+ seen_o = set()
205
+ for m in members:
206
+ k = norm_key(m["object"])
207
+ if k not in seen_o:
208
+ seen_o.add(k)
209
+ objects.append(m["object"])
210
+ obj_ids.append(obj_qid.get((m["source"], m["subject"], rid, m["object"])))
211
+
212
+ # spec 5.2: a functional group holding incompatible object identities is
213
+ # an unanswerable question (two people sharing a name, or a historical vs
214
+ # modern referent). A MISSING entity id is not evidence of sameness, so
215
+ # every member must carry an id and all ids must agree to survive.
216
+ if is_functional and len(objects) > 1:
217
+ ids = set(obj_ids)
218
+ if None in ids or len(ids) != 1:
219
+ rep["conflicts"][rid] += 1
220
+ continue
221
+
222
+ if len(members) > 1:
223
+ rep["merged_groups"] += 1
224
+ if len(srcs) > 1:
225
+ rep["cross_source_groups"] += 1
226
+
227
+ obj_aliases = dedup_aliases(
228
+ [a for m in members for a in obj_alias_raw(m)], junk_re, min_chars, cap)
229
+ sub_aliases = dedup_aliases(
230
+ [a for m in members for a in sub_alias_raw(m)], junk_re, min_chars, cap)
231
+
232
+ question = (cfg["qualification"] if cfg else spec["q"]).format(
233
+ s=primary["subject"])
234
+ facts.append({
235
+ "_sort": (rid, norm_key(primary["subject"])),
236
+ "subject": {"canonical": primary["subject"],
237
+ "entity_id": ident if str(ident).startswith("Q") else None,
238
+ "aliases": sub_aliases},
239
+ "relation": {"relation_id": cfg["relation_id"] if cfg else rid,
240
+ "canonical_name": cfg["relation_id"] if cfg else rid,
241
+ "source_relations": [rid],
242
+ "direction": cfg.get("direction", "forward") if cfg else "forward"},
243
+ "object": {"canonical": objects[0],
244
+ "entity_id": obj_ids[0],
245
+ "aliases": obj_aliases,
246
+ "variant_surface_forms": objects},
247
+ "qualification_question": question,
248
+ "sources": srcs,
249
+ "source_records": [m["raw_id"] for m in members],
250
+ "legacy_refs": [m["legacy_ref"] for m in members],
251
+ "is_functional": is_functional,
252
+ "is_inverse_well_posed": bool(cfg["is_inverse_well_posed"]) if cfg else False,
253
+ "answer_type": cfg["answer_type"] if cfg else spec["type"],
254
+ "answer_granularity": (cfg["answer_granularity"] if cfg
255
+ else (spec["gran"] or "entity")),
256
+ "is_core_source": bool({"counterfact", "lama_trex", "popqa"} & set(srcs)),
257
+ "is_benchmark_relation": cfg is not None,
258
+ "spec_6_2_flag": (cfg or {}).get("spec_6_2_flag"),
259
+ # The object string is literally contained in the subject name
260
+ # ("Airbus A318" -> "Airbus"). Such a fact is answerable by copying a
261
+ # substring of the question, so it measures string manipulation
262
+ # rather than knowledge retrieval. Not dropped here -- spec 16
263
+ # forbids silently removing facts -- but flagged so every downstream
264
+ # analysis can report with and without them.
265
+ "answer_in_subject_surface": bool(
266
+ normalize(objects[0]) and
267
+ normalize(objects[0]) in normalize(primary["subject"])),
268
+ })
269
+
270
+ exp.check("functional_conflicts_removed", sum(rep["conflicts"].values()),
271
+ EXPECTED_CONFLICTS)
272
+ exp.check("enriched_facts", len(facts), EXPECTED_ENRICHED)
273
+ exp.check("merged_groups", rep["merged_groups"], 1771)
274
+ exp.check("cross_source_groups", rep["cross_source_groups"], 1036)
275
+
276
+ # ---- stable, deterministic fact ids (spec 6.3) ----
277
+ print("[5/5] assigning deterministic fact ids ...", flush=True)
278
+ facts.sort(key=lambda f: f.pop("_sort"))
279
+ for i, f in enumerate(facts, 1):
280
+ f["fact_id"] = f"fact_{i:06d}"
281
+ facts = [{"fact_id": f.pop("fact_id"), **f} for f in facts]
282
+
283
+ path = out_path("enriched_facts_6180.jsonl")
284
+ write_jsonl(path, facts)
285
+
286
+ exp.report("Stage II counts")
287
+ meta = {"stage": "II_enrichment",
288
+ "n_enriched": len(facts),
289
+ "grouped": len(groups),
290
+ "conflicts_removed": dict(rep["conflicts"]),
291
+ "no_template": dict(rep["no_template"]),
292
+ "merged_groups": rep["merged_groups"],
293
+ "cross_source_groups": rep["cross_source_groups"],
294
+ "per_source": dict(collections.Counter(f["sources"][0] for f in facts)),
295
+ "counterfact_entity_ids_skipped": degraded,
296
+ "checks": exp.rows}
297
+ json.dump(meta, open(out_path("stage2_report.json"), "w"),
298
+ indent=2, ensure_ascii=False)
299
+ print(f"\nwrote {len(facts)} enriched facts -> {path}")
300
+ print(f" conflicts removed: {dict(rep['conflicts'])}")
301
+ return 1 if exp.deviations else 0
302
+
303
+
304
+ if __name__ == "__main__":
305
+ sys.exit(main())
ICLR dataset/runner/eval_run.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, 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 main():
45
+ ap = argparse.ArgumentParser()
46
+ ap.add_argument("--model", required=True, help="name from configs/models.yaml")
47
+ ap.add_argument("--queries", default=out_path("evaluation_queries_44418.jsonl"))
48
+ ap.add_argument("--conditions", nargs="*", default=None,
49
+ help="restrict to these condition families (default: all)")
50
+ ap.add_argument("--limit", type=int, default=0)
51
+ ap.add_argument("--batch", type=int, default=0, help="0 = value from config")
52
+ ap.add_argument("--resume", action="store_true",
53
+ help="skip queries already present in the output file")
54
+ args = ap.parse_args()
55
+
56
+ cfg = load_config("models.yaml")
57
+ entry = next((m for m in cfg["evaluated_models"] if m["name"] == args.model), None)
58
+ if entry is None:
59
+ raise SystemExit(f"{args.model} is not in configs/models.yaml:evaluated_models")
60
+ gen_cfg = cfg["generation"]
61
+ if gen_cfg.get("use_chat_template"):
62
+ raise SystemExit("spec 7.2: base and instruct models must share the raw "
63
+ "prompt string; chat templates are not applied")
64
+
65
+ rows = list(read_jsonl(args.queries))
66
+ if args.conditions:
67
+ rows = [r for r in rows if r["condition_family"] in args.conditions]
68
+ if args.limit:
69
+ rows = rows[:args.limit]
70
+
71
+ dest = out_path("evaluation", f"{args.model}.jsonl")
72
+ done = set()
73
+ if args.resume and os.path.exists(dest):
74
+ done = {r["query_id"] for r in read_jsonl(dest)}
75
+ rows = [r for r in rows if r["query_id"] not in done]
76
+ print(f"[{args.model}] resuming: {len(done)} already done", flush=True)
77
+ if not rows:
78
+ print(f"[{args.model}] nothing to do")
79
+ return
80
+
81
+ N = len(rows)
82
+ fam_counts = collections.Counter(r["condition_family"] for r in rows)
83
+ print(f"[{args.model}] N={N} {dict(fam_counts)}", flush=True)
84
+
85
+ path = os.path.join(cfg["model_root"], entry["path"])
86
+ torch.manual_seed(gen_cfg.get("seed", 0))
87
+ tok = AutoTokenizer.from_pretrained(path)
88
+ if tok.pad_token is None:
89
+ tok.pad_token = tok.eos_token
90
+ tok.padding_side = "left"
91
+ tok.truncation_side = "left"
92
+ model = AutoModelForCausalLM.from_pretrained(
93
+ path, dtype=getattr(torch, gen_cfg.get("dtype", "bfloat16")),
94
+ device_map={"": 0}).eval()
95
+
96
+ prompts = [build_prompt(r) for r in rows]
97
+ # context queries prepend distractor sentences, so they are much longer than
98
+ # the anchor; a single global max_len would silently truncate them
99
+ max_len = max(gen_cfg.get("max_prompt_len", 96), 192)
100
+ B = args.batch or gen_cfg.get("batch_size", 96)
101
+
102
+ out = [None] * N
103
+ order = sorted(range(N), key=lambda i: len(prompts[i]))
104
+ t0 = time.time()
105
+ with torch.no_grad():
106
+ for b in range(0, N, B):
107
+ idx = order[b:b + B]
108
+ enc = tok([prompts[i] for i in idx], return_tensors="pt", padding=True,
109
+ truncation=True, max_length=max_len).to(0)
110
+ plen = enc["input_ids"].shape[1]
111
+ gen = model.generate(**enc,
112
+ max_new_tokens=gen_cfg.get("max_new_tokens", 24),
113
+ do_sample=gen_cfg.get("do_sample", False),
114
+ num_beams=gen_cfg.get("num_beams", 1),
115
+ pad_token_id=tok.pad_token_id)
116
+ new_ids = gen[:, plen:]
117
+ texts = tok.batch_decode(new_ids, skip_special_tokens=True)
118
+ for j, i in enumerate(idx):
119
+ ids = new_ids[j].tolist()
120
+ n_tok, fin = len(ids), "length"
121
+ for k, t in enumerate(ids):
122
+ if t == tok.eos_token_id:
123
+ n_tok, fin = k, "eos"
124
+ break
125
+ out[i] = {"query_id": rows[i]["query_id"],
126
+ "fact_id": rows[i]["fact_id"],
127
+ "condition_family": rows[i]["condition_family"],
128
+ "model": args.model,
129
+ "prompt": prompts[i],
130
+ "raw_response": texts[j],
131
+ "generated_tokens": int(n_tok),
132
+ "finish_reason": fin}
133
+ if b % (B * 20) == 0:
134
+ d = b + len(idx)
135
+ print(f" {d}/{N} {d / max(time.time() - t0, 1e-9):.1f}/s", flush=True)
136
+
137
+ mode = "a" if (args.resume and done) else "w"
138
+ with open(dest, mode) as f:
139
+ for r in out:
140
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
141
+ json.dump({"model": args.model, "n_generated": N, "resumed_from": len(done),
142
+ "generation": gen_cfg, "max_prompt_len": max_len,
143
+ "model_entry": entry, "seconds": round(time.time() - t0, 1),
144
+ "by_condition": dict(fam_counts)},
145
+ open(out_path("evaluation", f"{args.model}.meta.json"), "w"),
146
+ indent=2, ensure_ascii=False)
147
+ print(f"[{args.model}] wrote {N} -> {dest} ({time.time() - t0:.0f}s) EVAL_DONE")
148
+
149
+
150
+ if __name__ == "__main__":
151
+ main()
ICLR dataset/runner/eval_score.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Stage VI scoring -> outputs/evaluation/<model>.scored.jsonl
3
+ outputs/stability_report.json
4
+
5
+ Reads the stored generations on CPU and produces the stability numbers.
6
+
7
+ Three reporting rules, all enforced here rather than left to the reader:
8
+
9
+ * conditions are grouped by the booleans carried on each query, which come
10
+ from configs/eval_conditions.yaml. `recognition` and `reverse_illposed`
11
+ never enter a main-forward average, and `reverse` is reported separately
12
+ because it changes the target slot (spec 2.3 / 16).
13
+
14
+ * two denominators are always reported side by side:
15
+ fixed all 2,592 benchmark facts (spec 2.1)
16
+ anchored restricted to K_m for that model conditional retention
17
+ The fixed one is the benchmark score; the anchored one answers "of the
18
+ facts this model demonstrably knows, how many survive the perturbation".
19
+
20
+ * every number is split by `answer_in_subject_surface`, because 28.9% of the
21
+ benchmark can be answered by copying a substring of the question and those
22
+ facts are near-ceiling stable for reasons unrelated to knowledge
23
+ (outputs/reconstruction_differences.md F1).
24
+ """
25
+ import os, sys, json, glob, argparse, collections
26
+ import numpy as np
27
+
28
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
29
+ from common import load_config, out_path, read_jsonl, write_jsonl, normalize
30
+ from scoring_full import score, needs_manual_review
31
+
32
+ import re
33
+ MCQ_LETTER = re.compile(r"^\s*[\(\[]?([A-Da-d])[\)\]\.:,\s]")
34
+
35
+
36
+ def score_recognition(raw, row):
37
+ """MCQ: accept either the option letter or the option text."""
38
+ m = MCQ_LETTER.match((raw or "") + " ")
39
+ if m and row.get("correct_option"):
40
+ ok = m.group(1).upper() == str(row["correct_option"]).upper()
41
+ return {"label": "correct" if ok else "incorrect",
42
+ "matched_alias": m.group(1).upper(), "scorer": "mcq_letter",
43
+ "span": (raw or "").strip()[:40], "flags": []}
44
+ return score(raw, row["gold_aliases"], answer_type=row["answer_type"],
45
+ granularity=row.get("answer_granularity"))
46
+
47
+
48
+ def bootstrap_ci(values, groups, n_boot=2000, seed=0, alpha=0.05):
49
+ """Cluster bootstrap over relations; the relation mix is heavily skewed."""
50
+ rng = np.random.default_rng(seed)
51
+ by = collections.defaultdict(list)
52
+ for v, g in zip(values, groups):
53
+ by[g].append(v)
54
+ keys = list(by)
55
+ if not keys:
56
+ return (float("nan"), float("nan"))
57
+ arrs = [np.asarray(by[k], dtype=float) for k in keys]
58
+ st = np.empty(n_boot)
59
+ for b in range(n_boot):
60
+ pick = rng.integers(0, len(keys), len(keys))
61
+ st[b] = np.concatenate([arrs[i] for i in pick]).mean()
62
+ return float(np.quantile(st, alpha / 2)), float(np.quantile(st, 1 - alpha / 2))
63
+
64
+
65
+ def main():
66
+ ap = argparse.ArgumentParser()
67
+ ap.add_argument("--queries", default=out_path("evaluation_queries_44418.jsonl"))
68
+ ap.add_argument("--facts", default=out_path("benchmark_facts_2592.jsonl"))
69
+ ap.add_argument("--models", nargs="*", default=None)
70
+ args = ap.parse_args()
71
+
72
+ cond_cfg = load_config("eval_conditions.yaml")["conditions"]
73
+ queries = {q["query_id"]: q for q in read_jsonl(args.queries)}
74
+ facts = {f["fact_id"]: f for f in read_jsonl(args.facts)}
75
+
76
+ known_path = out_path("known_labels.json")
77
+ known = json.load(open(known_path))["labels"] if os.path.exists(known_path) else {}
78
+ if not known:
79
+ print("WARNING: outputs/known_labels.json missing -> anchored (K_m) "
80
+ "numbers will be omitted. Run qualification_score.py first.")
81
+
82
+ edir = os.path.dirname(out_path("evaluation", "x"))
83
+ paths = sorted(p for p in glob.glob(os.path.join(edir, "*.jsonl"))
84
+ if not p.endswith(".scored.jsonl"))
85
+ if args.models:
86
+ paths = [p for p in paths
87
+ if os.path.basename(p)[:-len(".jsonl")] in args.models]
88
+ if not paths:
89
+ raise SystemExit(f"no generation files in {edir}; run eval_run.py first")
90
+
91
+ report = {"models": {}, "denominators": {
92
+ "fixed": "all benchmark facts (spec 2.1)",
93
+ "anchored": "facts whose anchor label is `correct` for that model (K_m)"}}
94
+
95
+ for p in paths:
96
+ model = os.path.basename(p)[:-len(".jsonl")]
97
+ km = {fid for fid, lab in known.items() if lab.get(model) == "correct"}
98
+ scored = []
99
+ # cond -> bucket -> list of (correct, relation)
100
+ acc = collections.defaultdict(lambda: collections.defaultdict(list))
101
+ labels = collections.defaultdict(collections.Counter)
102
+
103
+ for g in read_jsonl(p):
104
+ q = queries.get(g["query_id"])
105
+ if q is None:
106
+ raise SystemExit(f"{model}: generation for unknown query "
107
+ f"{g['query_id']}")
108
+ fam = q["condition_family"]
109
+ r = (score_recognition(g["raw_response"], q) if fam == "recognition"
110
+ else score(g["raw_response"], q["gold_aliases"],
111
+ answer_type=q["answer_type"],
112
+ granularity=q.get("answer_granularity")))
113
+ ok = 1.0 if r["label"] == "correct" else 0.0
114
+ copy_flag = bool(q.get("answer_in_subject_surface"))
115
+ rel = q["relation"]
116
+
117
+ rec = {"query_id": q["query_id"], "fact_id": q["fact_id"],
118
+ "model": model, "condition_family": fam,
119
+ "language": q.get("language", "en"),
120
+ "target_slot": q["target_slot"],
121
+ "raw_response": g["raw_response"],
122
+ "extracted_answer": r["span"], "label": r["label"],
123
+ "matched_alias": r["matched_alias"], "scorer": r["scorer"],
124
+ "relation": rel, "answer_type": q["answer_type"],
125
+ "answer_in_subject_surface": copy_flag,
126
+ "in_K_m": q["fact_id"] in km,
127
+ "use_for_main_forward": q["use_for_main_forward"],
128
+ "manual_review": needs_manual_review(r)}
129
+ scored.append(rec)
130
+ labels[fam][r["label"]] += 1
131
+
132
+ acc[fam]["fixed"].append((ok, rel))
133
+ acc[fam]["fixed_copy" if copy_flag else "fixed_real"].append((ok, rel))
134
+ if q["fact_id"] in km:
135
+ acc[fam]["anchored"].append((ok, rel))
136
+ acc[fam]["anchored_copy" if copy_flag else "anchored_real"].append((ok, rel))
137
+
138
+ write_jsonl(os.path.join(edir, f"{model}.scored.jsonl"), scored)
139
+
140
+ def stat(pairs):
141
+ if not pairs:
142
+ return None
143
+ v = [x for x, _ in pairs]
144
+ g = [r for _, r in pairs]
145
+ lo, hi = bootstrap_ci(v, g)
146
+ return {"acc": round(float(np.mean(v)), 4), "n": len(v),
147
+ "ci95_relation_clustered": [round(lo, 4), round(hi, 4)]}
148
+
149
+ per_cond = {}
150
+ for fam, buckets in acc.items():
151
+ per_cond[fam] = {
152
+ "role": cond_cfg[fam]["role"],
153
+ "use_for_main_forward": cond_cfg[fam]["use_for_main_forward"],
154
+ "labels": dict(labels[fam]),
155
+ **{b: stat(v) for b, v in buckets.items()}}
156
+
157
+ main_fams = [f for f in per_cond if cond_cfg[f]["use_for_main_forward"]
158
+ and f != "anchor"]
159
+ def macro(bucket):
160
+ vals = [per_cond[f][bucket]["acc"] for f in main_fams
161
+ if per_cond[f].get(bucket)]
162
+ return round(float(np.mean(vals)), 4) if vals else None
163
+
164
+ report["models"][model] = {
165
+ "K_m": len(km),
166
+ "per_condition": per_cond,
167
+ "main_forward_macro": {
168
+ "fixed": macro("fixed"), "anchored": macro("anchored"),
169
+ "anchored_real": macro("anchored_real"),
170
+ "anchored_copy": macro("anchored_copy"),
171
+ "note": "mean over paraphrase/format/context/multilingual; "
172
+ "anchor excluded (it is the baseline), reverse excluded "
173
+ "(different target slot), recognition and "
174
+ "reverse_illposed excluded (diagnostics)"},
175
+ "n_manual_review": sum(1 for r in scored if r["manual_review"]),
176
+ }
177
+
178
+ json.dump(report, open(out_path("stability_report.json"), "w"),
179
+ indent=2, ensure_ascii=False)
180
+
181
+ # ---------------------------------------------------------------- console
182
+ order = ["anchor", "paraphrase", "format", "context", "multilingual",
183
+ "reverse", "recognition", "reverse_illposed"]
184
+ for model, m in report["models"].items():
185
+ print(f"\n=== {model} K_m={m['K_m']} ===")
186
+ print(f"{'condition':18s} {'fixed':>7s} {'anchored':>9s} "
187
+ f"{' ·real':>8s} {' ·copy':>8s} {'n':>7s} role")
188
+ print("-" * 70)
189
+ for fam in order:
190
+ c = m["per_condition"].get(fam)
191
+ if not c:
192
+ continue
193
+ def g(b):
194
+ return f"{c[b]['acc']:.3f}" if c.get(b) else " -"
195
+ print(f"{fam:18s} {g('fixed'):>7s} {g('anchored'):>9s} "
196
+ f"{g('anchored_real'):>8s} {g('anchored_copy'):>8s} "
197
+ f"{c['fixed']['n']:7d} {c['role']}")
198
+ mm = m["main_forward_macro"]
199
+ print(f"{'MAIN macro':18s} {str(mm['fixed']):>7s} {str(mm['anchored']):>9s} "
200
+ f"{str(mm['anchored_real']):>8s} {str(mm['anchored_copy']):>8s}")
201
+ print("\n·real / ·copy split the anchored numbers by whether the answer is "
202
+ "contained in the subject name (see reconstruction_differences.md F1)")
203
+ print(f"\nwrote -> {out_path('stability_report.json')}")
204
+
205
+
206
+ if __name__ == "__main__":
207
+ main()
ICLR dataset/runner/filter_run.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Stage I first-token candidate filtering for ONE model (spec section 4.4) [GPU]
3
+
4
+ Regenerates the per-prompt verdict vector that build_candidate_known.py consumes.
5
+ The stored vectors under dataset/filter/ were produced by an equivalent script;
6
+ this one is config-driven per spec 4.4 and writes the richer per-prompt record
7
+ the specification asks for.
8
+
9
+ Protocol, unchanged from the original run so the vectors stay comparable:
10
+ 1. tokenize the cloze prompt
11
+ 2. take the logits at the final prompt position
12
+ 3. take the argmax token
13
+ 4. compare with the first token of " " + object
14
+ 5. record pass / fail
15
+
16
+ This is candidate RECALL only. Spec 4.4: a pass here is not a correctness
17
+ judgment, and spec 16 forbids treating first-token correctness as full-answer
18
+ correctness.
19
+ """
20
+ import os, sys, json, time, argparse
21
+ import numpy as np
22
+ import torch
23
+ from transformers import AutoModelForCausalLM, AutoTokenizer
24
+
25
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
26
+ from common import DATASET, load_config, out_path, read_jsonl
27
+
28
+
29
+ def main():
30
+ ap = argparse.ArgumentParser()
31
+ ap.add_argument("--model", required=True, help="name from configs/models.yaml")
32
+ ap.add_argument("--prompts", default=os.path.join(DATASET, "filter/prompts.jsonl"))
33
+ ap.add_argument("--out_dir", default=None)
34
+ ap.add_argument("--batch", type=int, default=384)
35
+ ap.add_argument("--max_len", type=int, default=64)
36
+ ap.add_argument("--limit", type=int, default=0)
37
+ ap.add_argument("--save_records", action="store_true",
38
+ help="also write the per-prompt JSONL of spec 4.4; large")
39
+ args = ap.parse_args()
40
+
41
+ cfg = load_config("models.yaml")
42
+ entry = next((m for m in cfg["filter_models"] if m["name"] == args.model), None)
43
+ if entry is None:
44
+ raise SystemExit(f"{args.model} is not in configs/models.yaml:filter_models")
45
+ path = os.path.join(cfg["model_root"], entry["path"])
46
+ out_dir = args.out_dir or out_path("filter_outputs", "x")[:-1]
47
+ os.makedirs(out_dir, exist_ok=True)
48
+
49
+ prompts, objects = [], []
50
+ ids = []
51
+ for d in read_jsonl(args.prompts):
52
+ prompts.append(d["prompt"])
53
+ objects.append(d["object"])
54
+ ids.append(d["id"])
55
+ if args.limit and len(prompts) >= args.limit:
56
+ break
57
+ N = len(prompts)
58
+ print(f"[{args.model}] N={N}", flush=True)
59
+
60
+ tok = AutoTokenizer.from_pretrained(path)
61
+ if tok.pad_token is None:
62
+ tok.pad_token = tok.eos_token
63
+ tok.padding_side = "left"
64
+ tok.truncation_side = "left" # keep the END of the prompt, the cloze cue
65
+ model = AutoModelForCausalLM.from_pretrained(
66
+ path, dtype=torch.bfloat16, device_map={"": 0}).eval()
67
+
68
+ gold_first = np.empty(N, dtype=np.int64)
69
+ for i, o in enumerate(objects):
70
+ t = tok(" " + o, add_special_tokens=False).input_ids
71
+ gold_first[i] = t[0] if t else -1
72
+
73
+ passed = np.zeros(N, dtype=np.uint8)
74
+ pred_ids = np.zeros(N, dtype=np.int64)
75
+ order = sorted(range(N), key=lambda i: len(prompts[i]))
76
+ t0 = time.time()
77
+ with torch.no_grad():
78
+ for b in range(0, N, args.batch):
79
+ idx = order[b:b + args.batch]
80
+ enc = tok([prompts[i] for i in idx], return_tensors="pt", padding=True,
81
+ truncation=True, max_length=args.max_len).to(0)
82
+ pred = model(**enc).logits[:, -1, :].argmax(-1).cpu().numpy()
83
+ for j, i in enumerate(idx):
84
+ pred_ids[i] = pred[j]
85
+ passed[i] = int(pred[j] == gold_first[i])
86
+ if b % (args.batch * 200) == 0:
87
+ done = b + len(idx)
88
+ el = max(time.time() - t0, 1e-9)
89
+ print(f" {done}/{N} {done / el:.0f} ex/s "
90
+ f"pass={passed[:done].mean():.4f}", flush=True)
91
+
92
+ np.save(os.path.join(out_dir, f"correct_{args.model}.npy"), passed)
93
+ if args.save_records:
94
+ with open(os.path.join(out_dir, f"records_{args.model}.jsonl"), "w") as f:
95
+ for i in range(N):
96
+ f.write(json.dumps({
97
+ "prompt_id": ids[i], "model": args.model,
98
+ "predicted_token_id": int(pred_ids[i]),
99
+ "predicted_token_text": tok.decode([int(pred_ids[i])]),
100
+ "gold_token_id": int(gold_first[i]),
101
+ "gold_token_text": tok.decode([int(gold_first[i])])
102
+ if gold_first[i] >= 0 else "",
103
+ "passed": bool(passed[i])}, ensure_ascii=False) + "\n")
104
+ print(f"[{args.model}] pass rate={passed.mean():.4f} "
105
+ f"({time.time() - t0:.0f}s) FILTER_DONE", flush=True)
106
+
107
+
108
+ if __name__ == "__main__":
109
+ main()
ICLR dataset/runner/qual_templates.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Qualification-only question templates.
3
+
4
+ DELIBERATELY SEPARATE from dataset/filter/rel_templates.py: the qualification
5
+ question must not be one of the eval-condition paraphrases, otherwise a fact
6
+ qualifies on exactly the phrasing that is later scored as a "perturbation" and
7
+ the stability measurement leaks. Every `q` below is checked against the eval
8
+ canonical/paraphrase set by validate_facts.py.
9
+
10
+ Per relation:
11
+ q qualification question, slot {s}; answer = object
12
+ type answer_type (drives the scorer and the per-type reporting breakdown)
13
+ gran answer_granularity, only meaningful for date/number types
14
+ multi relation is inherently multi-answer (an entity can have several
15
+ equally correct objects) -> facts get is_multi_answer=True even when
16
+ the candidate pool happens to contain only one object
17
+ """
18
+
19
+ # answer_type vocabulary (keep closed; validate_facts.py enforces it)
20
+ TYPES = {"person", "place", "city", "country", "language", "organization",
21
+ "occupation", "sport", "instrument", "genre", "religion", "color",
22
+ "year", "date", "entity", "concept", "action", "property"}
23
+
24
+ QUAL = {
25
+ # ---- language ----
26
+ "P103": dict(q="Which language did {s} grow up speaking?", type="language", multi=False),
27
+ "P1412": dict(q="Which language is {s} able to speak?", type="language", multi=True),
28
+ "P37": dict(q="Which language has official status in {s}?", type="language", multi=True),
29
+ "P364": dict(q="In which language was {s} originally produced?", type="language", multi=True),
30
+ "P407": dict(q="Which language is {s} written in?", type="language", multi=True),
31
+ # ---- geography ----
32
+ "P36": dict(q="Which city is the seat of government of {s}?", type="city", multi=False),
33
+ "P1376": dict(q="{s} is the capital city of which country?", type="country", multi=False),
34
+ "P17": dict(q="Which country does {s} belong to?", type="country", multi=False),
35
+ "P27": dict(q="Which country holds {s}'s citizenship?", type="country", multi=True),
36
+ "P30": dict(q="Which continent is {s} part of?", type="place", multi=False),
37
+ "P131": dict(q="Which administrative region contains {s}?", type="place", multi=False),
38
+ "P276": dict(q="At which location can {s} be found?", type="place", multi=False),
39
+ "P19": dict(q="In which place did {s} come into the world?", type="city", multi=False),
40
+ "P20": dict(q="At which place did {s} pass away?", type="city", multi=False),
41
+ "P159": dict(q="Which city hosts the main offices of {s}?", type="city", multi=False),
42
+ "P190": dict(q="{s} maintains a twin-town relationship with which city?", type="city", multi=True),
43
+ "P47": dict(q="Which territory lies adjacent to {s}?", type="place", multi=True),
44
+ "P495": dict(q="Which country did {s} originate from?", type="country", multi=False),
45
+ "P740": dict(q="{s} came into existence in which place?", type="city", multi=False),
46
+ "P937": dict(q="In which place did {s} carry out their work?", type="city", multi=True),
47
+ "P1001": dict(q="Which jurisdiction does {s} have legal force in?", type="place", multi=False),
48
+ # ---- people / organizations ----
49
+ "P178": dict(q="Which company or person created {s}?", type="organization", multi=False),
50
+ "P176": dict(q="Which company builds {s}?", type="organization", multi=False),
51
+ "P127": dict(q="Who is the owner of {s}?", type="organization", multi=False),
52
+ "P108": dict(q="For which organization does {s} work?", type="organization", multi=True),
53
+ "P463": dict(q="{s} holds membership in which organization?", type="organization", multi=True),
54
+ "P449": dict(q="Which network first broadcast {s}?", type="organization", multi=False),
55
+ "P264": dict(q="Under which record label is {s} signed?", type="organization", multi=True),
56
+ "P22": dict(q="{s} is the child of which father?", type="person", multi=False),
57
+ "P25": dict(q="{s} is the child of which mother?", type="person", multi=False),
58
+ "P50": dict(q="Which writer wrote {s}?", type="person", multi=True),
59
+ "P57": dict(q="Which filmmaker directed {s}?", type="person", multi=True),
60
+ "P58": dict(q="Which writer wrote the screenplay for {s}?", type="person", multi=True),
61
+ "P86": dict(q="Which composer wrote the music for {s}?", type="person", multi=True),
62
+ "P162": dict(q="Which person produced {s}?", type="person", multi=True),
63
+ # ---- attributes ----
64
+ "P106": dict(q="Which profession is {s} known for?", type="occupation", multi=True),
65
+ "P101": dict(q="Which subject area is {s} known for working on?", type="concept", multi=True),
66
+ "P641": dict(q="Which sport is {s} associated with?", type="sport", multi=False),
67
+ "P413": dict(q="On the field, which position is {s} assigned to?", type="occupation", multi=False),
68
+ "P1303": dict(q="Which musical instrument does {s} perform on?", type="instrument", multi=True),
69
+ "P136": dict(q="Which genre does {s} fall under?", type="genre", multi=True),
70
+ "P140": dict(q="Which faith does {s} follow?", type="religion", multi=False),
71
+ "P462": dict(q="Which colour does {s} have?", type="color", multi=True),
72
+ "P31": dict(q="{s} is an example of what kind of thing?", type="concept", multi=True),
73
+ "P279": dict(q="{s} is a more specific kind of what?", type="concept", multi=True),
74
+ "P527": dict(q="Which component does {s} contain?", type="entity", multi=True),
75
+
76
+ # ---- Google_RE (extension set) ----
77
+ "date_of_birth": dict(q="In which year was {s} born?", type="year", gran="year", multi=False),
78
+ "place_of_birth": dict(q="In which place did {s} come into the world?", type="city", multi=False),
79
+ "place_of_death": dict(q="At which place did {s} pass away?", type="city", multi=False),
80
+
81
+ # ---- ConceptNet (open-ended extension set; all inherently multi-answer) ----
82
+ "IsA": dict(q="Which category does {s} belong to?", type="concept", multi=True),
83
+ "UsedFor": dict(q="People use {s} in order to do what?", type="action", multi=True),
84
+ "AtLocation": dict(q="In what sort of place does {s} normally sit?", type="place", multi=True),
85
+ "HasA": dict(q="Which part does {s} come with?", type="entity", multi=True),
86
+ "HasProperty": dict(q="Which characteristic applies to {s}?", type="property", multi=True),
87
+ "CapableOf": dict(q="What is {s} able to do?", type="action", multi=True),
88
+ "PartOf": dict(q="Which larger whole includes {s}?", type="entity", multi=True),
89
+ "Causes": dict(q="Which outcome follows from {s}?", type="action", multi=True),
90
+ "CausesDesire": dict(q="After {s}, what urge follows?", type="action", multi=True),
91
+ "Desires": dict(q="Which thing does {s} wish for?", type="action", multi=True),
92
+ "NotDesires": dict(q="Which thing would {s} rather avoid?", type="action", multi=True),
93
+ "HasSubevent": dict(q="What happens as part of {s}?", type="action", multi=True),
94
+ "HasPrerequisite": dict(q="What has to happen before {s}?", type="action", multi=True),
95
+ "MotivatedByGoal": dict(q="Why would someone do {s}?", type="action", multi=True),
96
+ "MadeOf": dict(q="What material is {s} made of?", type="entity", multi=True),
97
+ "ReceivesAction": dict(q="Which action is commonly performed on {s}?", type="action", multi=True),
98
+ }
99
+
100
+ # instruction appended to every qualification prompt (no candidates shown, so
101
+ # this stays free generation; it only suppresses explanatory prose)
102
+ INSTRUCTION = "Answer with only the shortest correct answer."
103
+
104
+
105
+ def resolve(rid):
106
+ """Spec for a relation id, or None when the relation has no template.
107
+
108
+ No generic fallback on purpose: a fact whose relation lacks a hand-written
109
+ natural question would get an awkward auto-verbalization, and a wrong
110
+ qualification question silently shrinks the Known Set. Such facts are
111
+ dropped by enrich_facts.py and counted in the report.
112
+ """
113
+ spec = QUAL.get(rid)
114
+ if spec is None:
115
+ return None
116
+ return {"q": spec["q"], "type": spec["type"],
117
+ "gran": spec.get("gran"), "multi": spec.get("multi", False)}
118
+
119
+
120
+ def build_prompt(question, instruction=INSTRUCTION):
121
+ """Plain-completion qualification prompt (see README for why not chat)."""
122
+ return f"Question: {question}\n{instruction}\nAnswer:"
ICLR dataset/runner/qualification_run.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Stage V -> outputs/qualification/<model>.jsonl (spec section 7) [GPU]
3
+
4
+ Anchor qualification: does this model answer the canonical question correctly?
5
+
6
+ Spec 7.1: the result is a LABEL. It never removes a fact from the benchmark, so
7
+ the denominator stays at 2,592 for every model and adding a model later cannot
8
+ change any previously computed number.
9
+
10
+ Spec 7.2: identical raw prompt string for base and instruction-tuned models, no
11
+ chat template, no candidates, no few-shot.
12
+ Spec 7.3: greedy decoding, max_new_tokens 24, everything stored.
13
+ """
14
+ import os, sys, json, time, argparse
15
+ import torch
16
+ from transformers import AutoModelForCausalLM, AutoTokenizer
17
+
18
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
19
+ from common import load_config, out_path, read_jsonl
20
+
21
+ PROMPT = "Question: {q}\nAnswer with only the shortest correct answer.\nAnswer:"
22
+
23
+
24
+ def main():
25
+ ap = argparse.ArgumentParser()
26
+ ap.add_argument("--model", required=True, help="name from configs/models.yaml")
27
+ ap.add_argument("--facts", default=out_path("benchmark_facts_2592.jsonl"))
28
+ ap.add_argument("--limit", type=int, default=0)
29
+ ap.add_argument("--save_logprob", action="store_true",
30
+ help="one extra teacher-forced pass for the gold sequence score")
31
+ args = ap.parse_args()
32
+
33
+ cfg = load_config("models.yaml")
34
+ entry = next((m for m in cfg["evaluated_models"] if m["name"] == args.model), None)
35
+ if entry is None:
36
+ raise SystemExit(f"{args.model} is not in configs/models.yaml:evaluated_models")
37
+ gen_cfg = cfg["generation"]
38
+ if gen_cfg.get("use_chat_template"):
39
+ raise SystemExit("spec 7.2 forbids a chat template in anchor qualification")
40
+
41
+ path = os.path.join(cfg["model_root"], entry["path"])
42
+ facts = list(read_jsonl(args.facts))
43
+ if args.limit:
44
+ facts = facts[:args.limit]
45
+ N = len(facts)
46
+ print(f"[{args.model}] N={N} revision={entry.get('revision')}", flush=True)
47
+
48
+ torch.manual_seed(gen_cfg.get("seed", 0))
49
+ tok = AutoTokenizer.from_pretrained(path)
50
+ if tok.pad_token is None:
51
+ tok.pad_token = tok.eos_token
52
+ tok.padding_side = "left"
53
+ tok.truncation_side = "left"
54
+ model = AutoModelForCausalLM.from_pretrained(
55
+ path, dtype=getattr(torch, gen_cfg.get("dtype", "bfloat16")),
56
+ device_map={"": 0}).eval()
57
+
58
+ prompts = [PROMPT.format(q=f["qualification_question"]) for f in facts]
59
+ golds = [f["object"]["canonical"] for f in facts]
60
+ gold_ids = [tok(" " + g, add_special_tokens=False).input_ids for g in golds]
61
+
62
+ out = [None] * N
63
+ order = sorted(range(N), key=lambda i: len(prompts[i]))
64
+ B = gen_cfg.get("batch_size", 96)
65
+ t0 = time.time()
66
+
67
+ with torch.no_grad():
68
+ for b in range(0, N, B):
69
+ idx = order[b:b + B]
70
+ enc = tok([prompts[i] for i in idx], return_tensors="pt", padding=True,
71
+ truncation=True, max_length=gen_cfg.get("max_prompt_len", 96)).to(0)
72
+ plen = enc["input_ids"].shape[1]
73
+ gen = model.generate(**enc,
74
+ max_new_tokens=gen_cfg.get("max_new_tokens", 24),
75
+ do_sample=gen_cfg.get("do_sample", False),
76
+ num_beams=gen_cfg.get("num_beams", 1),
77
+ pad_token_id=tok.pad_token_id)
78
+ new_ids = gen[:, plen:]
79
+ texts = tok.batch_decode(new_ids, skip_special_tokens=True)
80
+ for j, i in enumerate(idx):
81
+ ids = new_ids[j].tolist()
82
+ n_tok, fin = len(ids), "length"
83
+ for k, t in enumerate(ids):
84
+ if t == tok.eos_token_id:
85
+ n_tok, fin = k, "eos"
86
+ break
87
+ out[i] = {"fact_id": facts[i]["fact_id"], "model": args.model,
88
+ "prompt": prompts[i],
89
+ "raw_response": texts[j],
90
+ "generated_token_ids": ids[:n_tok],
91
+ "generated_tokens": int(n_tok),
92
+ "finish_reason": fin,
93
+ "gold_token_len": len(gold_ids[i])}
94
+
95
+ if args.save_logprob:
96
+ full = [prompts[i] + " " + golds[i] for i in idx]
97
+ enc2 = tok(full, return_tensors="pt", padding=True, truncation=True,
98
+ max_length=gen_cfg.get("max_prompt_len", 96) + 32).to(0)
99
+ lp = torch.log_softmax(model(**enc2).logits.float(), dim=-1)
100
+ for j, i in enumerate(idx):
101
+ g = gold_ids[i]
102
+ if not g:
103
+ continue
104
+ seq = enc2["input_ids"][j]
105
+ end = seq.shape[0]
106
+ start = end - len(g)
107
+ L = int(enc2["attention_mask"][j].sum().item())
108
+ if start - 1 < end - L:
109
+ continue
110
+ vals = [lp[j, t - 1, seq[t]].item() for t in range(start, end)]
111
+ row = lp[j, start - 1]
112
+ out[i]["gold_sequence_logprob"] = float(sum(vals) / len(vals))
113
+ out[i]["gold_first_token_logprob"] = float(row[g[0]].item())
114
+ out[i]["gold_first_token_rank"] = int((row > row[g[0]]).sum().item()) + 1
115
+ out[i]["first_token_argmax_correct"] = bool(
116
+ int(row.argmax().item()) == g[0])
117
+
118
+ if b % (B * 20) == 0:
119
+ done = b + len(idx)
120
+ print(f" {done}/{N} {done / max(time.time() - t0, 1e-9):.1f}/s",
121
+ flush=True)
122
+
123
+ dest = out_path("qualification", f"{args.model}.jsonl")
124
+ with open(dest, "w") as f:
125
+ for r in out:
126
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
127
+ json.dump({"model": args.model, "n": N, "generation": gen_cfg,
128
+ "model_entry": entry, "seconds": round(time.time() - t0, 1)},
129
+ open(out_path("qualification", f"{args.model}.meta.json"), "w"),
130
+ indent=2, ensure_ascii=False)
131
+ print(f"[{args.model}] wrote {N} -> {dest} ({time.time() - t0:.0f}s) GEN_DONE")
132
+
133
+
134
+ if __name__ == "__main__":
135
+ main()
ICLR dataset/runner/qualification_score.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Stage V scoring -> outputs/qualification/<model>.scored.jsonl + K_m labels.
3
+
4
+ Spec 7.4: CPU-side, modular, five labels. Spec 7.1 / 16: K_m is a label set and
5
+ must never be used to redefine the benchmark denominator, so this script writes
6
+ a per-fact label table covering ALL 2,592 facts for every model rather than a
7
+ filtered subset.
8
+
9
+ Also emits outputs/known_labels.json:
10
+ {fact_id: {model: label}}
11
+ which downstream analysis joins against the query bank.
12
+ """
13
+ import os, sys, json, glob, argparse, collections
14
+ import numpy as np
15
+
16
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
17
+ from common import load_config, out_path, read_jsonl, write_jsonl
18
+ from scoring_full import score, needs_manual_review
19
+
20
+ LABELS = ["correct", "incorrect", "ambiguous", "abstain", "unparseable"]
21
+
22
+
23
+ def bootstrap_ci(values, groups, n_boot=2000, seed=0, alpha=0.05):
24
+ """Cluster bootstrap over RELATIONS: the relation mix is heavily skewed
25
+ (manufacturer + developer + native_language are a third of the benchmark),
26
+ so treating facts as independent would understate the interval."""
27
+ rng = np.random.default_rng(seed)
28
+ by = collections.defaultdict(list)
29
+ for v, g in zip(values, groups):
30
+ by[g].append(v)
31
+ keys = list(by)
32
+ if not keys:
33
+ return (float("nan"), float("nan"))
34
+ arrs = [np.asarray(by[k], dtype=float) for k in keys]
35
+ stats = np.empty(n_boot)
36
+ for b in range(n_boot):
37
+ pick = rng.integers(0, len(keys), len(keys))
38
+ stats[b] = np.concatenate([arrs[i] for i in pick]).mean()
39
+ return float(np.quantile(stats, alpha / 2)), float(np.quantile(stats, 1 - alpha / 2))
40
+
41
+
42
+ def main():
43
+ ap = argparse.ArgumentParser()
44
+ ap.add_argument("--models", nargs="*", default=None)
45
+ ap.add_argument("--facts", default=out_path("benchmark_facts_2592.jsonl"))
46
+ args = ap.parse_args()
47
+
48
+ facts = {f["fact_id"]: f for f in read_jsonl(args.facts)}
49
+ qdir = os.path.join(out_path("qualification", "x")[:-1])
50
+ paths = sorted(p for p in glob.glob(os.path.join(qdir, "*.jsonl"))
51
+ if not p.endswith(".scored.jsonl"))
52
+ if args.models:
53
+ paths = [p for p in paths
54
+ if os.path.basename(p)[:-len(".jsonl")] in args.models]
55
+ if not paths:
56
+ raise SystemExit(f"no generation files in {qdir}; run qualification_run.py first")
57
+
58
+ known = collections.defaultdict(dict)
59
+ summary = {}
60
+ for p in paths:
61
+ model = os.path.basename(p)[:-len(".jsonl")]
62
+ rows, counts = [], collections.Counter()
63
+ by_rel = collections.defaultdict(collections.Counter)
64
+ by_flag = collections.defaultdict(collections.Counter)
65
+ for g in read_jsonl(p):
66
+ f = facts.get(g["fact_id"])
67
+ if f is None:
68
+ raise SystemExit(f"{model}: generation for unknown fact {g['fact_id']}")
69
+ r = score(g["raw_response"], f["object"]["aliases"],
70
+ answer_type=f["answer_type"],
71
+ granularity=f["answer_granularity"])
72
+ rec = {"fact_id": g["fact_id"], "model": model,
73
+ "prompt": g["prompt"], "raw_response": g["raw_response"],
74
+ "extracted_answer": r["span"], "label": r["label"],
75
+ "matched_alias": r["matched_alias"], "scorer": r["scorer"],
76
+ "flags": r["flags"],
77
+ "relation": f["relation"]["relation_id"],
78
+ "answer_type": f["answer_type"],
79
+ "answer_in_subject_surface": bool(f.get("answer_in_subject_surface")),
80
+ "spec_6_2_flag": f.get("spec_6_2_flag"),
81
+ "manual_review": needs_manual_review(r)}
82
+ for k in ("gold_sequence_logprob", "gold_first_token_rank",
83
+ "first_token_argmax_correct"):
84
+ if k in g:
85
+ rec[k] = g[k]
86
+ rows.append(rec)
87
+ counts[r["label"]] += 1
88
+ by_rel[f["relation"]["relation_id"]][r["label"]] += 1
89
+ by_flag[bool(f.get("answer_in_subject_surface"))][r["label"]] += 1
90
+ known[g["fact_id"]][model] = r["label"]
91
+
92
+ write_jsonl(os.path.join(qdir, f"{model}.scored.jsonl"), rows)
93
+
94
+ n = len(rows)
95
+ vals = [1.0 if r["label"] == "correct" else 0.0 for r in rows]
96
+ rels = [r["relation"] for r in rows]
97
+ lo, hi = bootstrap_ci(vals, rels)
98
+ rel_macro = collections.defaultdict(list)
99
+ for v, rl in zip(vals, rels):
100
+ rel_macro[rl].append(v)
101
+ summary[model] = {
102
+ "n_facts": n,
103
+ "labels": {k: counts[k] for k in LABELS},
104
+ "label_rates": {k: round(counts[k] / n, 4) for k in LABELS},
105
+ "K_m": counts["correct"],
106
+ "anchor_accuracy_micro": round(counts["correct"] / n, 4),
107
+ "anchor_accuracy_relation_macro":
108
+ round(float(np.mean([np.mean(v) for v in rel_macro.values()])), 4),
109
+ "ci95_relation_clustered": [round(lo, 4), round(hi, 4)],
110
+ # the copy-shortcut split from reconstruction_differences.md F1
111
+ "accuracy_answer_in_subject":
112
+ round(by_flag[True]["correct"] / max(sum(by_flag[True].values()), 1), 4),
113
+ "accuracy_answer_not_in_subject":
114
+ round(by_flag[False]["correct"] / max(sum(by_flag[False].values()), 1), 4),
115
+ "n_manual_review": sum(1 for r in rows if r["manual_review"]),
116
+ "by_relation": {k: {"n": sum(v.values()), "correct": v["correct"]}
117
+ for k, v in sorted(by_rel.items())},
118
+ }
119
+
120
+ # spec 7.1: labels for every fact x model, benchmark denominator untouched
121
+ json.dump({"n_facts": len(facts), "models": sorted(summary),
122
+ "note": "K_m is a label set; the benchmark denominator stays 2,592 "
123
+ "for every model (spec 2.1 / 7.1)",
124
+ "labels": known},
125
+ open(out_path("known_labels.json"), "w"), ensure_ascii=False)
126
+ json.dump(summary, open(out_path("qualification_summary.json"), "w"),
127
+ indent=2, ensure_ascii=False)
128
+
129
+ print(f"{'model':22s} {'K_m':>6s} {'micro':>7s} {'macro':>7s} "
130
+ f"{'CI95':>16s} {'abst':>6s} {'ambig':>6s} {'copy':>6s} {'real':>6s}")
131
+ print("-" * 92)
132
+ for m, s in summary.items():
133
+ ci = s["ci95_relation_clustered"]
134
+ print(f"{m[:21]:22s} {s['K_m']:6d} {s['anchor_accuracy_micro']:7.3f} "
135
+ f"{s['anchor_accuracy_relation_macro']:7.3f} "
136
+ f"[{ci[0]:.3f},{ci[1]:.3f}] {s['label_rates']['abstain']:6.3f} "
137
+ f"{s['label_rates']['ambiguous']:6.3f} "
138
+ f"{s['accuracy_answer_in_subject']:6.3f} "
139
+ f"{s['accuracy_answer_not_in_subject']:6.3f}")
140
+ print("\ncopy = facts whose answer is inside the subject name; "
141
+ "real = the rest (see reconstruction_differences.md F1)")
142
+
143
+
144
+ if __name__ == "__main__":
145
+ main()
ICLR dataset/runner/scoring_full.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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")
ICLR dataset/runner/select_benchmark.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Stage III -> outputs/benchmark_facts_2592.jsonl (spec section 6)
3
+
4
+ Two filters, both driven by configs/relations.yaml:
5
+ 6.1 core sources only: CounterFact, LAMA-TREx, PopQA -> 3,705
6
+ 6.2 functional (single-valued) relations only -> 2,592
7
+
8
+ Spec 6.2 additionally NAMES `developer of` and `manufacturer of` as unsuitable,
9
+ yet the required benchmark size of 2,592 across 21 relations can only be reached
10
+ with them included. That contradiction is inside the specification itself, so
11
+ the default keeps them, tags them with `spec_6_2_flag`, and records the conflict
12
+ in outputs/reconstruction_differences.md. Set
13
+ `options.drop_spec_6_2_flagged: true` in relations.yaml to exclude them; the
14
+ script then reports the resulting size instead of failing.
15
+ """
16
+ import os, sys, json, argparse, collections
17
+
18
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
19
+ from common import load_config, out_path, read_jsonl, write_jsonl, Expect
20
+
21
+ EXPECTED_CORE = 3705
22
+ EXPECTED_BENCHMARK = 2592
23
+ EXPECTED_RELATIONS = 21
24
+
25
+
26
+ def main():
27
+ ap = argparse.ArgumentParser()
28
+ ap.add_argument("--enriched", default=out_path("enriched_facts_6180.jsonl"))
29
+ args = ap.parse_args()
30
+
31
+ cfg = load_config("relations.yaml")
32
+ opts = cfg.get("options", {})
33
+ drop_flagged = bool(opts.get("drop_spec_6_2_flagged", False))
34
+ exp = Expect()
35
+
36
+ facts = list(read_jsonl(args.enriched))
37
+ exp.check("enriched_input", len(facts), 6180)
38
+
39
+ core = [f for f in facts if f["is_core_source"]]
40
+ exp.check("core_source_facts", len(core), EXPECTED_CORE)
41
+
42
+ bench, dropped = [], collections.Counter()
43
+ for f in core:
44
+ if not f["is_benchmark_relation"]:
45
+ dropped["not_a_benchmark_relation"] += 1
46
+ continue
47
+ if not f["is_functional"]:
48
+ dropped["non_functional_relation"] += 1
49
+ continue
50
+ if drop_flagged and f.get("spec_6_2_flag"):
51
+ dropped["spec_6_2_flagged"] += 1
52
+ continue
53
+ bench.append(f)
54
+
55
+ rel_counts = collections.Counter(f["relation"]["relation_id"] for f in bench)
56
+ exp.check("benchmark_facts", len(bench),
57
+ None if drop_flagged else EXPECTED_BENCHMARK,
58
+ note="drop_spec_6_2_flagged=true" if drop_flagged else "")
59
+ exp.check("benchmark_relations", len(rel_counts),
60
+ None if drop_flagged else EXPECTED_RELATIONS)
61
+
62
+ flagged = sum(1 for f in bench if f.get("spec_6_2_flag"))
63
+
64
+ path = out_path("benchmark_facts_2592.jsonl")
65
+ write_jsonl(path, bench)
66
+
67
+ exp.report("Stage III counts")
68
+ meta = {
69
+ "stage": "III_benchmark_selection",
70
+ "n_enriched": len(facts),
71
+ "n_core_source": len(core),
72
+ "n_benchmark": len(bench),
73
+ "n_relations": len(rel_counts),
74
+ "per_relation": dict(rel_counts.most_common()),
75
+ "per_source": dict(collections.Counter(f["sources"][0] for f in bench)),
76
+ "per_answer_type": dict(collections.Counter(f["answer_type"] for f in bench)),
77
+ "dropped": dict(dropped),
78
+ "spec_6_2_flagged_kept": flagged,
79
+ "drop_spec_6_2_flagged": drop_flagged,
80
+ "inverse_well_posed_facts": sum(1 for f in bench if f["is_inverse_well_posed"]),
81
+ "checks": exp.rows,
82
+ }
83
+ json.dump(meta, open(out_path("stage3_report.json"), "w"),
84
+ indent=2, ensure_ascii=False)
85
+
86
+ print(f"\nwrote {len(bench)} benchmark facts -> {path}")
87
+ print(f" relations: {len(rel_counts)}")
88
+ print(f" dropped: {dict(dropped)}")
89
+ if flagged:
90
+ print(f" NOTE: {flagged} facts come from relations spec 6.2 calls "
91
+ f"unsuitable (manufacturer/developer); required to reach 2,592. "
92
+ f"See outputs/reconstruction_differences.md")
93
+ return 1 if exp.deviations else 0
94
+
95
+
96
+ if __name__ == "__main__":
97
+ sys.exit(main())
ICLR dataset/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())
ICLR dataset/runner/validate_facts.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Fact- and query-level validation -> outputs/validation_report.json
3
+
4
+ Spec 6.3 lists the fact-level gates, spec 13 the query-level ones, spec 14.2 the
5
+ report shape. Exits non-zero on any hard error so a broken build can never reach
6
+ a GPU run.
7
+ """
8
+ import os, re, sys, json, glob, argparse, collections
9
+
10
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
11
+ from common import load_config, out_path, read_jsonl, normalize
12
+
13
+ EVAL_LEGACY = "/scratch/rds-fei-rsfm-rw/cshi0459/ICLR27/eval_dataset"
14
+
15
+
16
+ def load_perturbation_prompts():
17
+ """Normalized text of every evaluation perturbation prompt, for the spec 16
18
+ check that a qualification template is never reused as an eval template."""
19
+ out = set()
20
+ for p in glob.glob(f"{EVAL_LEGACY}/query*.jsonl"):
21
+ for d in read_jsonl(p):
22
+ out.add(normalize(d.get("prompt", "")))
23
+ return out
24
+
25
+
26
+ def main():
27
+ ap = argparse.ArgumentParser()
28
+ ap.add_argument("--facts", default=out_path("benchmark_facts_2592.jsonl"))
29
+ ap.add_argument("--queries", default=out_path("evaluation_queries_44418.jsonl"))
30
+ ap.add_argument("--skip_leakage", action="store_true")
31
+ args = ap.parse_args()
32
+
33
+ cond_cfg = load_config("eval_conditions.yaml")
34
+ errors = collections.Counter()
35
+ warnings = collections.Counter()
36
+ examples = collections.defaultdict(list)
37
+
38
+ def err(tag, ref, detail=""):
39
+ errors[tag] += 1
40
+ if len(examples[tag]) < 5:
41
+ examples[tag].append(f"{ref} {detail}".strip())
42
+
43
+ def warn(tag, ref, detail=""):
44
+ warnings[tag] += 1
45
+ if len(examples[tag]) < 5:
46
+ examples[tag].append(f"{ref} {detail}".strip())
47
+
48
+ # =================================================== fact level (spec 6.3)
49
+ facts = list(read_jsonl(args.facts))
50
+ seen_ids, seen_norm = set(), collections.Counter()
51
+ for f in facts:
52
+ fid = f.get("fact_id")
53
+ s, r, o = f.get("subject", {}), f.get("relation", {}), f.get("object", {})
54
+ if not fid:
55
+ err("missing_fact_id", "?")
56
+ elif fid in seen_ids:
57
+ err("duplicate_fact_id", fid)
58
+ seen_ids.add(fid)
59
+
60
+ if not (s.get("canonical") or "").strip():
61
+ err("empty_subject", fid)
62
+ if not (r.get("relation_id") or "").strip():
63
+ err("empty_relation", fid)
64
+ if not (o.get("canonical") or "").strip():
65
+ err("empty_object", fid)
66
+
67
+ q = f.get("qualification_question") or ""
68
+ if not q.strip():
69
+ err("empty_qualification_question", fid)
70
+ elif normalize(s.get("canonical", "")) and \
71
+ normalize(s["canonical"]) not in normalize(q):
72
+ warn("subject_not_in_question", fid, q)
73
+
74
+ al = o.get("aliases") or []
75
+ if not al:
76
+ err("no_object_alias", fid)
77
+ elif normalize(o["canonical"]) not in {normalize(a) for a in al}:
78
+ err("canonical_object_not_in_aliases", fid, o.get("canonical", ""))
79
+
80
+ if not f.get("answer_type"):
81
+ err("missing_answer_type", fid)
82
+ if not f.get("answer_granularity"):
83
+ err("missing_answer_granularity", fid)
84
+ if not f.get("sources"):
85
+ err("missing_source_metadata", fid)
86
+ if not f.get("is_functional"):
87
+ err("main_relation_not_functional", fid, r.get("relation_id", ""))
88
+ if len(o.get("variant_surface_forms") or []) > 1 and f["is_functional"]:
89
+ # survived 5.2 only if all variants share one entity id
90
+ if not o.get("entity_id"):
91
+ err("unresolved_functional_conflict", fid)
92
+ if not (s.get("aliases") or []):
93
+ warn("no_subject_alias", fid)
94
+ seen_norm[(normalize(s.get("canonical", "")),
95
+ r.get("relation_id"),
96
+ normalize(o.get("canonical", "")))] += 1
97
+
98
+ dup_norm = {k: v for k, v in seen_norm.items() if v > 1}
99
+ if dup_norm:
100
+ errors["duplicate_normalized_fact"] = len(dup_norm)
101
+ examples["duplicate_normalized_fact"] = [str(k) for k in list(dup_norm)[:5]]
102
+
103
+ # spec 16: qualification template must not be an evaluation template
104
+ if not args.skip_leakage and os.path.isdir(EVAL_LEGACY):
105
+ pert = load_perturbation_prompts()
106
+ for f in facts:
107
+ if normalize(f["qualification_question"]) in pert:
108
+ err("qualification_question_reused_as_eval_template",
109
+ f["fact_id"], f["qualification_question"])
110
+
111
+ # ================================================== query level (spec 13)
112
+ facts_by_id = {f["fact_id"]: f for f in facts}
113
+ queries = []
114
+ if os.path.exists(args.queries):
115
+ queries = list(read_jsonl(args.queries))
116
+ fact_ids = seen_ids
117
+ seen_q = set()
118
+ main_families = {c for c, v in cond_cfg["conditions"].items()
119
+ if v["use_for_main_forward"]}
120
+ for q in queries:
121
+ qid = q.get("query_id")
122
+ if not qid:
123
+ err("missing_query_id", "?")
124
+ elif qid in seen_q:
125
+ err("duplicate_query_id", qid)
126
+ seen_q.add(qid)
127
+
128
+ if q.get("fact_id") not in fact_ids:
129
+ err("query_references_unknown_fact", qid, str(q.get("fact_id")))
130
+ if not (q.get("gold_aliases") or []):
131
+ err("missing_gold_aliases", qid)
132
+ if not q.get("query", "").strip():
133
+ err("empty_query_text", qid)
134
+
135
+ fam = q.get("condition_family")
136
+ spec_c = cond_cfg["conditions"].get(fam)
137
+ if spec_c is None:
138
+ err("unknown_condition_family", qid, str(fam))
139
+ continue
140
+ # booleans must agree with the registry, otherwise an aggregation
141
+ # that trusts the row would silently mix families
142
+ for flag in ("use_for_main_forward", "use_for_reverse_analysis",
143
+ "use_for_recognition_analysis", "is_assisted"):
144
+ if bool(q.get(flag)) != bool(spec_c[flag]):
145
+ err(f"flag_mismatch_{flag}", qid, fam)
146
+ if q.get("target_slot") != spec_c["target_slot"]:
147
+ err("target_slot_mismatch", qid, fam)
148
+
149
+ # spec 2.3 / 16 hard prohibitions
150
+ if fam == "recognition" and q.get("use_for_main_forward"):
151
+ err("recognition_in_main_forward", qid)
152
+ if fam == "reverse_illposed" and q.get("use_for_main_forward"):
153
+ err("reverse_illposed_in_main_forward", qid)
154
+ if fam in main_families and q.get("target_slot") != "object":
155
+ err("invalid_main_target_slot", qid, str(q.get("target_slot")))
156
+ # spec 13.9: an open-ended main query must not expose the answer.
157
+ # A gold string that is part of the SUBJECT name ("Airbus A318" ->
158
+ # "Airbus") is inherent to the fact, not leakage introduced by the
159
+ # template, so it is a warning carrying the count rather than a hard
160
+ # error. Only an occurrence that survives removing every subject
161
+ # mention is a genuine template leak.
162
+ if fam in main_families and not q.get("is_assisted"):
163
+ nq = normalize(q["query"])
164
+ gold = normalize(q.get("gold_canonical", ""))
165
+ if gold and gold in nq:
166
+ subj = normalize(
167
+ facts_by_id[q["fact_id"]]["subject"]["canonical"]
168
+ ) if q["fact_id"] in facts_by_id else ""
169
+ residual = nq.replace(subj, " ") if subj else nq
170
+ if gold in residual:
171
+ err("gold_exposed_by_template", qid, q["query"][:70])
172
+ else:
173
+ warn("gold_inside_subject_name", qid, q["query"][:70])
174
+
175
+ # ============================================================== report
176
+ report = {
177
+ "hard_errors": int(sum(errors.values())),
178
+ "warnings": [{"type": k, "count": v, "examples": examples[k][:3]}
179
+ for k, v in warnings.most_common()],
180
+ "errors": [{"type": k, "count": v, "examples": examples[k][:3]}
181
+ for k, v in errors.most_common()],
182
+ "fact_count": len(facts),
183
+ "query_count": len(queries),
184
+ "relation_count": len({f["relation"]["relation_id"] for f in facts}),
185
+ "duplicate_fact_ids": int(errors.get("duplicate_fact_id", 0)),
186
+ "duplicate_query_ids": int(errors.get("duplicate_query_id", 0)),
187
+ "missing_gold_aliases": int(errors.get("missing_gold_aliases", 0)),
188
+ "invalid_main_target_slots": int(errors.get("invalid_main_target_slot", 0)),
189
+ "recognition_in_main_forward": int(errors.get("recognition_in_main_forward", 0)),
190
+ "reverse_illposed_in_main_forward":
191
+ int(errors.get("reverse_illposed_in_main_forward", 0)),
192
+ }
193
+ json.dump(report, open(out_path("validation_report.json"), "w"),
194
+ indent=2, ensure_ascii=False)
195
+
196
+ print(f"facts={len(facts)} queries={len(queries)} "
197
+ f"relations={report['relation_count']}")
198
+ print(f"\nHARD ERRORS: {report['hard_errors']}")
199
+ for k, v in errors.most_common():
200
+ print(f" {k:46s} {v:6d} e.g. {examples[k][:1]}")
201
+ print(f"\nWARNINGS: {sum(warnings.values())}")
202
+ for k, v in warnings.most_common():
203
+ print(f" {k:46s} {v:6d} e.g. {examples[k][:1]}")
204
+ return 1 if report["hard_errors"] else 0
205
+
206
+
207
+ if __name__ == "__main__":
208
+ sys.exit(main())