"""VLR features for re-ranking the proposals of another planner (Drive-JEPA G2): for every proposal of a keyframe, clearance min over predicted objects and 0.5 .. 5 s of (centre distance - object radius - ego radius), all objects and only objects ahead of the ego along the proposal; soft overlap; first time of contact intent log p(a | M) of the nearest action template, soft log sum_a p(a) exp(-d(proposal, template_a)^2 / 2 s^2), and the same with the options of one decision question of the keyframe (test has ~1 per keyframe) risk P(Unsafe or Suboptimal | a) of the nearest action from the S2 reasoner Input --props npz with props (N, 32, 10, 3) at 0.5 .. 5 s and clips (N,) ; output npz feats (N, 32, F), names. Run (db): python vlr_select_feats.py --ckpt runs/s23_full/best.pt --cache --props props_val.npz --out sel_feats_val.npz """ import argparse import pickle import random from pathlib import Path import numpy as np import torch from torch.utils.data import DataLoader import vlr_s1 as S from vlr_model import VLRPlan, ego_template, rollout NAMES = ['clear_min', 'clear_min_ahead', 'overlap', 't_contact', 'logp_near', 'logp_soft', 'logp_near_opt', 'logp_soft_opt', 'risk_near'] EGO_R = 1.3 def main(): ap = argparse.ArgumentParser() ap.add_argument('--ckpt', required=True); ap.add_argument('--cache', required=True) ap.add_argument('--data', default=str(S.HERE / 'data')); ap.add_argument('--split', default='val') ap.add_argument('--props', required=True); ap.add_argument('--out', required=True) ap.add_argument('--device', default='cpu') a = ap.parse_args() dev = torch.device(a.device) ck = torch.load(a.ckpt, map_location='cpu', weights_only=False) voc = S.Vocab([]); voc.__dict__.update(ck['voc']) model = VLRPlan(n_cls=len(voc.cls), n_dir=len(voc.dir), n_rel=max(len(voc.rel), 1)).to(dev) model.load_state_dict(ck['model']); model.eval() pz = np.load(a.props, allow_pickle=True) props, clips = pz['props'].astype(np.float32), [str(c) for c in pz['clips']] recs = {r['clip']: r for r in pickle.load(open(Path(a.data) / f'{a.split}.pkl', 'rb'))} ds = S.KF([recs[c] for c in clips], Path(a.cache) / a.split, voc, False) assert len(ds) == len(clips), (len(ds), len(clips)) dl = DataLoader(ds, batch_size=2, num_workers=4, collate_fn=S.collate) pairs = torch.tensor(S.PAIRS, device=dev) rng = random.Random(0) feats = np.zeros((len(clips), props.shape[1], len(NAMES)), np.float32) with torch.no_grad(): for b in dl: tok, obj, ctx, out = model.forward_scene(b['front'].to(dev).float(), b['side'].to(dev).float(), 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]; n = clips.index(r['clip']) P = torch.from_numpy(props[n]).to(dev) # 32, 10, 3 c = out['center'][j, :, :2].float() # 64, 2 ot = c[:, None] + out['fut'][j].float().reshape(-1, 10, 2) # 64, 10, 2 at 0.5 .. 5 s rad = 0.5 * torch.linalg.norm(out['size'][j, :, :2].float().exp(), dim=-1) # 64 pex = 1 - out['cls'][j].float().softmax(-1)[:, -1] # 64 live = pex > 0.3 diff = ot[None] - P[:, None, :, :2] # 32, 64, 10, 2 clear = diff.norm(dim=-1) - rad[None, :, None] - EGO_R # 32, 64, 10 clear = torch.where(live[None, :, None], clear, torch.full_like(clear, 50.)) hd = P[:, :, 2] # heading along the proposal fwd = diff[..., 0] * torch.cos(hd)[:, None] + diff[..., 1] * torch.sin(hd)[:, None] clear_ahead = torch.where(fwd > 0, clear, torch.full_like(clear, 50.)) cm = clear.amin((1, 2)).clamp(-5, 30) cma = clear_ahead.amin((1, 2)).clamp(-5, 30) overlap = (pex[None, :, None] * torch.relu(1 - clear)).sum((1, 2)) hit = (clear < 0).any(1) # 32, 10 tc = torch.where(hit.any(1), hit.float().argmax(1).float() * .5 + .5, torch.full_like(cm, 6.)) # intent: nearest of the 57 action templates for this ego speed v0 = model._v0[j:j + 1].expand(len(pairs)) v_t, H_t = ego_template(v0, pairs[:, 0], pairs[:, 1]) tm = rollout(v_t, H_t)[:, 5::5, :2] # 57, 10, 2 d = (P[:, None, :, :2] - tm[None]).norm(dim=-1).mean(-1) # 32, 57 near = d.argmin(1) lp = dlog[j].float().log_softmax(-1) qs = [q for q in r['questions'] if q['sub'] in S.DECISION_SUBS] lpo = torch.from_numpy(S.pair_posterior(dlog[j], [rng.choice(qs)] if qs else [])).to(dev).float() lpo = torch.where(lpo < -1e8, torch.full_like(lpo, -30.), lpo) soft = lambda l: torch.logsumexp(l[None] - d ** 2 / (2 * 2.0 ** 2), 1) # noqa: E731 lo, _ = model.risk(obj, ctx, e, torch.full((len(pairs),), j, device=dev), pairs[:, 0], pairs[:, 1]) pr = lo.float().softmax(-1) f = torch.stack([cm, cma, overlap, tc, lp[near], soft(lp), lpo[near], soft(lpo), pr[near, 1] + pr[near, 2]], -1) feats[n] = f.cpu().numpy() np.savez(a.out, feats=feats, names=np.array(NAMES), clips=np.array(clips)) print('wrote', a.out, feats.shape, flush=True) if __name__ == '__main__': main()