"""Ablation without det_v1 and fold detectors (scripts/ablate_nodet_nofold.sh) vs the best configuration. python scripts/analysis/compare_nodet_nofold.py --tag nodetfold1 (writes eval_results/Bench2Drive/ablation_.txt) Baseline = every run of the best configuration: the 5 original sp_ft_det4hz_nomask runs and the 2 runs of reproduction repro1 (same recipe, retrained; within noise of the original). The ablation is "equivalent" when |mean_ablation - mean_baseline| <= 1.96 * sd * sqrt(1/n_ablation + 1/n_baseline) with the single-run sd measured on the original repeats; a run-label permutation test and a route-paired Wilcoxon test are reported too. """ import argparse import itertools import math import numpy as np from scipy import stats from compare_reproduction import (B, ORIG_EVALS, SINGLE_RUN_SD, detector_val, final_val_loss, fmt_metrics, load_eval, summarize, train_hours) BASELINE_EVALS = ORIG_EVALS + ["repro1_sp_ft_nomask_r1", "repro1_sp_ft_nomask_r2"] DETECTORS = {"sp_v1 (orig)": "outputs/stream_petr/sp_v1", "sp_v1 (repro1)": "outputs/stream_petr/sp_v1_repro1"} TRACKER_SP = {"orig": "outputs/fastvlm_stage3_tracker_sp/2026-11-03_16-38-38", "repro1": "outputs/fastvlm_stage3_tracker_sp/repro1"} def route_matrix(names): runs = [load_eval(n) for n in names] keys = sorted(runs[0]) return keys, np.array([[run[k]["scores"]["score_composed"] for k in keys] for run in runs]) def main(): ap = argparse.ArgumentParser() ap.add_argument("--tag", default="nodetfold1") args = ap.parse_args() tag = args.tag evals = sorted(p.name for p in B.glob(f"{tag}_sp_ft_nomask_r*") if (p / "merged.json").exists()) L = [f"# Ablation '{tag}': StreamPETR from FastVLM-0.5B (no det_v1), in-sample tracker banks (no folds)"] L += ["", "## Detector: last validation (frames with memory; recall = recall_pos; velocity error median, m/s)"] for name, d in {**DETECTORS, f"sp_direct ({tag})": f"outputs/stream_petr/sp_direct_{tag}"}.items(): L.append(f"{name:22s} {fmt_metrics(detector_val(d))}") L += ["", "## Stage 3 fine-tune: final validation loss", f"{'':10s} {'val/loss':>9s} {'route':>8s} {'speed_wps':>10s} {'hours':>6s}"] for lab, d in {**TRACKER_SP, tag: f"outputs/fastvlm_stage3_tracker_sp/{tag}"}.items(): v, h = final_val_loss(d), train_hours(d) if v is None: L.append(f"{lab:10s} {'pending':>9s}") else: L.append(f"{lab:10s} {v.get('loss', float('nan')):9.4f} {v.get('route_loss', float('nan')):8.4f} " f"{v.get('speed_wps_loss', float('nan')):10.4f} {h if h is not None else float('nan'):6.2f}") L += ["", f"## Closed loop, Bench2Drive-220 (single-run sd {SINGLE_RUN_SD} DS)", f"{'':9s} {'n':>2s} {'DS per run':>52s} {'mean':>6s} {'SR':>6s} {'veh.col':>8s} {'timeouts':>9s}"] base = summarize(BASELINE_EVALS) L.append(f"{'baseline':9s} {len(BASELINE_EVALS):2d} {' / '.join(f'{x:.2f}' for x in base['ds']):>52s} " f"{np.mean(base['ds']):6.2f} {np.mean(base['sr']):6.2f} {np.mean(base['col']):8.1f} {np.mean(base['stops']):9.1f}") if not evals: L.append(f"{'ablation':9s} 0 {'pending':>52s}") else: abl = summarize(evals) L.append(f"{'ablation':9s} {len(evals):2d} {' / '.join(f'{x:.2f}' for x in abl['ds']):>52s} " f"{np.mean(abl['ds']):6.2f} {np.mean(abl['sr']):6.2f} {np.mean(abl['col']):8.1f} {np.mean(abl['stops']):9.1f}") diff = np.mean(abl["ds"]) - np.mean(base["ds"]) band = 1.96 * SINGLE_RUN_SD * math.sqrt(1 / len(evals) + 1 / len(BASELINE_EVALS)) verdict = "equivalent (within noise)" if abs(diff) <= band else ("BETTER" if diff > 0 else "WORSE") L.append(f"ablation - baseline = {diff:+.2f} DS, 95% noise band +/-{band:.2f} -> {verdict}") ds = np.array(base["ds"] + abl["ds"]) n_abl, n_all = len(evals), len(ds) splits = list(itertools.combinations(range(n_all), n_abl)) null = np.array([ds[list(c)].mean() - np.delete(ds, list(c)).mean() for c in splits]) L.append(f"run-label permutation test ({len(splits)} splits): p = {(np.abs(null) >= abs(diff) - 1e-9).mean():.3f}") keys, mb = route_matrix(BASELINE_EVALS) keys_a, ma = route_matrix(evals) assert keys == keys_a, "route sets differ" rb, ra = mb.mean(0), ma.mean(0) w = stats.wilcoxon(ra, rb, zero_method="zsplit") L.append(f"route-paired Wilcoxon on per-route means: p = {w.pvalue:.3f}; routes better {int((ra > rb).sum())}, " f"worse {int((ra < rb).sum())}, equal {int((ra == rb).sum())}") worst = np.argsort(ra - rb)[:6] L.append("largest per-route losses: " + ", ".join( f"{keys[i].replace('RouteScenario_', '').replace('_rep0', '')} {ra[i] - rb[i]:+.0f}" for i in worst)) L.append(f"runs >= 92 DS: baseline {sum(x >= 92 for x in base['ds'])}/{len(base['ds'])}, " f"ablation {sum(x >= 92 for x in abl['ds'])}/{len(abl['ds'])}") text = "\n".join(L) print(text) (B / f"ablation_{tag}.txt").write_text(text + "\n") if __name__ == "__main__": main()