DeepanSadhukhan's picture
download
raw
11.2 kB
"""Environment test: one trained fleet (or one licensed driver) at one environment with n cars. Lights off,
deterministic actions (policy mean). One manifest line '<run id> <scene> <cars> <env seed>' is one test.
What a test records, per environment and traffic volume:
row totals: car-steps, the four cost parts, infractions, speed, time stopped, trip outcomes, conflict summary
trips every trip: outcome (arrive / crash / out / wrong / timeout = stood 30 s or took over 100 s), start and end
time in the episode, distance, duration, time stopped, safety cost
events every junction or merge conflict (sbcs/events.py): who went first, waits, PET, minimum TTC, collision
traj car positions, headings and speeds every 0.2 s over the first 100 s (trajectory plots)
An episode keeps n cars on the road for 100 s (a finished car is replaced); after that nobody is replaced and the
episode ends when the last trip does (MetaDrive's multi-agent horizon). The per-step totals of a row count the first
100 s only, where the volume is n; every trip starts there, and a trip's end time shows whether it finished in the
thinning tail. An episode also ends when every car on the road has just failed (with one car: at its first failed
trip), so a test drives until it has 'episodes' x 100 s at full volume, however many resets that takes.
Reading the tables: outcome shares come from the row counts or the trips table (every trip started at full volume).
Rates per time or per car-step (arrivals per minute, conflicts per car-step) come from the trips table (t0, t1, seconds)
and from events with t_open < 100 s, never from a row count divided by sim_s or steps. A row's event_collisions are
the collisions inside a recorded conflict only; all collisions are the crash trips and cost_collision. With one car,
average per operator (column operator): an episode ends at the first failed trip, so weak operators drive less.
Car slot j is driven by operator (j + episode * cars) % P, so with fewer cars than operators every network still
drives. Tests with fewer than 8 cars drive longer (at least 3,200 car-seconds per test).
python -m sbcs.envtest --tests manifests/envtest.txt --task 0 --per-task 64 --workdir /tmp/et
Output: bucket folder envtest/<manifest name>/ with NNNN.parquet (rows), trips_NNNN, events_NNNN and
traj_NNNN.parquet. Every table carries 'test' (the manifest line number) to join on.
"""
import argparse
import dataclasses
import multiprocessing as mp
import os
import sys
import time
import traceback
import numpy as np
import torch
from sbcs.citytest import OUTCOMES, outcome
from sbcs.crossplay import load_population
from sbcs.ppo_lag import Agents, Cfg
from sbcs.telemetry import Store, to_parquet_bytes
SUMS = ("cost", "cost_collision", "cost_ttc", "cost_pet", "cost_road", "inf_offside", "inf_kerb", "inf_reroute")
TRAJ = dict(test="int32", episode="int16", step="int16", slot="int16", x="float32", y="float32", heading="float32", speed="float32")
NAN = float("nan")
def drive(args):
test, rid, scene, n, seed, episodes, workdir = args
t_start = time.time()
os.environ["OMP_NUM_THREADS"] = "1"
torch.set_num_threads(1)
from sbcs.env import CityEnv
cfg, path = load_population(rid, workdir)
P = cfg.policies or cfg.num_agents
env = CityEnv(dict(scene=scene, obs_preset=cfg.obs_preset, num_agents=n, horizon=Cfg.horizon, start_seed=seed,
num_scenarios=1, log_level=50, signals=False))
o, _ = env.reset()
D = next(iter(o.values())).shape[0]
ag = Agents(dataclasses.replace(cfg, num_agents=P, policies=P), D)
ag.load_state_dict(torch.load(path, weights_only=True))
ag.eval()
tag = dict(test=test, fleet=rid, scene=scene, n=n)
tot = dict.fromkeys(("steps", "seen", "speed", "stopped") + SUMS, 0.0)
trips, events, traj, full, ep, H = [], [], [], 0, 0, Cfg.horizon # full: env steps driven at full volume
rng = np.random.default_rng(seed)
while full < episodes * H and ep < 50 * episodes:
if ep or n == 1:
if n == 1: # MetaDrive starts a lone car in the first spawn slot at every reset: vary it
rng.shuffle(env.engine.spawn_manager.available_agent_configs)
o, _ = env.reset()
op = (np.arange(n) + ep * n) % P
life, step, done_all = {}, 0, False
while not done_all:
steady = step < H
obs = np.zeros((n, D), np.float32)
for vid, x in o.items():
if vid in env.slot_of: # finished lives still report an obs (delay_done); only live slots act
obs[env.slot_of[vid]] = x
with torch.no_grad(): # every car through every operator's network; each takes its own operator's action
mu = ag.dist(torch.as_tensor(np.repeat(obs[:, None], P, 1))).mean.numpy()
act = mu[np.arange(n), op].clip(-1, 1)
for vid, v in env.agents.items():
x, y, sp = float(v.position[0]), float(v.position[1]), float(v.speed)
L = life.setdefault(vid, dict(x0=x, y0=y, t0=step, stop=0, cost=0.0))
L.update(x1=x, y1=y, stop=L["stop"] + (sp < 0.5))
if steady:
tot["seen"] += 1
tot["speed"] += sp
tot["stopped"] += sp < 0.5
if full + step < H and step % 2 == 0:
traj.append((test, ep, step, env.slot_of.get(vid, -1), x, y, float(v.heading_theta), sp))
slots = dict(env.slot_of) # a finished car's slot is freed inside step
o, r, tm, tc, info = env.step({vid: act[s] for vid, s in env.slot_of.items() if vid in env.agents})
step += 1
for vid, i in info.items():
if i.get("new_life"):
continue
if steady:
tot["steps"] += 1
for k in SUMS:
tot[k] += float(i.get(k, 0.0))
L = life.get(vid, {})
L["cost"] = L.get("cost", 0.0) + float(i.get("cost", 0.0))
if not (tm.get(vid) or tc.get(vid)):
continue
life.pop(vid, None)
out, s = outcome(i), slots.get(vid, -1)
trips.append(dict(tag, seed=seed, episode=ep, slot=s, operator=int(op[s]) if s >= 0 else -1, outcome=out,
cause=i.get("out_cause", "") if out == "out" else "",
x0=L.get("x0", NAN), y0=L.get("y0", NAN), x1=L.get("x1", NAN), y1=L.get("y1", NAN),
t0=0.1 * L.get("t0", step), t1=0.1 * step, dist=float(env.odo.get(vid, NAN)),
seconds=0.1 * (step - L.get("t0", step)),
stopped=0.1 * L.get("stop", 0), cost=L["cost"]))
for e in env.events.pop_records():
events.append(dict(e, **tag, episode=ep))
done_all = tm["__all__"] or tc["__all__"]
env.events.step(0.1 * step, {}, {}) # close what is still open: the tracker is not reset with the episode
env.events.merge_step(0.1 * step, {}, env._merge_defs())
events += [dict(e, **tag, episode=ep) for e in env.events.pop_records()]
full += min(step, H)
ep += 1
env.close()
ev = [e for e in events if e["complete"]]
row = dict(tag, seed=seed, episodes=ep, operators=P, train_scene=cfg.scene, train_seed=cfg.seed,
lagrangian=cfg.lagrangian, budget=cfg.budget if cfg.lagrangian != "none" else NAN, error="",
sim_s=0.1 * full, wall_s=time.time() - t_start, **tot, trips=len(trips), **{k: sum(t["outcome"] == k for t in trips) for k in OUTCOMES},
events=len(events), complete=len(ev), event_collisions=sum(bool(e["collision"]) for e in events),
wait_mean=float(np.mean([e["a_wait"] + e["b_wait"] for e in ev]) / 2) if ev else NAN)
return row, trips, events, np.asarray(traj, np.float32).reshape(-1, len(TRAJ))
def failed(args, error):
"""One failed test must not lose the other 63 of its task: it becomes a row with the error."""
print(f"test {args[0]} {args[1:5]} failed:\n{error}", flush=True)
return dict(test=args[0], fleet=args[1], scene=args[2], n=args[3], seed=args[4], error=error[-800:]), [], [], \
np.zeros((0, len(TRAJ)), np.float32)
def safe(args):
try:
return drive(args)
except Exception: # noqa: BLE001
return failed(args, traceback.format_exc())
def main():
p = argparse.ArgumentParser()
p.add_argument("--tests", required=True, help="file with lines '<run id> <scene> <cars> <env seed>'")
p.add_argument("--task", type=int, default=0)
p.add_argument("--per-task", type=int, default=64)
p.add_argument("--episodes", type=int, default=0, help="x 100 s at full volume; 0: max(4, 32 // cars)")
p.add_argument("--minutes", type=float, default=135, help="a test with no result by then becomes an error row")
p.add_argument("--workdir", default="/tmp/envtest")
p.add_argument("--procs", type=int, default=os.cpu_count())
a = p.parse_args()
os.makedirs(a.workdir, exist_ok=True)
lines, k0 = [l.split() for l in open(a.tests) if l.strip()], a.task * a.per_task
jobs = [(k0 + k, x[0], x[1], int(x[2]), int(x[3]), a.episodes or max(4, 32 // int(x[2])), a.workdir)
for k, x in enumerate(lines[k0:k0 + a.per_task])]
end, out = time.time() + 60 * a.minutes, []
with mp.get_context("spawn").Pool(min(a.procs, len(jobs)), maxtasksperchild=1) as pool: # a fresh process per
res = [pool.apply_async(safe, (j,)) for j in jobs] # test: a failed one leaves its MetaDrive engine behind
for j, r in zip(jobs, res):
try:
out.append(r.get(max(1.0, end - time.time())))
except Exception as e: # noqa: BLE001 the worker died or hangs: pool.map would wait for it forever
out.append(failed(j, f"no result: {e!r}"))
T = np.concatenate([t for *_, t in out])
tables = {"": [r for r, *_ in out], "trips_": [t for _, tr, _, _ in out for t in tr],
"events_": [e for _, _, ev, _ in out for e in ev],
"traj_": {c: T[:, k].astype(d) for k, (c, d) in enumerate(TRAJ.items())}}
st, name = Store("envtest"), os.path.basename(a.tests).split(".")[0]
for pre, rows in tables.items():
if len(rows):
local = os.path.join(a.workdir, f"{pre}{a.task:04d}.parquet")
with open(local, "wb") as f:
f.write(to_parquet_bytes(rows))
st.put(local, f"{name}/{pre}{a.task:04d}.parquet")
st.flush(timeout=1800) # the results are the whole output of the task: wait for the upload
bad = [r for r in tables[""] if r["error"]]
print(f"task {a.task}: {len(jobs)} tests, {len(bad)} failed, {len(tables['trips_'])} trips, {len(tables['events_'])} events")
if bad or (st.enabled and (st.busy or not st.q.empty())): # Slurm then shows the task as failed: run it again
sys.exit(1)
if __name__ == "__main__":
main()

Xet Storage Details

Size:
11.2 kB
·
Xet hash:
00e50e80aaf76bf4ecb5959500cb1c471ff888f2b930c0cd76f6c8c6688ce1f7

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.