File size: 8,623 Bytes
f36cc9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""Shared helpers: package paths, the arm registry, readers for (compressed) JSONL records, the answer-equality rule.

All paths are relative to the package root, so every script runs from any working directory.
"""

from __future__ import annotations

import io
import json
import re
import subprocess
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
RECORDS = ROOT / "records"

# Panel strata: the stratum names used in the records and the public source of each.
STRATA = {
    "hardmath": "competition mathematics (MathArena)",
    "mathconfirm": "MATH",
    "sgpqa": "SuperGPQA",
    "retention": "MMLU-Pro",
}

# Every generation arm in the package: experiment -> arm -> (run directory under records/, file stem, scored file).
# The trace of an arm is records/<run>/<stem>.jsonl.zst; its scored rows are records/<run>/scored/<scored>.
ARMS = {
    "main256_32k": {
        "parent": ("confirm_baseline", "base", "base.scored.jsonl"),
        "transplant_all32": ("confirm_full_mlp_forward", "base_mlp_all", "base_mlp_all.scored.jsonl"),
        "reverse_all32": ("confirm_full_mlp_reverse", "concise_restore_mlp_all", "concise_restore_mlp_all.scored.jsonl"),
        "donor": ("confirm_concise", "concise", "concise.scored.jsonl"),
        "transplant_late16": ("confirm_broad", "base_mlp_all_l16_31", "base_mlp_all_l16_31.scored.jsonl"),
        "activation_edit": ("confirm_wsp", "base_wsp_pair4_a6", "base_wsp_pair4_a6.scored.jsonl"),
        "random_direction": ("confirm_wsp", "base_wsp_pair4_random", "base_wsp_pair4_random.scored.jsonl"),
    },
    "replication512_32k": {
        "parent": ("replicate_baseline", "base", "base.scored.jsonl"),
        "transplant_all32": ("replicate_full_mlp_forward", "base_mlp_all", "base_mlp_all.scored.jsonl"),
    },
    "main256_8k": {
        "parent": ("rank8k_base", "base", "base.scored.jsonl"),
        "dial_plus1": ("rank8k_full", "base_mlp_all", "base_mlp_all.scored.jsonl"),
        "dial_minus1": ("dial8k_m100", "base_mlp_all_alpha_m100", "base_mlp_all_alpha_m100.scored.jsonl"),
        "dial_plus2": ("dial8k_p200", "base_mlp_all_alpha_p200", "base_mlp_all_alpha_p200.scored.jsonl"),
        "placement_late16": ("placement8k_late16", "base_mlp_all_l16_31", "base_mlp_all_l16_31.scored.jsonl"),
        "placement_exact_count_spread": (
            "placement8k_spread_exact",
            "base_mlp_support_norm_width_channels",
            "base_mlp_support_norm_width_channels.scored.jsonl",
        ),
        "neo_recipient": ("port_neo8k_recipient", "child_neo", "child_neo.scored.jsonl"),
        "neo_patched": ("port_neo8k_patch", "child_neo_mlp_patch", "child_neo_mlp_patch.scored.jsonl"),
    },
    "competition64_64k": {
        "parent": ("signed_hard64_at65536_base", "base", "base.scored.jsonl"),
        "dial_plus1": ("signed_hard64_at65536_plus1", "base_mlp_all", "base_mlp_all.scored.jsonl"),
        "dial_minus1": ("signed_hard64_at65536_negative", "base_mlp_all_alpha_m100", "base_mlp_all_alpha_m100.scored.jsonl"),
    },
    "shorterbetter_math128": {
        "parent": ("independent_lineage/native/math128/base", "arm", "base.scored.jsonl"),
        "transplant_all": ("independent_lineage/native/math128/mlp", "arm", "mlp.scored.jsonl"),
        "donor": ("independent_lineage/native/math128/donor", "arm", "donor.scored.jsonl"),
    },
}

# Model behind each arm (Hugging Face names where public).
MODELS = {
    "parent": "Qwen3.5-9B",
    "transplant_all32": "Qwen3.5-9B with the Concise-9B MLPs of all 32 layers",
    "reverse_all32": "Concise-9B with the Qwen3.5-9B MLPs of all 32 layers",
    "donor": "Concise-9B",
    "transplant_late16": "Qwen3.5-9B with the Concise-9B MLPs of layers 16-31",
    "activation_edit": "Qwen3.5-9B with an activation-informed edit of 128 MLP columns",
    "random_direction": "Qwen3.5-9B with a random edit of the same 128 columns",
    "dial_plus1": "Qwen3.5-9B + 1 x the stored MLP update (equals the all-32 transplant)",
    "dial_minus1": "Qwen3.5-9B - 1 x the stored MLP update",
    "dial_plus2": "Qwen3.5-9B + 2 x the stored MLP update",
    "placement_late16": "Qwen3.5-9B with the Concise-9B MLPs of layers 16-31",
    "placement_exact_count_spread": "Qwen3.5-9B with trained MLP weights spread over all 32 layers, matched in count and norm",
    "neo_recipient": "Qwen3.5-9B-Neo",
    "neo_patched": "Qwen3.5-9B-Neo with the Concise-9B MLP update installed",
    "transplant_all": "DeepSeek-R1-Distill-Qwen-1.5B with the ShorterBetter-1.5B MLPs of all layers",
}
SHORTERBETTER_MODELS = {"parent": "DeepSeek-R1-Distill-Qwen-1.5B", "donor": "ShorterBetter-1.5B (alpha = 2)"}


def trace_path(experiment: str, arm: str) -> Path:
    run, stem, _ = ARMS[experiment][arm]
    return RECORDS / run / f"{stem}.jsonl.zst"


def scored_path(experiment: str, arm: str) -> Path:
    run, _, scored = ARMS[experiment][arm]
    return RECORDS / run / "scored" / scored


def _zstd_bytes(path: Path) -> bytes:
    try:
        import zstandard  # noqa: PLC0415

        with path.open("rb") as f:
            return zstandard.ZstdDecompressor().stream_reader(f).read()
    except ImportError:
        return subprocess.run(["zstd", "-dc", str(path)], capture_output=True, check=True).stdout


def iter_jsonl(path: Path | str):
    """Yield rows of a .jsonl file, or of its compressed .jsonl.zst twin when only that exists."""
    path = Path(path)
    if not path.exists() and path.with_name(path.name + ".zst").exists():
        path = path.with_name(path.name + ".zst")
    if path.suffix == ".zst":
        stream = io.StringIO(_zstd_bytes(path).decode("utf-8"))
    else:
        stream = path.open(encoding="utf-8")
    with stream:
        for line in stream:
            if line.strip():
                yield json.loads(line)


def read_json(path: Path | str):
    return json.loads(Path(path).read_text())


def source_dataset(question_id: str) -> dict:
    """Map a question ID to its public source dataset and the key that identifies it there."""
    if question_id.startswith("mmlu_pro__test_"):
        return {"source_dataset": "MMLU-Pro", "hf_dataset": "TIGER-Lab/MMLU-Pro", "split": "test",
                "source_key": str(int(question_id.removeprefix("mmlu_pro__test_")))}
    if question_id.startswith("math__test_"):
        subject, number = question_id.removeprefix("math__test_").rsplit("_", 1)
        folder = {"counting_probability": "counting_and_probability"}.get(subject, subject)  # ID short form
        return {"source_dataset": "MATH", "hf_dataset": "hendrycks/competition_math (original release)", "split": "test",
                "source_key": f"test/{folder}/{number}.json"}
    if question_id.startswith("supergpqa__"):
        return {"source_dataset": "SuperGPQA", "hf_dataset": "m-a-p/SuperGPQA", "split": "train",
                "source_key": question_id.removeprefix("supergpqa__")}
    m = re.fullmatch(r"([a-z]+(?:_[a-z]+)?_\d{4})__(\d+)", question_id)
    if m:
        return {"source_dataset": "MathArena", "hf_dataset": f"MathArena/{m.group(1)}", "split": "train",
                "source_key": m.group(2)}
    m = re.fullmatch(r"([a-z_]+)\.(\d+)", question_id)
    if m:
        return {"source_dataset": "JMMLU", "hf_dataset": "nlp-waseda/JMMLU", "split": "test",
                "source_key": f"JMMLU/{m.group(1)}.csv row {m.group(2)}"}
    raise ValueError(question_id)


# ------------------------------------------------------------------------------ answer equality
def canon(k):
    """Lenient answer key, used only to compare two wrong answers."""
    if k is None:
        return None
    s = str(k).lower()
    s = re.sub(r"\((?:option|choice)\s*[a-j]\)", "", s)
    s = re.sub(r"\\(?:text|mathrm|mathbf|rm|operatorname)\{([^{}]*)\}", r"\1", s)
    s = re.sub(r"\\(?:left|right|displaystyle)", "", s)
    s = re.sub(r"[\s$\\{}]", "", s)
    s = re.sub(r"^[a-z][a-z0-9_]{0,3}=", "", s)
    m = re.fullmatch(r"(-?\d+(?:\.\d+)?)(?:[a-z%°]+)?", s.replace(",", ""))
    if m:
        return round(float(m.group(1)), 9)
    return s


def same(final_correct, final_key, readout_correct, readout_key) -> bool:
    """Is a forced readout the same answer as the trace's final answer? Two correct answers agree; a correct and a
    wrong answer differ; two wrong answers agree when their keys match exactly or after canonicalization."""
    if final_correct and readout_correct:
        return True
    if bool(final_correct) != bool(readout_correct):
        return False
    if final_key is None or readout_key is None:
        return False
    return final_key == readout_key or canon(final_key) == canon(readout_key)