"""Merge per-condition Phase 3 CSVs and compare trained D against the D_indep proxy. Phase 2/2b measured D_indep, a zero-training estimate of how far a span's true joint sits from the product of its per-position marginals. Phase 3 measures D = BPB(MTP) - BPB(NTP), the trained cost of predicting that span with independent heads. Whether the cheap proxy predicts the expensive outcome is the question this phase exists to answer, so the comparison is emitted alongside the raw metrics rather than left to a reader. """ import argparse import csv import logging from pathlib import Path import yaml logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") logger = logging.getLogger("phase3_aggregate") TRAINING_METRICS = { "seed", "use_shared_trunk", "train_tokens", "train_steps", "tokens_per_second", "peak_gpu_mib", "wall_seconds", } def parse_args() -> argparse.Namespace: p = argparse.ArgumentParser(description=__doc__) p.add_argument("--config", default="configs/phase3.yaml") p.add_argument("--in-dir", required=True, help="directory holding the per-condition CSVs") p.add_argument("--conditions", default="L4,L2,E1") p.add_argument("--out-training", default="results/phase3_training.csv") p.add_argument("--out-measurements", default="results/phase3_measurements.csv") return p.parse_args() def main() -> None: args = parse_args() with open(args.config, encoding="utf-8") as f: cfg = yaml.safe_load(f) conditions = args.conditions.split(",") training_rows = [["condition", "metric", "value", "n"]] measurement_rows = [["condition", "metric", "value", "n"]] d_by_condition = {} ntp_bpb_by_condition = {} for condition in conditions: path = Path(args.in_dir) / f"{condition}.csv" if not path.exists(): logger.warning("missing %s, skipping", path) continue for row in csv.DictReader(path.open(encoding="utf-8")): # label by filename, not by the row's own condition field: repeat-seed # and ablation runs record the condition they trained on, so they # would otherwise collide with the primary run of that condition target = training_rows if row["metric"] in TRAINING_METRICS or row["metric"].startswith("train_loss") else measurement_rows target.append([condition, row["metric"], row["value"], row["n"]]) if row["metric"] == "d_bpb_mtp_minus_ntp": d_by_condition[condition] = float(row["value"]) if row["metric"] == "bpb_ntp": ntp_bpb_by_condition[condition] = float(row["value"]) # Pair each condition's trained D with its zero-training proxy. Three # conditions cannot support a fitted relationship; the rows record the # pairs and their orderings so the direction of association is checkable. reference = cfg["d_indep_reference"] for condition, d_value in d_by_condition.items(): if condition not in reference: continue measurement_rows.append([condition, "d_indep_k2_reference", reference[condition]["d_indep_k2"], 1]) measurement_rows.append([condition, "d_indep_k3_reference", reference[condition]["d_indep_k3"], 1]) measurement_rows.append([condition, "d_trained_bpb", f"{d_value:.6f}", 1]) # Absolute BPB levels are not comparable across these conditions: L2 and # L4 carry identical content, but Devanagari occupies three UTF-8 bytes # per character against one for its romanization, so the same # information is spread over roughly a third as many bytes and every # per-byte quantity scales with it. D as a fraction of the condition's # own NTP baseline divides that encoding density out. baseline = ntp_bpb_by_condition.get(condition) if baseline: measurement_rows.append([condition, "d_trained_relative", f"{d_value / baseline:.6f}", 1]) # only the primary runs enter the ordering comparison; repeat-seed and # ablation runs have no proxy value of their own and would double-count # the condition they retrain primary = {c: v for c, v in d_by_condition.items() if c in reference} if len(primary) >= 2: relative = {c: primary[c] / ntp_bpb_by_condition[c] for c in primary if ntp_bpb_by_condition.get(c)} by_proxy = sorted(primary, key=lambda c: reference[c]["d_indep_k3"]) by_trained = sorted(primary, key=lambda c: primary[c]) measurement_rows.append(["comparison", "condition_order_by_d_indep_k3", "|".join(by_proxy), len(by_proxy)]) measurement_rows.append(["comparison", "condition_order_by_d_trained_absolute", "|".join(by_trained), len(by_trained)]) measurement_rows.append(["comparison", "orders_agree_absolute", int(by_proxy == by_trained), len(by_proxy)]) if relative: by_relative = sorted(relative, key=relative.get) measurement_rows.append(["comparison", "condition_order_by_d_trained_relative", "|".join(by_relative), len(by_relative)]) measurement_rows.append(["comparison", "orders_agree_relative", int(by_proxy == by_relative), len(by_relative)]) for out_path, rows in ((args.out_training, training_rows), (args.out_measurements, measurement_rows)): Path(out_path).parent.mkdir(parents=True, exist_ok=True) with open(out_path, "w", newline="", encoding="utf-8") as f: csv.writer(f).writerows(rows) logger.info("wrote %s (%d rows)", out_path, len(rows) - 1) if __name__ == "__main__": main()