File size: 14,137 Bytes
cfa2024
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
242
243
244
245
"""VLR joint model: one scene memory for VQA and planning (S2 model + the parts below), trained end to end on frozen
V-JEPA 2.1 latents.

  relative velocity  head 'vrel' on object and box queries: velocity relative to the ego (v - [v0, 0]), the quantity the
                     cameras observe; absolute velocity = vrel + ego speed (known input). The future_motion label is
                     ~0.995 a function of (position, relative velocity) (measured on train), so it is answered by a
                     small rule rho(curve of distance change to the ego) learned on annotated quantities only.
  critical           16 queries over the camera tokens, Hungarian-matched to the keyframe's Driving -> Critical
                     components (class from the annotation text: group, light colour, sign, routing, ego state; no
                     map-derived position); their tokens feed the planner.
  speed              distribution over K progress profiles s(t) - v0 t (k-means of train ego futures, 10 knots
                     0.5 .. 5 s) + a residual per profile; chosen at test by the Bayes rule under L1 (no averaging of
                     modes).
  path               M heading curves over arc length (2.5 .. 50 m) + mode logits (winner-takes-all training).
  trajectory         path o speed: the 51 waypoints follow the chosen path at the chosen progress.
  interaction bias   the speed / path queries attend over [objects, context, ego, critical] with a per-head bias from
                     the predicted object position, relative velocity, time to contact and existence (detached: the
                     planner reads the verified quantities, it does not rewrite them).
  decision           S1 decision logits + a zero-initialised term from the speed / path distributions, so the decision
                     supervision also trains the speed / path heads.
"""
import math

import numpy as np
import torch
import torch.nn.functional as F
from scipy.optimize import linear_sum_assignment
from torch import nn

from vlr_model import BiasedDecoder, Decoder, VLRPlan, mlp

CRIT_CLS = ['Vehicle', 'VRU', 'Construction', 'Road events', 'TL red', 'TL yellow', 'TL green', 'TL other', 'Sign stop',
            'Sign yield', 'Sign other', 'Lane', 'Route left', 'Route right', 'Route straight', 'Route other', 'ODD',
            'Visibility', 'Weather', 'Ego stopped', 'Ego other']
N_CRIT_Q = 16
K_SPEED = 48
M_PATH = 6
ELL = torch.arange(1, 21, dtype=torch.float32) * 2.5          # path knots along the arc (m)
T10 = torch.arange(1, 11, dtype=torch.float32) * 0.5          # speed knots (s)
T51 = torch.arange(51, dtype=torch.float32) * 0.1
RHO_T = torch.arange(1, 11, dtype=torch.float32) * 0.5


# ------------------------------------------------------------------------------------------------ targets
def ego_targets(fut, v0):
    """fut (51, 3) ego future (x, y, heading; 0.1 s) -> progress deviation (10,) = s(t) - v0 t at 0.5 .. 5 s, path
    headings (20,) at 2.5 .. 50 m of arc, their validity (20,) (the ego must travel that far)."""
    xy = fut[:, :2]
    s = np.r_[0.0, np.cumsum(np.linalg.norm(np.diff(xy, axis=0), axis=1))]
    ds = s[5::5] - v0 * T10.numpy()
    head = np.unwrap(fut[:, 2])
    ell = ELL.numpy()
    ok = ell <= s[-1]
    # heading at an arc length: interpolate over the strictly increasing part of s
    keep = np.r_[True, np.diff(s) > 1e-3]
    h = np.interp(ell, s[keep], head[keep]) if keep.sum() >= 2 else np.zeros_like(ell)
    return ds.astype(np.float32), h.astype(np.float32), ok


def speed_profiles(devs, k=K_SPEED, iters=40, seed=0):
    """k-means (k-means++ init) of progress deviations (N, 10) -> (k, 10)."""
    rng = np.random.default_rng(seed)
    X = np.asarray(devs, np.float64)
    C = [X[rng.integers(len(X))]]
    for _ in range(k - 1):
        d = np.min(np.abs(X[:, None] - np.asarray(C)[None]).mean(-1), 1) ** 2
        C.append(X[rng.choice(len(X), p=d / d.sum())] if d.sum() > 0 else X[rng.integers(len(X))])
    C = np.asarray(C)
    for _ in range(iters):
        a = np.abs(X[:, None] - C[None]).mean(-1).argmin(1)
        C = np.stack([np.median(X[a == j], 0) if (a == j).any() else C[j] for j in range(k)])
    return C.astype(np.float32)


# ------------------------------------------------------------------------------------------------ geometry
def compose(H, s, ell=None):
    """path headings H (Q, 20) at ELL, progress s (Q, T) -> (Q, T, 3) x, y, heading. Heading is linear between knots
    (0 at arc 0); positions by the midpoint rule per 2.5 m segment, linear inside a segment, straight beyond 50 m."""
    ell = (ELL if ell is None else ell).to(H.device, H.dtype)
    Q = H.shape[0]
    Hk = torch.cat([torch.zeros(Q, 1, device=H.device, dtype=H.dtype), H], 1)              # Q, 21 at 0 .. 50 m
    mid = (Hk[:, 1:] + Hk[:, :-1]) / 2
    step = 2.5
    px = torch.cat([torch.zeros(Q, 1, device=H.device, dtype=H.dtype), torch.cumsum(step * torch.cos(mid), 1)], 1)
    py = torch.cat([torch.zeros(Q, 1, device=H.device, dtype=H.dtype), torch.cumsum(step * torch.sin(mid), 1)], 1)
    s = s.clamp(min=0)
    seg = (s / step).floor().long().clamp(max=19)                                          # Q, T
    w = (s - seg.to(s.dtype) * step) / step                                                # beyond 50 m: w > 1
    g = lambda a: a.gather(1, seg)  # noqa: E731
    g1 = lambda a: a.gather(1, seg + 1)  # noqa: E731
    beyond = (s > 50).to(s.dtype)
    ang = g(mid)
    ang = ang * (1 - beyond) + Hk[:, -1:].expand_as(ang) * beyond
    x = g(px) + w * step * torch.cos(ang)
    y = g(py) + w * step * torch.sin(ang)
    hd = g(Hk) + (g1(Hk) - g(Hk)) * w.clamp(max=1)
    return torch.stack([x, y, hd], -1)


def rho_features(xy, vrel):
    """change of the distance to the ego over 0.5 .. 5 s under constant relative velocity, / 10 m."""
    t = RHO_T.to(xy.device, xy.dtype)
    f = xy[:, None] + vrel[:, None] * t[None, :, None]
    return (f.norm(dim=-1) - xy.norm(dim=-1, keepdim=True)) / 10


# ------------------------------------------------------------------------------------------------ model
class VLRJoint(VLRPlan):
    def __init__(self, *args, d=256, heads=8, **kw):
        super().__init__(*args, d=d, heads=heads, **kw)
        self.h_obj['vrel'] = mlp(d, d, 2)
        self.h_box['vrel'] = mlp(d, d, 2)
        self.rho_mot = mlp(10, 64, 3)
        self.q_crit = nn.Parameter(torch.randn(N_CRIT_Q, d) * .02)
        self.crit_dec = Decoder(d, 2, heads)
        self.h_crit = nn.Linear(d, len(CRIT_CLS) + 1)
        self.q_plan = nn.Parameter(torch.randn(2, d) * .02)                  # speed query, path query
        self.phi_plan = mlp(6, 64, heads)
        self.plan_dec2 = BiasedDecoder(d, 2, heads)
        self.h_spd = mlp(d, d, K_SPEED)
        self.h_spd_res = mlp(d, d, K_SPEED * 10)
        self.h_path = mlp(d, d, M_PATH * 21)                                 # per mode: logit + 20 headings
        self.h_dec2 = mlp(K_SPEED + 20, d, 57)
        for h in (self.phi_plan, self.h_spd_res, self.h_dec2):
            nn.init.zeros_(h[-1].weight); nn.init.zeros_(h[-1].bias)
        self.register_buffer('speed_prof', torch.zeros(K_SPEED, 10))
        self._last = self._heads = None

    # -------------------------------------------------------------- scene + heads
    def forward_scene(self, front, side, rays, cam_ok):
        tok, obj, ctx, out = super().forward_scene(front, side, rays, cam_ok)
        self._last = dict(tok=tok, obj=obj, ctx=ctx, out=out, mask=(~cam_ok).repeat_interleave(576, 1))
        self._heads = None
        return tok, obj, ctx, out

    def plan_bias(self, out):
        """per-object interaction features from the predicted (detached) object state -> (B, 64, heads)."""
        c = out['center'].detach().float()[..., :2]
        vr = out['vrel'].detach().float()
        ex = 1 - out['cls'].detach().float().softmax(-1)[..., -1]
        x, y = c[..., 0], c[..., 1]
        closing = -vr[..., 0]                                                # > 0: the gap ahead shrinks
        ttc = torch.where((x > 0) & (closing > 0.3), x / closing.clamp(min=0.3), torch.full_like(x, 10.)).clamp(max=10)
        f = torch.stack([x / 20, y / 10, torch.exp(-y ** 2 / 4), closing / 10, ttc / 10, ex], -1)
        return self.phi_plan(f)

    def joint_heads(self, e):
        """critical components, speed and path distributions for the last forward_scene batch."""
        L = self._last
        tok, obj, ctx, out = L['tok'], L['obj'], L['ctx'], L['out']
        B = tok.shape[0]
        crit = self.crit_dec(self.q_crit[None].expand(B, -1, -1), tok, L['mask'])
        mem = torch.cat([obj, ctx, e[:, None], crit], 1)                    # B, 64 + 4 + 1 + 16, d
        bias = torch.cat([self.plan_bias(out), torch.zeros(B, mem.shape[1] - obj.shape[1], self.heads,
                                                            device=mem.device, dtype=obj.dtype)], 1)
        q = self.q_plan[None].expand(B, -1, -1).reshape(B * 2, 1, -1)
        h = self.plan_dec2(q, mem.repeat_interleave(2, 0), bias.repeat_interleave(2, 0).to(q.dtype))[:, 0].reshape(B, 2, -1)
        hs, hp = h[:, 0].float(), h[:, 1].float()
        path = self.h_path(hp).reshape(B, M_PATH, 21)
        self._heads = dict(crit=self.h_crit(crit), spd=self.h_spd(hs), spd_res=self.h_spd_res(hs).reshape(B, K_SPEED, 10),
                           path_logit=path[..., 0], path_H=path[..., 1:])
        return self._heads

    def decision(self, ctx, e):
        hd = self.joint_heads(e) if self._heads is None else self._heads
        p_s = hd['spd'].float().softmax(-1)
        p_m = hd['path_logit'].float().softmax(-1)
        H = (p_m[..., None] * hd['path_H'].float()).sum(1)
        return super().decision(ctx, e).float() + self.h_dec2(torch.cat([p_s, H], -1))

    # -------------------------------------------------------------- planning at test
    def plan_traj(self, e, v0, top=8):
        """-> (B, 51, 3) trajectory: most likely path mode o Bayes-L1 progress profile."""
        hd = self.joint_heads(e) if self._heads is None else self._heads
        B = v0.shape[0]
        t10 = T10.to(v0.device)
        p = hd['spd'].float().softmax(-1)                                       # B, K
        cand = self.speed_prof[None] + hd['spd_res'].float()                    # B, K, 10
        s = (v0[:, None, None] * t10 + cand).clamp(min=0)
        s = torch.cummax(s, -1).values
        k = p.topk(min(top, K_SPEED), -1).indices                               # B, top
        sc = s.gather(1, k[..., None].expand(-1, -1, 10))                       # B, top, 10
        risk = (p[:, None, :, None] * (sc[:, :, None] - s[:, None]).abs()).sum((-1, -2))   # B, top
        best = sc[torch.arange(B), risk.argmin(-1)]                             # B, 10
        s51 = torch.stack([torch.from_numpy(np.interp(T51.numpy(), np.r_[0, t10.cpu().numpy()], np.r_[0, b.cpu().numpy()]))
                           for b in best]).to(v0.device).float()
        H = hd['path_H'].float()[torch.arange(B), hd['path_logit'].float().argmax(-1)]
        return compose(H, s51)


# ------------------------------------------------------------------------------------------------ losses
def crit_loss(logits, labels):
    """set loss over the 16 critical queries: Hungarian on -log p(class), unmatched queries -> 'none' (weight 0.1)."""
    C1 = logits.shape[-1]
    lbl = torch.full((logits.shape[0],), C1 - 1, dtype=torch.long, device=logits.device)
    if len(labels):
        lp = logits.float().log_softmax(-1)[:, labels]                          # 16, n
        qi, gi = linear_sum_assignment((-lp).detach().cpu().numpy())
        lbl[torch.as_tensor(qi, device=logits.device)] = labels[torch.as_tensor(gi, device=logits.device)]
    w = torch.ones(C1, device=logits.device); w[-1] = 0.1
    return F.cross_entropy(logits.float(), lbl, weight=w)


def plan_losses(model, hd, b, dev):
    """speed (soft CE over profiles + residual), path (winner-takes-all) and composed-trajectory losses on the
    keyframes with an ego future; -> (speed, path, traj) or zeros."""
    zero = hd['spd'].sum() * 0
    rows = [j for j in range(len(b['i'])) if b['fut_m'][j]]
    if not rows:
        return zero, zero, zero
    rows_t = torch.tensor(rows, device=dev)
    v0 = (b['ego'][rows, 0] * 20).float().to(dev)
    tg = [ego_targets(b['fut'][j].numpy(), float(v0[n])) for n, j in enumerate(rows)]
    ds = torch.from_numpy(np.stack([x[0] for x in tg])).to(dev)                  # R, 10
    Hg = torch.from_numpy(np.stack([x[1] for x in tg])).to(dev)                  # R, 20
    ok = torch.from_numpy(np.stack([x[2] for x in tg])).to(dev)                  # R, 20
    prof = model.speed_prof
    dist = (ds[:, None] - prof[None]).abs().mean(-1)                             # R, K
    target = (-dist / 2.0).softmax(-1)
    logit = hd['spd'][rows_t].float()
    l_cls = -(target * logit.log_softmax(-1)).sum(-1).mean()
    kstar = dist.argmin(-1)
    res = hd['spd_res'][rows_t].float()[torch.arange(len(rows)), kstar]
    l_speed = l_cls + F.l1_loss(prof[kstar] + res, ds)
    # path: winner-takes-all over modes on the valid knots
    Hp = hd['path_H'][rows_t].float()                                            # R, M, 20
    err = ((Hp - Hg[:, None]).abs() * ok[:, None]).sum(-1) / ok.sum(-1, keepdim=True).clamp(min=1)
    has = ok.any(-1)
    win = err.argmin(-1)
    if has.any():
        l_path = err[torch.arange(len(rows)), win][has].mean() + F.cross_entropy(hd['path_logit'][rows_t].float()[has], win[has])
    else:
        l_path = zero
    # composed trajectory with the winning path and the target-nearest profile + residual
    t10 = T10.to(dev)
    s10 = (v0[:, None] * t10 + prof[kstar] + res).clamp(min=0)
    s51 = torch.cat([torch.zeros(len(rows), 1, device=dev), s10], 1)
    idx = torch.arange(51, device=dev) / 5.0
    lo = idx.floor().long().clamp(max=9); w = idx - lo
    s51 = s51[:, lo] * (1 - w) + s51[:, (lo + 1).clamp(max=10)] * w
    traj = compose(Hp[torch.arange(len(rows)), win], s51)
    g = b['fut'][rows].to(dev).float()
    l_traj = F.l1_loss(traj[:, 1:, :2], g[:, 1:, :2])
    return l_speed, l_path, l_traj