File size: 8,118 Bytes
314ecfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
"""Original runs vs a reproduction (scripts/reproduce_pipeline.sh) of the best configuration.

python scripts/analysis/compare_reproduction.py --tag repro1   (writes eval_results/Bench2Drive/reproduction_<tag>.txt)

Training level: final validation loss of stage1 / speeddrop / tracker_sp and the last validation of the
detectors. Closed loop: Bench2Drive-220 driving score of the final model (sp_v1 detector at 4 Hz, no speed
mask) against the five original runs. The DS difference is judged against the simulator noise measured on the
original repeats (single-run sd ~0.6 DS on the fixed 220 routes): "within noise" when
|mean_repro - mean_orig| <= 1.96 * sqrt(sd^2/n_repro + sd^2/n_orig). Unfinished stages show as pending.
"""
import argparse
import csv
import json
import math
import re
from pathlib import Path

import numpy as np

B = Path("eval_results/Bench2Drive")
SINGLE_RUN_SD = 0.62  # per-route variance across the original repeats, routes fixed

ORIG_TRAIN = {"stage1": "outputs/fastvlm_stage1/2026-10-31_14-19-40",
              "speeddrop": "outputs/fastvlm_stage3_speeddrop/2026-11-02_06-08-03",
              "tracker_sp": "outputs/fastvlm_stage3_tracker_sp/2026-11-03_16-38-38"}
ORIG_DET = {"det_v1": "outputs/detector/det_v1", "sp_v1": "outputs/stream_petr/sp_v1",
            "sp_fold0": "outputs/stream_petr/sp_fold0of2", "sp_fold1": "outputs/stream_petr/sp_fold1of2"}
ORIG_EVALS = ["sp_ft_det4hz_nomask", "sp_ft_det4hz_nomask_repeat", "sp_ft_det4hz_nomask_run3",
              "sp_ft_det4hz_nomask_run4", "sp_ft_det4hz_nomask_run5"]


def repro_paths(tag):
    train = {"stage1": f"outputs/fastvlm_stage1/{tag}", "speeddrop": f"outputs/fastvlm_stage3_speeddrop/{tag}",
             "tracker_sp": f"outputs/fastvlm_stage3_tracker_sp/{tag}"}
    det = {"det_v1": f"outputs/detector/det_v1_{tag}", "sp_v1": f"outputs/stream_petr/sp_v1_{tag}",
           "sp_fold0": f"outputs/stream_petr/sp_fold0of2_{tag}", "sp_fold1": f"outputs/stream_petr/sp_fold1of2_{tag}"}
    evals = sorted(p.name for p in B.glob(f"{tag}_sp_ft_nomask_r*") if (p / "merged.json").exists())
    return train, det, evals


def final_val_loss(train_dir):
    """Last val/loss, route and speed-waypoint losses from Lightning's metrics.csv."""
    p = Path(train_dir) / "logs" / "metrics.csv"
    if not p.exists():
        return None
    rows = [r for r in csv.DictReader(open(p)) if r.get("val/loss")]
    if not rows:
        return None
    r = rows[-1]
    return {k.split("/")[-1]: float(r[k]) for k in ("val/loss", "val_losses/route_loss", "val_losses/speed_wps_loss") if r.get(k)}


def train_hours(train_dir):
    p = Path(train_dir) / "train.log"
    if not p.exists():
        return None
    # tqdm prints MM:SS under one hour and H:MM:SS above, and re-renders the bar many times near 100 %:
    # take the largest elapsed time seen per epoch.
    per_epoch = {}
    for ep, a, b, c in re.findall(r"Epoch (\d+): 100%\|[^|]*\| \d+/\d+ \[(\d+):(\d+)(?::(\d+))?<", p.read_text(errors="ignore")):
        secs = int(a) * 3600 + int(b) * 60 + int(c) if c else int(a) * 60 + int(b)
        per_epoch[ep] = max(per_epoch.get(ep, 0), secs)
    return sum(per_epoch.values()) / 3600 if per_epoch else None


def detector_val(det_dir):
    vals = sorted(Path(det_dir).glob("val_*.json"))
    if not vals:
        return None
    d = json.load(open(vals[-1]))
    out = {"step": int(vals[-1].stem.split("_")[1]), "fp@0.3": d["fp_per_frame"].get("0.3")}
    for cls in ("car", "walker"):
        for rng in ("0-10", "20-30", "40-50"):
            if rng in d.get(cls, {}):
                out[f"{cls}_recall_{rng}"] = d[cls][rng].get("recall_pos")
    for k, v in d.get("car_velocity_by_speed", {}).items():
        out[f"vel_med_{k}"] = v.get("vel_err_med")
    return out


def fmt_metrics(d):
    if d is None:
        return "pending"
    return "  ".join(f"{k}={v:.3f}" if isinstance(v, float) else f"{k}={v}" for k, v in d.items() if v is not None)


def load_eval(name):
    return {r["route_id"]: r for r in json.load(open(B / name / "merged.json"))["_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 summarize(names):
    runs = [load_eval(n) for n in names]
    return dict(runs=runs,
                ds=[np.mean([r["scores"]["score_composed"] for r in run.values()]) for run in runs],
                sr=[100 * np.mean([success(r) for r in run.values()]) for run in runs],
                col=[sum(len(r["infractions"].get("collisions_vehicle", [])) for r in run.values()) for run in runs],
                stops=[sum(len(r["infractions"].get("scenario_timeouts", [])) + len(r["infractions"].get("route_timeout", []))
                           for r in run.values()) for run in runs])


def route_means(summary):
    keys = sorted(summary["runs"][0])
    return keys, np.array([[run[k]["scores"]["score_composed"] for k in keys] for run in summary["runs"]]).mean(0)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--tag", default="repro1")
    args = ap.parse_args()
    rtrain, rdet, revals = repro_paths(args.tag)
    L = [f"# Reproduction '{args.tag}' vs original runs (best configuration: speed-dropout stage 3 fine-tuned on "
         "StreamPETR tracker banks, sp_v1 detector at 4 Hz, no speed mask)"]

    L += ["", "## Training: final validation loss (Lightning metrics.csv) and wall time",
          f"{'stage':12s} {'':6s} {'val/loss':>9s} {'route':>8s} {'speed_wps':>10s} {'hours':>6s}"]
    for stage in ("stage1", "speeddrop", "tracker_sp"):
        for lab, d in (("orig", ORIG_TRAIN[stage]), ("repro", rtrain[stage])):
            v, h = final_val_loss(d), train_hours(d)
            if v is None:
                L.append(f"{stage:12s} {lab:6s} {'pending':>9s}")
            else:
                L.append(f"{stage:12s} {lab:6s} {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 += ["", "## Detectors: last validation (sp_*: frames with memory; recall = recall_pos; velocity error median, m/s)"]
    for name in ("det_v1", "sp_v1", "sp_fold0", "sp_fold1"):
        for lab, d in (("orig", ORIG_DET[name]), ("repro", rdet[name])):
            L.append(f"{name:10s} {lab:6s} {fmt_metrics(detector_val(d))}")

    L += ["", f"## Closed loop, Bench2Drive-220 (single-run sd {SINGLE_RUN_SD} DS)",
          f"{'':6s} {'n':>2s} {'DS per run':>36s} {'mean':>6s} {'SR':>6s} {'veh.col':>8s} {'timeouts':>9s}"]
    o = summarize(ORIG_EVALS)
    L.append(f"{'orig':6s} {len(ORIG_EVALS):2d} {' / '.join(f'{x:.2f}' for x in o['ds']):>36s} {np.mean(o['ds']):6.2f} "
             f"{np.mean(o['sr']):6.2f} {np.mean(o['col']):8.1f} {np.mean(o['stops']):9.1f}")
    if not revals:
        L.append(f"{'repro':6s}  0 {'pending':>36s}")
    else:
        r = summarize(revals)
        diff = np.mean(r["ds"]) - np.mean(o["ds"])
        band = 1.96 * SINGLE_RUN_SD * math.sqrt(1 / len(revals) + 1 / len(ORIG_EVALS))
        verdict = "within noise" if abs(diff) <= band else ("BETTER than original" if diff > 0 else "WORSE than original")
        L.append(f"{'repro':6s} {len(revals):2d} {' / '.join(f'{x:.2f}' for x in r['ds']):>36s} {np.mean(r['ds']):6.2f} "
                 f"{np.mean(r['sr']):6.2f} {np.mean(r['col']):8.1f} {np.mean(r['stops']):9.1f}")
        L.append(f"repro - orig = {diff:+.2f} DS, 95% noise band +/-{band:.2f} -> {verdict}")
        keys, om = route_means(o)
        _, rm = route_means(r)
        big = np.argsort(-np.abs(rm - om))[:6]
        L.append(f"per-route mean |diff| {np.mean(np.abs(rm - om)):.2f}; routes differing by >= 20 DS: {int((np.abs(rm - om) >= 20).sum())}; "
                 "largest: " + ", ".join(f"{keys[i].replace('RouteScenario_', '').replace('_rep0', '')} {rm[i] - om[i]:+.0f}" for i in big))

    text = "\n".join(L)
    print(text)
    (B / f"reproduction_{args.tag}.txt").write_text(text + "\n")


if __name__ == "__main__":
    main()