delivered-sooner / code /confirm.py
Boesgaard's picture
Initial private upload
f36cc9a verified
Raw History Blame Contribute Delete
10.6 kB
"""Registered primary analysis of three arms on the 256-question panel (parent, activation edit, random control).
uv run --no-project --with numpy --with zstandard python code/confirm.py records/confirmation256/panel.jsonl \
--base records/confirm_baseline/scored/base.scored.jsonl \
--edit records/confirm_wsp/scored/base_wsp_pair4_a6.scored.jsonl \
--control records/confirm_wsp/scored/base_wsp_pair4_random.scored.jsonl
The analysis is unchanged from the registered script; only file fingerprints are resolved for the package (see
ORIGINAL below). Its output equals stats/main256/activation_edit_registered.json.
"""
import argparse
import hashlib
import json
from collections import Counter
from pathlib import Path
import numpy as np
ROOT = Path(__file__).resolve().parent.parent
# Package files whose bytes differ from the experiment originals (paths normalized, or prompt token IDs removed from
# the panel) are listed with their original SHA-256 in records/ORIGINAL_SHA256.tsv. Integrity checks compare the
# recorded original digests, and a compressed trace is hashed after decompression.
ORIGINAL = {}
for _line in (ROOT / "records/ORIGINAL_SHA256.tsv").read_text().splitlines()[1:]:
_path, _orig = _line.split("\t")[:2]
ORIGINAL[_path] = _orig
AREAS = ("hardmath", "mathconfirm", "sgpqa", "retention")
DRAWS = 10_000
SEED = 2026112901
REGISTERED_PAIRS = {
("base_wsp_pair4_a6", "base_wsp_pair4_random"): "activation-informed, primary",
("base_late_neurons_1of16_donor", "base_late_neurons_1of16_sign"): "donor-informed, secondary",
}
def fingerprint(path):
path = Path(path)
try:
rel = str(path.resolve().relative_to(ROOT))
except ValueError:
rel = None
if rel in ORIGINAL:
return ORIGINAL[rel]
if not path.exists() and path.with_name(path.name + ".zst").exists():
import zstandard # noqa: PLC0415
hasher = hashlib.sha256()
with path.with_name(path.name + ".zst").open("rb") as file:
reader = zstandard.ZstdDecompressor().stream_reader(file)
for block in iter(lambda: reader.read(1024 * 1024), b""):
hasher.update(block)
return hasher.hexdigest()
hasher = hashlib.sha256()
with path.open("rb") as file:
for block in iter(lambda: file.read(1024 * 1024), b""):
hasher.update(block)
return hasher.hexdigest()
def read(path):
return json.loads(path.read_bytes())
def read_rows(path):
with path.open() as file:
return [json.loads(line) for line in file if line.strip()]
def item_key(row):
return row["set"], row["id"], row["sample"]
def require(condition, message):
if not condition:
raise ValueError(message)
def verified_arm(path, expected, dataset_hash):
arm = path.name.removesuffix(".scored.jsonl")
directory = path.parent.parent
plan_path = directory / "PLAN.json"
outcome = read(directory / "OUTCOME.json")
summary_path = path.parent / "SUMMARY.json"
summary = read(summary_path)
plan = read(plan_path)
checks = [
(outcome["status"] == "complete", "experiment did not complete"),
(outcome["plan_sha256"] == fingerprint(plan_path), "plan hash changed"),
(outcome["scores_sha256"] == fingerprint(summary_path), "summary hash changed"),
(arm in outcome["complete"], "arm omitted from outcome"),
(summary["dataset_sha256"] == plan["dataset_sha256"] == dataset_hash, "dataset hash changed"),
(plan["batch"] == 16 and plan["cap"] == 32768, "wrong batch or context"),
]
for condition, message in checks:
require(condition, f"{arm}: {message}")
source = directory / f"{arm}.jsonl"
generation = read(directory / f"{arm}.jsonl.RUN.json")
details = summary["arms"][arm]
require(details["status"] == "eval_completed" and details["expected_records"] == 256, f"{arm}: incomplete scores")
require(generation["status"] == "completed" and generation["completed_requests"] == 256, f"{arm}: incomplete generations")
require(details["records_sha256"] == fingerprint(source), f"{arm}: generation records changed")
manifest = next(model["manifest_sha256"] for model in plan["models"] if model["name"] == arm)
require(generation["checkpoint_receipt"]["sha256"] == manifest, f"{arm}: wrong checkpoint")
rows = read_rows(path)
require(len(rows) == 256 and {item_key(r) for r in rows} == set(expected), f"{arm}: unpaired scores")
indexed = {}
for row in rows:
key = item_key(row)
require(row["arm"] == arm and row["status"] == "scored", f"{arm}: invalid record at {key}")
require(row["seed"] == expected[key]["seed"] and row["area"] == expected[key]["area"], f"{arm}: seed or stratum mismatch at {key}")
require(row["comparison_surface_hash"] == generation["protocol_hash"], f"{arm}: serving mismatch at {key}")
require(row["correct_v2"] in (0, 1) and row["native_correct_v2"] in (0, 1), f"{arm}: missing score at {key}")
require(row["natural_completion"] == (not row["forced"]), f"{arm}: inconsistent native completion at {key}")
indexed[key] = row
meta = {"name": arm, "checkpoint_sha256": manifest, "generation_sha256": details["records_sha256"],
"scored_sha256": fingerprint(path), "plan_sha256": outcome["plan_sha256"], "summary_sha256": outcome["scores_sha256"],
"surface_sha256": generation["protocol_hash"], "scorer_sources": summary["scorer_source_sha256"]}
return indexed, meta
def as_arrays(rows, keys):
ordered = [rows[key] for key in keys]
return {
"thinking": np.array([r["thinking_tokens"] for r in ordered]),
"generated": np.array([r["generated_tokens"] for r in ordered]),
"natural": np.array([int(r["natural_completion"] and r["native_correct_v2"]) for r in ordered]),
"final": np.array([int(r["correct_v2"]) for r in ordered]),
"forced": np.array([int(r["forced"]) for r in ordered]),
"at_native_cap": np.array([int(r["native_generated_tokens"] == r["max_new_tokens"]) for r in ordered]),
}
def interval(sample):
return np.quantile(sample, [0.025, 0.975]).tolist()
def contrast(left, right, indices):
reference_total = right["thinking"][indices].sum(axis=1)
require((reference_total > 0).all(), "zero denominator in bootstrap")
ratio = left["thinking"].sum() / right["thinking"].sum()
ratios = left["thinking"][indices].sum(axis=1) / reference_total
report = {"thinking_ratio": float(ratio), "thinking_ratio_95ci": interval(ratios)}
for metric in ("natural", "final"):
signed = left[metric] - right[metric]
report[metric] = {
"difference_pp": float(100 * signed.mean()),
"difference_pp_95ci": interval(100 * signed[indices].mean(axis=1)),
"gains": int((signed > 0).sum()),
"losses": int((signed < 0).sum()),
"both_correct": int((left[metric] * right[metric]).sum()),
"both_incorrect": int(((1 - left[metric]) * (1 - right[metric])).sum()),
}
return report
def total_counts(arrays, indices):
out = {metric: int(values[indices].sum()) for metric, values in arrays.items()}
out.update(n=len(indices), mean_thinking=out["thinking"] / len(indices), mean_generated=out["generated"] / len(indices))
return out
def analyze(dataset, base, edit, control):
frozen = read(dataset.parent / "MANIFEST.json")
dataset_hash = fingerprint(dataset)
require(frozen["dataset_sha256"] == dataset_hash and frozen["question_count"] == 256, "bad panel manifest")
original = read_rows(dataset)
expected = {item_key(r): r for r in original}
require(len(original) == len(expected) == len({r["id"] for r in original}) == 256, "expected 256 distinct questions")
require(Counter(r["area"] for r in original) == {a: 64 for a in AREAS}, "wrong stratum counts")
keys = sorted(expected)
arms, receipts = {}, {}
for role, path in [("base", base), ("edit", edit), ("control", control)]:
rows, receipts[role] = verified_arm(path, expected, dataset_hash)
arms[role] = as_arrays(rows, keys)
require(receipts["base"]["name"] == "base", "expected unchanged parent")
pair = receipts["edit"]["name"], receipts["control"]["name"]
require(pair in REGISTERED_PAIRS, "unregistered or mislabeled edit/control pair")
require(len({r["checkpoint_sha256"] for r in receipts.values()}) == 3, "checkpoint reused")
require(len({r["surface_sha256"] for r in receipts.values()}) == 1, "serving differs across arms")
require(all(r["scorer_sources"] == receipts["base"]["scorer_sources"] for r in receipts.values()), "scorers differ")
rng = np.random.Generator(np.random.PCG64(SEED))
strata = {a: [i for i, k in enumerate(keys) if expected[k]["area"] == a] for a in AREAS}
draws = np.column_stack([rng.choice(members, size=(DRAWS, len(members))) for members in strata.values()])
comparisons = {f"{left}_vs_{right}": contrast(arms[left], arms[right], draws)
for left, right in [("edit", "base"), ("edit", "control"), ("control", "base")]}
full = {role: total_counts(arrays, list(range(256))) for role, arrays in arms.items()}
by_area = {area: {role: total_counts(arrays, members) for role, arrays in arms.items()} for area, members in strata.items()}
vs_base = comparisons["edit_vs_base"]
return {"n": 256, "comparison": REGISTERED_PAIRS[pair], "manifest_sha256": fingerprint(dataset.parent / "MANIFEST.json"), "dataset_sha256": dataset_hash,
"receipts": receipts, "checks": {"accuracy_lower_95ci_above_minus_2pp_on_both_endpoints":
all(vs_base[m]["difference_pp_95ci"][0] > -2.0 for m in ("natural", "final"))},
"method": {"bootstrap": "paired question, stratified by the four equally weighted item areas, percentile",
"draws": DRAWS, "seed": SEED, "numpy": np.__version__},
"arms": full, "by_area": by_area, "comparisons": comparisons}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("dataset", type=Path, help="records/confirmation256/panel.jsonl (next to MANIFEST.json)")
for name in ("base", "edit", "control"):
parser.add_argument(f"--{name}", type=Path, required=True, help="Path to <arm>.scored.jsonl inside the completed run")
args = parser.parse_args()
print(json.dumps(analyze(args.dataset, args.base, args.edit, args.control), indent=2, allow_nan=False))