File size: 8,657 Bytes
5a5e5cf | 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 | #!/usr/bin/env python3
"""Run sequential PDM-Lite acceptance over the frozen CoDrive routes."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import shutil
import subprocess
import sys
import time
import xml.etree.ElementTree as ET
from collections import Counter
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
RUN_ONE = ROOT / "closed_dataset/scripts/run_pdm_acceptance_route.sh"
VALIDATE_ONE = ROOT / "closed_dataset/scripts/validate_pdm_acceptance.py"
FAMILY_ORDER = (
"occluded_pedestrian",
"lane_cut_in",
"reveal_obstacle",
"ghost_driver_left_turn",
"ghost_driver_right_turn",
"right_turn_on_red",
)
DEFAULT_GRAPHICS_ADAPTER = {0: 1, 1: 2, 2: 0, 3: 3}
def _route_family(route: Path) -> str:
return route.parent.name
def _route_id(route: Path) -> str:
return ET.parse(route).getroot().find("route").attrib["id"]
def _sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _quarantine_incomplete(run_dir: Path) -> None:
if not run_dir.exists() or not any(run_dir.iterdir()):
return
suffix = time.strftime("%Y%m%d_%H%M%S")
destination = run_dir.with_name(f"{run_dir.name}_incomplete_{suffix}")
counter = 1
while destination.exists():
destination = run_dir.with_name(
f"{run_dir.name}_incomplete_{suffix}_{counter:02d}"
)
counter += 1
shutil.move(str(run_dir), str(destination))
print(f"quarantined incomplete artifact: {destination}", flush=True)
def _select_routes(route_root: Path, families: list[str], one_per_family: bool) -> list[Path]:
routes = []
for family in FAMILY_ORDER:
if families and family not in families:
continue
family_routes = sorted((route_root / family).glob("*.xml"))
if one_per_family:
family_routes = family_routes[:1]
routes.extend(family_routes)
return routes
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--route-root",
type=Path,
default=ROOT / "closed_dataset/routes",
)
parser.add_argument(
"--run-root",
type=Path,
default=ROOT / "closed_dataset/acceptance_runs",
)
parser.add_argument("--family", action="append", choices=FAMILY_ORDER)
parser.add_argument("--one-per-family", action="store_true")
parser.add_argument("--max-routes", type=int, default=0)
parser.add_argument("--gpu", type=int, default=2)
parser.add_argument("--graphics-adapter", type=int)
parser.add_argument("--port", type=int, default=4897)
parser.add_argument("--tm-port", type=int, default=10897)
parser.add_argument("--walltime", type=int, default=480)
parser.add_argument("--rerun", action="store_true")
parser.add_argument(
"--revalidate-cache",
action="store_true",
help="Re-run the current validator before accepting a hash-matched cache.",
)
parser.add_argument("--fail-fast", action="store_true")
args = parser.parse_args()
route_root = args.route_root.resolve()
run_root = args.run_root.resolve()
run_root.mkdir(parents=True, exist_ok=True)
routes = _select_routes(route_root, args.family or [], args.one_per_family)
if args.max_routes > 0:
routes = routes[: args.max_routes]
if not routes:
raise SystemExit(f"No routes found under {route_root}")
summaries = []
total = len(routes)
for index, route in enumerate(routes, 1):
route_id = _route_id(route)
family = _route_family(route)
run_dir = run_root / family / route_id
report_path = run_dir / "acceptance_report.json"
route_sha256 = _sha256(route)
if report_path.is_file() and not args.rerun:
report = json.loads(report_path.read_text(encoding="utf-8"))
cache_matches = report.get("route_sha256") == route_sha256
if cache_matches and args.revalidate_cache:
validate_status = subprocess.run(
[
sys.executable,
str(VALIDATE_ONE),
str(run_dir),
"--output",
str(report_path),
],
start_new_session=True,
).returncode
report = json.loads(report_path.read_text(encoding="utf-8"))
report["validator_status"] = validate_status
report["route_id"] = route_id
report["family"] = family
report["route_sha256"] = route_sha256
if report.get("runner_status", 0) != 0:
report["accepted"] = False
report["errors"] = list(report.get("errors", []))
report["errors"].append(
f"acceptance runner exited with status "
f"{report['runner_status']}"
)
report_path.write_text(
json.dumps(report, indent=2, sort_keys=True) + "\n"
)
cache_matches = report["accepted"]
if cache_matches:
print(
f"[{index}/{total}] cached {route_id}: "
f"accepted={report['accepted']} hash={route_sha256[:12]}",
flush=True,
)
summaries.append(report)
if args.fail_fast and not report["accepted"]:
break
continue
print(
f"[{index}/{total}] stale cache for {route_id}; rerunning",
flush=True,
)
_quarantine_incomplete(run_dir)
run_dir.mkdir(parents=True, exist_ok=True)
env = os.environ.copy()
env.update(
{
"ROUTE": str(route),
"RUN_DIR": str(run_dir),
"GPU_RANK": str(args.gpu),
"CARLA_GRAPHICS_ADAPTER": str(
args.graphics_adapter
if args.graphics_adapter is not None
else DEFAULT_GRAPHICS_ADAPTER.get(args.gpu, args.gpu)
),
"PORT": str(args.port),
"TM_PORT": str(args.tm_port),
"EVAL_WALLTIME_SECONDS": str(args.walltime),
}
)
print(f"[{index}/{total}] running {route_id}", flush=True)
run_status = subprocess.run(
["bash", str(RUN_ONE)],
env=env,
start_new_session=True,
).returncode
validate_status = subprocess.run(
[
sys.executable,
str(VALIDATE_ONE),
str(run_dir),
"--output",
str(report_path),
],
start_new_session=True,
).returncode
report = json.loads(report_path.read_text(encoding="utf-8"))
report["runner_status"] = run_status
report["validator_status"] = validate_status
report["route_id"] = route_id
report["family"] = family
report["route_sha256"] = route_sha256
if run_status != 0:
report["accepted"] = False
report["errors"] = list(report.get("errors", []))
report["errors"].append(
f"acceptance runner exited with status {run_status}"
)
report_path.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n")
summaries.append(report)
print(
f"[{index}/{total}] {route_id}: accepted={report['accepted']} "
f"errors={report['errors']}",
flush=True,
)
if args.fail_fast and not report["accepted"]:
break
counts = Counter("accepted" if item["accepted"] else "rejected" for item in summaries)
suite_report = {
"route_root": str(route_root),
"run_root": str(run_root),
"route_count": len(summaries),
"accepted": counts["accepted"],
"rejected": counts["rejected"],
"routes": summaries,
}
(run_root / "acceptance_summary.json").write_text(
json.dumps(suite_report, indent=2, sort_keys=True) + "\n"
)
print(json.dumps({key: value for key, value in suite_report.items() if key != "routes"}, indent=2))
return 0 if counts["rejected"] == 0 else 1
if __name__ == "__main__":
raise SystemExit(main())
|