Download code/vlr_v2.py from ThuongBuiRVC/datariengcuathuongbui: direct link, hf CLI and curl.
- Browser
- Download file 13.3 kB
-
https://huggingface.co/datasets/ThuongBuiRVC/datariengcuathuongbui/resolve/main/code/vlr_v2.py
- Command line
-
hf download hf://datasets/ThuongBuiRVC/datariengcuathuongbui/code/vlr_v2.py
-
curl -L -o vlr_v2.py https://huggingface.co/datasets/ThuongBuiRVC/datariengcuathuongbui/resolve/main/code/vlr_v2.py
13.3 kB
| """VLR v2 (one model, figure "VLR Planner v2"): frozen V-JEPA 2.1 -> predictor -> Z -> Perception / Reasoning -> Planning. | |
| Predictor the S1 adapter + scene decoder (64 object + 4 context queries) and the ego MLP: Z = [O 64, C 4, e 1] | |
| Perception the S1 query heads (box, point, distance, rho) read Z: the perception VQA answers (unchanged) | |
| Reasoning 57 action queries (Emb lon + Emb lat) + 16 critical queries, Decoder x2 (self-attention, cross-attention | |
| to Z, FFN) -> R (73 tokens); heads: feasibility of each action (Safe / Unsafe / Suboptimal + unsafe | |
| score), critical component class, driving decision (one logit per action token -> 57-way softmax). | |
| VQA confirmation (training only): the risk / unsafe / decision questions are queries of one | |
| cross-attention layer over R, with their own heads and losses. | |
| Planning K learnable trajectory queries (+ ego token), [Cross-Attention, FFN] x2 over [Z; R] -> per candidate a | |
| path (20 headings over 2.5 .. 50 m of arc) and a speed profile (progress increments over 10 x 0.5 s), | |
| composed into 51 waypoints; a scorer MLP (candidate token + its positions and speeds) predicts the | |
| devkit sub-scores EP, CF, HL of the candidate; the candidate with the highest 0.3 EP + 0.2 CF + 0.5 HL | |
| is the plan. Scorer targets are computed per candidate against the ego's true future with the devkit's | |
| own formulas (progress ratio, comfort bounds, human-likeness of the 5 s endpoint). | |
| """ | |
| import math | |
| import sys | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| from torch import nn | |
| from vlr_joint import VLRJoint, compose, ego_targets, T10 | |
| from vlr_model import Decoder, mlp | |
| N_ACT, K_TRAJ = 57, 16 | |
| DEVKIT = next((p for p in ('/home/db/ThuongBui/localization/third_party/nureasoning-devkit', | |
| str(__import__('pathlib').Path.home() / 'nuReasoning/third_party/nureasoning-devkit')) | |
| if __import__('os').path.isdir(p)), '') | |
| W_EP, W_CF, W_HL = 0.3, 0.2, 0.5 | |
| class CrossLayer(nn.Module): | |
| """pre-norm cross-attention + FFN (no self-attention).""" | |
| def __init__(self, d, heads): | |
| super().__init__() | |
| self.nq, self.nm, self.nf = nn.LayerNorm(d), nn.LayerNorm(d), nn.LayerNorm(d) | |
| self.att = nn.MultiheadAttention(d, heads, dropout=0.1, batch_first=True) | |
| self.ffn = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Dropout(0.1), nn.Linear(4 * d, d)) | |
| self.drop = nn.Dropout(0.1) | |
| def forward(self, q, mem): | |
| m = self.nm(mem) | |
| q = q + self.drop(self.att(self.nq(q), m, m, need_weights=False)[0]) | |
| return q + self.drop(self.ffn(self.nf(q))) | |
| class VLRv2(VLRJoint): | |
| def __init__(self, *args, pairs, d=256, heads=8, **kw): | |
| super().__init__(*args, d=d, heads=heads, **kw) | |
| lut = torch.full((9, 7), -1, dtype=torch.long) | |
| for k, (lo, la) in enumerate(pairs): | |
| lut[lo, la] = k | |
| lut[0] = lut[0, 6] # "Remain stopped" exists only without lateral action | |
| self.register_buffer('pair_lut', lut) | |
| self.register_buffer('pair_lon', torch.tensor([p[0] for p in pairs])) | |
| self.register_buffer('pair_lat', torch.tensor([p[1] for p in pairs])) | |
| # reasoning | |
| self.reason = Decoder(d, 2, heads) | |
| self.h_feas = mlp(d, d, 4) | |
| self.h_dec_tok = mlp(d, d, 1) | |
| # VQA confirmation (training only) | |
| self.qa_att = CrossLayer(d, heads) | |
| self.q_qa_dec = nn.Parameter(torch.randn(1, d) * .02) | |
| self.h_qa_risk = mlp(d, d, 4) | |
| self.h_qa_dec = mlp(d, d, N_ACT) | |
| # planning | |
| self.q_traj = nn.Parameter(torch.randn(K_TRAJ, d) * .02) | |
| self.plan_x = nn.ModuleList([CrossLayer(d, heads) for _ in range(2)]) | |
| self.plan_norm = nn.LayerNorm(d) | |
| self.h_head = mlp(d, d, 20) # path headings at 2.5 .. 50 m of arc | |
| self.h_ds = mlp(d, d, 10) # progress increments over 10 x 0.5 s | |
| self.h_score = mlp(d + 30, d, 3) # EP, CF, HL logits | |
| for h in (self.h_head, self.h_ds): # start from straight paths at constant speed | |
| nn.init.zeros_(h[-1].weight); nn.init.zeros_(h[-1].bias) | |
| self._reason_out = self._e_plan = None | |
| # -------------------------------------------------------------- predictor output | |
| def forward_scene(self, front, side, rays, cam_ok): | |
| self._reason_out = None | |
| return super().forward_scene(front, side, rays, cam_ok) | |
| def ego_token(self, ego, drop=0.0): | |
| """the undropped token is kept for planning; the reasoning sees the (training-time) dropped one.""" | |
| self._v0 = (ego[:, 0] * 20).float() | |
| e = self.ego(ego) | |
| self._e_plan = e | |
| if self.training and drop > 0: | |
| e = e * (torch.rand(e.shape[0], 1, device=e.device) > drop) | |
| self._reason_out = None | |
| return e | |
| # -------------------------------------------------------------- reasoning | |
| def reasoning(self, e): | |
| if self._reason_out is not None: | |
| return self._reason_out | |
| L = self._last | |
| Z = torch.cat([L['obj'], L['ctx'], e[:, None]], 1) # B, 69, d | |
| B = Z.shape[0] | |
| qa = self.act['lon'](self.pair_lon) + self.act['lat'](self.pair_lat) # 57, d | |
| q = torch.cat([qa, self.q_crit], 0)[None].expand(B, -1, -1) | |
| R = self.reason(q, Z) # B, 73, d | |
| A, Cr = R[:, :N_ACT], R[:, N_ACT:] | |
| self._reason_out = dict(Z=Z, R=R, feas=self.h_feas(A), dec=self.h_dec_tok(A)[..., 0], crit=self.h_crit(Cr)) | |
| return self._reason_out | |
| def decision(self, ctx, e): | |
| return self.reasoning(e)['dec'] | |
| def pair_of(self, lon, lat): | |
| return self.pair_lut[lon, lat].clamp(min=0) | |
| def risk(self, obj, ctx, e, kf_idx, lon, lat): | |
| f = self.reasoning(e)['feas'][kf_idx, self.pair_of(lon, lat)] | |
| return f[:, :-1], f[:, -1] | |
| def qa_risk(self, kf_idx, lon, lat): | |
| """VQA confirmation: the asked action is the query of a cross-attention over R.""" | |
| R = self._reason_out['R'] | |
| q = (self.act['lon'](lon) + self.act['lat'](lat))[:, None] | |
| o = self.h_qa_risk(self.qa_att(q, R[kf_idx])[:, 0]) | |
| return o[:, :-1], o[:, -1] | |
| def qa_decision(self): | |
| R = self._reason_out['R'] | |
| q = self.q_qa_dec[None].expand(R.shape[0], -1, -1) | |
| return self.h_qa_dec(self.qa_att(q, R)[:, 0]) | |
| # -------------------------------------------------------------- planning | |
| def plan_candidates(self): | |
| """-> traj (B, K, 51, 3), progress s10 (B, K, 10), headings (B, K, 20), score logits (B, K, 3).""" | |
| out = self._reason_out | |
| ep = self._e_plan | |
| mem = torch.cat([out['Z'][:, :-1], ep[:, None], out['R']], 1) # [Z (undropped ego); R] | |
| B = mem.shape[0] | |
| q = self.q_traj[None].expand(B, -1, -1) + ep[:, None] | |
| for blk in self.plan_x: | |
| q = blk(q, mem) | |
| h = self.plan_norm(q).float() | |
| H = self.h_head(h).float() # B, K, 20 | |
| v0 = self._v0.float()[:, None, None] | |
| base = torch.log(torch.expm1((v0 * 0.5).clamp(min=1e-3))) # softplus^-1 of the constant-speed step | |
| ds = F.softplus(self.h_ds(h).float() + base) # B, K, 10 (>= 0) | |
| s10 = torch.cumsum(ds, -1) | |
| s11 = torch.cat([torch.zeros_like(s10[..., :1]), s10], -1) | |
| idx = torch.arange(51, device=h.device) / 5.0 | |
| lo = idx.floor().long().clamp(max=9); w = idx - lo | |
| s51 = s11[..., lo] * (1 - w) + s11[..., (lo + 1).clamp(max=10)] * w | |
| K = H.shape[1] | |
| traj = compose(H.reshape(B * K, 20), s51.reshape(B * K, 51)).reshape(B, K, 51, 3) | |
| feat = torch.cat([traj[:, :, 5::5, 0] / 50, traj[:, :, 5::5, 1] / 20, ds / 10], -1) # B, K, 30 | |
| sc = self.h_score(torch.cat([h, feat.detach()], -1)).float() | |
| return dict(traj=traj, s10=s10, H=H, score=sc) | |
| def select(sc): | |
| p = sc.float().sigmoid() | |
| return W_EP * p[..., 0] + W_CF * p[..., 1] + W_HL * p[..., 2] | |
| # ------------------------------------------------------------------------------------------------ targets / losses | |
| _dk = {} | |
| def devkit(): | |
| if not _dk: | |
| sys.path.insert(0, DEVKIT) | |
| from nureasoning.planning.benchmark import BenchmarkConfig, score_comfort, score_human_likeness | |
| _dk.update(cfg=BenchmarkConfig(), comfort=score_comfort, human=score_human_likeness) | |
| return _dk | |
| def candidate_targets(traj, g): | |
| """devkit sub-scores of each candidate against the true future g (51, 3), ego frame: EP (progress ratio of the | |
| endpoints, the devkit's no-route fallback), CF (comfort bounds), HL (5 s endpoint).""" | |
| dk = devkit() | |
| gp = float(np.linalg.norm(g[-1, :2] - g[0, :2])) | |
| out = np.zeros((len(traj), 3), np.float32) | |
| for k, tr in enumerate(traj): | |
| pp = float(np.linalg.norm(tr[-1, :2] - tr[0, :2])) | |
| out[k, 0] = 1.0 if gp < 0.1 else min(max(pp / gp, 0.0), 1.0) | |
| out[k, 1] = dk['comfort'](tr.astype(np.float64), dk['cfg'])[0] | |
| out[k, 2] = dk['human'](tr.astype(np.float64), g.astype(np.float64), dk['cfg'])[0] | |
| return out | |
| def plan_losses_v2(model, pc, b, dev): | |
| """winner-takes-all trajectory loss (ADE + endpoint + progress + path headings) and the scorer BCE on the | |
| devkit sub-scores of every candidate; keyframes with an ego future only.""" | |
| zero = pc['score'].sum() * 0 | |
| rows = [j for j in range(len(b['i'])) if b['fut_m'][j]] | |
| if not rows: | |
| return zero, zero | |
| rt = torch.tensor(rows, device=dev) | |
| traj = pc['traj'][rt] # R, K, 51, 3 | |
| g = b['fut'][rows].to(dev).float() # R, 51, 3 | |
| d = (traj[:, :, 1:, :2] - g[:, None, 1:, :2]).norm(dim=-1) # R, K, 50 | |
| ade = d.mean(-1) | |
| win = ade.argmin(-1) | |
| ar = torch.arange(len(rows), device=dev) | |
| v0 = (b['ego'][rows, 0] * 20).float() | |
| tg = [ego_targets(b['fut'][j].numpy(), float(v0[n])) for n, j in enumerate(rows)] | |
| s_gt = torch.from_numpy(np.stack([x[0] for x in tg])).to(dev) + v0.to(dev)[:, None] * T10.to(dev) | |
| H_gt = torch.from_numpy(np.stack([x[1] for x in tg])).to(dev) | |
| ok = torch.from_numpy(np.stack([x[2] for x in tg])).to(dev).float() | |
| l_traj = (ade[ar, win] + 0.5 * d[ar, win, -1] | |
| + 0.5 * (pc['s10'][rt][ar, win] - s_gt).abs().mean(-1) | |
| + ((pc['H'][rt][ar, win] - H_gt).abs() * ok).sum(-1) / ok.sum(-1).clamp(min=1)).mean() | |
| tgt = torch.from_numpy(np.stack([candidate_targets(traj[n].detach().float().cpu().numpy(), b['fut'][j].numpy()) | |
| for n, j in enumerate(rows)])).to(dev) # R, K, 3 | |
| l_score = F.binary_cross_entropy_with_logits(pc['score'][rt].float(), tgt) | |
| return l_traj, l_score | |
| # ------------------------------------------------------------------------------------------------ devkit NPS on val | |
| _bench = {} | |
| def _nps_one(args): | |
| clip_dir, kf, traj = args | |
| if not _bench: | |
| sys.path.insert(0, DEVKIT) | |
| from nureasoning.planning.benchmark import BenchmarkConfig, evaluate_clip | |
| from nureasoning.submission.format import normalize_ego_trajectory | |
| from nureasoning.nuvla.trajectory_provider import VLATrajectoryProvider | |
| from nureasoning.common.pickle_io import load_pickle | |
| _bench.update(BC=BenchmarkConfig, evaluate=evaluate_clip, normalize=normalize_ego_trajectory, | |
| to_global=VLATrajectoryProvider._ego_to_global, load=load_pickle) | |
| bk = _bench | |
| import json | |
| import os | |
| try: | |
| meta = json.load(open(os.path.join(clip_dir, 'metadata.json'))) | |
| fr = next(f for f in meta['frames'] if int(f['frame_index']) == int(kf)) | |
| pose = bk['load'](os.path.join(clip_dir, fr['ego_state'])).pose | |
| plan = bk['to_global'](bk['normalize'](np.asarray(traj, np.float64)), pose['x'], pose['y'], pose['yaw']) | |
| r = bk['evaluate'](clip_dir, bk['BC'](key_frame_index=int(kf)), planned_trajectory=plan) | |
| if r.error: | |
| return None | |
| return [r.planning_score, r.s_collision, r.s_driveable, r.s_progress, r.s_comfort, r.s_human] | |
| except Exception: # noqa: BLE001 | |
| return None | |
| def val_nps(trajs, recs, workers=6): | |
| """devkit planning score of {kf_id: (51, 3) ego-frame trajectory} on the records' clips -> means.""" | |
| from concurrent.futures import ProcessPoolExecutor | |
| from pathlib import Path | |
| jobs = [(str(Path(r['video']['front'][0]).parents[2]), int(r['kf']), trajs[r['kf_id']]) for r in recs if r['kf_id'] in trajs] | |
| with ProcessPoolExecutor(workers) as pool: | |
| rows = [x for x in pool.map(_nps_one, jobs, chunksize=8) if x is not None] | |
| if not rows: | |
| return {} | |
| m = np.asarray(rows).mean(0) | |
| return dict(n=len(rows), NPS=round(float(m[0]), 4), NC=round(float(m[1]), 4), DA=round(float(m[2]), 4), | |
| EP=round(float(m[3]), 4), CF=round(float(m[4]), 4), HL=round(float(m[5]), 4)) | |