File size: 21,716 Bytes
2230fab | 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 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 | #!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""CPU-reference goldens of centerpoint-p150 (research venv: torch + onnxruntime, CPU only, <= 4 threads).
cd bundles/centerpoint-p150 && OMP_NUM_THREADS=4 PYTHONPATH=code \\
/home/ubuntu/experiments/tt-models/tools/research-venv/bin/python -I code/scripts/make_goldens.py \\
--weights /home/ubuntu/experiments/tt-models/assets/centerpoint/hf_lidar_centerpoint \\
--research /home/ubuntu/experiments/tt-models/research/centerpoint \\
--out /home/ubuntu/experiments/tt-models/research/centerpoint/goldens
For every frame and variant (base, tiny) the fp32 torch reference (``reference/pipeline.py``: host pre-processing,
the deployed network rebuilt from the ONNX initializers, host post-processing) runs once, and ONNX Runtime runs the
deployed ONNX on the same voxel tensors; the agreement (PCC and max |diff| per module tap, detection counts) is
recorded with the golden. Written:
- ``<out>/<variant>/<frame>.heads.npz``: voxel tensors (``features`` of the kept pillars, ``coords``,
``num_points``, ``canvas_index``), ``pfn`` and the six head maps (float32); ``<frame>.detections.json``: the
reference output (``Detections3D.to_dict``), per-stage counts, pillar statistics, the ORT agreement;
- ``<out>/<variant>/<frame>.taps.npz`` (``--taps`` frames only; up to ~0.5 GB for base): every module tap of
``reference.model.MODULE_TAPS`` plus ``pfn.layer0``;
- ``<out>/manifest.json``: sha256 of every file, tool versions, inputs;
- in the bundle (small; Apache-2.0 / CC BY 4.0 inputs only): ``tests/goldens/voxels.json`` (voxel tensor hashes of
the two samples), ``tests/goldens/detections/test_pcd.<variant>.json`` and the smoke references
``samples/test_pcd.<variant>.reference.json`` of the shipped sample; the PandaSet sample's reference and small
golden go next to it in the git-ignored ``staging_samples_pandaset/`` (``pandaset_019_f40.<variant>.reference.json``,
``goldens/pandaset_019_f40.<variant>.json``) until it ships (research/DATASETS.md N5).
Frames (``--set core``, the development set): the two samples (``pandaset_019_f40``, staged; ``test_pcd``), the public
core frames of research/centerpoint/public_data (inputs/*: PandaSet 090 f40, nuScenes 0103 / 0916 kf20, AV2 s080 x 3;
NC data: research only), and the Autoware sample-rosbag frames 151+150 and 181+180 (the 41,918-pillar overflow case;
license unstated: research only), densified by the server-side stream path.
``--set heldout`` (the held-out set of tests/test_heldout_device.py; ``tests/_data.py`` ``heldout_frames``): the
45 other public input frames and the 9 PLAN.md 2.3 sample-rosbag pairs the development set does not use (152+151,
statistics pairs 0/30/60/90/120/210/240/270). Compact goldens, no voxel tensors and no taps, under
``<out>/<variant>/heldout/``:
- ``<frame>.json``: the reference output, the cells of its objects, counts, pillar statistics, the input source;
public frames: ``research_agreement`` with the independent research ORT golden of the same input
(``public_data/goldens/<variant>/<dataset>/<frame>.json``: same object cells, labels, pillar counts, values within
float rounding; any disagreement fails the run); rosbag pairs (no research golden): ``ort_agreement`` (ONNX Runtime on
the same voxel tensors: head-map PCC and max |diff|, same detections);
- ``<frame>.cells.npz``: the reference head maps at every candidate cell (fp32 max sigmoid >= 0.2;
``ttaw.decode.head_values_at``): the device test decodes both sides at the same cells (``ttaw.decode.decode_cells``)
to compare scores, boxes and the yaw-norm / score gates cell by cell.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import platform
import sys
import time
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent
CODE = HERE.parent
sys.path.insert(0, str(CODE))
from tt_centerpoint import __version__ # noqa: E402
from tt_centerpoint import io as tio # noqa: E402
from tt_centerpoint.reference.model import MODULE_TAPS # noqa: E402
from tt_centerpoint.reference.pipeline import CenterPointReference # noqa: E402
from tt_centerpoint.ttaw import __version__ as ttaw_version # noqa: E402
from tt_centerpoint.tests._data import PUBLIC_CORE, ROSBAG_CORE as ROSBAG, find_sample, heldout_frames # noqa: E402
from tt_centerpoint.ttaw.decode import AUTOWARE_LABELS, head_values_at, sigmoid_f32 # noqa: E402
from tt_centerpoint.ttaw.golden import TapRegistry, save_goldens # noqa: E402
from tt_centerpoint.ttaw.metrics import pcc # noqa: E402
SAMPLES = CODE / "tt_centerpoint" / "samples"
BUNDLE_GOLDENS = CODE / "tt_centerpoint" / "tests" / "goldens"
SHIPPED = ("pandaset_019_f40", "test_pcd") # the two samples (PandaSet staged until it ships: tests/_data.py)
def sample_input(name: str) -> Path:
"""The sample's input file: ``samples/`` (shipped) or the PandaSet staging copy."""
path = find_sample(f"{name}.npz")
if path is None:
sys.exit(f"{name}.npz not found in samples/ or staging_samples_pandaset/ (run code/scripts/make_samples.py)")
return path
def small_golden_dir(sample: Path) -> Path:
"""Where the small golden of a sample goes: ``tests/goldens/detections`` for a shipped sample, ``goldens/`` of the
staging directory for the staged one (no PandaSet-derived file enters code/ before it ships)."""
return BUNDLE_GOLDENS / "detections" if sample.parent == SAMPLES else sample.parent / "goldens"
CANDIDATE_MIN_SCORE = 0.2 # held-out cell goldens: every cell whose fp32 max sigmoid reaches this
# research ORT golden vs this reference (6-decimal JSON, torch vs ORT fp32): agreement tolerances
RESEARCH_TOL = {"score": 2e-5, "xyz": 2e-4, "size": 2e-4, "yaw": 2e-4}
def sha(a: np.ndarray) -> str:
return hashlib.sha256(np.ascontiguousarray(a).tobytes()).hexdigest()
def file_sha(p: Path) -> str:
return hashlib.sha256(p.read_bytes()).hexdigest()
def frames(research: Path, workspace: Path):
"""(name, call kwargs list, license, shippable): the last kwargs entry is the frame; earlier ones prime the
stream state (rosbag)."""
for name in SHIPPED:
lic = "CC BY 4.0 + PandaSet Dataset Terms" if name.startswith("pandaset") else "Apache-2.0 (autoware_universe)"
yield name, [{"points": sample_input(name)}], lic, True
for rel in PUBLIC_CORE:
path = research / "public_data" / "inputs" / f"{rel}.npy"
if not path.is_file():
print(f"skip {rel}: {path} missing")
continue
meta = json.loads(path.with_suffix(".json").read_text())
cloud = tio.PointCloud(np.load(path, allow_pickle=False), ("x", "y", "z", "time_lag"))
yield Path(rel).name, [{"points": cloud}], meta.get("license", "?"), bool(meta.get("shippable", False))
bag = workspace / "assets" / "centerpoint" / "derived_sample_rosbag_frames"
for name, past, cur, sub in ROSBAG:
d = bag / sub if sub else bag
if not (d / cur).is_file():
print(f"skip {name}: {d / cur} missing")
continue
calls = []
for f in (past, cur):
z = np.load(d / f, allow_pickle=False)
calls.append({"points": z["points_xyzirc"][:, :3],
"stream": {"id": name, "timestamp_s": float(z["stamp"]),
"T_world_from_ego": z["world_T_base"]}})
yield name, calls, "Autoware sample-rosbag (license unstated): research only", False
def agreement(tt: TapRegistry, to: TapRegistry) -> dict:
out = {}
for k in to.names():
if k in tt:
a, b = tt[k], to[k]
out[k] = {"pcc": float(pcc(a, b)), "max_abs": float(np.abs(a - b).max())}
return out
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--weights", type=Path, required=True)
ap.add_argument("--research", type=Path, required=True)
ap.add_argument("--out", type=Path, required=True)
ap.add_argument("--workspace", type=Path, default=Path("/home/ubuntu/experiments/tt-models"))
ap.add_argument("--variants", default="base,tiny")
ap.add_argument("--taps", default="pandaset_019_f40,test_pcd,rosbag_0181_0180",
help="frames whose module taps are saved")
ap.add_argument("--threads", type=int, default=4)
ap.add_argument("--only", default="", help="comma list of frame names (default: all)")
ap.add_argument("--set", default="core", choices=("core", "heldout"), dest="frame_set",
help="core: the development frames (full goldens); heldout: the held-out frames (compact)")
a = ap.parse_args()
if a.frame_set == "heldout":
return heldout(a)
import onnxruntime
import torch
torch.set_num_threads(a.threads)
taps_for = set(filter(None, a.taps.split(",")))
only = set(filter(None, a.only.split(",")))
a.out.mkdir(parents=True, exist_ok=True)
manifest_path = a.out / "manifest.json"
manifest = json.loads(manifest_path.read_text()) if manifest_path.is_file() else {"files": {}}
manifest.update({"bundle_version": __version__, "ttaw": ttaw_version, "torch": torch.__version__,
"onnxruntime": onnxruntime.__version__, "numpy": np.__version__, "python": platform.python_version(),
"weights": "AutowareFoundation/lidar_centerpoint@494c8171 (v4.1)", "shuffle_seed": 0,
"written": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"command": " ".join(sys.argv)})
voxels = {}
for variant in a.variants.split(","):
rt = CenterPointReference(a.weights, variant, backend="torch", threads=a.threads)
ro = CenterPointReference(a.weights, variant, backend="ort", threads=a.threads, intermediates=True)
vdir = a.out / variant
vdir.mkdir(parents=True, exist_ok=True)
for name, calls, lic, shippable in frames(a.research, a.workspace):
if only and name not in only:
continue
t0 = time.perf_counter()
include = tuple(MODULE_TAPS) + ("pfn.layer0",)
tt, to = TapRegistry(include=include), TapRegistry(include=include)
for call in calls[:-1]: # prime the stream caches (cold start)
rt.pre(**call)
ro.pre(**call)
run = rt.run(**calls[-1], taps=tt)
run_o = ro.run(**calls[-1], taps=to)
t1 = time.perf_counter()
p = run.prepared
n = p.num_pillars
assert np.array_equal(p.features, run_o.prepared.features), name
heads_path = vdir / f"{name}.heads.npz"
save_goldens(heads_path, {"features": p.features[:n], "coords": p.coords[:n],
"num_points": p.pillars.num_points[:n], "canvas_index": p.canvas_index,
"pfn": tt["pfn"], **{f"head_{k}": v for k, v in run.heads.items()}},
meta={"frame": name, "variant": variant, "num_pillars": n, "license": lic,
"shippable": shippable, "points_sha256": sha(p.points)}, compress=True)
files = [heads_path]
if name in taps_for:
taps_path = vdir / f"{name}.taps.npz"
tt.save(taps_path, meta={"frame": name, "variant": variant, "taps": tt.names()}, compress=True)
files.append(taps_path)
agree = agreement(tt, to)
body = run.output.to_dict()
same = run.counts == run_o.counts and [d["label"] for d in body["detections"]] == \
[d["label"] for d in run_o.output.to_dict()["detections"]]
rec = {"frame": name, "variant": variant, "license": lic, "shippable": shippable,
"reference": "tt_centerpoint.reference torch fp32 (ONNX initializers, BN folded)",
"counts": run.counts, "pillars": {k: v for k, v in p.stats().items() if k != "densify"},
"densify": p.densify,
"ort_agreement": {"min_pcc": min(v["pcc"] for v in agree.values()), "taps": agree,
"same_detections": bool(same), "ort_counts": run_o.counts},
"cells": run.objects.extra["cell"].tolist(), "output": body}
det_path = vdir / f"{name}.detections.json"
det_path.write_text(json.dumps(rec, indent=1))
files.append(det_path)
for f in files:
manifest["files"][str(f.relative_to(a.out))] = {"sha256": file_sha(f), "bytes": f.stat().st_size}
if name in SHIPPED:
src = sample_input(name)
small = {k: rec[k] for k in ("frame", "variant", "license", "counts", "pillars", "cells", "output")}
small["ort_agreement"] = {"min_pcc": rec["ort_agreement"]["min_pcc"],
"same_detections": rec["ort_agreement"]["same_detections"]}
small_dir = small_golden_dir(src)
small_dir.mkdir(parents=True, exist_ok=True)
(small_dir / f"{name}.{variant}.json").write_text(json.dumps(small, indent=1))
(src.parent / f"{name}.{variant}.reference.json").write_text(json.dumps(body, indent=1))
voxels[f"{name}.npz"] = {"num_pillars": n, "num_pillars_total": p.pillars.num_pillars_total,
"points_sha256": sha(p.points), "features_sha256": sha(p.features[:n]),
"coords_sha256": sha(p.coords[:n]),
"canvas_index_sha256": sha(p.canvas_index)}
print(f"{variant} {name}: pillars {n}/{p.pillars.num_pillars_total} counts {run.counts} "
f"ort min pcc {rec['ort_agreement']['min_pcc']:.10f} same {same} ({t1 - t0:.1f} s + "
f"{time.perf_counter() - t1:.1f} s io)", flush=True)
manifest_path.write_text(json.dumps(manifest, indent=1))
if voxels:
(BUNDLE_GOLDENS / "voxels.json").write_text(json.dumps(voxels, indent=1))
return 0
def _wrap(a: np.ndarray) -> np.ndarray:
return np.abs((np.asarray(a, np.float64) + np.pi) % (2 * np.pi) - np.pi)
def research_agreement(run, golden_path: Path) -> dict:
"""This reference's objects vs the research ORT golden of the same input (independent code: research/centerpoint
scripts, ONNX Runtime): matched by cell; ``same`` needs the same cells, labels, counts and pillar counts and
values within :data:`RESEARCH_TOL`."""
g = json.loads(golden_path.read_text())
objs = run.objects
cells = objs.extra["cell"].tolist()
ref = {int(o["cell"]): o for o in g["objects"]}
rec = {"golden": str(golden_path), "reference": g.get("reference"), "objects": len(cells),
"objects_research": len(g["objects"]), "same_cells": sorted(cells) == sorted(ref),
"pillars": [run.prepared.num_pillars, run.prepared.pillars.num_pillars_total],
"pillars_research": [g["num_pillars"], g["num_pillars_total"]], "counts_research": g["counts"]}
if rec["same_cells"] and cells:
o = [ref[c] for c in cells]
rec["same_labels"] = [AUTOWARE_LABELS[int(v)] for v in objs.label] == [r["label"] for r in o]
col = {k: np.array([r[k] for r in o], np.float64) for k in ("score", "x", "y", "z", "length", "width",
"height", "yaw")}
rec["max_diff"] = {
"score": float(np.abs(objs.existence_probability - col["score"]).max()),
"xyz": float(max(np.abs(objs.x - col["x"]).max(), np.abs(objs.y - col["y"]).max(),
np.abs(objs.z - col["z"]).max())),
"size": float(max(np.abs(objs.length - col["length"]).max(), np.abs(objs.width - col["width"]).max(),
np.abs(objs.height - col["height"]).max())),
"yaw": float(_wrap(objs.yaw - col["yaw"]).max())}
else:
rec["same_labels"] = rec["same_cells"]
rec["max_diff"] = {k: 0.0 for k in RESEARCH_TOL}
rec["same"] = bool(rec["same_cells"] and rec["same_labels"] and rec["pillars"] == rec["pillars_research"]
and run.counts == g["counts"]
and all(rec["max_diff"][k] <= tol for k, tol in RESEARCH_TOL.items()))
return rec
def heldout(a) -> int:
"""``--set heldout``: compact goldens of the held-out frames (module docstring)."""
import onnxruntime
import torch
torch.set_num_threads(a.threads)
only = set(filter(None, a.only.split(",")))
frames = [f for f in heldout_frames(a.research, workspace=a.workspace) if not only or f.name in only]
manifest_path = a.out / "manifest.json"
manifest = json.loads(manifest_path.read_text()) if manifest_path.is_file() else {"files": {}}
manifest.setdefault("heldout", {}).update({
"bundle_version": __version__, "ttaw": ttaw_version, "torch": torch.__version__,
"onnxruntime": onnxruntime.__version__, "numpy": np.__version__, "python": platform.python_version(),
"candidate_min_score": CANDIDATE_MIN_SCORE, "written": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"command": " ".join(sys.argv), "frames": [f.name for f in frames]})
bad = []
for variant in a.variants.split(","):
rt = CenterPointReference(a.weights, variant, backend="torch", threads=a.threads)
ro = None
vdir = a.out / variant / "heldout"
vdir.mkdir(parents=True, exist_ok=True)
for fr in frames:
t0 = time.perf_counter()
calls = fr.calls()
for call in calls[:-1]: # prime the stream cache (cold start)
rt.pre(**call)
run = rt.run(**calls[-1])
p = run.prepared
cfg = rt.config
hm = np.asarray(run.heads["heatmap"], np.float32)[:len(cfg.class_names)]
cand = np.nonzero(sigmoid_f32(hm).max(axis=0).reshape(-1) >= np.float32(CANDIDATE_MIN_SCORE))[0]
cells_path = vdir / f"{fr.name}.cells.npz"
values = head_values_at(run.heads, cand)
save_goldens(cells_path, {"cell": cand.astype(np.int64), **values},
meta={"frame": fr.name, "variant": variant, "grid": list(hm.shape[1:]),
"min_score": CANDIDATE_MIN_SCORE, "license": fr.license}, compress=True)
body = run.output.to_dict()
rec = {"frame": fr.name, "dataset": fr.dataset, "variant": variant, "set": "heldout",
"license": fr.license, "shippable": fr.shippable, "source": fr.source,
"reference": "tt_centerpoint.reference torch fp32 (ONNX initializers, BN folded)",
"counts": run.counts, "pillars": {k: v for k, v in p.stats().items() if k != "densify"},
"densify": p.densify, "cells": run.objects.extra["cell"].tolist(),
"candidates": {"file": cells_path.name, "min_score": CANDIDATE_MIN_SCORE, "count": int(cand.size),
"grid": list(hm.shape[1:])}}
if fr.dataset == "rosbag": # no research golden: ONNX Runtime on the same voxels
if ro is None:
ro = CenterPointReference(a.weights, variant, backend="ort", threads=a.threads)
for call in calls[:-1]:
ro.pre(**call)
run_o = ro.run(**calls[-1])
assert np.array_equal(p.features, run_o.prepared.features), fr.name
heads = {k: {"pcc": float(pcc(run.heads[k], run_o.heads[k])),
"max_abs": float(np.abs(run.heads[k] - run_o.heads[k]).max())} for k in run.heads}
same = (run.counts == run_o.counts and run.objects.extra["cell"].tolist()
== run_o.objects.extra["cell"].tolist()
and run.objects.label.tolist() == run_o.objects.label.tolist())
rec["ort_agreement"] = {"min_pcc": min(v["pcc"] for v in heads.values()), "heads": heads,
"same_detections": bool(same), "ort_counts": run_o.counts}
ok = same and rec["ort_agreement"]["min_pcc"] >= 0.9999
else:
gpath = a.research / "public_data" / "goldens" / variant / fr.dataset / f"{fr.name}.json"
rec["research_agreement"] = research_agreement(run, gpath)
ok = rec["research_agreement"]["same"]
if not ok:
bad.append(f"{variant}/{fr.name}")
rec["output"] = body
det_path = vdir / f"{fr.name}.json"
det_path.write_text(json.dumps(rec, indent=1))
for f in (det_path, cells_path):
manifest["files"][str(f.relative_to(a.out))] = {"sha256": file_sha(f), "bytes": f.stat().st_size}
manifest_path.write_text(json.dumps(manifest, indent=1))
agree = rec.get("research_agreement", rec.get("ort_agreement"))
print(f"{variant} {fr.name}: pillars {p.num_pillars}/{p.pillars.num_pillars_total} counts {run.counts} "
f"candidates {cand.size} {'OK' if ok else 'DISAGREE'} "
f"{json.dumps(agree.get('max_diff', {'min_pcc': agree.get('min_pcc')}))} "
f"({time.perf_counter() - t0:.1f} s)", flush=True)
if bad:
print(f"reference disagreement on {bad}", flush=True)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
|