ThuongBuiRVC's picture
Add files using upload-large-folder tool
cfa2024 verified
Raw History Blame Contribute Delete
52.5 kB
"""VLR stage S1: train the scene memory and the verifiable query heads; answer the benchmark questions from quantities.
Supervision (all from the annotation of the keyframe, with the devkit's own label rules):
objects Hungarian on 64 object queries: class, centre, log size, yaw, velocity, future xy, visible cameras
box queries every (object, camera) observation: distance, xy, velocity, class, direction text, future-motion label,
motion relation, path intersection, conflict
point queries every object (x, y): visible cameras (cross-view set), image region in each observing camera
distance listwise CE over 4 ground-distance hypotheses of a box: the train questions' own options, plus option
sets drawn as the devkit draws them (the distances of the other nearest grounded objects)
decision Driving decision as one of the 57 valid (lon, lat) pairs (Remain stopped only with No lateral action)
risk Counterfactual actions (Safe / Unsafe / Suboptimal) + the decision itself as Safe;
unsafe listwise CE over the 4 actions of the train unsafe-action questions
Losses are combined with learned uncertainty weights (Kendall 2018). Cameras absent at encoding (npz cam_ok) are masked.
Answering: every decision question of a keyframe reads one pair distribution restricted to the pairs consistent with
the options of all its decision questions (the devkit keeps the true label among the options).
Evaluation: the QAP val questions (3000), answered by rules from the predicted quantities; accuracy per subcategory,
plus the accuracy re-weighted to the test route mix (30 % turns). --export writes test answers {question_id: letter}.
Run: python vlr_s1.py --name s1 --cache <latent dir> --epochs 20
"""
import argparse
import json
import math
import pickle
import random
import time
from collections import Counter, defaultdict
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
from scipy.optimize import linear_sum_assignment
from torch.utils.data import DataLoader, Dataset
from gpu_take import take_gpu
from vlr_model import VLR, VLRPlan, rollout
from vlr_joint import VLRJoint, crit_loss, ego_targets, plan_losses, rho_features, speed_profiles
from vlr_v2 import VLRv2, plan_losses_v2, val_nps
# a batch carries many small tensors; sharing them by file descriptor exceeds `ulimit -n 1024` on the data machine
torch.multiprocessing.set_sharing_strategy('file_system')
HERE = Path(__file__).resolve().parent
CAMERAS = ['front', 'front_left', 'front_right', 'left', 'right', 'back', 'back_left', 'back_right']
REGIONS = ['upper left', 'upper center', 'upper right', 'middle left', 'middle center', 'middle right',
'lower left', 'lower center', 'lower right']
MOTION = ['approaching ego', 'moving away from ego', 'maintaining relative distance']
RISK = ['Safe', 'Unsafe', 'Suboptimal']
LON = ['Remain stopped', 'Quickly come to a stop', 'Gently come to a stop', 'Slow down quickly', 'Slow down gently',
'Quickly accelerate', 'Gently accelerate', 'Maintain speed', 'Reverse']
LAT = ['Slightly move left in the lane', 'Slightly move right in the lane', 'Left lane change', 'Right lane change',
'Turn left', 'Turn right', 'No lateral action']
CATEGORY_DISPLAY = {'vehicle.car': 'car', 'vehicle.truck': 'truck', 'vehicle.bus': 'bus', 'vehicle.motorcycle': 'motorcycle',
'vehicle.bicycle': 'bicycle', 'human.pedestrian': 'pedestrian', 'vehicle.construction': 'construction vehicle',
'vehicle.emergency': 'emergency vehicle', 'vehicle.trailer': 'trailer', 'movable_object.barrier': 'barrier',
'movable_object.trafficcone': 'traffic cone', 'static_object.bicycle_rack': 'bicycle rack'}
DIRECTION_DISPLAY = {'front': 'in front of', 'front_aligned': 'directly in front of', 'front_left': 'to the front-left of',
'front_right': 'to the front-right of', 'rear': 'behind', 'rear_aligned': 'directly behind',
'rear_left': 'to the rear-left of', 'rear_right': 'to the rear-right of', 'behind': 'behind',
'behind_aligned': 'directly behind', 'back_left': 'to the rear-left of', 'back_right': 'to the rear-right of',
'left_side': 'to the left of', 'right_side': 'to the right of'}
PAIRS = [(i, j) for i in range(9) for j in range(7) if i != 0 or j == 6] # devkit _all_valid_action_pairs: 57
PAIR_I = {p: k for k, p in enumerate(PAIRS)}
LOSSES = ['obj', 'box', 'point', 'decision', 'risk', 'unsafe', 'distance']
JOINT_LOSSES = ['vrel', 'rho', 'crit', 'speed', 'path', 'traj']
V2_LOSSES = ['vrel', 'rho', 'crit', 'qa_risk', 'qa_dec', 'traj', 'score']
FIXED = {'traj': 1.0, 'score': 1.0} # v2 planning losses: fixed weights, not uncertainty-weighted
MOTION_ANSWER = ['rho'] # future_motion answer of the joint model: 'rho' or 'head'
norm = lambda t: str(t).strip().lower().replace('_', ' ') # noqa: E731
def display_cat(c):
return CATEGORY_DISPLAY.get(c, c.split('.')[-1] if '.' in c else c)
def direction(o):
fr, lr = o.get('front_rear') or '', o.get('left_right') or ''
return DIRECTION_DISPLAY.get(f'{fr}_{lr}' if fr and lr else fr)
def region_of(box, W, H):
cx = int(round(((box[0] + box[2]) / 2) / (W - 1) * 1000)); cy = int(round(((box[1] + box[3]) / 2) / (H - 1) * 1000))
return (0 if cy < 333 else 1 if cy < 667 else 2) * 3 + (0 if cx < 333 else 1 if cx < 667 else 2)
# ------------------------------------------------------------------------------------------------ geometry
def cam_arrays(cam):
return np.asarray(cam['K'], np.float64), np.asarray(cam['R'], np.float64), np.asarray(cam['t'], np.float64), cam['W'], cam['H']
def pixel_rays(cam, u, v):
K, R, _, _, _ = cam_arrays(cam)
r = np.stack([u, v, np.ones_like(u)], -1) @ np.linalg.inv(K).T @ R.T
return r / np.linalg.norm(r, axis=-1, keepdims=True)
def grid_rays(cam):
j, i = np.meshgrid(np.arange(24), np.arange(24))
u, v = (j.reshape(-1) + .5) / 24 * cam['W'], (i.reshape(-1) + .5) / 24 * cam['H']
return np.concatenate([pixel_rays(cam, u, v), np.broadcast_to(np.asarray(cam['t']), (576, 3))], -1).astype(np.float32)
def box_feat(cam, b1000):
K, R, t, W, H = cam_arrays(cam)
x1, y1, x2, y2 = [c / 1000 for c in b1000]
u = np.array([(x1 + x2) / 2, (x1 + x2) / 2, (x1 + x2) / 2]) * (W - 1)
v = np.array([(y1 + y2) / 2, y2, y1]) * (H - 1)
return np.concatenate([pixel_rays(cam, u, v).reshape(-1), t, [x2 - x1, y2 - y1], [x1, y1, x2, y2]]).astype(np.float32)
def pair_index(a):
if not a or None in a:
return -1
lon, lat = a
return PAIR_I.get((lon, 6 if lon == 0 else lat), -1)
def _ray_at(t, d, v):
"""the point t + s d of a ray whose ground distance from the ego origin is v, and s."""
a, b, c = d[:2] @ d[:2], 2 * t[:2] @ d[:2], t[:2] @ t[:2] - v * v
s = (-b + math.sqrt(max(b * b - 4 * a * c, 0.0))) / (2 * max(a, 1e-6))
return t + s * d, s
def hyp_feat(cam, b1000, v):
"""geometric consistency of "the boxed object is at ground distance v" (devkit euclidean_distance_m = |centre_xy|):
the point of the box-centre ray at distance v, and the heights of the box bottom / top rays there (the bottom should
touch the ground; top - bottom is the implied object height)."""
_, _, t, W, H = cam_arrays(cam)
x1, y1, x2, y2 = [c / 1000 for c in b1000]
u = np.full(3, (x1 + x2) / 2 * (W - 1))
d = pixel_rays(cam, u, np.array([(y1 + y2) / 2, y2, y1]) * (H - 1))
p, s = _ray_at(t, d[0], v)
zb, zt = _ray_at(t, d[1], v)[0][2], _ray_at(t, d[2], v)[0][2]
return np.asarray([p[0] / 50, p[1] / 50, p[2] / 5, math.log(max(v, .5)) / 4, v / 50, s / 50,
zb, zt / 2, (zt - zb) / 2, math.log(max(zt - zb, .1))], np.float32)
HYP_DIM = 10
def coord_evidence(q, questions, cam):
"""other questions of the keyframe give exact ego-frame [x, y] of some objects: an option equal to |xy| of a point
that projects into the asked box is the answer (+1); one whose point projects elsewhere is a distractor (-1)."""
K, R, t, W, H = cam_arrays(cam)
x1, y1, x2, y2 = [c / 1000 for c in q['box']]
ev = np.zeros(len(q['options']))
for k, o in enumerate(q['options']):
v = opt_dist(o)
for x in questions:
if x is q or not x.get('xy') or abs(math.hypot(*x['xy']) - v) >= 0.06:
continue
inside = False
for z in (0.3, 0.8, 1.3):
pc = R.T @ (np.array([x['xy'][0], x['xy'][1], z]) - t)
if pc[2] > .1:
uu, vv = (K @ pc)[:2] / pc[2]
inside |= x1 * (W - 1) - 15 <= uu <= x2 * (W - 1) + 15 and y1 * (H - 1) - 15 <= vv <= y2 * (H - 1) + 15
ev[k] = max(ev[k], 1.0) if inside else (ev[k] if ev[k] > 0 else -1.0)
return ev
def opt_dist(o):
return float(o.split()[0])
def point_feat(cams, xy):
x, y = xy; d = math.hypot(x, y); th = math.atan2(y, x)
f = [x / 50, y / 50, d / 50, math.sin(th), math.cos(th)]
for c in CAMERAS:
K, R, t, W, H = cam_arrays(cams[c])
for z in (0.0, 1.0):
pc = R.T @ (np.array([x, y, z]) - t)
front = pc[2] > 0.1
uv = (K @ pc)[:2] / max(pc[2], 1e-3) if front else np.array([-1.0, -1.0])
inside = front and 0 <= uv[0] < W and 0 <= uv[1] < H
f += [float(np.clip(uv[0] / W, -2, 3)), float(np.clip(uv[1] / H, -2, 3)), float(front), float(inside)]
return np.asarray(f, np.float32)
def ego_feat(geo):
k = geo['kinematics']; p = geo['past']; r = int(geo['route'])
return np.asarray([k[0] / 20, k[1] / 5, k[2] / 5, k[3]] + [v for px, py, pyaw in p for v in (px / 20, py / 20, pyaw)]
+ [float(r == i) for i in (1, 2, 3)], np.float32)
# ------------------------------------------------------------------------------------------------ vocab / data
class Vocab:
def __init__(self, train):
cats = Counter(display_cat(o['cat']) for r in train for o in r.get('objects', []))
self.cls = [c for c, _ in cats.most_common(11)] + ['other']
dirs = Counter(direction(o) for r in train for o in r.get('objects', []) if direction(o))
self.dir = [d for d, _ in dirs.most_common(12)]
rels = Counter(norm(o['motion_rel']) for r in train for o in r.get('objects', []) if o.get('motion_rel'))
self.rel = [d for d, _ in rels.most_common(8)]
def cls_i(self, cat):
c = display_cat(cat)
return self.cls.index(c) if c in self.cls else len(self.cls) - 1
def npz_path(r, cache):
"""latent file of a record: set per record when several splits are merged (load_splits), else <cache>/<kf_id>.npz"""
return Path(r['_npz']) if r.get('_npz') else cache / f"{r['kf_id']}.npz"
def load_splits(data, cache, names):
"""records of one or more splits ('train,val,train_supp'); each record remembers its own latent file."""
out = []
for s in names.split(','):
cp = Path(data) / f'crit_{s}.pkl' # critical-component classes from the annotation text
crit = pickle.load(open(cp, 'rb')) if cp.is_file() else {}
for r in pickle.load(open(Path(data) / f'{s}.pkl', 'rb')):
r['_npz'] = str(Path(cache) / s / f"{r['kf_id']}.npz")
c = crit.get(r['kf_id'])
r['_crit'] = c['c'] if c and c.get('has_cc') else None
out.append(r)
return out
class KF(Dataset):
def __init__(self, recs, cache, voc, train, max_box=32, max_pt=16, ego_fut=None):
self.recs = [r for r in recs if npz_path(r, cache).is_file() and r.get('geo')]
self.cache, self.voc, self.train, self.max_box, self.max_pt = cache, voc, train, max_box, max_pt
self.ego_fut = ego_fut or {} # kf_id -> (51, 3) ego future (x, y, heading), 0.1 s
def __len__(self):
return len(self.recs)
def __getitem__(self, i):
r = self.recs[i]
z = np.load(npz_path(r, self.cache))
cams = r['geo']['cameras']
# cameras whose images were absent at encoding time (black frames) are masked out
cam_ok = z['cam_ok'].tolist() if 'cam_ok' in z.files else [True] * len(CAMERAS)
item = dict(i=i, front=torch.from_numpy(z['front']), side=torch.from_numpy(z['side']),
rays=torch.from_numpy(np.stack([grid_rays(cams[c]) for c in CAMERAS])),
ego=torch.from_numpy(ego_feat(r['geo'])), cam_ok=torch.tensor(cam_ok))
f = self.ego_fut.get(r['kf_id'])
item['fut'] = torch.from_numpy(f) if f is not None else torch.zeros(51, 3)
item['fut_m'] = torch.tensor(f is not None)
if not self.train:
return item
ok = {c for c, f in zip(CAMERAS, cam_ok) if f}
objs = [o for o in r.get('objects') or [] if not o['obs'] or ok & set(o['obs'])]
t = dict(cls=[], center=[], size=[], size_m=[], yaw=[], yaw_m=[], vel=[], fut=[], fut_m=[], vis=[])
for o in objs:
t['cls'].append(self.voc.cls_i(o['cat'])); t['center'].append(o['center']); t['vel'].append(o['vel'])
t['size'].append([math.log(max(s, .1)) for s in o['size']] if o['size'] else [0, 0, 0]); t['size_m'].append(o['size'] is not None)
t['yaw'].append([math.sin(o['yaw']), math.cos(o['yaw'])] if o['yaw'] is not None else [0, 0]); t['yaw_m'].append(o['yaw'] is not None)
fut = np.asarray(o['fut'], np.float32).reshape(-1, 2)
f10, m10 = np.zeros((10, 2), np.float32), np.zeros(10, bool)
if len(fut):
idx = np.linspace(0, len(fut) - 1, 11)[1:].round().astype(int)
f10, m10 = fut[idx] - np.asarray(o['center'][:2], np.float32), np.ones(10, bool)
t['fut'].append(f10.reshape(-1)); t['fut_m'].append(m10)
t['vis'].append([float(c in o['obs']) for c in CAMERAS])
item['obj'] = {k: torch.tensor(np.asarray(v), dtype=torch.long if k == 'cls' else (torch.bool if k.endswith('_m') else torch.float32)) for k, v in t.items()}
boxes = [(o, c, b) for o in objs for c, b in o['obs'].items() if c in cams and c in ok]
random.shuffle(boxes)
bx = defaultdict(list)
for o, c, b in boxes[:self.max_box]:
W, H = cams[c]['W'], cams[c]['H']
b1000 = [round(b[0] / (W - 1) * 1000), round(b[1] / (H - 1) * 1000), round(b[2] / (W - 1) * 1000), round(b[3] / (H - 1) * 1000)]
d = o['dist'] if o['dist'] is not None else math.hypot(*o['center'])
dr, rel = direction(o), norm(o['motion_rel']) if o.get('motion_rel') else None
bx['cam'].append(CAMERAS.index(c)); bx['feat'].append(box_feat(cams[c], b1000))
bx['dist'].append(math.log(max(d, .5))); bx['xy'].append(o['center'][:2]); bx['vel'].append(o['vel'])
bx['cls'].append(self.voc.cls_i(o['cat'])); bx['dir'].append(self.voc.dir.index(dr) if dr in self.voc.dir else -1)
bx['motion'].append(o['motion'] if o['motion'] is not None and o['motion'] < 3 else -1)
bx['rel'].append(self.voc.rel.index(rel) if rel in self.voc.rel else -1)
bx['path'].append(float(o['path_x'])); bx['conflict'].append(float(o['conflict']))
item['box'] = {k: torch.tensor(np.asarray(v)) for k, v in bx.items()}
pts = list(objs); random.shuffle(pts)
pt = defaultdict(list)
for o in pts[:self.max_pt]:
pt['feat'].append(point_feat(cams, o['center'][:2]))
pt['vis'].append([float(c in (o['views'] or o['obs'])) for c in CAMERAS])
pt['region'].append([region_of(o['obs'][c], cams[c]['W'], cams[c]['H']) if c in o['obs'] else -1 for c in CAMERAS])
item['pt'] = {k: torch.tensor(np.asarray(v)) for k, v in pt.items()}
dec = pair_index(r.get('decision'))
item['dec'] = torch.tensor(dec)
acts = [[*a['a'], a['risk']] for a in r.get('cf', []) if None not in a['a'] and a['risk'] < 3]
if dec >= 0 and list(PAIRS[dec]) not in [a[:2] for a in acts]:
acts.append([*PAIRS[dec], 0]) # the chosen decision is a safe action
item['risk'] = torch.tensor(acts, dtype=torch.long).reshape(-1, 3)
uq = [(q['opt_actions'], q['answer']) for q in r['questions'] if q['sub'] == 'unsafe_action_identification'
and len(q['opt_actions']) == 4 and all(a and None not in a for a in q['opt_actions'])]
item['uq'] = (torch.tensor([u[0] for u in uq], dtype=torch.long).reshape(-1, 4, 2), torch.tensor([u[1] for u in uq], dtype=torch.long))
item['dq'] = self.distance_sets(r, objs, cams, ok)
item['crit'] = torch.tensor(r['_crit'], dtype=torch.long) if r.get('_crit') is not None else None
return item
def distance_sets(self, r, objs, cams, ok):
"""the keyframe's distance questions + option sets drawn as gen_2d_to_3d_distance_choice does: the 5 nearest
grounded objects are asked, distractors are the (0.1 m rounded) distances of the 6 nearest, else +8/+12/-6/-10."""
rows = []
for q in r['questions']:
if q['sub'] == 'distance_from_2d_bbox' and q.get('cam') in ok and q.get('box') and len(q['options']) == 4:
rows.append((q['cam'], q['box'], [opt_dist(o) for o in q['options']], q['answer']))
near = sorted([o for o in objs if o['obs'] and o['dist'] is not None], key=lambda o: o['dist'])[:6]
for o in near[:5]:
cs = [c for c in o['obs'] if c in ok]
if not cs:
continue
c = random.choice(cs); b = o['obs'][c]; W, H = cams[c]['W'], cams[c]['H']
b1000 = [round(b[0] / (W - 1) * 1000), round(b[1] / (H - 1) * 1000), round(b[2] / (W - 1) * 1000), round(b[3] / (H - 1) * 1000)]
right = round(o['dist'], 1)
cand = {round(o2['dist'], 1) for o2 in near} - {right}
if len(cand) < 3:
cand |= {max(0.0, round(right + dl, 1)) for dl in (8.0, 12.0, -6.0, -10.0)} - {right}
opts = [right] + random.sample(sorted(cand), 3)
random.shuffle(opts)
rows.append((c, b1000, opts, opts.index(right)))
return dict(cam=torch.tensor([CAMERAS.index(c) for c, *_ in rows], dtype=torch.long),
feat=torch.from_numpy(np.stack([box_feat(cams[c], b) for c, b, *_ in rows])) if rows else torch.zeros(0, 18),
hyp=torch.from_numpy(np.stack([[hyp_feat(cams[c], b, v) for v in vs] for c, b, vs, _ in rows])) if rows else torch.zeros(0, 4, HYP_DIM),
ans=torch.tensor([x[3] for x in rows], dtype=torch.long))
def collate(b):
out = {k: torch.stack([x[k] for x in b]) for k in ('front', 'side', 'rays', 'ego', 'cam_ok', 'fut', 'fut_m')}
out['i'] = [x['i'] for x in b]
for k in ('obj', 'box', 'pt', 'risk', 'dec', 'uq', 'dq', 'crit'):
if k in b[0]:
out[k] = [x[k] for x in b]
return out
# ------------------------------------------------------------------------------------------------ losses
def vrel_l1(pred, vel, v0):
"""L1 to the velocity relative to the ego (v - [v0, 0]); moving objects weigh more (most objects are static,
and the static ones are already right; measured: velocity error ~0 static vs 2.6-3.8 m/s moving)."""
tgt = vel - torch.stack([v0, torch.zeros_like(v0)], -1)
w = 1 + vel.norm(dim=-1).clamp(max=10) / 2
return ((pred.float() - tgt).abs().sum(-1) * w).sum() / w.sum() / 2
def obj_loss(out, tgt, b, v0=None, side=None):
p = out['cls'][b].float().softmax(-1)
n = len(tgt['cls'])
C1 = out['cls'].shape[-1]
lbl = torch.full((out['cls'].shape[1],), C1 - 1, dtype=torch.long, device=p.device)
if n == 0:
return F.cross_entropy(out['cls'][b].float(), lbl, weight=_w(C1, p.device))
cost = -p[:, tgt['cls']] + 0.1 * torch.cdist(out['center'][b].float(), tgt['center'], p=1)
qi, gi = linear_sum_assignment(cost.detach().cpu().numpy())
qi, gi = torch.as_tensor(qi, device=p.device), torch.as_tensor(gi, device=p.device)
lbl[qi] = tgt['cls'][gi]
l = F.cross_entropy(out['cls'][b].float(), lbl, weight=_w(C1, p.device))
l = l + F.l1_loss(out['center'][b][qi].float(), tgt['center'][gi]) / 5 + F.l1_loss(out['vel'][b][qi].float(), tgt['vel'][gi]) / 2
sm, ym, fm = tgt['size_m'][gi], tgt['yaw_m'][gi], tgt['fut_m'][gi]
if sm.any():
l = l + F.l1_loss(out['size'][b][qi][sm].float(), tgt['size'][gi][sm])
if ym.any():
l = l + F.l1_loss(out['yaw'][b][qi][ym].float(), tgt['yaw'][gi][ym])
if fm.any():
f = out['fut'][b][qi].float().reshape(-1, 10, 2)[fm]; g = tgt['fut'][gi].reshape(-1, 10, 2)[fm]
l = l + F.l1_loss(f, g) / 5
if side is not None and 'vrel' in out:
side.append(vrel_l1(out['vrel'][b][qi], tgt['vel'][gi], v0.expand(len(gi))))
return l + F.binary_cross_entropy_with_logits(out['vis'][b][qi].float(), tgt['vis'][gi])
def _w(C1, dev):
w = torch.ones(C1, device=dev); w[-1] = 0.1
return w
def ce(logit, y):
m = y >= 0
return F.cross_entropy(logit[m].float(), y[m]) if m.any() else logit.sum() * 0
# ------------------------------------------------------------------------------------------------ answering
DECISION_SUBS = ('driving_decision_longitudinal', 'driving_decision_lateral', 'driving_decision_joint')
def answer(model, recs, cache, voc, dev, use_options=True):
"""-> res {question_id: (pred_index, answer_index, subcategory, route)}, risk {question_id: (P(risk), options)}.
Subcategories starting with '~' are diagnostics, not counted in the accuracy."""
model.eval()
res, risk = {}, {}
ds = KF(recs, cache, voc, False)
dl = DataLoader(ds, batch_size=2, num_workers=4, collate_fn=collate)
with torch.no_grad():
for b in dl:
with torch.autocast('cuda', dtype=torch.bfloat16):
tok, obj, ctx, _ = model.forward_scene(b['front'].to(dev), b['side'].to(dev), b['rays'].to(dev), b['cam_ok'].to(dev))
e = model.ego_token(b['ego'].to(dev))
dlog = model.decision(ctx, e)
for j, i in enumerate(b['i']):
r = ds.recs[i]; cams = r['geo']['cameras']; route = int(r['geo']['route'])
lp = pair_posterior(dlog[j], r['questions'] if use_options else [])
lp_own = pair_posterior(dlog[j], [])
for q in r['questions']:
if q['sub'] in DECISION_SUBS: # test-like diagnostic: most test keyframes have one decision question
res[q['id'] + '~own'] = (answer_one(model, q, tok, obj, ctx, e, lp_own, j, cams, voc, dev, {}, res, route, []),
q['answer'], '~' + q['sub'] + '_own_options', route)
try:
p = answer_one(model, q, tok, obj, ctx, e, lp, j, cams, voc, dev, risk, res, route,
r['questions'] if use_options else [])
except Exception as ex: # noqa: BLE001
print('answer failed', q['sub'], repr(ex)[:120], flush=True); p = 0
res[q['id']] = (p, q['answer'], q['sub'], route)
model.train()
return res, risk
def pair_posterior(logit, questions):
"""log P(pair | scene) restricted to the pairs consistent with the options of every decision question."""
lp = logit.float().log_softmax(-1).cpu().numpy()
keep = np.ones(len(PAIRS), bool)
for q in questions:
if q['sub'] == 'driving_decision_longitudinal':
al = {LON.index(o) for o in q['options'] if o in LON}
keep &= np.array([p[0] in al for p in PAIRS])
elif q['sub'] == 'driving_decision_lateral':
al = {LAT.index(o) for o in q['options'] if o in LAT}
keep &= np.array([p[1] in al for p in PAIRS])
elif q['sub'] == 'driving_decision_joint':
al = {pair_index(a) for a in q.get('opt_actions', [])}
keep &= np.array([k in al for k in range(len(PAIRS))])
return np.where(keep, lp, -1e9) if keep.any() else lp
def answer_one(model, q, tok, obj, ctx, e, lp, j, cams, voc, dev, risk, res, route, questions):
sub, opts = q['sub'], q['options']
kf = torch.tensor([j], device=dev)
if 'box' in q and q.get('cam') in cams:
ci = torch.tensor([CAMERAS.index(q['cam'])], device=dev)
bf = torch.from_numpy(box_feat(cams[q['cam']], q['box']))[None].to(dev)
if sub == 'distance_from_2d_bbox':
vals = [opt_dist(o) for o in opts]
hyp = torch.from_numpy(np.stack([hyp_feat(cams[q['cam']], q['box'], v) for v in vals]))[None].to(dev)
with torch.autocast('cuda', dtype=torch.bfloat16):
sc = model.query_distance(tok, obj, ctx, kf, ci, bf, hyp)[0].float()
d = float(model.query_box(tok, obj, ctx, kf, ci, bf)['dist'][0, 0].float().exp())
reg = int(np.argmin([abs(math.log(max(v, .1)) - math.log(d)) for v in vals]))
res[q['id'] + '~reg'] = (reg, q['answer'], '~distance_regression_rule', route)
res[q['id'] + '~model'] = (int(sc.argmax()), q['answer'], '~distance_model_only', route)
return int(np.argmax(sc.cpu().numpy() + 100 * coord_evidence(q, questions, cams[q['cam']])))
with torch.autocast('cuda', dtype=torch.bfloat16):
out = model.query_box(tok, obj, ctx, kf, ci, bf)
if sub in ('ego_position_from_2d_bbox', 'object_relative_position'):
return pick(out['dir'][0], voc.dir, opts)
if sub == 'closest_object_type':
return pick(out['cls'][0], voc.cls, opts)
if sub == 'future_motion_label':
head = pick(out['motion'][0], MOTION, opts)
if 'vrel' not in out:
return head
rho = pick(model.rho_mot(rho_features(out['xy'].float(), out['vrel'].float()))[0], MOTION, opts)
res[q['id'] + '~mot'] = (rho if MOTION_ANSWER[0] == 'head' else head, q['answer'],
'~future_motion_head' if MOTION_ANSWER[0] == 'rho' else '~future_motion_rho', route)
return rho if MOTION_ANSWER[0] == 'rho' else head
if sub == 'motion_relation':
return pick(out['rel'][0], voc.rel, opts)
if sub in ('future_path_intersection', 'conflict_prediction'):
yes = float(torch.sigmoid(out['path' if sub == 'future_path_intersection' else 'conflict'][0, 0].float())) > 0.5
return next((k for k, o in enumerate(opts) if o.lower().startswith('yes') == yes), 0)
if 'xy' in q and sub in ('camera_view_for_3d_object', 'multiview_camera_pair', 'image_region_from_3d_object'):
with torch.autocast('cuda', dtype=torch.bfloat16):
out = model.query_point(obj, ctx, kf, torch.from_numpy(point_feat(cams, q['xy']))[None].to(dev))
vis = out['vis'][0].float()
if sub == 'camera_view_for_3d_object':
return int(np.argmax([float(vis[CAMERAS.index(norm(o).replace(' ', '_'))]) for o in opts]))
if sub == 'multiview_camera_pair':
return int(np.argmax([sum(float(vis[CAMERAS.index(c.strip().replace(' ', '_'))]) for c in norm(o).split('+')) for o in opts]))
c = CAMERAS.index(q['cam']) if q.get('cam') in CAMERAS else int(vis.argmax())
return pick(out['region'][0, c].float(), REGIONS, opts)
if sub == 'driving_decision_longitudinal':
m = marginal(lp, 0, len(LON))
return int(np.argmax([m[LON.index(o)] if o in LON else -1e9 for o in opts]))
if sub == 'driving_decision_lateral':
m = marginal(lp, 1, len(LAT))
return int(np.argmax([m[LAT.index(o)] if o in LAT else -1e9 for o in opts]))
if sub == 'driving_decision_joint':
return int(np.argmax([lp[pair_index(a)] if pair_index(a) >= 0 else -1e9 for a in q.get('opt_actions', [])]))
if sub == 'action_risk_assessment' and q.get('action') and None not in q['action']:
pr, _ = risk_out(model, obj, ctx, e, j, [q['action']], dev)
risk[q['id']] = (pr[0], opts)
return risk_pick(pr[0], opts, 0.0)
if sub == 'unsafe_action_identification':
acts = [a if a and None not in a else [7, 6] for a in q.get('opt_actions', [])]
_, sc = risk_out(model, obj, ctx, e, j, acts, dev)
return int(np.argmax(sc))
return 0
def marginal(lp, k, n):
m = np.full(n, -1e9)
for (p, v) in zip(PAIRS, lp):
m[p[k]] = np.logaddexp(m[p[k]], v)
return m
def risk_pick(pr, opts, bias):
"""devkit: correct + distractors from [Safe, Unsafe, Moderate risk, Highly dangerous], so 'Suboptimal' is listed only
when it is the answer; otherwise Safe vs Unsafe, with a log-prior shift `bias` on Safe."""
if 'Suboptimal' in opts:
return opts.index('Suboptimal')
safe = math.log(max(pr[0], 1e-9)) + bias > math.log(max(pr[1] + pr[2], 1e-9))
want = 'Safe' if safe else 'Unsafe'
return opts.index(want) if want in opts else 0
def tune_risk(res, risk):
"""the Safe log-prior shift that maximises the risk-question accuracy (one scalar)."""
best = (-1, 0.0)
for bias in np.linspace(-4, 4, 33):
acc = np.mean([risk_pick(pr, o, bias) == res[k][1] for k, (pr, o) in risk.items()]) if risk else 0
best = max(best, (acc, float(bias)))
return best[1]
def apply_risk(res, risk, bias):
for k, (pr, o) in risk.items():
p, a, s, r = res[k]; res[k] = (risk_pick(pr, o, bias), a, s, r)
def pick(logit, vocab, opts):
lp = logit.float().log_softmax(-1)
v = [norm(x) for x in vocab]
return int(np.argmax([float(lp[v.index(norm(o))]) if norm(o) in v else -1e9 for o in opts]))
def risk_out(model, obj, ctx, e, j, acts, dev):
a = torch.tensor(acts, device=dev)
kf = torch.full((len(acts),), j, device=dev)
with torch.autocast('cuda', dtype=torch.bfloat16):
lo, sc = model.risk(obj, ctx, e, kf, a[:, 0], a[:, 1])
return lo.float().softmax(-1).cpu().numpy(), sc.float().cpu().numpy()
def plan_select(model, obj, ctx, e, j, dlog, dev, k=5):
"""S3 at test time: top-k actions of the decision distribution, weight w = p(a) * P(Safe | a); path of the best
action, speed = expectation of the action speeds under w (Bayes choice under action uncertainty)."""
p = dlog.float().softmax(-1)
top = p.argsort(descending=True)[:k]
a = torch.tensor([PAIRS[int(i)] for i in top], device=dev)
kf = torch.full((len(top),), j, device=dev)
with torch.autocast('cuda', dtype=torch.bfloat16):
_, v, H, lo = model.plan(obj, ctx, e, kf, a[:, 0], a[:, 1])
w = p[top] * lo.float().softmax(-1)[:, 0]
w = w / w.sum().clamp(min=1e-9)
traj = rollout((w[:, None] * v.float()).sum(0, keepdim=True), H[int(w.argmax())][None].float())[0]
return traj.cpu().numpy()
def plan_predict(model, recs, cache, voc, dev, ego_fut=None):
"""{kf_id: (51, 3)} planned trajectories and the errors against the labelled ego futures."""
if isinstance(model, VLRv2):
return plan_predict_v2(model, recs, cache, voc, dev, ego_fut)
if isinstance(model, VLRJoint):
return plan_predict_joint(model, recs, cache, voc, dev, ego_fut)
model.eval()
ds = KF(recs, cache, voc, False, ego_fut=ego_fut)
dl = DataLoader(ds, batch_size=2, num_workers=4, collate_fn=collate)
out, err = {}, defaultdict(list)
with torch.no_grad():
for b in dl:
with torch.autocast('cuda', dtype=torch.bfloat16):
tok, obj, ctx, _ = model.forward_scene(b['front'].to(dev), b['side'].to(dev), b['rays'].to(dev), b['cam_ok'].to(dev))
e = model.ego_token(b['ego'].to(dev))
dlog = model.decision(ctx, e)
for j, i in enumerate(b['i']):
tr = plan_select(model, obj, ctx, e, j, dlog[j], dev)
out[ds.recs[i]['kf_id']] = tr
if b['fut_m'][j]:
g = b['fut'][j].numpy(); d = tr[1:, :2] - g[1:, :2]
u = g[-1, :2] - g[-6, :2]; u = u / max(np.linalg.norm(u), 1e-6) if np.linalg.norm(u) > .05 else np.array([1., 0.])
err['ade'].append(np.linalg.norm(d, axis=1).mean()); err['fde'].append(np.linalg.norm(d[-1]))
err['along'].append(abs(d[-1] @ u)); err['cross'].append(abs(d[-1, 0] * u[1] - d[-1, 1] * u[0]))
model.train()
return out, {k: round(float(np.mean(v)), 3) for k, v in err.items()}
def traj_errors(err, tr, g):
d = tr[1:, :2] - g[1:, :2]
u = g[-1, :2] - g[-6, :2]; u = u / max(np.linalg.norm(u), 1e-6) if np.linalg.norm(u) > .05 else np.array([1., 0.])
err['ade'].append(np.linalg.norm(d, axis=1).mean()); err['fde'].append(np.linalg.norm(d[-1]))
err['along'].append(abs(d[-1] @ u)); err['cross'].append(abs(d[-1, 0] * u[1] - d[-1, 1] * u[0]))
def plan_predict_joint(model, recs, cache, voc, dev, ego_fut=None):
"""joint model: trajectory = most likely path o Bayes-L1 progress profile (no action enumeration)."""
model.eval()
ds = KF(recs, cache, voc, False, ego_fut=ego_fut)
dl = DataLoader(ds, batch_size=2, num_workers=4, collate_fn=collate)
out, err = {}, defaultdict(list)
with torch.no_grad():
for b in dl:
with torch.autocast('cuda', dtype=torch.bfloat16):
model.forward_scene(b['front'].to(dev), b['side'].to(dev), b['rays'].to(dev), b['cam_ok'].to(dev))
e = model.ego_token(b['ego'].to(dev))
model.joint_heads(e)
tr = model.plan_traj(e, (b['ego'][:, 0] * 20).float().to(dev)).float().cpu().numpy()
for j, i in enumerate(b['i']):
out[ds.recs[i]['kf_id']] = tr[j]
if b['fut_m'][j]:
traj_errors(err, tr[j], b['fut'][j].numpy())
model.train()
return out, {k: round(float(np.mean(v)), 3) for k, v in err.items()}
def plan_predict_v2(model, recs, cache, voc, dev, ego_fut=None):
"""v2: K candidates from the planning queries, the one with the highest predicted 0.3 EP + 0.2 CF + 0.5 HL."""
model.eval()
ds = KF(recs, cache, voc, False, ego_fut=ego_fut)
dl = DataLoader(ds, batch_size=2, num_workers=4, collate_fn=collate)
out, err = {}, defaultdict(list)
with torch.no_grad():
for b in dl:
with torch.autocast('cuda', dtype=torch.bfloat16):
model.forward_scene(b['front'].to(dev), b['side'].to(dev), b['rays'].to(dev), b['cam_ok'].to(dev))
model.reasoning(model.ego_token(b['ego'].to(dev)))
pc = model.plan_candidates()
sel = VLRv2.select(pc['score']).argmax(-1)
tr = pc['traj'][torch.arange(len(sel), device=sel.device), sel].float().cpu().numpy()
for j, i in enumerate(b['i']):
out[ds.recs[i]['kf_id']] = tr[j]
if b['fut_m'][j]:
traj_errors(err, tr[j], b['fut'][j].numpy())
model.train()
return out, {k: round(float(np.mean(v)), 3) for k, v in err.items()}
TEST_MIX = {} # subcategory -> share of the test questions (set in main)
def report(res):
"""-> accuracy over all questions, test-like accuracy, per-subcategory accuracy. Test-like = the per-subcategory
accuracies weighted by the test question mix (TEST_MIX) when it is set, else re-weighted to the test route mix."""
per = defaultdict(list); route = defaultdict(list)
for p, a, s, r in res.values():
if a >= 0:
per[s].append(p == a)
if not s.startswith('~'):
route['turn' if r in (2, 3) else 'straight'].append(p == a)
acc = float(np.mean([x for s, v in per.items() if not s.startswith('~') for x in v])) if per else float('nan')
tl = 0.7 * np.mean(route['straight']) + 0.3 * np.mean(route['turn']) if route['turn'] and route['straight'] else float('nan')
if TEST_MIX:
# a test keyframe carries ~0.5 decision questions, so a decision question is scored with its own options only
acc_of = {s: np.mean(per.get(f'~{s}_own_options') or per[s]) if s in DECISION_SUBS else np.mean(per[s]) for s in per}
w = {s: TEST_MIX[s] for s in per if s in TEST_MIX}
tl = sum(w[s] * acc_of[s] for s in w) / sum(w.values()) if w else float('nan')
return acc, float(tl), {k: round(float(np.mean(v)), 3) for k, v in sorted(per.items())}
# ------------------------------------------------------------------------------------------------ main
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--name', required=True); ap.add_argument('--cache', required=True)
ap.add_argument('--data', default=str(HERE / 'data')); ap.add_argument('--epochs', type=int, default=20)
ap.add_argument('--batch', type=int, default=4); ap.add_argument('--lr', type=float, default=2e-4)
ap.add_argument('--train-split', default='train', help='one split or several, e.g. train,val,train_supp')
ap.add_argument('--val-split', default='val'); ap.add_argument('--limit', type=int, default=0)
ap.add_argument('--export', action='store_true'); ap.add_argument('--ego-drop', type=float, default=0.3)
ap.add_argument('--no-options', action='store_true', help='decision questions without the cross-question option constraint')
ap.add_argument('--model', choices=['s1', 'plan', 'joint', 'v2'], default='s1',
help='plan = S1 + S2 action reasoner + S3 planner; joint = S2 + relative velocity, critical components, speed / path (vlr_joint.py)')
ap.add_argument('--motion-answer', choices=['rho', 'head'], default='rho', help='joint: future_motion from rho(xy, vrel) or the direct head')
ap.add_argument('--init', default='', help='checkpoint to start from (S1 best.pt for the plan stage)')
ap.add_argument('--ego-fut', default='', help='pickle {kf_id: (51, 3) ego future} for the planner')
a = ap.parse_args()
random.seed(0); torch.manual_seed(0)
dev = torch.device('cuda'); cache = Path(a.cache)
out = HERE / 'runs' / a.name; out.mkdir(parents=True, exist_ok=True)
tr = load_splits(a.data, cache, a.train_split); va = load_splits(a.data, cache, a.val_split)
assert not {r['clip'] for r in tr} & {r['clip'] for r in va}, 'train and val share clips'
# test = the QAP test keyframes + the submission clips without a question (test_extra): every clip gets a trajectory
te = load_splits(a.data, cache, 'test' + (',test_extra' if (Path(a.data) / 'test_extra.pkl').is_file() else ''))
mix = Counter(q['sub'] for r in te for q in r['questions'])
TEST_MIX.update({k: v / sum(mix.values()) for k, v in mix.items()})
if a.limit:
tr = tr[:a.limit]
voc = Vocab(tr)
if a.init:
ck0 = torch.load(a.init, map_location='cpu', weights_only=False); voc.__dict__.update(ck0['voc'])
ego_fut = pickle.load(open(a.ego_fut, 'rb')) if a.ego_fut else None
plan = a.model == 'plan'
joint = a.model == 'joint'
v2 = a.model == 'v2'
MOTION_ANSWER[0] = a.motion_answer
names = LOSSES + (['plan'] if plan else []) + (JOINT_LOSSES if joint else []) + (V2_LOSSES if v2 else [])
if joint or v2:
assert ego_fut, '--ego-fut is required for the joint model'
print('critical-component labels on', sum(r['_crit'] is not None for r in tr), '/', len(tr), 'train keyframes', flush=True)
ds = KF(tr, cache, voc, True, ego_fut=ego_fut)
print(f'train keyframes with latents {len(ds)} / {len(tr)} | vocab cls {voc.cls} dir {voc.dir} rel {voc.rel}', flush=True)
take_gpu(10000) # shared GPU: hand-over from gpu_hold.py (or wait), right before allocating
model = (VLRv2 if v2 else VLRJoint if joint else VLRPlan if plan else VLR)(
n_cls=len(voc.cls), n_dir=len(voc.dir), n_rel=max(len(voc.rel), 1), **(dict(pairs=PAIRS) if v2 else {})).to(dev)
if a.init:
sd = ck0['model']
if (plan or joint) and not any(k.startswith('risk2.') for k in sd): # from S1: the S2 reasoner starts from the S1 one
sd = dict(sd, **{k.replace('risk_dec.', 'risk2.'): v for k, v in sd.items() if k.startswith('risk_dec.')},
**{k.replace('h_risk.', 'h_risk2.'): v for k, v in sd.items() if k.startswith('h_risk.')})
if v2 and not any(k.startswith('reason.') for k in sd): # the v2 reasoning decoder starts from the S2 reasoner
sd = dict(sd, **{'reason.' + k[len('risk2.'):]: v for k, v in sd.items() if k.startswith('risk2.')},
**{'h_feas.' + k[len('h_risk2.'):]: v for k, v in sd.items() if k.startswith('h_risk2.')})
missing, unexpected = model.load_state_dict(sd, strict=False)
print('init from', a.init, '| new / missing:', sorted({'.'.join(k.split('.')[:2]) for k in missing}), '| unused:', sorted({k.split('.')[0] for k in unexpected}), flush=True)
if joint and not (a.init and 'speed_prof' in ck0['model']):
devs = []
for r in ds.recs:
f = ego_fut.get(r['kf_id'])
if f is not None:
devs.append(ego_targets(np.asarray(f), float(ego_feat(r['geo'])[0] * 20))[0])
model.speed_prof.copy_(torch.from_numpy(speed_profiles(np.stack(devs))).to(dev))
print('speed profiles from', len(devs), 'train ego futures', flush=True)
print('PARAMETERS', sum(p.numel() for p in model.parameters()) / 1e6, 'M', flush=True)
logv = torch.zeros(len(names), device=dev, requires_grad=True)
opt = torch.optim.AdamW(list(model.parameters()) + [logv], lr=a.lr, weight_decay=0.05)
dl = DataLoader(ds, batch_size=a.batch, shuffle=True, num_workers=6, collate_fn=collate, drop_last=True, persistent_workers=True)
steps = a.epochs * len(dl)
sched = torch.optim.lr_scheduler.OneCycleLR(opt, a.lr, total_steps=max(steps, 1), pct_start=0.05)
log = (out / 'log.jsonl').open('a'); best = -1; best_ade = 1e9; use_opt = not a.no_options
for ep in range(1, a.epochs + 1):
t0, agg = time.time(), np.zeros(len(names))
for b in dl:
with torch.autocast('cuda', dtype=torch.bfloat16):
tok, obj, ctx, o = model.forward_scene(b['front'].to(dev), b['side'].to(dev), b['rays'].to(dev), b['cam_ok'].to(dev))
e = model.ego_token(b['ego'].to(dev), a.ego_drop)
dlog = model.decision(ctx, e)
zero = dlog.sum() * 0
v0b = (b['ego'][:, 0] * 20).float().to(dev); side = [] if (joint or v2) else None; jl = {}
L = [sum(obj_loss(o, {k: v.to(dev) for k, v in t.items()}, j, v0b[j], side) for j, t in enumerate(b['obj'])) / len(b['obj'])]
boxes = [(j, x) for j, x in enumerate(b['box']) if len(x)]
if boxes:
kfi = torch.cat([torch.full((len(x['cam']),), j) for j, x in boxes]).to(dev)
bb = {k: torch.cat([x[k] for _, x in boxes]).to(dev) for k in boxes[0][1]}
with torch.autocast('cuda', dtype=torch.bfloat16):
qo = model.query_box(tok, obj, ctx, kfi, bb['cam'].long(), bb['feat'].float())
L.append(F.l1_loss(qo['dist'][:, 0].float(), bb['dist'].float()) + F.l1_loss(qo['xy'].float(), bb['xy'].float()) / 5
+ F.l1_loss(qo['vel'].float(), bb['vel'].float()) / 2 + ce(qo['cls'], bb['cls'].long()) + ce(qo['dir'], bb['dir'].long())
+ ce(qo['motion'], bb['motion'].long()) + ce(qo['rel'], bb['rel'].long())
+ F.binary_cross_entropy_with_logits(qo['path'][:, 0].float(), bb['path'].float())
+ F.binary_cross_entropy_with_logits(qo['conflict'][:, 0].float(), bb['conflict'].float()))
if joint or v2: # relative velocity of the box query; rho learned on annotated quantities only
rel = bb['vel'].float() - torch.stack([v0b[kfi], torch.zeros_like(v0b[kfi])], -1)
jl['vrel_box'] = vrel_l1(qo['vrel'], bb['vel'].float(), v0b[kfi])
jl['rho'] = ce(model.rho_mot(rho_features(bb['xy'].float(), rel)), bb['motion'].long())
else:
L.append(zero)
pts = [(j, x) for j, x in enumerate(b['pt']) if len(x)]
if pts:
pki = torch.cat([torch.full((len(x['feat']),), j) for j, x in pts]).to(dev)
pp = {k: torch.cat([x[k] for _, x in pts]).to(dev) for k in pts[0][1]}
with torch.autocast('cuda', dtype=torch.bfloat16):
po = model.query_point(obj, ctx, pki, pp['feat'].float())
rg = pp['region'].long(); m = rg >= 0
L.append(F.binary_cross_entropy_with_logits(po['vis'].float(), pp['vis'].float())
+ (F.cross_entropy(po['region'][m].float(), rg[m]) if m.any() else 0))
else:
L.append(zero)
L.append(ce(dlog, torch.stack(b['dec']).to(dev)))
rk = [(j, x) for j, x in enumerate(b['risk']) if len(x)]
if rk:
ki = torch.cat([torch.full((len(x),), j) for j, x in rk]).to(dev); rr = torch.cat([x for _, x in rk]).to(dev)
with torch.autocast('cuda', dtype=torch.bfloat16):
lo, _ = model.risk(obj, ctx, e, ki, rr[:, 0], rr[:, 1])
L.append(F.cross_entropy(lo.float(), rr[:, 2]))
else:
L.append(zero)
uq = [(j, x) for j, x in enumerate(b['uq']) if len(x[1])]
if uq:
ua = torch.cat([x[0] for _, x in uq]).to(dev).reshape(-1, 2)
ui = torch.cat([torch.full((len(x[1]) * 4,), j) for j, x in uq]).to(dev)
with torch.autocast('cuda', dtype=torch.bfloat16):
_, sc = model.risk(obj, ctx, e, ui, ua[:, 0], ua[:, 1])
L.append(F.cross_entropy(sc.float().reshape(-1, 4), torch.cat([x[1] for _, x in uq]).to(dev)))
else:
L.append(zero)
dq = [(j, x) for j, x in enumerate(b['dq']) if len(x['ans'])]
if dq:
di = torch.cat([torch.full((len(x['ans']),), j) for j, x in dq]).to(dev)
dd = {k: torch.cat([x[k] for _, x in dq]).to(dev) for k in dq[0][1]}
with torch.autocast('cuda', dtype=torch.bfloat16):
sc = model.query_distance(tok, obj, ctx, di, dd['cam'], dd['feat'].float(), dd['hyp'].float())
L.append(F.cross_entropy(sc.float(), dd['ans']))
else:
L.append(zero)
if plan:
pl = [(j, int(d)) for j, d in enumerate(b['dec']) if d >= 0 and b['fut_m'][j]]
if pl:
ki = torch.tensor([j for j, _ in pl], device=dev)
aa = torch.tensor([PAIRS[d] for _, d in pl], device=dev)
with torch.autocast('cuda', dtype=torch.bfloat16):
traj, _, _, _ = model.plan(obj, ctx, e, ki, aa[:, 0], aa[:, 1])
g = b['fut'][ki.cpu()].to(dev)
dh = torch.atan2(torch.sin(traj[:, 1:, 2] - g[:, 1:, 2]), torch.cos(traj[:, 1:, 2] - g[:, 1:, 2]))
L.append(F.l1_loss(traj[:, 1:, :2], g[:, 1:, :2]) + .5 * dh.abs().mean())
else:
L.append(zero)
if joint:
vr = side + ([jl['vrel_box']] if 'vrel_box' in jl else [])
L.append(sum(vr) / len(vr) if vr else zero)
L.append(jl.get('rho', zero))
hd = model._heads
cr = [(j, c) for j, c in enumerate(b['crit']) if c is not None]
L.append(sum(crit_loss(hd['crit'][j], c.to(dev)) for j, c in cr) / len(cr) if cr else zero)
L.extend(plan_losses(model, hd, b, dev))
if v2:
vr = side + ([jl['vrel_box']] if 'vrel_box' in jl else [])
L.append(sum(vr) / len(vr) if vr else zero)
L.append(jl.get('rho', zero))
ro = model._reason_out
cr = [(j, c) for j, c in enumerate(b['crit']) if c is not None]
L.append(sum(crit_loss(ro['crit'][j], c.to(dev)) for j, c in cr) / len(cr) if cr else zero)
with torch.autocast('cuda', dtype=torch.bfloat16):
l_qa = zero
if rk:
ki = torch.cat([torch.full((len(x),), j) for j, x in rk]).to(dev); rr = torch.cat([x for _, x in rk]).to(dev)
lo2, _ = model.qa_risk(ki, rr[:, 0], rr[:, 1])
l_qa = l_qa + F.cross_entropy(lo2.float(), rr[:, 2])
if uq:
ua = torch.cat([x[0] for _, x in uq]).to(dev).reshape(-1, 2)
ui = torch.cat([torch.full((len(x[1]) * 4,), j) for j, x in uq]).to(dev)
_, sc2 = model.qa_risk(ui, ua[:, 0], ua[:, 1])
l_qa = l_qa + F.cross_entropy(sc2.float().reshape(-1, 4), torch.cat([x[1] for _, x in uq]).to(dev))
qd = model.qa_decision()
pc = model.plan_candidates()
L.append(l_qa)
L.append(ce(qd, torch.stack(b['dec']).to(dev)))
L.extend(plan_losses_v2(model, pc, b, dev))
assert len(L) == len(names), (len(L), names)
loss = sum(FIXED[names[k]] * L[k] if (v2 and names[k] in FIXED) else torch.exp(-logv[k]) * L[k] + logv[k]
for k in range(len(names)))
opt.zero_grad(set_to_none=True); loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step(); sched.step()
agg += [float(x.detach()) if torch.is_tensor(x) else float(x) for x in L]
res, risk = answer(model, va, cache, voc, dev, use_opt)
acc0 = report(res)[0]
bias = tune_risk(res, risk); apply_risk(res, risk, bias)
acc, tl, per = report(res)
m = dict(epoch=ep, sec=round(time.time() - t0), loss=dict(zip(names, np.round(agg / len(dl), 4).tolist())),
val_acc=round(acc, 4), val_testlike=round(tl, 4), val_acc_risk_bias0=round(acc0, 4), risk_bias=bias, per=per)
if plan or joint or v2:
vtraj, m['val_plan'] = plan_predict(model, va, cache, voc, dev, ego_fut)
if v2:
m['val_nps'] = val_nps(vtraj, va)
if m['val_plan'].get('ade', 1e9) < best_ade:
best_ade = m['val_plan']['ade']; torch.save(dict(model=model.state_dict(), voc=voc.__dict__, epoch=ep, risk_bias=bias), out / 'best_plan.pt')
log.write(json.dumps(m) + '\n'); log.flush()
print('EPOCH', json.dumps(m), flush=True)
torch.save(dict(model=model.state_dict(), voc=voc.__dict__, epoch=ep, risk_bias=bias), out / 'last.pt')
sel = acc if math.isnan(tl) else tl
if sel > best:
best = sel; torch.save(dict(model=model.state_dict(), voc=voc.__dict__, epoch=ep, risk_bias=bias), out / 'best.pt')
if a.export:
# joint: one model, the final epoch of the fixed schedule (no checkpoint picked on val) for answers and trajectories
ck = torch.load(out / ('last.pt' if (joint or v2) else 'best.pt'), map_location='cpu', weights_only=False); model.load_state_dict(ck['model'])
res, risk = answer(model, te, cache, voc, dev, use_opt)
apply_risk(res, risk, ck['risk_bias'])
letters = {}
for r in te:
for q in r['questions']:
if q['id'] in res:
letters[q['id']] = 'ABCDEFGH'[res[q['id']][0]]
(out / 'test_answers.json').write_text(json.dumps(letters))
print('exported', len(letters), 'test answers', flush=True)
if plan or joint or v2:
if plan: # S3: its own best-ADE checkpoint; joint: the same checkpoint as the answers (one model)
ck = torch.load(out / ('best_plan.pt' if (out / 'best_plan.pt').is_file() else 'last.pt'), map_location='cpu', weights_only=False)
model.load_state_dict(ck['model'])
trajs, _ = plan_predict(model, te, cache, voc, dev)
clip_of = {r['kf_id']: r['clip'] for r in te}
(out / 'test_traj.json').write_text(json.dumps({clip_of[k]: np.round(v, 4).tolist() for k, v in trajs.items()}))
print('exported', len(trajs), 'test trajectories (epoch', ck['epoch'], ')', flush=True)
if __name__ == '__main__':
main()