SamZou commited on
Commit
fcd8ee2
·
verified ·
1 Parent(s): a544de6

Remove Phase 2 source code (code lives on GitHub; HF holds artifacts only)

Browse files
phase2_scaling/extract_activations.py DELETED
@@ -1,314 +0,0 @@
1
- """Extract activations from Llama models via NDIF for Phase 2.
2
-
3
- Handles both pilot timing runs and full six-relation extraction.
4
- Uses the blackboxnlp-ndif conda environment.
5
-
6
- Usage:
7
- # Pilot: one relation, N50, both models, record timing
8
- python extract_activations.py --pilot
9
-
10
- # Full extraction after N_final is frozen
11
- python extract_activations.py --subset N50 # or N75, N100
12
- """
13
-
14
- from __future__ import annotations
15
-
16
- import argparse
17
- import hashlib
18
- import json
19
- import math
20
- import os
21
- import time
22
- from pathlib import Path
23
- from typing import Any
24
-
25
- import numpy as np
26
- import pandas as pd
27
-
28
- ROOT = Path(__file__).resolve().parent
29
- ENV_PATH = ROOT / ".env"
30
- DATA_PATH = ROOT / "data" / "processed" / "examples.parquet"
31
- ACTIVATIONS_DIR = ROOT / "activations"
32
- PILOT_DIR = ROOT / "activations" / "pilot"
33
-
34
- MODELS = {
35
- "llama_3_1_8b": "meta-llama/Llama-3.1-8B",
36
- "llama_3_1_70b": "meta-llama/Llama-3.1-70B",
37
- }
38
-
39
- DEPTHS = [0.25, 0.50, 0.75, 1.00]
40
-
41
- PILOT_RELATION = "P19"
42
-
43
- def load_env() -> str:
44
- if not ENV_PATH.exists():
45
- raise FileNotFoundError(f"Missing .env: {ENV_PATH}")
46
- for line in ENV_PATH.read_text(encoding="utf-8").splitlines():
47
- line = line.strip()
48
- if not line or line.startswith("#"):
49
- continue
50
- if "=" in line:
51
- k, v = line.split("=", 1)
52
- os.environ.setdefault(k.strip(), v.strip())
53
- api_key = os.environ.get("NDIF_API_KEY", "").strip()
54
- if not api_key or api_key.startswith("PASTE_YOUR_"):
55
- raise RuntimeError("Set NDIF_API_KEY in .env")
56
- hf_token = os.environ.get("HF_TOKEN", "").strip()
57
- if not hf_token or hf_token.startswith("PASTE_YOUR_"):
58
- raise RuntimeError("Set HF_TOKEN in .env")
59
- return api_key
60
-
61
-
62
- def get_layer_indices(num_layers: int) -> list[tuple[float, int]]:
63
- return [(d, math.ceil(d * num_layers) - 1) for d in DEPTHS]
64
-
65
-
66
- def load_sentences(subset: str, relation: str | None = None) -> pd.DataFrame:
67
- df = pd.read_parquet(DATA_PATH)
68
- df = df[df["subset"] == subset]
69
- if relation:
70
- df = df[df["relation_id"] == relation]
71
- return df.sort_values("example_id").reset_index(drop=True)
72
-
73
-
74
- def extract_for_model(
75
- model_key: str,
76
- model_id: str,
77
- sentences: list[str],
78
- api_key: str,
79
- ) -> dict[str, Any]:
80
- """Run extraction for one model, one sentence at a time.
81
-
82
- Passes each sentence as a raw string to match the NNsight/NDIF
83
- remote trace pattern validated in the smoke test.
84
- """
85
- from nnsight import CONFIG, LanguageModel
86
-
87
- CONFIG.set_default_api_key(api_key)
88
-
89
- print(f"\n{'='*50}")
90
- print(f"Model: {model_id}")
91
- print(f"Sentences: {len(sentences)}")
92
- print(f"{'='*50}")
93
-
94
- t_init_start = time.time()
95
- model = LanguageModel(model_id)
96
- num_layers = model.config.num_hidden_layers
97
- hidden_dim = model.config.hidden_size
98
- t_init = time.time() - t_init_start
99
- print(f"Model init: {t_init:.1f}s (layers={num_layers}, hidden={hidden_dim})")
100
-
101
- layers = get_layer_indices(num_layers)
102
- print(f"Target layers: {[(d, i) for d, i in layers]}")
103
-
104
- tokenizer = model.tokenizer
105
-
106
- assert len(layers) == 4, f"Expected 4 depths, got {len(layers)}"
107
- li0, li1, li2, li3 = [idx for _, idx in layers]
108
-
109
- all_activations: dict[int, list[np.ndarray]] = {
110
- li0: [], li1: [], li2: [], li3: [],
111
- }
112
- all_positions: list[int] = []
113
-
114
- t_remote_total = 0.0
115
- t_wall_start = time.time()
116
-
117
- for i, sent in enumerate(sentences):
118
- tok_len = len(tokenizer(sent)["input_ids"])
119
- last_pos = tok_len - 1
120
- all_positions.append(last_pos)
121
-
122
- t_sub = time.time()
123
-
124
- # NNsight 0.7 does not trace Python for-loops inside the
125
- # context manager — .save() calls inside a loop are silently
126
- # dropped. Unroll the four depths explicitly.
127
- with model.trace(sent, remote=True):
128
- s0 = model.model.layers[li0].output[0].save()
129
- s1 = model.model.layers[li1].output[0].save()
130
- s2 = model.model.layers[li2].output[0].save()
131
- s3 = model.model.layers[li3].output[0].save()
132
-
133
- t_remote_total += time.time() - t_sub
134
-
135
- for li, tensor in [(li0, s0), (li1, s1), (li2, s2), (li3, s3)]:
136
- t = tensor[0] if tensor.dim() == 3 else tensor
137
- vec = t[last_pos, :].detach().cpu().float().numpy()
138
- all_activations[li].append(vec)
139
-
140
- if (i + 1) % 10 == 0 or i == 0:
141
- elapsed = time.time() - t_wall_start
142
- print(f" {i+1}/{len(sentences)} "
143
- f"({elapsed:.0f}s elapsed, "
144
- f"~{elapsed/(i+1):.2f}s/sent)")
145
-
146
- t_wall_total = time.time() - t_wall_start
147
-
148
- activation_arrays = {}
149
- for layer_idx, vecs in all_activations.items():
150
- arr = np.stack(vecs).astype(np.float16)
151
- activation_arrays[layer_idx] = arr
152
- print(f" Layer {layer_idx}: shape={arr.shape}, dtype={arr.dtype}")
153
-
154
- timing = {
155
- "model_id": model_id,
156
- "model_key": model_key,
157
- "num_layers": num_layers,
158
- "hidden_dim": hidden_dim,
159
- "sentences_processed": len(sentences),
160
- "model_init_seconds": round(t_init, 2),
161
- "remote_execution_seconds": round(t_remote_total, 2),
162
- "total_wall_clock_seconds": round(t_wall_total, 2),
163
- "seconds_per_sentence": round(t_wall_total / len(sentences), 3),
164
- }
165
-
166
- return {
167
- "activations": activation_arrays,
168
- "positions": all_positions,
169
- "layers": layers,
170
- "timing": timing,
171
- }
172
-
173
-
174
- def save_activations(
175
- result: dict[str, Any],
176
- output_dir: Path,
177
- model_key: str,
178
- df: pd.DataFrame,
179
- dataset_hash: str,
180
- ) -> None:
181
- model_dir = output_dir / model_key
182
- model_dir.mkdir(parents=True, exist_ok=True)
183
-
184
- for layer_idx, arr in result["activations"].items():
185
- np.save(model_dir / f"layer_{layer_idx}.npy", arr)
186
-
187
- sample_index = df[["example_id", "pair_id", "case_id", "relation_id",
188
- "subject", "label", "subset"]].copy()
189
- sample_index["token_position"] = result["positions"]
190
- sample_index.to_parquet(model_dir / "sample_index.parquet", index=False)
191
-
192
- manifest = {
193
- **result["timing"],
194
- "target_layers": [
195
- {"depth": d, "layer_index": i} for d, i in result["layers"]
196
- ],
197
- "activation_shapes": {
198
- str(idx): list(arr.shape)
199
- for idx, arr in result["activations"].items()
200
- },
201
- "activation_dtype": "float16",
202
- "dataset_hash": dataset_hash,
203
- "token_position_strategy": "last_real_token (= final subtoken of target attribute)",
204
- }
205
- (model_dir / "manifest.json").write_text(
206
- json.dumps(manifest, indent=2) + "\n", encoding="utf-8"
207
- )
208
-
209
-
210
- def run_pilot(api_key: str) -> None:
211
- print("=" * 60)
212
- print(f"PILOT TIMING: relation={PILOT_RELATION}, subset=N50")
213
- print("=" * 60)
214
-
215
- df = load_sentences("N50", PILOT_RELATION)
216
- sentences = df["sentence"].tolist()
217
- print(f"Loaded {len(sentences)} pilot sentences")
218
-
219
- dataset_hash = hashlib.sha256(
220
- "\n".join(sentences).encode()
221
- ).hexdigest()[:16]
222
-
223
- all_timing = {}
224
-
225
- for model_key, model_id in MODELS.items():
226
- result = extract_for_model(model_key, model_id, sentences, api_key)
227
- all_timing[model_key] = result["timing"]
228
-
229
- save_activations(result, PILOT_DIR, model_key, df, dataset_hash)
230
- print(f"\nSaved pilot activations to {PILOT_DIR / model_key}")
231
-
232
- print("\n" + "=" * 60)
233
- print("PILOT TIMING SUMMARY")
234
- print("=" * 60)
235
-
236
- for mk, t in all_timing.items():
237
- print(f"\n {mk}:")
238
- print(f" Wall clock: {t['total_wall_clock_seconds']:.1f}s")
239
- print(f" Remote exec: {t['remote_execution_seconds']:.1f}s")
240
- print(f" Per sentence: {t['seconds_per_sentence']:.3f}s")
241
- print(f" Sentences: {t['sentences_processed']}")
242
-
243
- total_8b = all_timing["llama_3_1_8b"]["total_wall_clock_seconds"]
244
- total_70b = all_timing["llama_3_1_70b"]["total_wall_clock_seconds"]
245
-
246
- print("\n Estimated full extraction times:")
247
- for label, n_pairs in [("N50", 50), ("N75", 75), ("N100", 100)]:
248
- multiplier = (6 * n_pairs * 2) / 100
249
- est_8b = total_8b * multiplier
250
- est_70b = total_70b * multiplier
251
- est_total = est_8b + est_70b
252
- print(f" {label}: 8B={est_8b/60:.0f}min + 70B={est_70b/60:.0f}min "
253
- f"= {est_total/60:.0f}min total")
254
-
255
- decision_path = ROOT / "sample_size_decision.json"
256
- decision = {
257
- "pilot_relation": PILOT_RELATION,
258
- "pilot_subset": "N50",
259
- "pilot_sentences": len(sentences),
260
- "pilot_timing": all_timing,
261
- "estimated_full_extraction": {},
262
- }
263
- for label, n_pairs in [("N50", 50), ("N75", 75), ("N100", 100)]:
264
- mult = (6 * n_pairs * 2) / 100
265
- decision["estimated_full_extraction"][label] = {
266
- "sentences": 6 * n_pairs * 2,
267
- "multiplier": mult,
268
- "estimated_8b_seconds": round(total_8b * mult, 1),
269
- "estimated_70b_seconds": round(total_70b * mult, 1),
270
- "estimated_total_seconds": round((total_8b + total_70b) * mult, 1),
271
- }
272
- decision_path.write_text(json.dumps(decision, indent=2) + "\n", encoding="utf-8")
273
- print(f"\nSaved timing decision to {decision_path}")
274
-
275
-
276
- def run_full(api_key: str, subset: str) -> None:
277
- print("=" * 60)
278
- print(f"FULL EXTRACTION: subset={subset}, all relations")
279
- print("=" * 60)
280
-
281
- df = load_sentences(subset)
282
- sentences = df["sentence"].tolist()
283
- print(f"Loaded {len(sentences)} sentences across {df['relation_id'].nunique()} relations")
284
-
285
- dataset_hash = hashlib.sha256(
286
- "\n".join(sentences).encode()
287
- ).hexdigest()[:16]
288
-
289
- for model_key, model_id in MODELS.items():
290
- result = extract_for_model(model_key, model_id, sentences, api_key)
291
- out_dir = ACTIVATIONS_DIR / model_key
292
- save_activations(result, ACTIVATIONS_DIR, model_key, df, dataset_hash)
293
- print(f"\nSaved activations to {out_dir}")
294
-
295
-
296
- def main() -> None:
297
- parser = argparse.ArgumentParser()
298
- group = parser.add_mutually_exclusive_group(required=True)
299
- group.add_argument("--pilot", action="store_true",
300
- help="Run pilot timing with one relation")
301
- group.add_argument("--subset", choices=["N50", "N75", "N100"],
302
- help="Run full extraction for this subset")
303
- args = parser.parse_args()
304
-
305
- api_key = load_env()
306
-
307
- if args.pilot:
308
- run_pilot(api_key)
309
- else:
310
- run_full(api_key, args.subset)
311
-
312
-
313
- if __name__ == "__main__":
314
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
phase2_scaling/generate_figures.py DELETED
@@ -1,389 +0,0 @@
1
- """Generate Phase 2 publication figures.
2
-
3
- Run from workspace/reproduction/scaling/ under the blackboxnlp conda env:
4
- python generate_figures.py
5
- """
6
- from __future__ import annotations
7
-
8
- import json
9
- from pathlib import Path
10
-
11
- import matplotlib
12
- matplotlib.use("Agg")
13
- import matplotlib.pyplot as plt
14
- import matplotlib.ticker as mticker
15
- import numpy as np
16
- import pandas as pd
17
- from matplotlib.colors import LinearSegmentedColormap
18
-
19
- ROOT = Path(__file__).resolve().parent
20
- RESULTS_DIR = ROOT / "results"
21
- FIGURES_DIR = ROOT / "figures"
22
- FIGURES_DIR.mkdir(exist_ok=True)
23
-
24
- RELATION_ORDER = ["P19", "P103", "P101", "P159", "P176", "P138"]
25
- RELATION_LABELS = {
26
- "P19": "P19\nplace of birth",
27
- "P103": "P103\nnative language",
28
- "P101": "P101\nfield of work",
29
- "P159": "P159\nHQ location",
30
- "P176": "P176\nmanufacturer",
31
- "P138": "P138\nnamed after",
32
- }
33
- RELATION_SHORT = {
34
- "P19": "P19",
35
- "P103": "P103",
36
- "P101": "P101",
37
- "P159": "P159",
38
- "P176": "P176",
39
- "P138": "P138",
40
- }
41
-
42
- C_8B = "#2a78d6"
43
- C_70B = "#1baf7a"
44
- C_8B_LIGHT = "#86b6ef"
45
- C_70B_LIGHT = "#7dd4b0"
46
-
47
- DEPTHS = [0.25, 0.5, 0.75, 1.0]
48
- DEPTH_LABELS = ["25%", "50%", "75%", "100%"]
49
-
50
-
51
- def setup_style():
52
- plt.rcParams.update({
53
- "font.family": "sans-serif",
54
- "font.sans-serif": ["Segoe UI", "Arial", "Helvetica", "sans-serif"],
55
- "font.size": 9,
56
- "axes.titlesize": 10,
57
- "axes.labelsize": 9,
58
- "xtick.labelsize": 8,
59
- "ytick.labelsize": 8,
60
- "legend.fontsize": 8,
61
- "figure.dpi": 300,
62
- "savefig.dpi": 300,
63
- "savefig.bbox": "tight",
64
- "savefig.pad_inches": 0.05,
65
- "axes.spines.top": False,
66
- "axes.spines.right": False,
67
- "axes.linewidth": 0.6,
68
- "xtick.major.width": 0.6,
69
- "ytick.major.width": 0.6,
70
- "axes.grid": True,
71
- "grid.alpha": 0.3,
72
- "grid.linewidth": 0.5,
73
- "lines.linewidth": 1.8,
74
- "lines.markersize": 6,
75
- })
76
-
77
-
78
- def load_data():
79
- gap = pd.read_csv(RESULTS_DIR / "generality_gap.csv")
80
- with open(RESULTS_DIR / "selected_layers.json") as f:
81
- selected = json.load(f)
82
- matrix_8b = pd.read_csv(RESULTS_DIR / "stage2_matrix_8b.csv", index_col=0)
83
- matrix_70b = pd.read_csv(RESULTS_DIR / "stage2_matrix_70b.csv", index_col=0)
84
- return gap, selected, matrix_8b, matrix_70b
85
-
86
-
87
- def fig1_depth_profile(gap: pd.DataFrame, selected: dict):
88
- """Within-relation and LOO AUC across depths for both models."""
89
- fig, ax = plt.subplots(figsize=(4.5, 3.2))
90
-
91
- for model_key, color, label in [
92
- ("llama_3_1_8b", C_8B, "8B"),
93
- ("llama_3_1_70b", C_70B, "70B"),
94
- ]:
95
- m = gap[gap["model_key"] == model_key]
96
-
97
- within_means = []
98
- within_stds = []
99
- loo_means = []
100
- loo_stds = []
101
- for d in DEPTHS:
102
- depth_data = m[m["normalized_depth"] == d]
103
- within_means.append(depth_data["within_mean_auc"].mean())
104
- within_stds.append(depth_data["within_mean_auc"].std())
105
- loo_means.append(depth_data["loo_auc"].mean())
106
- loo_stds.append(depth_data["loo_auc"].std())
107
-
108
- x = np.arange(len(DEPTHS))
109
-
110
- ax.errorbar(x, within_means, yerr=within_stds, color=color,
111
- marker="o", linestyle="-", label=f"{label} within",
112
- capsize=3, capthick=1.2, markeredgecolor="white",
113
- markeredgewidth=1)
114
- ax.errorbar(x, loo_means, yerr=loo_stds, color=color,
115
- marker="s", linestyle="--", label=f"{label} leave-one-out",
116
- capsize=3, capthick=1.2, markeredgecolor="white",
117
- markeredgewidth=1)
118
-
119
- best_8b_idx = DEPTHS.index(selected["llama_3_1_8b"]["normalized_depth"])
120
- best_70b_idx = DEPTHS.index(selected["llama_3_1_70b"]["normalized_depth"])
121
- ax.axvline(best_8b_idx, color=C_8B, alpha=0.15, linewidth=8, zorder=0)
122
- ax.axvline(best_70b_idx, color=C_70B, alpha=0.15, linewidth=8, zorder=0)
123
-
124
- ax.set_xticks(range(len(DEPTHS)))
125
- ax.set_xticklabels(DEPTH_LABELS)
126
- ax.set_xlabel("Normalized depth")
127
- ax.set_ylabel("ROC-AUC")
128
- ax.set_ylim(0.88, 1.005)
129
- ax.yaxis.set_major_formatter(mticker.FormatStrFormatter("%.2f"))
130
- ax.legend(loc="lower left", framealpha=0.9, edgecolor="none")
131
- ax.set_title("Within-relation and leave-one-out AUC by depth")
132
-
133
- fig.tight_layout()
134
- fig.savefig(FIGURES_DIR / "fig1_depth_profile.pdf")
135
- fig.savefig(FIGURES_DIR / "fig1_depth_profile.png")
136
- plt.close(fig)
137
- print(" fig1_depth_profile.pdf")
138
-
139
-
140
- def fig2_generality_gap(gap: pd.DataFrame, selected: dict):
141
- """Mean absolute generality gap by depth for both models."""
142
- fig, ax = plt.subplots(figsize=(4.0, 3.0))
143
-
144
- bar_width = 0.35
145
- x = np.arange(len(DEPTHS))
146
-
147
- for i, (model_key, color, label) in enumerate([
148
- ("llama_3_1_8b", C_8B, "8B"),
149
- ("llama_3_1_70b", C_70B, "70B"),
150
- ]):
151
- m = gap[gap["model_key"] == model_key]
152
- mean_abs_gaps = []
153
- for d in DEPTHS:
154
- depth_data = m[m["normalized_depth"] == d]
155
- mean_abs_gaps.append(depth_data["generality_gap"].abs().mean())
156
-
157
- offset = (i - 0.5) * bar_width
158
- bars = ax.bar(x + offset, mean_abs_gaps, bar_width * 0.88,
159
- color=color, alpha=0.85, label=label,
160
- edgecolor="white", linewidth=0.5)
161
- for bar, val in zip(bars, mean_abs_gaps):
162
- ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.001,
163
- f"{val:.3f}", ha="center", va="bottom", fontsize=7,
164
- color="#52514e")
165
-
166
- ax.set_xticks(x)
167
- ax.set_xticklabels(DEPTH_LABELS)
168
- ax.set_xlabel("Normalized depth")
169
- ax.set_ylabel("Mean |generality gap|")
170
- ax.set_ylim(0, 0.06)
171
- ax.legend(framealpha=0.9, edgecolor="none")
172
- ax.set_title("Generality gap: 8B vs 70B")
173
-
174
- fig.tight_layout()
175
- fig.savefig(FIGURES_DIR / "fig2_generality_gap.pdf")
176
- fig.savefig(FIGURES_DIR / "fig2_generality_gap.png")
177
- plt.close(fig)
178
- print(" fig2_generality_gap.pdf")
179
-
180
-
181
- def _draw_heatmap(ax, matrix: pd.DataFrame, title: str, vmin: float, vmax: float,
182
- cmap, show_cbar: bool = False):
183
- """Draw a single transfer matrix heatmap."""
184
- ordered = matrix.loc[RELATION_ORDER, RELATION_ORDER].astype(float)
185
- data = ordered.values
186
-
187
- im = ax.imshow(data, cmap=cmap, vmin=vmin, vmax=vmax, aspect="equal")
188
-
189
- n = len(RELATION_ORDER)
190
- for i in range(n):
191
- for j in range(n):
192
- val = data[i, j]
193
- text_color = "white" if val > 0.97 else "#0b0b0b"
194
- weight = "bold" if i == j else "normal"
195
- ax.text(j, i, f"{val:.3f}", ha="center", va="center",
196
- fontsize=7, color=text_color, fontweight=weight)
197
-
198
- ax.set_xticks(range(n))
199
- ax.set_yticks(range(n))
200
- short_labels = [RELATION_SHORT[r] for r in RELATION_ORDER]
201
- ax.set_xticklabels(short_labels, fontsize=8)
202
- ax.set_yticklabels(short_labels, fontsize=8)
203
- ax.set_xlabel("Target relation", fontsize=9)
204
- ax.set_ylabel("Source relation", fontsize=9)
205
- ax.set_title(title, fontsize=10, pad=8)
206
-
207
- ax.spines[:].set_visible(True)
208
- ax.spines[:].set_linewidth(0.5)
209
- ax.spines[:].set_color("#c3c2b7")
210
- ax.tick_params(length=0)
211
-
212
- return im
213
-
214
-
215
- def fig3_transfer_matrices(matrix_8b: pd.DataFrame, matrix_70b: pd.DataFrame):
216
- """Side-by-side 6×6 transfer matrix heatmaps."""
217
- blues = LinearSegmentedColormap.from_list("custom_blues", [
218
- "#cde2fb", "#86b6ef", "#3987e5", "#1c5cab", "#104281"
219
- ])
220
-
221
- fig = plt.figure(figsize=(9.5, 3.8))
222
- gs = fig.add_gridspec(1, 3, width_ratios=[1, 1, 0.05], wspace=0.3)
223
- ax1 = fig.add_subplot(gs[0, 0])
224
- ax2 = fig.add_subplot(gs[0, 1])
225
- cax = fig.add_subplot(gs[0, 2])
226
-
227
- _draw_heatmap(ax1, matrix_8b, "Llama-3.1-8B (layer 7, depth 25%)",
228
- vmin=0.84, vmax=1.0, cmap=blues)
229
- im = _draw_heatmap(ax2, matrix_70b, "Llama-3.1-70B (layer 39, depth 50%)",
230
- vmin=0.84, vmax=1.0, cmap=blues)
231
-
232
- cbar = fig.colorbar(im, cax=cax)
233
- cbar.set_label("ROC-AUC", fontsize=9)
234
- cbar.ax.tick_params(labelsize=8)
235
- cbar.outline.set_linewidth(0.5)
236
-
237
- fig.savefig(FIGURES_DIR / "fig3_transfer_matrices.pdf")
238
- fig.savefig(FIGURES_DIR / "fig3_transfer_matrices.png")
239
- plt.close(fig)
240
- print(" fig3_transfer_matrices.pdf")
241
-
242
-
243
- def _fmt_gap(val: float) -> str:
244
- if abs(val) < 0.0005:
245
- return "0.000"
246
- return f"{val:+.3f}"
247
-
248
-
249
- def fig4_relation_gap_detail(gap: pd.DataFrame, selected: dict):
250
- """Per-relation generality gap at the selected layer for each model."""
251
- fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(7.5, 3.0))
252
-
253
- n = len(RELATION_ORDER)
254
- y_positions = np.arange(n)
255
-
256
- for ax, model_key, color, title, layer_depth in [
257
- (ax1, "llama_3_1_8b", C_8B, "8B (layer 7)", 0.25),
258
- (ax2, "llama_3_1_70b", C_70B, "70B (layer 39)", 0.5),
259
- ]:
260
- m = gap[(gap["model_key"] == model_key) &
261
- (gap["normalized_depth"] == layer_depth)]
262
- m = m.set_index("target_relation").loc[RELATION_ORDER]
263
-
264
- gaps = m["generality_gap"].values
265
-
266
- colors = [color if g >= 0 else "#e34948" for g in gaps]
267
- bars = ax.barh(y_positions, gaps, height=0.6, color=colors, alpha=0.8,
268
- edgecolor="white", linewidth=0.5)
269
-
270
- for bar, val in zip(bars, gaps):
271
- x_pos = val + 0.002 if val >= 0 else val - 0.002
272
- ha = "left" if val >= 0 else "right"
273
- ax.text(x_pos, bar.get_y() + bar.get_height() / 2,
274
- _fmt_gap(val), ha=ha, va="center", fontsize=7,
275
- color="#52514e")
276
-
277
- ax.set_yticks(y_positions)
278
- ax.set_yticklabels(RELATION_ORDER, fontsize=8)
279
- ax.axvline(0, color="#c3c2b7", linewidth=0.8, zorder=0)
280
- ax.set_xlabel("Generality gap (within − leave-one-out)", fontsize=8)
281
- ax.set_title(title, fontsize=10)
282
- ax.set_xlim(-0.035, 0.065)
283
- ax.set_ylim(n - 0.5, -0.5)
284
-
285
- fig.suptitle("Per-relation generality gap at selected layer",
286
- fontsize=10)
287
- fig.tight_layout(rect=[0, 0, 1, 0.95])
288
- fig.savefig(FIGURES_DIR / "fig4_relation_gap_detail.pdf")
289
- fig.savefig(FIGURES_DIR / "fig4_relation_gap_detail.png")
290
- plt.close(fig)
291
- print(" fig4_relation_gap_detail.pdf")
292
-
293
-
294
- def fig5_relation_depth_profiles(gap: pd.DataFrame):
295
- """Small multiples: each relation's within AUC trajectory across depths."""
296
- fig, axes = plt.subplots(2, 3, figsize=(8, 4.5), sharex=True, sharey=True)
297
-
298
- for idx, rel in enumerate(RELATION_ORDER):
299
- ax = axes[idx // 3, idx % 3]
300
-
301
- for model_key, color, label in [
302
- ("llama_3_1_8b", C_8B, "8B"),
303
- ("llama_3_1_70b", C_70B, "70B"),
304
- ]:
305
- m = gap[(gap["model_key"] == model_key) &
306
- (gap["target_relation"] == rel)]
307
- m = m.sort_values("normalized_depth")
308
- x = np.arange(len(DEPTHS))
309
- ax.plot(x, m["within_mean_auc"].values, color=color,
310
- marker="o", markersize=4, label=f"{label} within",
311
- markeredgecolor="white", markeredgewidth=0.8)
312
- ax.plot(x, m["loo_auc"].values, color=color,
313
- marker="s", markersize=4, linestyle="--",
314
- label=f"{label} leave-one-out",
315
- markeredgecolor="white", markeredgewidth=0.8)
316
-
317
- ax.set_title(f"{rel}", fontsize=9, fontweight="bold")
318
- ax.set_xticks(range(len(DEPTHS)))
319
- ax.set_xticklabels(DEPTH_LABELS, fontsize=7)
320
- ax.set_ylim(0.80, 1.01)
321
- ax.yaxis.set_major_formatter(mticker.FormatStrFormatter("%.2f"))
322
-
323
- if idx == 0:
324
- ax.legend(fontsize=6, loc="lower left", framealpha=0.9,
325
- edgecolor="none")
326
-
327
- fig.supxlabel("Normalized depth", fontsize=9)
328
- fig.supylabel("ROC-AUC", fontsize=9)
329
- fig.suptitle("Per-relation AUC profiles", fontsize=10, y=1.0)
330
- fig.tight_layout()
331
- fig.savefig(FIGURES_DIR / "fig5_relation_profiles.pdf")
332
- fig.savefig(FIGURES_DIR / "fig5_relation_profiles.png")
333
- plt.close(fig)
334
- print(" fig5_relation_profiles.pdf")
335
-
336
-
337
- def table1_relation_results(gap: pd.DataFrame, selected: dict):
338
- """Relation-level table at selected layers."""
339
- rows = []
340
- for rel in RELATION_ORDER:
341
- row = {"Relation": rel}
342
- for model_key, short, depth in [
343
- ("llama_3_1_8b", "8B", 0.25),
344
- ("llama_3_1_70b", "70B", 0.5),
345
- ]:
346
- m = gap[(gap["model_key"] == model_key) &
347
- (gap["normalized_depth"] == depth) &
348
- (gap["target_relation"] == rel)]
349
- row[f"{short} within"] = f"{m['within_mean_auc'].values[0]:.3f}"
350
- row[f"{short} std"] = f"{m['within_std_auc'].values[0]:.3f}"
351
- row[f"{short} leave-one-out"] = f"{m['loo_auc'].values[0]:.3f}"
352
- row[f"{short} gap"] = _fmt_gap(m['generality_gap'].values[0])
353
- rows.append(row)
354
-
355
- mean_row = {"Relation": "Mean"}
356
- for model_key, short, depth in [
357
- ("llama_3_1_8b", "8B", 0.25),
358
- ("llama_3_1_70b", "70B", 0.5),
359
- ]:
360
- m = gap[(gap["model_key"] == model_key) &
361
- (gap["normalized_depth"] == depth)]
362
- mean_row[f"{short} within"] = f"{m['within_mean_auc'].mean():.3f}"
363
- mean_row[f"{short} std"] = f"{m['within_std_auc'].mean():.3f}"
364
- mean_row[f"{short} leave-one-out"] = f"{m['loo_auc'].mean():.3f}"
365
- mean_row[f"{short} gap"] = _fmt_gap(m['generality_gap'].mean())
366
- rows.append(mean_row)
367
-
368
- table = pd.DataFrame(rows)
369
- table.to_csv(RESULTS_DIR / "table1_relation_results.csv", index=False)
370
- print(" table1_relation_results.csv")
371
- print(table.to_string(index=False))
372
-
373
-
374
- def main():
375
- setup_style()
376
- gap, selected, matrix_8b, matrix_70b = load_data()
377
-
378
- print("Generating figures...")
379
- fig1_depth_profile(gap, selected)
380
- fig2_generality_gap(gap, selected)
381
- fig3_transfer_matrices(matrix_8b, matrix_70b)
382
- fig4_relation_gap_detail(gap, selected)
383
- fig5_relation_depth_profiles(gap)
384
- table1_relation_results(gap, selected)
385
- print("\nAll figures saved to figures/")
386
-
387
-
388
- if __name__ == "__main__":
389
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
phase2_scaling/generate_splits.py DELETED
@@ -1,106 +0,0 @@
1
- """Generate 3-fold pair-grouped cross-validation splits for N100.
2
-
3
- True/false examples from the same pair are always in the same fold.
4
- Downstream code joins on example_id, never on row index.
5
-
6
- Run from workspace/reproduction/scaling/ under the blackboxnlp conda env:
7
- python generate_splits.py
8
- """
9
-
10
- from __future__ import annotations
11
-
12
- import json
13
- from pathlib import Path
14
-
15
- import numpy as np
16
- import pandas as pd
17
-
18
- SEED = 20260712_03
19
- ROOT = Path(__file__).resolve().parent
20
- DATA_PATH = ROOT / "data" / "processed" / "examples.parquet"
21
- OUTPUT_PATH = ROOT / "data" / "processed" / "splits.parquet"
22
-
23
- N_FOLDS = 3
24
-
25
-
26
- def main() -> None:
27
- df = pd.read_parquet(DATA_PATH)
28
- df = df[df["subset"] == "N100"]
29
- print(f"Loaded {len(df)} N100 examples across "
30
- f"{df['relation_id'].nunique()} relations")
31
-
32
- rng = np.random.RandomState(SEED)
33
-
34
- fold_assignments: list[dict] = []
35
-
36
- for rel in sorted(df["relation_id"].unique()):
37
- rel_df = df[df["relation_id"] == rel]
38
- pairs = sorted(rel_df[rel_df["label"] == 1]["case_id"].unique())
39
- n_pairs = len(pairs)
40
-
41
- shuffled = rng.permutation(pairs)
42
- folds = np.array_split(shuffled, N_FOLDS)
43
- fold_sizes = [len(f) for f in folds]
44
-
45
- pair_to_fold = {}
46
- for fold_idx, fold_pairs in enumerate(folds):
47
- for case_id in fold_pairs:
48
- pair_to_fold[case_id] = fold_idx
49
-
50
- for _, row in rel_df.iterrows():
51
- fold_assignments.append({
52
- "example_id": row["example_id"],
53
- "pair_id": row["pair_id"],
54
- "case_id": row["case_id"],
55
- "relation_id": row["relation_id"],
56
- "within_relation_fold": pair_to_fold[row["case_id"]],
57
- })
58
-
59
- print(f" {rel}: {n_pairs} pairs -> folds {fold_sizes}")
60
-
61
- splits = pd.DataFrame(fold_assignments)
62
-
63
- # --- Validation ---
64
- errors = []
65
-
66
- for rel in splits["relation_id"].unique():
67
- rel_splits = splits[splits["relation_id"] == rel]
68
-
69
- for case_id in rel_splits["case_id"].unique():
70
- pair_rows = rel_splits[rel_splits["case_id"] == case_id]
71
- if pair_rows["within_relation_fold"].nunique() != 1:
72
- errors.append(f"{rel} case_id={case_id}: pair split across folds")
73
-
74
- fold_counts = rel_splits.groupby("within_relation_fold").size()
75
- if len(fold_counts) != N_FOLDS:
76
- errors.append(f"{rel}: expected {N_FOLDS} folds, got {len(fold_counts)}")
77
-
78
- joined = splits.merge(
79
- df[["example_id", "label"]], on="example_id", how="left"
80
- )
81
- for rel in splits["relation_id"].unique():
82
- rel_j = joined[joined["relation_id"] == rel]
83
- for fold in range(N_FOLDS):
84
- fold_j = rel_j[rel_j["within_relation_fold"] == fold]
85
- n_true = (fold_j["label"] == 1).sum()
86
- n_false = (fold_j["label"] == 0).sum()
87
- if n_true != n_false:
88
- errors.append(f"{rel} fold {fold}: {n_true} true vs {n_false} false")
89
-
90
- if errors:
91
- for e in errors:
92
- print(f" ERROR: {e}")
93
- raise RuntimeError("Split validation failed")
94
-
95
- print(f"\nValidation passed:")
96
- print(f" All pairs have true/false in same fold")
97
- print(f" All relations have {N_FOLDS} folds")
98
- print(f" Class balance OK within every fold")
99
-
100
- splits.to_parquet(OUTPUT_PATH, index=False, engine="pyarrow")
101
- print(f"\nSaved {len(splits)} rows to {OUTPUT_PATH}")
102
- print(f"Split seed: {SEED}")
103
-
104
-
105
- if __name__ == "__main__":
106
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
phase2_scaling/ndif_smoke_test.py DELETED
@@ -1,77 +0,0 @@
1
- """Minimal remote Llama-3.1-8B test using NNsight and NDIF.
2
-
3
- Before running:
4
- 1. Put NDIF_API_KEY and HF_TOKEN in the adjacent .env file.
5
- 2. Ensure the Hugging Face account behind HF_TOKEN has Meta Llama 3.1 access.
6
- 3. Install the workspace requirements.
7
-
8
- Run from workspace/reproduction/scaling:
9
- python ndif_smoke_test.py
10
-
11
- This script sends one short prompt to NDIF. It does not download or run
12
- Llama weights on the local computer.
13
- """
14
-
15
- from __future__ import annotations
16
-
17
- import os
18
- from pathlib import Path
19
-
20
-
21
- def load_local_env(env_path: Path) -> None:
22
- """Load simple KEY=VALUE entries without adding a python-dotenv dependency."""
23
- if not env_path.exists():
24
- raise FileNotFoundError(f"Missing credentials file: {env_path}")
25
-
26
- for raw_line in env_path.read_text(encoding="utf-8").splitlines():
27
- line = raw_line.strip()
28
- if not line or line.startswith("#"):
29
- continue
30
- if "=" not in line:
31
- raise ValueError(f"Invalid .env line: {raw_line!r}")
32
-
33
- key, value = line.split("=", 1)
34
- os.environ.setdefault(key.strip(), value.strip())
35
-
36
-
37
- def require_secret(name: str) -> str:
38
- value = os.environ.get(name, "").strip()
39
- if not value or value.startswith("PASTE_YOUR_"):
40
- raise RuntimeError(
41
- f"Set {name} in .env before running this script. "
42
- "Do not paste the key into Python code or commit it to Git."
43
- )
44
- return value
45
-
46
-
47
- def main() -> None:
48
- load_local_env(Path(__file__).with_name(".env"))
49
-
50
- ndif_api_key = require_secret("NDIF_API_KEY")
51
- require_secret("HF_TOKEN")
52
- from nnsight import CONFIG, LanguageModel
53
-
54
- # The key is read from the local environment, never written into source code.
55
- CONFIG.set_default_api_key(ndif_api_key)
56
-
57
- print("Creating the lightweight local model definition...")
58
- # This exact ID is currently listed by ndif_status() as a running model.
59
- model = LanguageModel("meta-llama/Llama-3.1-8B")
60
-
61
- prompt = "The Eiffel Tower is located in"
62
- print("Submitting one remote NDIF trace for Llama-3.1-8B...")
63
- with model.trace(prompt, remote=True):
64
- # Save the final layer's small sequence tensor. Indexing is performed
65
- # locally below because this NDIF deployment does not whitelist the
66
- # internal module NNsight uses to serialize remote tensor slicing.
67
- hidden_sequence = model.model.layers[-1].output[0].save()
68
-
69
- hidden = hidden_sequence[-1, :]
70
-
71
- print("Success: NDIF returned one hidden representation.")
72
- print(f"Returned shape: {tuple(hidden.shape)}")
73
- print(f"Returned dtype: {hidden.dtype}")
74
-
75
-
76
- if __name__ == "__main__":
77
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
phase2_scaling/prepare_counterfact_multirelation.py DELETED
@@ -1,552 +0,0 @@
1
- """Prepare multi-relation CounterFact dataset for Phase 2 scaling experiment.
2
-
3
- Processes six CounterFact relations into balanced true/false sentence pairs
4
- with derangement-based negative construction. Produces nested N50/N75/N100
5
- subsets for the timing-gate sample-size selection.
6
-
7
- Run from workspace/reproduction/scaling/ under the blackboxnlp conda env:
8
- python prepare_counterfact_multirelation.py
9
- """
10
-
11
- from __future__ import annotations
12
-
13
- import hashlib
14
- import json
15
- import random
16
- from collections import Counter, defaultdict
17
- from pathlib import Path
18
- from typing import Any
19
-
20
- import pandas as pd
21
-
22
- SEED = 20260712
23
-
24
- RELATIONS = ["P19", "P103", "P176", "P101", "P159", "P138"]
25
- RELATION_NAMES = {
26
- "P19": "place of birth",
27
- "P103": "native language",
28
- "P176": "manufacturer",
29
- "P101": "field of work",
30
- "P159": "headquarters location",
31
- "P138": "named after",
32
- }
33
-
34
- SUBSET_SIZES = [("N50", 50), ("N75", 75), ("N100", 100)]
35
-
36
- P103_FRENCH_CAPS = {"N50": 20, "N75": 30, "N100": 40}
37
-
38
- ROOT = Path(__file__).resolve().parent
39
- RAW_PATH = ROOT / "data" / "raw" / "counterfact.json"
40
- OUTPUT_DIR = ROOT / "data" / "processed"
41
-
42
-
43
- def make_sentence(template: str, subject: str, attribute: str) -> str:
44
- return f"{template.format(subject).rstrip()} {attribute.strip()}"
45
-
46
-
47
- def load_raw(path: Path) -> list[dict]:
48
- if not path.exists():
49
- raise FileNotFoundError(f"Raw CounterFact not found: {path}")
50
- with path.open("r", encoding="utf-8") as f:
51
- return json.load(f)
52
-
53
-
54
- def relation_seed(rel: str) -> int:
55
- return SEED + RELATIONS.index(rel) * 10007
56
-
57
-
58
- # ---------------------------------------------------------------------------
59
- # Cleaning
60
- # ---------------------------------------------------------------------------
61
-
62
- def filter_relations(records: list[dict]) -> dict[str, list[dict]]:
63
- by_rel: dict[str, list[dict]] = defaultdict(list)
64
- for r in records:
65
- rel = r["requested_rewrite"]["relation_id"]
66
- if rel in RELATIONS:
67
- by_rel[rel].append(r)
68
- return dict(by_rel)
69
-
70
-
71
- def dedup_subjects(records: list[dict]) -> list[dict]:
72
- """Keep lowest case_id per subject."""
73
- sorted_recs = sorted(records, key=lambda r: r["case_id"])
74
- seen: set[str] = set()
75
- out = []
76
- for r in sorted_recs:
77
- subj = r["requested_rewrite"]["subject"]
78
- if subj not in seen:
79
- seen.add(subj)
80
- out.append(r)
81
- return out
82
-
83
-
84
- def find_cross_relation_subjects(
85
- by_rel: dict[str, list[dict]],
86
- ) -> set[str]:
87
- subj_rels: dict[str, set[str]] = defaultdict(set)
88
- for rel, recs in by_rel.items():
89
- for r in recs:
90
- subj_rels[r["requested_rewrite"]["subject"]].add(rel)
91
- return {s for s, rels in subj_rels.items() if len(rels) > 1}
92
-
93
-
94
- def remove_subjects(records: list[dict], subjects: set[str]) -> list[dict]:
95
- return [r for r in records if r["requested_rewrite"]["subject"] not in subjects]
96
-
97
-
98
- def dedup_sentences(records: list[dict]) -> list[dict]:
99
- seen: set[str] = set()
100
- out = []
101
- for r in records:
102
- rw = r["requested_rewrite"]
103
- sent = make_sentence(rw["prompt"], rw["subject"], rw["target_true"]["str"])
104
- if sent not in seen:
105
- seen.add(sent)
106
- out.append(r)
107
- return out
108
-
109
-
110
- # ---------------------------------------------------------------------------
111
- # Sampling
112
- # ---------------------------------------------------------------------------
113
-
114
- def sample_nested(
115
- records: list[dict],
116
- rel: str,
117
- ) -> dict[str, list[dict]]:
118
- if rel == "P103":
119
- return _sample_p103(records)
120
-
121
- rng = random.Random(relation_seed(rel))
122
- pool = list(records)
123
- rng.shuffle(pool)
124
-
125
- subsets = {}
126
- for name, size in SUBSET_SIZES:
127
- if size > len(pool):
128
- raise ValueError(f"{rel}: need {size} records for {name}, have {len(pool)}")
129
- subsets[name] = sorted(pool[:size], key=lambda r: r["case_id"])
130
- return subsets
131
-
132
-
133
- def _sample_p103(records: list[dict]) -> dict[str, list[dict]]:
134
- french = [r for r in records if r["requested_rewrite"]["target_true"]["str"] == "French"]
135
- non_french = [r for r in records if r["requested_rewrite"]["target_true"]["str"] != "French"]
136
-
137
- base = relation_seed("P103")
138
- rng_fr = random.Random(base + 1)
139
- rng_oth = random.Random(base + 2)
140
- rng_fr.shuffle(french)
141
- rng_oth.shuffle(non_french)
142
-
143
- subsets = {}
144
- for name, size in SUBSET_SIZES:
145
- cap = P103_FRENCH_CAPS[name]
146
- n_other = size - cap
147
- if cap > len(french):
148
- raise ValueError(f"P103: need {cap} French for {name}, have {len(french)}")
149
- if n_other > len(non_french):
150
- raise ValueError(f"P103: need {n_other} non-French for {name}, have {len(non_french)}")
151
- selected = french[:cap] + non_french[:n_other]
152
- subsets[name] = sorted(selected, key=lambda r: r["case_id"])
153
- return subsets
154
-
155
-
156
- # ---------------------------------------------------------------------------
157
- # Derangement
158
- # ---------------------------------------------------------------------------
159
-
160
- def construct_derangement(
161
- records: list[dict],
162
- ) -> list[tuple[dict, str, int]]:
163
- """Attribute-shifted derangement.
164
-
165
- Sort records by (attribute, case_id), then shift indices by max group
166
- size. Since max_group <= n//2, the shifted block never overlaps the
167
- original block for any attribute, guaranteeing no self-match.
168
-
169
- Returns (record, false_attribute, source_case_id) for each record.
170
- """
171
- n = len(records)
172
- attrs = [r["requested_rewrite"]["target_true"]["str"] for r in records]
173
-
174
- sorted_idx = sorted(range(n), key=lambda i: (attrs[i], records[i]["case_id"]))
175
- sorted_attrs = [attrs[i] for i in sorted_idx]
176
-
177
- max_group = max(Counter(attrs).values())
178
- if max_group > n // 2:
179
- attr_counts = Counter(attrs).most_common(3)
180
- raise ValueError(
181
- f"Derangement impossible: max group {max_group} > n//2={n // 2}. "
182
- f"Top attributes: {attr_counts}"
183
- )
184
-
185
- shift = max_group
186
- result: list[tuple[dict, str, int]] = []
187
- for pos, orig_i in enumerate(sorted_idx):
188
- target_pos = (pos + shift) % n
189
- target_i = sorted_idx[target_pos]
190
- false_attr = attrs[target_i]
191
- assert false_attr != attrs[orig_i], (
192
- f"Self-match at pos {pos}: {false_attr}"
193
- )
194
- result.append((records[orig_i], false_attr, records[target_i]["case_id"]))
195
-
196
- return result
197
-
198
-
199
- # ---------------------------------------------------------------------------
200
- # Example construction
201
- # ---------------------------------------------------------------------------
202
-
203
- def build_examples(
204
- deranged: list[tuple[dict, str, int]],
205
- subset_name: str,
206
- ) -> list[dict]:
207
- examples = []
208
- for record, false_attr, source_case_id in deranged:
209
- rw = record["requested_rewrite"]
210
- cid = record["case_id"]
211
- subj = rw["subject"]
212
- tpl = rw["prompt"]
213
- true_attr = rw["target_true"]["str"]
214
- rel = rw["relation_id"]
215
-
216
- common = {
217
- "pair_id": f"{rel}_{subset_name}_{cid}",
218
- "case_id": cid,
219
- "relation_id": rel,
220
- "subject": subj,
221
- "template": tpl,
222
- "true_attribute": true_attr,
223
- "false_attribute_source_id": source_case_id,
224
- "subset": subset_name,
225
- }
226
- examples.append({
227
- **common,
228
- "example_id": f"{rel}_{subset_name}_{cid}_true",
229
- "used_attribute": true_attr,
230
- "sentence": make_sentence(tpl, subj, true_attr),
231
- "label": 1,
232
- })
233
- examples.append({
234
- **common,
235
- "example_id": f"{rel}_{subset_name}_{cid}_false",
236
- "used_attribute": false_attr,
237
- "sentence": make_sentence(tpl, subj, false_attr),
238
- "label": 0,
239
- })
240
- return examples
241
-
242
-
243
- # ---------------------------------------------------------------------------
244
- # Validation
245
- # ---------------------------------------------------------------------------
246
-
247
- def validate_subset(
248
- examples: list[dict],
249
- subset_name: str,
250
- rel: str,
251
- ) -> dict[str, Any]:
252
- true_ex = [e for e in examples if e["label"] == 1]
253
- false_ex = [e for e in examples if e["label"] == 0]
254
- errors: list[str] = []
255
-
256
- expected = dict(SUBSET_SIZES)[subset_name]
257
- if len(true_ex) != expected:
258
- errors.append(f"Expected {expected} pairs, got {len(true_ex)}")
259
- if len(true_ex) != len(false_ex):
260
- errors.append(f"Class imbalance: {len(true_ex)} true vs {len(false_ex)} false")
261
-
262
- ids = [e["example_id"] for e in examples]
263
- if len(ids) != len(set(ids)):
264
- errors.append("Duplicate example_ids")
265
-
266
- sents = [e["sentence"] for e in examples]
267
- if len(sents) != len(set(sents)):
268
- n_dup = len(sents) - len(set(sents))
269
- errors.append(f"{n_dup} duplicate sentences")
270
-
271
- subjects = [e["subject"] for e in true_ex]
272
- if len(subjects) != len(set(subjects)):
273
- errors.append("Duplicate subjects")
274
-
275
- for e in false_ex:
276
- if e["used_attribute"] == e["true_attribute"]:
277
- errors.append(f"false==true for case_id {e['case_id']}")
278
- break
279
-
280
- true_marginals = Counter(e["used_attribute"] for e in true_ex)
281
- false_marginals = Counter(e["used_attribute"] for e in false_ex)
282
- marginals_match = true_marginals == false_marginals
283
- if not marginals_match:
284
- errors.append("Attribute marginals differ between true and false")
285
-
286
- if rel == "P103":
287
- n_french = sum(1 for e in true_ex if e["true_attribute"] == "French")
288
- expected_cap = P103_FRENCH_CAPS[subset_name]
289
- if n_french != expected_cap:
290
- errors.append(f"P103 French count {n_french} != cap {expected_cap}")
291
-
292
- return {
293
- "relation_id": rel,
294
- "subset": subset_name,
295
- "pairs": len(true_ex),
296
- "examples": len(examples),
297
- "unique_subjects": len(set(subjects)),
298
- "unique_attributes_true": len(true_marginals),
299
- "unique_attributes_false": len(false_marginals),
300
- "marginals_match": marginals_match,
301
- "errors": errors,
302
- "valid": len(errors) == 0,
303
- }
304
-
305
-
306
- def validate_nesting(
307
- subsets: dict[str, list[dict]],
308
- rel: str,
309
- ) -> list[str]:
310
- """Check N50 ⊂ N75 ⊂ N100 by case_id."""
311
- errors = []
312
- ids = {name: {e["example_id"] for e in exs if e["label"] == 1}
313
- for name, exs in subsets.items()}
314
- case_ids = {name: {e["case_id"] for e in exs if e["label"] == 1}
315
- for name, exs in subsets.items()}
316
-
317
- if not case_ids["N50"] <= case_ids["N75"]:
318
- errors.append(f"{rel}: N50 not subset of N75")
319
- if not case_ids["N75"] <= case_ids["N100"]:
320
- errors.append(f"{rel}: N75 not subset of N100")
321
- return errors
322
-
323
-
324
- # ---------------------------------------------------------------------------
325
- # Output
326
- # ---------------------------------------------------------------------------
327
-
328
- def sha256_file(path: Path) -> str:
329
- h = hashlib.sha256()
330
- with path.open("rb") as f:
331
- for chunk in iter(lambda: f.read(8192), b""):
332
- h.update(chunk)
333
- return h.hexdigest()
334
-
335
-
336
- def save_outputs(
337
- all_examples: list[dict],
338
- relation_meta: dict[str, Any],
339
- manifest: dict[str, Any],
340
- ) -> None:
341
- OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
342
-
343
- parquet_path = OUTPUT_DIR / "examples.parquet"
344
- df = pd.DataFrame(all_examples)
345
- col_order = [
346
- "example_id", "pair_id", "case_id", "relation_id", "subject",
347
- "template", "true_attribute", "used_attribute", "sentence",
348
- "label", "false_attribute_source_id", "subset",
349
- ]
350
- df = df[col_order]
351
- df.to_parquet(parquet_path, index=False, engine="pyarrow")
352
- print(f"\nSaved {len(df)} examples to {parquet_path}")
353
-
354
- manifest["output_hash"] = sha256_file(parquet_path)
355
-
356
- rel_path = OUTPUT_DIR / "relations.json"
357
- rel_path.write_text(
358
- json.dumps(relation_meta, indent=2, ensure_ascii=False) + "\n",
359
- encoding="utf-8",
360
- )
361
-
362
- manifest_path = OUTPUT_DIR / "dataset_manifest.json"
363
- manifest_path.write_text(
364
- json.dumps(manifest, indent=2, ensure_ascii=False) + "\n",
365
- encoding="utf-8",
366
- )
367
- print(f"Saved relations.json and dataset_manifest.json")
368
-
369
-
370
- # ---------------------------------------------------------------------------
371
- # Main
372
- # ---------------------------------------------------------------------------
373
-
374
- def main() -> None:
375
- print("=" * 60)
376
- print("CounterFact multi-relation preprocessing")
377
- print("=" * 60)
378
-
379
- raw = load_raw(RAW_PATH)
380
- print(f"Loaded {len(raw)} raw CounterFact records\n")
381
-
382
- # --- Stage 1: filter ---
383
- by_rel = filter_relations(raw)
384
- s1 = {r: len(v) for r, v in by_rel.items()}
385
- print("Stage 1 — Filter to target relations:")
386
- for rel in RELATIONS:
387
- print(f" {rel} ({RELATION_NAMES[rel]}): {s1[rel]}")
388
-
389
- # --- Stage 2: within-relation subject dedup ---
390
- for rel in RELATIONS:
391
- by_rel[rel] = dedup_subjects(by_rel[rel])
392
- s2 = {r: len(v) for r, v in by_rel.items()}
393
- print("\nStage 2 — Within-relation subject dedup:")
394
- for rel in RELATIONS:
395
- d = s1[rel] - s2[rel]
396
- print(f" {rel}: {s1[rel]} -> {s2[rel]} ({d} removed)")
397
-
398
- # --- Stage 3: cross-relation subject removal ---
399
- cross_subjs = find_cross_relation_subjects(by_rel)
400
- for rel in RELATIONS:
401
- by_rel[rel] = remove_subjects(by_rel[rel], cross_subjs)
402
- s3 = {r: len(v) for r, v in by_rel.items()}
403
- print(f"\nStage 3 — Cross-relation subject removal ({len(cross_subjs)} subjects):")
404
- for rel in RELATIONS:
405
- d = s2[rel] - s3[rel]
406
- print(f" {rel}: {s2[rel]} -> {s3[rel]} ({d} removed)")
407
- print(f" Removed subjects: {sorted(cross_subjs)}")
408
-
409
- # --- Stage 4: sentence dedup ---
410
- for rel in RELATIONS:
411
- by_rel[rel] = dedup_sentences(by_rel[rel])
412
- s4 = {r: len(v) for r, v in by_rel.items()}
413
- print("\nStage 4 — Sentence dedup:")
414
- for rel in RELATIONS:
415
- d = s3[rel] - s4[rel]
416
- print(f" {rel}: {s3[rel]} -> {s4[rel]} ({d} removed)")
417
-
418
- # --- P103 attribute distribution after cleaning ---
419
- p103_attrs = Counter(
420
- r["requested_rewrite"]["target_true"]["str"] for r in by_rel["P103"]
421
- )
422
- n_french = p103_attrs.get("French", 0)
423
- print(f"\nP103 after cleaning: {s4['P103']} records, "
424
- f"French={n_french} ({100*n_french/s4['P103']:.1f}%)")
425
-
426
- # --- Sample, derange, build examples ---
427
- all_examples: list[dict] = []
428
- all_validations: list[dict] = []
429
- nesting_errors: list[str] = []
430
- relation_meta: dict[str, Any] = {}
431
-
432
- for rel in RELATIONS:
433
- print(f"\nProcessing {rel}...")
434
- subsets_records = sample_nested(by_rel[rel], rel)
435
-
436
- rel_info: dict[str, Any] = {
437
- "relation_id": rel,
438
- "relation_name": RELATION_NAMES[rel],
439
- "cleaning_counts": {
440
- "raw": s1[rel],
441
- "after_subject_dedup": s2[rel],
442
- "after_cross_relation_removal": s3[rel],
443
- "after_sentence_dedup": s4[rel],
444
- },
445
- "subsets": {},
446
- }
447
-
448
- subset_examples: dict[str, list[dict]] = {}
449
-
450
- for subset_name, size in SUBSET_SIZES:
451
- recs = subsets_records[subset_name]
452
- deranged = construct_derangement(recs)
453
- exs = build_examples(deranged, subset_name)
454
-
455
- val = validate_subset(exs, subset_name, rel)
456
- all_validations.append(val)
457
- subset_examples[subset_name] = exs
458
- all_examples.extend(exs)
459
-
460
- attr_dist = Counter(
461
- r["requested_rewrite"]["target_true"]["str"] for r in recs
462
- )
463
- rel_info["subsets"][subset_name] = {
464
- "pairs": len(recs),
465
- "examples": len(exs),
466
- "attribute_distribution": dict(attr_dist.most_common()),
467
- "unique_templates": len({r["requested_rewrite"]["prompt"] for r in recs}),
468
- "unique_subjects": len({r["requested_rewrite"]["subject"] for r in recs}),
469
- "validation": val,
470
- }
471
-
472
- status = "PASS" if val["valid"] else f"FAIL: {val['errors']}"
473
- print(f" {subset_name}: {size} pairs -> {len(exs)} examples {status}")
474
-
475
- nest_err = validate_nesting(subset_examples, rel)
476
- nesting_errors.extend(nest_err)
477
- if nest_err:
478
- print(f" NESTING ERROR: {nest_err}")
479
- else:
480
- print(f" Nesting N50 ⊂ N75 ⊂ N100: OK")
481
-
482
- relation_meta[rel] = rel_info
483
-
484
- # --- Cross-relation duplicate check on N100 ---
485
- n100_subjects: dict[str, set[str]] = defaultdict(set)
486
- for e in all_examples:
487
- if e["subset"] == "N100" and e["label"] == 1:
488
- n100_subjects[e["relation_id"]].add(e["subject"])
489
- cross_check_errors = []
490
- for i, r1 in enumerate(RELATIONS):
491
- for r2 in RELATIONS[i + 1:]:
492
- overlap = n100_subjects[r1] & n100_subjects[r2]
493
- if overlap:
494
- cross_check_errors.append(f"{r1}+{r2}: {len(overlap)} shared subjects")
495
- if cross_check_errors:
496
- print(f"\nCROSS-RELATION SUBJECT LEAK: {cross_check_errors}")
497
- else:
498
- print("\nCross-relation subject check on N100: OK (no overlap)")
499
-
500
- # --- Build manifest ---
501
- manifest: dict[str, Any] = {
502
- "seed": SEED,
503
- "relations": RELATIONS,
504
- "subset_sizes": {name: size for name, size in SUBSET_SIZES},
505
- "p103_french_caps": P103_FRENCH_CAPS,
506
- "cleaning_stages": {
507
- "stage1_raw": s1,
508
- "stage2_subject_dedup": s2,
509
- "stage3_cross_relation": s3,
510
- "stage4_sentence_dedup": s4,
511
- },
512
- "cross_relation_subjects": sorted(cross_subjs),
513
- "total_examples": len(all_examples),
514
- "examples_per_subset": {
515
- name: sum(1 for e in all_examples if e["subset"] == name)
516
- for name, _ in SUBSET_SIZES
517
- },
518
- "validation": {
519
- "all_subset_checks_passed": all(v["valid"] for v in all_validations),
520
- "nesting_checks_passed": len(nesting_errors) == 0,
521
- "cross_relation_check_passed": len(cross_check_errors) == 0,
522
- "checks_passed": sum(1 for v in all_validations if v["valid"]),
523
- "checks_total": len(all_validations),
524
- },
525
- "raw_data_hash": sha256_file(RAW_PATH),
526
- }
527
-
528
- save_outputs(all_examples, relation_meta, manifest)
529
-
530
- # --- Final report ---
531
- all_passed = (
532
- all(v["valid"] for v in all_validations)
533
- and len(nesting_errors) == 0
534
- and len(cross_check_errors) == 0
535
- )
536
- print("\n" + "=" * 60)
537
- print("VALIDATION SUMMARY")
538
- print("=" * 60)
539
- for v in all_validations:
540
- status = "PASS" if v["valid"] else f"FAIL: {v['errors']}"
541
- print(f" {v['relation_id']} {v['subset']}: {status}")
542
- if nesting_errors:
543
- for err in nesting_errors:
544
- print(f" NESTING: {err}")
545
- print(f"\n{'ALL CHECKS PASSED' if all_passed else 'FAILURES DETECTED'}")
546
-
547
- if not all_passed:
548
- raise RuntimeError("Validation failures — see output above")
549
-
550
-
551
- if __name__ == "__main__":
552
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
phase2_scaling/prepare_counterfact_p103.py DELETED
@@ -1,214 +0,0 @@
1
- """Create a controlled, balanced true/false P103 dataset from CounterFact.
2
-
3
- French occurs in more than half of raw P103 records, making a frequency-
4
- preserving derangement of all P103 examples mathematically impossible. We
5
- therefore retain every non-French record and deterministically sample an equal
6
- number of French records. False attributes then exchange the French and
7
- non-French pools. Every attribute has exactly the same frequency in both
8
- labels, and no false sentence retains its own true attribute. This prevents a
9
- linear probe from succeeding merely because a language name is more frequent
10
- in one label.
11
-
12
- Run from any directory:
13
- python prepare_counterfact_p103.py
14
- """
15
-
16
- from __future__ import annotations
17
-
18
- import json
19
- import random
20
- from collections import Counter
21
- from pathlib import Path
22
- from typing import Any
23
-
24
-
25
- SEED = 20260711
26
- RELATION_ID = "P103"
27
- ROOT = Path(__file__).resolve().parent
28
- RAW_PATH = ROOT / "data" / "raw" / "counterfact.json"
29
- OUTPUT_PATH = ROOT / "data" / "processed" / "counterfact_p103_balanced_pairs.jsonl"
30
- SUMMARY_PATH = ROOT / "data" / "processed" / "counterfact_p103_balanced_summary.json"
31
-
32
-
33
- def make_sentence(template: str, subject: str, attribute: str) -> str:
34
- """Fill CounterFact's subject placeholder and add exactly one word space."""
35
- return f"{template.format(subject).rstrip()} {attribute.strip()}"
36
-
37
-
38
- def load_p103_records(path: Path) -> list[dict[str, Any]]:
39
- if not path.exists():
40
- raise FileNotFoundError(
41
- f"Raw CounterFact file is missing: {path}\n"
42
- "Download it before running this preparation script."
43
- )
44
-
45
- with path.open("r", encoding="utf-8") as handle:
46
- raw_records = json.load(handle)
47
-
48
- records = [
49
- record
50
- for record in raw_records
51
- if record["requested_rewrite"]["relation_id"] == RELATION_ID
52
- ]
53
- if not records:
54
- raise RuntimeError(f"No records found for relation {RELATION_ID}.")
55
- return records
56
-
57
-
58
- def select_balanced_records(
59
- records: list[dict[str, Any]],
60
- ) -> tuple[list[dict[str, Any]], str, int]:
61
- """Balance the dominant attribute against the aggregate of all others."""
62
- attributes = [record["requested_rewrite"]["target_true"]["str"] for record in records]
63
- dominant_attribute, dominant_count = Counter(attributes).most_common(1)[0]
64
- dominant_records = [
65
- record
66
- for record in records
67
- if record["requested_rewrite"]["target_true"]["str"] == dominant_attribute
68
- ]
69
- other_records = [record for record in records if record not in dominant_records]
70
-
71
- if not other_records:
72
- raise RuntimeError("P103 has no non-dominant attributes to construct negatives from.")
73
-
74
- rng = random.Random(SEED)
75
- sampled_dominant = rng.sample(dominant_records, len(other_records))
76
- selected = sorted(sampled_dominant + other_records, key=lambda record: record["case_id"])
77
- excluded = dominant_count - len(sampled_dominant)
78
- return selected, dominant_attribute, excluded
79
-
80
-
81
- def build_examples(records: list[dict[str, Any]], dominant_attribute: str) -> list[dict[str, Any]]:
82
- dominant_records = [
83
- record
84
- for record in records
85
- if record["requested_rewrite"]["target_true"]["str"] == dominant_attribute
86
- ]
87
- other_records = [record for record in records if record not in dominant_records]
88
-
89
- false_by_case_id: dict[int, str] = {}
90
- other_attributes = [record["requested_rewrite"]["target_true"]["str"] for record in other_records]
91
- random.Random(SEED).shuffle(other_attributes)
92
- for record, false_attribute in zip(dominant_records, other_attributes):
93
- false_by_case_id[record["case_id"]] = false_attribute
94
- for record in other_records:
95
- false_by_case_id[record["case_id"]] = dominant_attribute
96
-
97
- examples: list[dict[str, Any]] = []
98
- for record in records:
99
- rewrite = record["requested_rewrite"]
100
- case_id = record["case_id"]
101
- subject = rewrite["subject"]
102
- template = rewrite["prompt"]
103
- true_attribute = rewrite["target_true"]["str"]
104
- false_attribute = false_by_case_id[case_id]
105
-
106
- common = {
107
- "pair_id": case_id,
108
- "case_id": case_id,
109
- "relation_id": rewrite["relation_id"],
110
- "subject": subject,
111
- "template": template,
112
- "target_true": true_attribute,
113
- "target_false": false_attribute,
114
- "construction": "P103_balanced_dominant_attribute_exchange",
115
- }
116
- examples.append(
117
- {
118
- **common,
119
- "example_id": f"{case_id}_true",
120
- "label": 1,
121
- "sentence": make_sentence(template, subject, true_attribute),
122
- }
123
- )
124
- examples.append(
125
- {
126
- **common,
127
- "example_id": f"{case_id}_false",
128
- "label": 0,
129
- "sentence": make_sentence(template, subject, false_attribute),
130
- }
131
- )
132
-
133
- return examples
134
-
135
-
136
- def validate(
137
- source_records: int,
138
- records: list[dict[str, Any]],
139
- examples: list[dict[str, Any]],
140
- dominant_attribute: str,
141
- excluded_records: int,
142
- ) -> dict[str, Any]:
143
- true_examples = [example for example in examples if example["label"] == 1]
144
- false_examples = [example for example in examples if example["label"] == 0]
145
-
146
- if len(examples) != 2 * len(records):
147
- raise AssertionError("Each source record must create exactly two examples.")
148
- if len(true_examples) != len(false_examples):
149
- raise AssertionError("The labels are not balanced.")
150
- if any(example["target_true"] == example["target_false"] for example in examples):
151
- raise AssertionError("A false example retained its true attribute.")
152
- if Counter(example["target_true"] for example in true_examples) != Counter(
153
- example["target_false"] for example in false_examples
154
- ):
155
- raise AssertionError("True and false attribute frequencies are not balanced.")
156
-
157
- return {
158
- "source": str(RAW_PATH),
159
- "relation_id": RELATION_ID,
160
- "seed": SEED,
161
- "source_records": source_records,
162
- "selected_records": len(records),
163
- "excluded_records": excluded_records,
164
- "dominant_attribute": dominant_attribute,
165
- "pairs": len(records),
166
- "examples": len(examples),
167
- "true_examples": len(true_examples),
168
- "false_examples": len(false_examples),
169
- "unique_attributes": len({example["target_true"] for example in true_examples}),
170
- "validation": {
171
- "labels_balanced": True,
172
- "no_false_attribute_equals_its_true_attribute": True,
173
- "true_false_attribute_frequencies_match": True,
174
- },
175
- }
176
-
177
-
178
- def write_jsonl(path: Path, examples: list[dict[str, Any]]) -> None:
179
- path.parent.mkdir(parents=True, exist_ok=True)
180
- with path.open("w", encoding="utf-8") as handle:
181
- for example in examples:
182
- handle.write(json.dumps(example, ensure_ascii=False) + "\n")
183
-
184
-
185
- def main() -> None:
186
- source_records = load_p103_records(RAW_PATH)
187
- records, dominant_attribute, excluded_records = select_balanced_records(source_records)
188
- examples = build_examples(records, dominant_attribute)
189
- summary = validate(
190
- len(source_records), records, examples, dominant_attribute, excluded_records
191
- )
192
- write_jsonl(OUTPUT_PATH, examples)
193
- SUMMARY_PATH.write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
194
-
195
- print("P103 CounterFact preparation completed.")
196
- print(
197
- f"Source P103 records: {summary['source_records']}; "
198
- f"balanced pairs: {summary['pairs']}; examples: {summary['examples']}"
199
- )
200
- print(
201
- f"Balanced dominant attribute: {summary['dominant_attribute']}; "
202
- f"excluded source records: {summary['excluded_records']}"
203
- )
204
- print(f"Output: {OUTPUT_PATH}")
205
- print("\nFirst five true/false pairs:")
206
- for index in range(0, min(10, len(examples)), 2):
207
- true_example, false_example = examples[index], examples[index + 1]
208
- print(f"\nPair {true_example['pair_id']}")
209
- print(f" TRUE : {true_example['sentence']}")
210
- print(f" FALSE: {false_example['sentence']}")
211
-
212
-
213
- if __name__ == "__main__":
214
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
phase2_scaling/run_probing.py DELETED
@@ -1,639 +0,0 @@
1
- """Phase 2 probing pipeline: Stage 1A, 1B, layer selection, Stage 2.
2
-
3
- Run from workspace/reproduction/scaling/ under the blackboxnlp conda env:
4
- python run_probing.py
5
- """
6
- from __future__ import annotations
7
-
8
- import hashlib
9
- import json
10
- import warnings
11
- from pathlib import Path
12
-
13
- import numpy as np
14
- import pandas as pd
15
- import sklearn
16
- from sklearn.linear_model import LogisticRegression
17
- from sklearn.metrics import balanced_accuracy_score, roc_auc_score
18
- from sklearn.preprocessing import StandardScaler
19
-
20
- ROOT = Path(__file__).resolve().parent
21
- CONFIG_PATH = ROOT / "experiment_config.json"
22
- DATA_DIR = ROOT / "data" / "processed"
23
- ACT_DIR = ROOT / "activations"
24
- RESULTS_DIR = ROOT / "results"
25
- WEIGHTS_DIR = RESULTS_DIR / "probe_weights"
26
-
27
- MODELS = {
28
- "llama_3_1_8b": {"model_id": "meta-llama/Llama-3.1-8B"},
29
- "llama_3_1_70b": {"model_id": "meta-llama/Llama-3.1-70B"},
30
- }
31
-
32
- RELATION_ORDER = ["P19", "P103", "P101", "P159", "P176", "P138"]
33
-
34
-
35
- def load_config() -> dict:
36
- with open(CONFIG_PATH) as f:
37
- return json.load(f)
38
-
39
-
40
- def config_hash(cfg: dict) -> str:
41
- blob = json.dumps(cfg["probe"], sort_keys=True).encode()
42
- return hashlib.sha256(blob).hexdigest()[:16]
43
-
44
-
45
- def load_data():
46
- examples = pd.read_parquet(DATA_DIR / "examples.parquet")
47
- examples = examples[examples["subset"] == "N100"]
48
- splits = pd.read_parquet(DATA_DIR / "splits.parquet")
49
- merged = examples.merge(splits[["example_id", "within_relation_fold"]],
50
- on="example_id", how="inner")
51
- return merged
52
-
53
-
54
- def load_activations(model_key: str) -> tuple[dict[int, np.ndarray], pd.DataFrame]:
55
- model_dir = ACT_DIR / model_key
56
- with open(model_dir / "manifest.json") as f:
57
- manifest = json.load(f)
58
- sample_index = pd.read_parquet(model_dir / "sample_index.parquet")
59
-
60
- acts = {}
61
- for layer_info in manifest["target_layers"]:
62
- li = layer_info["layer_index"]
63
- arr = np.load(model_dir / f"layer_{li}.npy").astype(np.float32)
64
- acts[li] = arr
65
-
66
- return acts, sample_index
67
-
68
-
69
- def make_probe(cfg: dict) -> LogisticRegression:
70
- p = cfg["probe"]
71
- return LogisticRegression(
72
- solver=p["solver"],
73
- penalty=p["penalty"],
74
- C=p["C"],
75
- max_iter=p["max_iter"],
76
- tol=p["tol"],
77
- fit_intercept=p["fit_intercept"],
78
- class_weight=p["class_weight"],
79
- random_state=p["random_state"],
80
- )
81
-
82
-
83
- def fit_and_predict(
84
- X_train: np.ndarray, y_train: np.ndarray,
85
- X_test: np.ndarray, y_test: np.ndarray,
86
- cfg: dict,
87
- ) -> tuple[LogisticRegression, StandardScaler, np.ndarray, float, float, int]:
88
- scaler = StandardScaler()
89
- X_train_s = scaler.fit_transform(X_train)
90
- X_test_s = scaler.transform(X_test)
91
-
92
- probe = make_probe(cfg)
93
- with warnings.catch_warnings(record=True) as caught:
94
- warnings.simplefilter("always")
95
- probe.fit(X_train_s, y_train)
96
-
97
- for w in caught:
98
- if issubclass(w.category, sklearn.exceptions.ConvergenceWarning):
99
- raise RuntimeError(
100
- f"Probe did not converge within max_iter={cfg['probe']['max_iter']}. "
101
- f"Training samples={len(y_train)}, features={X_train.shape[1]}"
102
- )
103
-
104
- scores = probe.predict_proba(X_test_s)[:, 1]
105
- auc = roc_auc_score(y_test, scores)
106
- preds = (scores >= 0.5).astype(int)
107
- bal_acc = balanced_accuracy_score(y_test, preds)
108
- n_iter = int(probe.n_iter_[0])
109
-
110
- return probe, scaler, scores, auc, bal_acc, n_iter
111
-
112
-
113
- def save_probe(
114
- probe: LogisticRegression, scaler: StandardScaler,
115
- probe_id: str, meta: dict,
116
- ) -> None:
117
- np.savez(
118
- WEIGHTS_DIR / f"{probe_id}.npz",
119
- coefficient=probe.coef_,
120
- intercept=probe.intercept_,
121
- scaler_mean=scaler.mean_,
122
- scaler_scale=scaler.scale_,
123
- classes=probe.classes_,
124
- )
125
- manifest_path = WEIGHTS_DIR / f"{probe_id}_manifest.json"
126
- with open(manifest_path, "w") as f:
127
- json.dump(meta, f, indent=2)
128
-
129
-
130
- def build_activation_index(sample_index: pd.DataFrame, data: pd.DataFrame):
131
- eid_to_row = {eid: i for i, eid in enumerate(sample_index["example_id"])}
132
- data = data.copy()
133
- data["act_row"] = data["example_id"].map(eid_to_row)
134
- assert data["act_row"].notna().all(), "example_id mismatch between data and activations"
135
- data["act_row"] = data["act_row"].astype(int)
136
- return data
137
-
138
-
139
- def run_stage1a(data: pd.DataFrame, model_key: str, acts: dict[int, np.ndarray],
140
- manifest: dict, cfg: dict, cfg_h: str):
141
- relations = RELATION_ORDER
142
- metrics_rows = []
143
- pred_rows = []
144
- probe_count = 0
145
-
146
- for layer_info in manifest["target_layers"]:
147
- li = layer_info["layer_index"]
148
- depth = layer_info["depth"]
149
- X_all = acts[li]
150
-
151
- for rel in relations:
152
- rel_data = data[data["relation_id"] == rel]
153
-
154
- for fold in range(3):
155
- train_mask = rel_data["within_relation_fold"] != fold
156
- test_mask = rel_data["within_relation_fold"] == fold
157
-
158
- train_rows = rel_data[train_mask]["act_row"].values
159
- test_rows = rel_data[test_mask]["act_row"].values
160
-
161
- X_train = X_all[train_rows]
162
- y_train = rel_data[train_mask]["label"].values
163
- X_test = X_all[test_rows]
164
- y_test = rel_data[test_mask]["label"].values
165
-
166
- probe, scaler, scores, auc, bal_acc, n_iter = fit_and_predict(
167
- X_train, y_train, X_test, y_test, cfg
168
- )
169
-
170
- probe_id = f"s1a_{model_key}_L{li}_{rel}_f{fold}"
171
- train_eids = rel_data[train_mask]["example_id"].tolist()
172
-
173
- save_probe(probe, scaler, probe_id, {
174
- "probe_id": probe_id,
175
- "stage": "1A",
176
- "protocol": "within_relation",
177
- "model_id": MODELS[model_key]["model_id"],
178
- "model_revision": "served via NDIF",
179
- "layer_index": li,
180
- "normalized_depth": depth,
181
- "source_relations": [rel],
182
- "target_relation": rel,
183
- "fold": fold,
184
- "training_example_ids": train_eids,
185
- "probe_configuration_hash": cfg_h,
186
- "sklearn_version": sklearn.__version__,
187
- "n_iter": n_iter,
188
- })
189
-
190
- metrics_rows.append({
191
- "stage": "1A",
192
- "model_id": MODELS[model_key]["model_id"],
193
- "model_key": model_key,
194
- "layer_index": li,
195
- "normalized_depth": depth,
196
- "protocol": "within_relation",
197
- "source_relations": rel,
198
- "target_relation": rel,
199
- "fold": fold,
200
- "auc": auc,
201
- "balanced_accuracy": bal_acc,
202
- "n_train": len(y_train),
203
- "n_test": len(y_test),
204
- "n_iter": n_iter,
205
- })
206
-
207
- test_eids = rel_data[test_mask]["example_id"].values
208
- for eid, true_label, score in zip(test_eids, y_test, scores):
209
- pred_rows.append({
210
- "stage": "1A",
211
- "model_id": MODELS[model_key]["model_id"],
212
- "model_key": model_key,
213
- "layer_index": li,
214
- "normalized_depth": depth,
215
- "protocol": "within_relation",
216
- "source_relations": rel,
217
- "target_relation": rel,
218
- "fold": fold,
219
- "example_id": eid,
220
- "true_label": true_label,
221
- "prediction_score": float(score),
222
- })
223
-
224
- probe_count += 1
225
-
226
- print(f" Stage 1A: {probe_count} probes fitted for {model_key}")
227
- return metrics_rows, pred_rows
228
-
229
-
230
- def run_stage1b(data: pd.DataFrame, model_key: str, acts: dict[int, np.ndarray],
231
- manifest: dict, cfg: dict, cfg_h: str):
232
- relations = RELATION_ORDER
233
- metrics_rows = []
234
- pred_rows = []
235
- probe_count = 0
236
-
237
- for layer_info in manifest["target_layers"]:
238
- li = layer_info["layer_index"]
239
- depth = layer_info["depth"]
240
- X_all = acts[li]
241
-
242
- for target_rel in relations:
243
- train_data = data[data["relation_id"] != target_rel]
244
- test_data = data[data["relation_id"] == target_rel]
245
-
246
- train_rows = train_data["act_row"].values
247
- test_rows = test_data["act_row"].values
248
-
249
- X_train = X_all[train_rows]
250
- y_train = train_data["label"].values
251
- X_test = X_all[test_rows]
252
- y_test = test_data["label"].values
253
-
254
- source_rels = [r for r in relations if r != target_rel]
255
-
256
- probe, scaler, scores, auc, bal_acc, n_iter = fit_and_predict(
257
- X_train, y_train, X_test, y_test, cfg
258
- )
259
-
260
- probe_id = f"s1b_{model_key}_L{li}_target_{target_rel}"
261
- train_eids = train_data["example_id"].tolist()
262
-
263
- save_probe(probe, scaler, probe_id, {
264
- "probe_id": probe_id,
265
- "stage": "1B",
266
- "protocol": "leave_one_out",
267
- "model_id": MODELS[model_key]["model_id"],
268
- "model_revision": "served via NDIF",
269
- "layer_index": li,
270
- "normalized_depth": depth,
271
- "source_relations": source_rels,
272
- "target_relation": target_rel,
273
- "fold": None,
274
- "training_example_ids": train_eids,
275
- "probe_configuration_hash": cfg_h,
276
- "sklearn_version": sklearn.__version__,
277
- "n_iter": n_iter,
278
- })
279
-
280
- metrics_rows.append({
281
- "stage": "1B",
282
- "model_id": MODELS[model_key]["model_id"],
283
- "model_key": model_key,
284
- "layer_index": li,
285
- "normalized_depth": depth,
286
- "protocol": "leave_one_out",
287
- "source_relations": ";".join(source_rels),
288
- "target_relation": target_rel,
289
- "fold": None,
290
- "auc": auc,
291
- "balanced_accuracy": bal_acc,
292
- "n_train": len(y_train),
293
- "n_test": len(y_test),
294
- "n_iter": n_iter,
295
- })
296
-
297
- for eid, true_label, score in zip(test_data["example_id"].values,
298
- y_test, scores):
299
- pred_rows.append({
300
- "stage": "1B",
301
- "model_id": MODELS[model_key]["model_id"],
302
- "model_key": model_key,
303
- "layer_index": li,
304
- "normalized_depth": depth,
305
- "protocol": "leave_one_out",
306
- "source_relations": ";".join(source_rels),
307
- "target_relation": target_rel,
308
- "fold": None,
309
- "example_id": eid,
310
- "true_label": true_label,
311
- "prediction_score": float(score),
312
- })
313
-
314
- probe_count += 1
315
-
316
- print(f" Stage 1B: {probe_count} probes fitted for {model_key}")
317
- return metrics_rows, pred_rows
318
-
319
-
320
- def select_layers(metrics_1a: pd.DataFrame, cfg: dict) -> dict:
321
- tol = cfg["layer_selection_tie_tolerance"]
322
- selected = {}
323
-
324
- for model_key in metrics_1a["model_key"].unique():
325
- m = metrics_1a[metrics_1a["model_key"] == model_key]
326
- mean_by_depth = (
327
- m.groupby(["layer_index", "normalized_depth"])["auc"]
328
- .mean()
329
- .reset_index()
330
- )
331
- best_auc = mean_by_depth["auc"].max()
332
- candidates = mean_by_depth[mean_by_depth["auc"] >= best_auc - tol]
333
- chosen = candidates.loc[candidates["normalized_depth"].idxmin()]
334
-
335
- selected[model_key] = {
336
- "layer_index": int(chosen["layer_index"]),
337
- "normalized_depth": float(chosen["normalized_depth"]),
338
- "mean_auc": float(chosen["auc"]),
339
- "best_auc": float(best_auc),
340
- "all_depths": mean_by_depth.to_dict(orient="records"),
341
- }
342
- print(f" {model_key}: selected layer {int(chosen['layer_index'])} "
343
- f"(depth={chosen['normalized_depth']}, "
344
- f"mean_auc={chosen['auc']:.4f}, best={best_auc:.4f})")
345
-
346
- return selected
347
-
348
-
349
- def fit_probe_only(
350
- X_train: np.ndarray, y_train: np.ndarray, cfg: dict,
351
- ) -> tuple[LogisticRegression, StandardScaler, int]:
352
- scaler = StandardScaler()
353
- X_train_s = scaler.fit_transform(X_train)
354
-
355
- probe = make_probe(cfg)
356
- with warnings.catch_warnings(record=True) as caught:
357
- warnings.simplefilter("always")
358
- probe.fit(X_train_s, y_train)
359
-
360
- for w in caught:
361
- if issubclass(w.category, sklearn.exceptions.ConvergenceWarning):
362
- raise RuntimeError(
363
- f"Probe did not converge within max_iter={cfg['probe']['max_iter']}. "
364
- f"Training samples={len(y_train)}, features={X_train.shape[1]}"
365
- )
366
-
367
- return probe, scaler, int(probe.n_iter_[0])
368
-
369
-
370
- def run_stage2(all_indexed: dict[str, pd.DataFrame], selected: dict,
371
- acts_cache: dict, manifests: dict,
372
- metrics_1a: pd.DataFrame, cfg: dict, cfg_h: str):
373
- relations = RELATION_ORDER
374
- metrics_rows = []
375
- pred_rows = []
376
- matrices = {}
377
- probe_count = 0
378
-
379
- for model_key, layer_info in selected.items():
380
- li = layer_info["layer_index"]
381
- depth = layer_info["normalized_depth"]
382
- X_all = acts_cache[model_key][li]
383
- data = all_indexed[model_key]
384
-
385
- matrix = pd.DataFrame(index=relations, columns=relations, dtype=float)
386
-
387
- s1a_at_layer = metrics_1a[
388
- (metrics_1a["model_key"] == model_key) &
389
- (metrics_1a["layer_index"] == li)
390
- ]
391
- for rel in relations:
392
- rel_aucs = s1a_at_layer[s1a_at_layer["target_relation"] == rel]["auc"]
393
- matrix.loc[rel, rel] = rel_aucs.mean()
394
-
395
- for source_rel in relations:
396
- source_data = data[data["relation_id"] == source_rel]
397
- X_train = X_all[source_data["act_row"].values]
398
- y_train = source_data["label"].values
399
-
400
- probe, scaler, n_iter = fit_probe_only(X_train, y_train, cfg)
401
-
402
- probe_id = f"s2_{model_key}_L{li}_src_{source_rel}"
403
- train_eids = source_data["example_id"].tolist()
404
-
405
- save_probe(probe, scaler, probe_id, {
406
- "probe_id": probe_id,
407
- "stage": "2",
408
- "protocol": "transfer",
409
- "model_id": MODELS[model_key]["model_id"],
410
- "model_revision": "served via NDIF",
411
- "layer_index": li,
412
- "normalized_depth": depth,
413
- "source_relations": [source_rel],
414
- "target_relation": "all",
415
- "fold": None,
416
- "training_example_ids": train_eids,
417
- "probe_configuration_hash": cfg_h,
418
- "sklearn_version": sklearn.__version__,
419
- "n_iter": n_iter,
420
- })
421
- probe_count += 1
422
-
423
- for target_rel in relations:
424
- if target_rel == source_rel:
425
- continue
426
-
427
- target_data = data[data["relation_id"] == target_rel]
428
- X_test = X_all[target_data["act_row"].values]
429
- y_test = target_data["label"].values
430
-
431
- X_test_s = scaler.transform(X_test)
432
- scores = probe.predict_proba(X_test_s)[:, 1]
433
- auc = roc_auc_score(y_test, scores)
434
- preds = (scores >= 0.5).astype(int)
435
- bal_acc = balanced_accuracy_score(y_test, preds)
436
-
437
- matrix.loc[source_rel, target_rel] = auc
438
-
439
- metrics_rows.append({
440
- "stage": "2",
441
- "model_id": MODELS[model_key]["model_id"],
442
- "model_key": model_key,
443
- "layer_index": li,
444
- "normalized_depth": depth,
445
- "protocol": "transfer",
446
- "source_relations": source_rel,
447
- "target_relation": target_rel,
448
- "fold": None,
449
- "auc": auc,
450
- "balanced_accuracy": bal_acc,
451
- "n_train": len(y_train),
452
- "n_test": len(y_test),
453
- "n_iter": n_iter,
454
- })
455
-
456
- for eid, true_label, score in zip(target_data["example_id"].values,
457
- y_test, scores):
458
- pred_rows.append({
459
- "stage": "2",
460
- "model_id": MODELS[model_key]["model_id"],
461
- "model_key": model_key,
462
- "layer_index": li,
463
- "normalized_depth": depth,
464
- "protocol": "transfer",
465
- "source_relations": source_rel,
466
- "target_relation": target_rel,
467
- "fold": None,
468
- "example_id": eid,
469
- "true_label": true_label,
470
- "prediction_score": float(score),
471
- })
472
-
473
- matrices[model_key] = matrix
474
- print(f" Stage 2: {probe_count} source probes fitted for {model_key}")
475
-
476
- return metrics_rows, pred_rows, matrices
477
-
478
-
479
- def main() -> None:
480
- cfg = load_config()
481
- cfg_h = config_hash(cfg)
482
- print(f"Config hash: {cfg_h}")
483
-
484
- RESULTS_DIR.mkdir(parents=True, exist_ok=True)
485
- WEIGHTS_DIR.mkdir(parents=True, exist_ok=True)
486
-
487
- print("\nLoading data...")
488
- data = load_data()
489
- print(f" {len(data)} N100 examples, {data['relation_id'].nunique()} relations")
490
-
491
- all_metrics_1a = []
492
- all_preds_1a = []
493
- all_metrics_1b = []
494
- all_preds_1b = []
495
- acts_cache = {}
496
- manifests = {}
497
-
498
- for model_key in MODELS:
499
- print(f"\n{'='*50}")
500
- print(f"Model: {model_key}")
501
- print(f"{'='*50}")
502
-
503
- acts, sample_index = load_activations(model_key)
504
- model_dir = ACT_DIR / model_key
505
- with open(model_dir / "manifest.json") as f:
506
- manifest = json.load(f)
507
-
508
- indexed_data = build_activation_index(sample_index, data)
509
- acts_cache[model_key] = acts
510
- manifests[model_key] = manifest
511
-
512
- m1a, p1a = run_stage1a(indexed_data, model_key, acts, manifest, cfg, cfg_h)
513
- all_metrics_1a.extend(m1a)
514
- all_preds_1a.extend(p1a)
515
-
516
- m1b, p1b = run_stage1b(indexed_data, model_key, acts, manifest, cfg, cfg_h)
517
- all_metrics_1b.extend(m1b)
518
- all_preds_1b.extend(p1b)
519
-
520
- metrics_1a_df = pd.DataFrame(all_metrics_1a)
521
- metrics_1b_df = pd.DataFrame(all_metrics_1b)
522
- preds_1a_df = pd.DataFrame(all_preds_1a)
523
- preds_1b_df = pd.DataFrame(all_preds_1b)
524
-
525
- print(f"\n{'='*50}")
526
- print("Layer Selection")
527
- print(f"{'='*50}")
528
- selected = select_layers(metrics_1a_df, cfg)
529
-
530
- with open(RESULTS_DIR / "selected_layers.json", "w") as f:
531
- json.dump(selected, f, indent=2)
532
-
533
- print(f"\n{'='*50}")
534
- print("Stage 2: Transfer Matrices")
535
- print(f"{'='*50}")
536
-
537
- all_indexed = {}
538
- for model_key in MODELS:
539
- sample_index = pd.read_parquet(ACT_DIR / model_key / "sample_index.parquet")
540
- all_indexed[model_key] = build_activation_index(sample_index, data)
541
-
542
- m2, p2, matrices = run_stage2(
543
- all_indexed, selected, acts_cache, manifests,
544
- metrics_1a_df, cfg, cfg_h
545
- )
546
- metrics_2_df = pd.DataFrame(m2)
547
- preds_2_df = pd.DataFrame(p2)
548
-
549
- print(f"\n{'='*50}")
550
- print("Saving results")
551
- print(f"{'='*50}")
552
-
553
- stage1_metrics = pd.concat([metrics_1a_df, metrics_1b_df], ignore_index=True)
554
- stage1_metrics.to_csv(RESULTS_DIR / "stage1_metrics.csv", index=False)
555
- print(f" stage1_metrics.csv: {len(stage1_metrics)} rows (1A + 1B)")
556
-
557
- metrics_2_df.to_csv(RESULTS_DIR / "stage2_metrics.csv", index=False)
558
- print(f" stage2_metrics.csv: {len(metrics_2_df)} rows")
559
-
560
- stage1_preds = pd.concat([preds_1a_df, preds_1b_df], ignore_index=True)
561
- stage1_preds.to_parquet(RESULTS_DIR / "stage1_predictions.parquet", index=False)
562
- print(f" Stage 1 predictions: {len(stage1_preds)} rows")
563
-
564
- preds_2_df.to_parquet(RESULTS_DIR / "stage2_predictions.parquet", index=False)
565
- print(f" Stage 2 predictions: {len(preds_2_df)} rows (off-diagonal only)")
566
-
567
- for model_key, matrix in matrices.items():
568
- ordered_matrix = matrix.loc[RELATION_ORDER, RELATION_ORDER]
569
- fname = f"stage2_matrix_{model_key.split('_')[-1]}.csv"
570
- ordered_matrix.to_csv(RESULTS_DIR / fname)
571
- print(f" Transfer matrix: {fname}")
572
- print(ordered_matrix.round(3).to_string())
573
- print()
574
-
575
- # --- Generality gap CSV ---
576
- gap_rows = []
577
- for model_key in MODELS:
578
- for layer_info in manifests[model_key]["target_layers"]:
579
- li = layer_info["layer_index"]
580
- depth = layer_info["depth"]
581
- for rel in RELATION_ORDER:
582
- within_aucs = metrics_1a_df[
583
- (metrics_1a_df["model_key"] == model_key) &
584
- (metrics_1a_df["layer_index"] == li) &
585
- (metrics_1a_df["target_relation"] == rel)
586
- ]["auc"]
587
- mean_within = within_aucs.mean()
588
- std_within = within_aucs.std()
589
-
590
- loo_auc = metrics_1b_df[
591
- (metrics_1b_df["model_key"] == model_key) &
592
- (metrics_1b_df["layer_index"] == li) &
593
- (metrics_1b_df["target_relation"] == rel)
594
- ]["auc"].values[0]
595
-
596
- gap_rows.append({
597
- "model_key": model_key,
598
- "model_id": MODELS[model_key]["model_id"],
599
- "layer_index": li,
600
- "normalized_depth": depth,
601
- "target_relation": rel,
602
- "within_mean_auc": mean_within,
603
- "within_std_auc": std_within,
604
- "loo_auc": loo_auc,
605
- "generality_gap": mean_within - loo_auc,
606
- })
607
-
608
- gap_df = pd.DataFrame(gap_rows)
609
- gap_df.to_csv(RESULTS_DIR / "generality_gap.csv", index=False)
610
- print(f" generality_gap.csv: {len(gap_df)} rows")
611
-
612
- print(f"\n{'='*50}")
613
- print("Generality Gap Summary")
614
- print(f"{'='*50}")
615
- for model_key in MODELS:
616
- print(f"\n {model_key}:")
617
- for layer_info in manifests[model_key]["target_layers"]:
618
- li = layer_info["layer_index"]
619
- depth = layer_info["depth"]
620
- model_gaps = gap_df[
621
- (gap_df["model_key"] == model_key) &
622
- (gap_df["layer_index"] == li)
623
- ]
624
- mean_abs_gap = model_gaps["generality_gap"].abs().mean()
625
- print(f" Layer {li} (depth={depth}) mean|gap|={mean_abs_gap:.4f}")
626
- for _, row in model_gaps.iterrows():
627
- print(f" {row['target_relation']}: "
628
- f"within={row['within_mean_auc']:.3f} "
629
- f"LOO={row['loo_auc']:.3f} "
630
- f"gap={row['generality_gap']:+.3f}")
631
-
632
- total_probes = len(all_metrics_1a) + len(all_metrics_1b) + len(m2)
633
- print(f"\nTotal probes fitted: {total_probes}")
634
- print(f"Probe weights saved to: {WEIGHTS_DIR}")
635
- print("Done.")
636
-
637
-
638
- if __name__ == "__main__":
639
- main()