| |
| from __future__ import annotations |
|
|
| import argparse |
| import csv |
| import json |
| import subprocess |
| import sys |
| from pathlib import Path |
| from typing import Any |
|
|
| import pandas as pd |
|
|
|
|
| DISPLAY_NAME = { |
| "continuous": "Continuous reference", |
| "standard_rvq_8bit": "standard RVQ 8-bit", |
| "pq_8bit": "PQ 8-bit", |
| "opq_8bit": "OPQ 8-bit", |
| "metadata_basic": "Metadata basic", |
| "metadata_calendar": "Metadata calendar", |
| "random_permuted_continuous": "Random-permuted continuous", |
| } |
|
|
| PUBLIC_METHODS = [ |
| "continuous", |
| "standard_rvq_8bit", |
| "pq_8bit", |
| "opq_8bit", |
| "metadata_basic", |
| "metadata_calendar", |
| "random_permuted_continuous", |
| ] |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser( |
| description="Recompute the released CB-Telemetry retrieval and shortcut-control tables." |
| ) |
| parser.add_argument("--root", default=".", help="CB-Telemetry dataset root.") |
| parser.add_argument("--output-dir", default="evaluation_runs/release_retrieval", help="Output directory under --root.") |
| parser.add_argument("--bootstrap-samples", type=int, default=2000, help="Bootstrap resamples.") |
| parser.add_argument("--bootstrap-seed", type=int, default=42, help="Bootstrap random seed.") |
| parser.add_argument("--random-seed", type=int, default=42, help="Random-permuted control seed.") |
| parser.add_argument("--include-gap2", action="store_true", help="Also run the supplemental gap=2 retrieval controls.") |
| parser.add_argument("--tolerance", type=float, default=5e-3, help="Rounded-table comparison tolerance.") |
| return parser.parse_args() |
|
|
|
|
| def resolve(root: Path, raw_path: str) -> Path: |
| path = Path(raw_path).expanduser() |
| if not path.is_absolute(): |
| path = (root / path).resolve() |
| return path |
|
|
|
|
| def release_path(root: Path, path: Path) -> str: |
| try: |
| return path.resolve().relative_to(root).as_posix() |
| except ValueError: |
| return path.as_posix() |
|
|
|
|
| def track_feature_table(track: str) -> str: |
| return "features/feature_table_default.csv.gz" if track == "default" else "features/feature_table_strict_clean.csv.gz" |
|
|
|
|
| def bottleneck_representations(root: Path, track: str) -> list[str]: |
| result = [] |
| for method in ["standard_rvq_8bit", "pq_8bit", "opq_8bit"]: |
| rel = f"features/bottlenecks/{track}/{method}_feature_table.csv.gz" |
| if (root / rel).exists(): |
| result.append(f"{method}={rel}") |
| return result |
|
|
|
|
| def run_command(cmd: list[str]) -> None: |
| subprocess.run(cmd, check=True) |
|
|
|
|
| def run_retrieval_suite( |
| root: Path, |
| output_dir: Path, |
| bootstrap_samples: int, |
| bootstrap_seed: int, |
| random_seed: int, |
| include_gap2: bool, |
| ) -> list[dict[str, Any]]: |
| script = Path(__file__).resolve().parent / "run_retrieval_eval.py" |
| run_rows: list[dict[str, Any]] = [] |
| gaps = [1, 2] if include_gap2 else [1] |
| for track in ["default", "strict_clean"]: |
| feature_table = track_feature_table(track) |
| representations = [f"continuous={feature_table}", *bottleneck_representations(root, track)] |
| for scope_label, archive_scope in [("global", "global"), ("same-archive", "same_archive_only")]: |
| for gap in gaps: |
| run_dir = output_dir / track / f"{archive_scope}_gap{gap}" |
| cmd = [ |
| sys.executable, |
| script.as_posix(), |
| "--root", |
| root.as_posix(), |
| "--feature-table", |
| feature_table, |
| "--output-dir", |
| run_dir.as_posix(), |
| "--archive-scope", |
| archive_scope, |
| "--max-slot-gap", |
| str(gap), |
| "--bootstrap-samples", |
| str(bootstrap_samples), |
| "--bootstrap-seed", |
| str(bootstrap_seed), |
| "--random-seed", |
| str(random_seed), |
| "--include-metadata-controls", |
| ] |
| for item in representations: |
| cmd.extend(["--representation", item]) |
| run_command(cmd) |
| run_rows.append( |
| { |
| "track": track, |
| "scope": scope_label, |
| "gap": gap, |
| "archive_scope": archive_scope, |
| "summary_json_path": (run_dir / "summary.json").as_posix(), |
| "summary_json": release_path(root, run_dir / "summary.json"), |
| } |
| ) |
| return run_rows |
|
|
|
|
| def load_json(path: Path) -> dict[str, Any]: |
| return json.loads(path.read_text(encoding="utf-8")) |
|
|
|
|
| def build_overview(run_rows: list[dict[str, Any]]) -> pd.DataFrame: |
| rows: list[dict[str, Any]] = [] |
| for run in run_rows: |
| summary = load_json(Path(run["summary_json_path"])) |
| aggregate_df = pd.DataFrame(summary["aggregate_rows"]).set_index("method") |
| bootstrap_df = pd.DataFrame(summary["bootstrap_rows"]) |
| for _, boot in bootstrap_df.iterrows(): |
| method = str(boot["method"]) |
| aggregate = aggregate_df.loc[method] |
| rows.append( |
| { |
| "track": run["track"], |
| "scope": run["scope"], |
| "gap": int(run["gap"]), |
| "archive_scope": run["archive_scope"], |
| "method": method, |
| "display_name": DISPLAY_NAME.get(method, method), |
| "bootstrap_unit": str(boot["bootstrap_unit"]), |
| "top1": float(aggregate["mean_top1_hit_rate"]), |
| "top1_ci_low": float(boot["top1_hit_rate_ci_low"]), |
| "top1_ci_high": float(boot["top1_hit_rate_ci_high"]), |
| "mrr": float(aggregate["mean_mrr"]), |
| "mrr_ci_low": float(boot["mrr_ci_low"]), |
| "mrr_ci_high": float(boot["mrr_ci_high"]), |
| "top5": float(aggregate["mean_top5_hit_rate"]), |
| "top5_ci_low": float(boot["top5_hit_rate_ci_low"]), |
| "top5_ci_high": float(boot["top5_hit_rate_ci_high"]), |
| "mean_candidate_size": float(aggregate["mean_candidate_size"]), |
| "mean_chance_top1": float(aggregate["mean_chance_top1"]), |
| "summary_json": str(run["summary_json"]), |
| } |
| ) |
| return pd.DataFrame(rows).sort_values(["track", "scope", "gap", "bootstrap_unit", "method"]).reset_index(drop=True) |
|
|
|
|
| def date_row(df: pd.DataFrame, track: str, method: str, scope: str, gap: int) -> pd.Series: |
| rows = df[ |
| (df["track"] == track) |
| & (df["method"] == method) |
| & (df["scope"] == scope) |
| & (df["gap"] == gap) |
| & (df["bootstrap_unit"] == "date") |
| ] |
| if rows.empty: |
| raise KeyError(f"Missing row: track={track}, method={method}, scope={scope}, gap={gap}") |
| return rows.iloc[0] |
|
|
|
|
| def ci_text(row: pd.Series, metric: str) -> str: |
| return f"{float(row[metric]):.4f} [{float(row[f'{metric}_ci_low']):.4f}, {float(row[f'{metric}_ci_high']):.4f}]" |
|
|
|
|
| def build_table3_recomputed(overview: pd.DataFrame) -> pd.DataFrame: |
| rows = [] |
| for method in PUBLIC_METHODS: |
| global_row = date_row(overview, "default", method, "global", 1) |
| same_row = date_row(overview, "default", method, "same-archive", 1) |
| rows.append( |
| { |
| "method": method, |
| "display_name": DISPLAY_NAME.get(method, method), |
| "global_top1": round(float(global_row["top1"]), 4), |
| "global_mrr": round(float(global_row["mrr"]), 4), |
| "global_top5": round(float(global_row["top5"]), 4), |
| "same_archive_top1": round(float(same_row["top1"]), 4), |
| "same_archive_mrr": round(float(same_row["mrr"]), 4), |
| "same_archive_top5": round(float(same_row["top5"]), 4), |
| "global_mrr_ci": ci_text(global_row, "mrr"), |
| "same_archive_mrr_ci": ci_text(same_row, "mrr"), |
| } |
| ) |
| return pd.DataFrame(rows) |
|
|
|
|
| def build_dual_track_recomputed(root: Path, overview: pd.DataFrame) -> pd.DataFrame: |
| rows = [] |
| for track in ["default", "strict_clean"]: |
| feature_df = pd.read_csv(root / track_feature_table(track), usecols=["date"]) |
| for scope_label, archive_scope in [("global", "global"), ("same-archive", "same_archive_only")]: |
| row = date_row(overview, track, "continuous", scope_label, 1) |
| rows.append( |
| { |
| "track": f"{track}__{archive_scope}", |
| "subset": track, |
| "archive_scope": archive_scope, |
| "rows": int(feature_df.shape[0]), |
| "date_count": int(feature_df["date"].astype(str).nunique()), |
| "top1": round(float(row["top1"]), 4), |
| "mrr": round(float(row["mrr"]), 4), |
| "top5": round(float(row["top5"]), 4), |
| "chance_top1": round(float(row["mean_chance_top1"]), 4), |
| } |
| ) |
| return pd.DataFrame(rows) |
|
|
|
|
| def compare_table( |
| expected_path: Path, |
| actual_df: pd.DataFrame, |
| key_columns: list[str], |
| metric_columns: list[str], |
| tolerance: float, |
| ) -> list[dict[str, Any]]: |
| mismatches: list[dict[str, Any]] = [] |
| if not expected_path.exists(): |
| return [{"table": expected_path.name, "issue": "missing_expected_table"}] |
| expected_df = pd.read_csv(expected_path) |
| merged = expected_df.merge(actual_df, on=key_columns, how="outer", suffixes=("_expected", "_actual"), indicator=True) |
| for _, row in merged.iterrows(): |
| key = {column: row[column] for column in key_columns} |
| if row["_merge"] != "both": |
| mismatches.append({"table": expected_path.name, "key": key, "issue": str(row["_merge"])}) |
| continue |
| for column in metric_columns: |
| expected = float(row[f"{column}_expected"]) |
| actual = float(row[f"{column}_actual"]) |
| if abs(expected - actual) > tolerance: |
| mismatches.append( |
| { |
| "table": expected_path.name, |
| "key": key, |
| "metric": column, |
| "expected": expected, |
| "actual": actual, |
| "abs_delta": abs(expected - actual), |
| } |
| ) |
| return mismatches |
|
|
|
|
| def write_markdown(path: Path, check: dict[str, Any]) -> None: |
| lines = [ |
| "# CB-Telemetry Release Evaluation Check", |
| "", |
| f"- status: `{check['status']}`", |
| f"- bootstrap_samples: `{check['bootstrap_samples']}`", |
| f"- overview_rows: `{check['overview_rows']}`", |
| f"- mismatches: `{len(check['mismatches'])}`", |
| "", |
| "## Mismatches", |
| "", |
| ] |
| if check["mismatches"]: |
| for item in check["mismatches"]: |
| lines.append(f"- `{item}`") |
| else: |
| lines.append("- none") |
| path.write_text("\n".join(lines) + "\n", encoding="utf-8") |
|
|
|
|
| def main() -> None: |
| args = parse_args() |
| root = Path(args.root).expanduser().resolve() |
| output_dir = resolve(root, args.output_dir) |
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| run_rows = run_retrieval_suite( |
| root=root, |
| output_dir=output_dir, |
| bootstrap_samples=int(args.bootstrap_samples), |
| bootstrap_seed=int(args.bootstrap_seed), |
| random_seed=int(args.random_seed), |
| include_gap2=bool(args.include_gap2), |
| ) |
| overview = build_overview(run_rows) |
| overview_path = output_dir / "release_retrieval_overview.csv" |
| overview.to_csv(overview_path, index=False) |
|
|
| table3 = build_table3_recomputed(overview) |
| table3_path = output_dir / "table_3_retrieval_baselines_and_controls_recomputed.csv" |
| table3.to_csv(table3_path, index=False) |
|
|
| dual = build_dual_track_recomputed(root, overview) |
| dual_path = output_dir / "table_3_dual_track_retrieval_recomputed.csv" |
| dual.to_csv(dual_path, index=False) |
|
|
| mismatches: list[dict[str, Any]] = [] |
| mismatches.extend( |
| compare_table( |
| expected_path=root / "baselines" / "table_3_retrieval_baselines_and_controls.csv", |
| actual_df=table3, |
| key_columns=["method"], |
| metric_columns=[ |
| "global_top1", |
| "global_mrr", |
| "global_top5", |
| "same_archive_top1", |
| "same_archive_mrr", |
| "same_archive_top5", |
| ], |
| tolerance=float(args.tolerance), |
| ) |
| ) |
| mismatches.extend( |
| compare_table( |
| expected_path=root / "baselines" / "table_3_dual_track_retrieval.csv", |
| actual_df=dual, |
| key_columns=["track"], |
| metric_columns=["top1", "mrr", "top5", "chance_top1"], |
| tolerance=float(args.tolerance), |
| ) |
| ) |
|
|
| check = { |
| "status": "pass" if not mismatches else "fail", |
| "root": root.name, |
| "output_dir": release_path(root, output_dir), |
| "bootstrap_samples": int(args.bootstrap_samples), |
| "include_gap2": bool(args.include_gap2), |
| "overview_rows": int(overview.shape[0]), |
| "files": { |
| "overview": release_path(root, overview_path), |
| "table3_recomputed": release_path(root, table3_path), |
| "dual_track_recomputed": release_path(root, dual_path), |
| }, |
| "mismatches": mismatches, |
| } |
| (output_dir / "release_evaluation_check.json").write_text( |
| json.dumps(check, ensure_ascii=False, indent=2) + "\n", |
| encoding="utf-8", |
| ) |
| write_markdown(output_dir / "release_evaluation_check.md", check) |
| print(json.dumps(check, ensure_ascii=False, indent=2)) |
| raise SystemExit(0 if check["status"] == "pass" else 1) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|