"""Speed mask (SPEED_MASK_STALL_S=15) vs no mask on the StreamPETR stage-3 model, from repeated 220-route evals. python scripts/analysis/compare_speed_mask.py (run from the repo root; writes eval_results/Bench2Drive/speed_mask_summary.txt) Fixed-benchmark CIs treat the 220 routes as fixed and use only simulator noise: the variance of a run's DS is estimated from the per-route variance across repeats (routes are simulated independently). Routes where the mask never fired in any mask15 run ran identical inputs in both arms and serve as an A/A control. """ import glob import json import math import re from collections import Counter from pathlib import Path import numpy as np B = Path("eval_results/Bench2Drive") NOMASK = ["sp_ft_det4hz_nomask", "sp_ft_det4hz_nomask_repeat", "sp_ft_det4hz_nomask_run3", "sp_ft_det4hz_nomask_run4", "sp_ft_det4hz_nomask_run5"] MASK15 = ["sp_ft_det4hz_mask15", "sp_ft_det4hz_mask15_repeat", "sp_ft_det4hz_mask15_run3", "sp_ft_det4hz_mask15_run4", "sp_ft_det4hz_mask15_run5"] ORACLE = ["fastvlm_stage3_oracle_2026-11-01_07-40-56", "stage3_oracle_repeat_clean"] DETV1 = ["tracker_ft_det4hz_mask15", "tracker_ft_det4hz_mask15_repeat"] OBSTACLE = ("Construction", "StaticCutIn", "Accident", "HazardAtSideLane", "ParkedObstacle", "VehicleOpensDoor", "MergerIntoSlowTraffic", "ParkingExit", "InvadingTurn") INFRACTIONS = ["collisions_vehicle", "collisions_layout", "red_light", "stop_infraction", "route_dev", "route_timeout", "scenario_timeouts", "outside_route_lanes"] def route_key(route_id): return route_id.replace("RouteScenario_", "").replace("_rep0", "") def load(path): return {route_key(r["route_id"]): r for r in json.load(open(path))["_checkpoint"]["records"]} def success(r): return r["status"] in ("Completed", "Perfect") and all( len(v) == 0 for k, v in r["infractions"].items() if k != "min_speed_infractions") def masked_steps(run): steps = {} for f in glob.glob(str(B / run / "logs" / "w*.log")): route = None for line in open(f, errors="ignore"): m = re.search(r"Preparing RouteScenario_(\d+)", line) if m: route = m.group(1) m = re.search(r"Speed-masked steps: (\d+)", line) if m and route: steps[route] = int(m.group(1)) return steps R = {n: load(B / n / "merged.json") for n in NOMASK + MASK15 + ORACLE + DETV1} R["stage1"] = load("/tmp/s1_view/merged.json") keys = sorted(R[NOMASK[0]], key=int) scenario = {e["route"]: e["scenario"] for e in json.load(open(B / ORACLE[0] / "analysis" / "report.json"))} X = {name: np.array([[R[n][k]["scores"]["score_composed"] for k in keys] for n in runs]) for name, runs in (("nomask", NOMASK), ("mask15", MASK15), ("oracle", ORACLE), ("detv1", DETV1), ("stage1", ["stage1"]))} X["sp_all10"] = np.vstack([X["nomask"], X["mask15"]]) lines = ["# Speed mask after 15 s standstill vs no mask; StreamPETR stage-3 fine-tune " "(outputs/fastvlm_stage3_tracker_sp/2026-11-03_16-38-38), sp_v1 detector at 4 Hz, 5 x 220 routes per arm.", f"{'run':28s} {'DS':>6s} {'SR':>6s} " + " ".join( f"{k.replace('collisions_', 'col_')[:9]:>9s}" for k in INFRACTIONS) + " game_s timed_out"] for n in NOMASK + MASK15: recs = R[n].values() tot = {k: sum(len(r["infractions"].get(k, [])) for r in recs) for k in INFRACTIONS} lines.append(f"{n.replace('sp_ft_det4hz_', ''):28s} {np.mean([r['scores']['score_composed'] for r in recs]):6.2f} " f"{sum(map(success, recs)) / 2.2:6.2f} " + " ".join(f"{tot[k]:9d}" for k in INFRACTIONS) + f" {np.mean([r['meta']['duration_game'] for r in recs]):6.1f}" + f" {sum(r['status'] == 'Failed - Agent timed out' for r in recs):9d}") single_sd = {n: math.sqrt(a.var(0, ddof=1).sum()) / 220 for n, a in X.items() if len(a) > 1} single_sd["stage1"] = single_sd["sp_all10"] lines += ["", "arm runs mean DS sd(run means) single-run sd from per-route variance"] for n in ("nomask", "mask15", "sp_all10", "oracle", "detv1"): rm = X[n].mean(1) lines.append(f"{n:10s} {len(rm):5d} {rm.mean():8.2f} {rm.std(ddof=1):14.2f} {single_sd[n]:10.2f}") def fixed(a, b): m = X[a].mean() - X[b].mean() se = math.sqrt(single_sd[a] ** 2 / len(X[a]) + single_sd[b] ** 2 / len(X[b])) lines.append(f"{a:9s} - {b:7s} {m:+.2f} fixed-benchmark 95% CI [{m - 1.96 * se:+.2f},{m + 1.96 * se:+.2f}]") lines.append("") for a, b in (("mask15", "nomask"), ("sp_all10", "oracle"), ("sp_all10", "detv1"), ("sp_all10", "stage1"), ("oracle", "detv1")): fixed(a, b) steps = {n: masked_steps(n) for n in MASK15} fired = {k for n in MASK15 for k, v in steps[n].items() if v > 0} lines += ["", f"mask fired on {[sum(v > 0 for v in steps[n].values()) for n in MASK15]} routes per run " f"({len(fired)} distinct); masked time per run " f"{[round(sum(steps[n].values()) / 20) for n in MASK15]} s"] diff = X["mask15"].mean(0) - X["nomask"].mean(0) groups = {"A/A (never fired)": [i for i, k in enumerate(keys) if k not in fired], "fired: junction / yield": [i for i, k in enumerate(keys) if k in fired and not any(s in scenario[k] for s in OBSTACLE)], "fired: obstacle bypass": [i for i, k in enumerate(keys) if k in fired and any(s in scenario[k] for s in OBSTACLE)]} rng = np.random.default_rng(0) for name, ix in groups.items(): a, b = X["mask15"][:, ix], X["nomask"][:, ix] se = math.sqrt(a.var(0, ddof=1).sum() / len(a) + b.var(0, ddof=1).sum() / len(b)) / 220 both = np.vstack([a, b]) obs = abs(a.mean() - b.mean()) perm = [abs(both[p[:5]].mean() - both[p[5:]].mean()) >= obs - 1e-9 for p in (rng.permutation(10) for _ in range(20000))] lines.append(f"{name:24s} n={len(ix):3d} nomask {b.mean():5.1f} mask15 {a.mean():5.1f} DS contribution " f"{diff[ix].sum() / 220:+.2f} +/- {1.96 * se:.2f} run-label permutation p={np.mean(perm):.3f}") lines += ["", "routes with the largest mean difference (mask15 - nomask), scores per run:"] order = np.argsort(diff) for i in list(order[:8]) + list(order[-8:][::-1]): k = keys[i] lines.append(f" {k:>6} {scenario[k][:36]:36s} {diff[i]:+6.1f} nomask {X['nomask'][:, i].round().astype(int).tolist()}" f" mask15 {X['mask15'][:, i].round().astype(int).tolist()}" f" masked_s {[round(steps[n].get(k, 0) / 20) for n in MASK15]}") lines += ["", "per-scenario success over 5 runs (differences >= 3):"] count = Counter() for k in keys: s = scenario[k] count[s, "n"] += sum(success(R[n][k]) for n in NOMASK) count[s, "m"] += sum(success(R[n][k]) for n in MASK15) count[s, "r"] += 5 for s in sorted({s for s, _ in count}, key=lambda s: count[s, "m"] - count[s, "n"]): if abs(count[s, "m"] - count[s, "n"]) >= 3: lines.append(f" {s:42s} nomask {count[s, 'n']:2d}/{count[s, 'r']} mask15 {count[s, 'm']:2d}/{count[s, 'r']}") text = "\n".join(lines) print(text) (B / "speed_mask_summary.txt").write_text(text + "\n")