File size: 15,431 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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
"""VLR stage S1: geometry-aware scene memory + verifiable query heads (frozen V-JEPA 2.1 latents in, quantities out).

  tokenizer     per camera: LN, Linear 1024->d; attention over the time slices of every cell (front 8, others 3),
                last slice kept; + ray embedding MLP(direction, camera origin) + camera embedding -> 8 x 576 tokens
  camera enc    2 shared self-attention layers inside each camera (576 tokens)
  scene memory  64 object queries + 4 context queries, 6 decoder layers over the tokens of the available cameras
                object heads: class, centre xyz, log size, yaw, velocity, future xy (10 x 0.5 s), visible cameras
  box query     (camera, 2D box) -> rays of box centre / bottom / top + size -> query; 3 decoder layers over
                [objects, context, that camera's tokens] -> distance, xy, velocity, class, direction label,
                future-motion label, motion relation, path intersection, conflict
  distance      the same box query plus one hypothesis "the object is at ground distance v" (the 3D point on the box
                ray at that distance, heights of the box bottom / top rays there) -> score; options are ranked by it
  point query   (x, y) + its projections into the 8 cameras -> query; 2 decoder layers over [objects, context]
                -> visible cameras (8), image region (9) in each camera
  decision      context tokens + ego (kinematics, past poses, route; dropout in training) -> one distribution over the
                57 valid (longitudinal, lateral) pairs; every decision question is read from it
  risk          action (lon, lat) query over [objects, context, ego] -> Safe / Unsafe / Suboptimal + "most unsafe" score
"""
import math

import torch
from torch import nn

D_IN, GRID, N_CAM = 1024, 24, 8


def mlp(i, h, o, n=2):
    layers, d = [], i
    for _ in range(n - 1):
        layers += [nn.Linear(d, h), nn.GELU()]; d = h
    return nn.Sequential(*layers, nn.Linear(d, o))


class Decoder(nn.Module):
    def __init__(self, d, layers, heads=8):
        super().__init__()
        self.layers = nn.ModuleList([nn.TransformerDecoderLayer(d, heads, 4 * d, 0.1, batch_first=True, norm_first=True)
                                     for _ in range(layers)])
        self.norm = nn.LayerNorm(d)

    def forward(self, q, mem, mem_mask=None):
        for blk in self.layers:
            q = blk(q, mem, memory_key_padding_mask=mem_mask)
        return self.norm(q)


class VLR(nn.Module):
    def __init__(self, d=256, n_obj=64, n_ctx=4, n_cls=12, n_dir=12, n_motion=3, n_rel=8, n_lon=9, n_lat=7, n_pair=57, n_risk=3, n_hyp=10):
        super().__init__()
        self.d, self.n_obj = d, n_obj
        self.inp = nn.Sequential(nn.LayerNorm(D_IN), nn.Linear(D_IN, d))
        self.t_front, self.t_side = nn.Parameter(torch.randn(8, d) * .02), nn.Parameter(torch.randn(3, d) * .02)
        self.temporal = nn.TransformerEncoderLayer(d, 8, 4 * d, 0.1, batch_first=True, norm_first=True)
        self.ray = mlp(6, d, d)
        self.cam = nn.Embedding(N_CAM, d)
        self.cam_enc = nn.ModuleList([nn.TransformerEncoderLayer(d, 8, 4 * d, 0.1, batch_first=True, norm_first=True) for _ in range(2)])
        self.q_obj, self.q_ctx = nn.Parameter(torch.randn(n_obj, d) * .02), nn.Parameter(torch.randn(n_ctx, d) * .02)
        self.scene = Decoder(d, 6)
        self.h_obj = nn.ModuleDict(dict(cls=nn.Linear(d, n_cls + 1), center=mlp(d, d, 3), size=mlp(d, d, 3), yaw=mlp(d, d, 2),
                                        vel=mlp(d, d, 2), fut=mlp(d, d, 20), vis=nn.Linear(d, N_CAM)))
        self.box_in = mlp(9 + 3 + 2 + 4, d, d)
        self.box_dec = Decoder(d, 3)
        self.h_box = nn.ModuleDict(dict(dist=mlp(d, d, 1), xy=mlp(d, d, 2), vel=mlp(d, d, 2), cls=nn.Linear(d, n_cls),
                                        dir=nn.Linear(d, n_dir), motion=nn.Linear(d, n_motion), rel=nn.Linear(d, n_rel),
                                        path=nn.Linear(d, 1), conflict=nn.Linear(d, 1)))
        self.hyp_in = mlp(n_hyp, d, d)
        self.h_hyp = mlp(d, d, 1)
        self.pt_in = mlp(5 + N_CAM * 2 * 4, d, d)
        self.pt_dec = Decoder(d, 2)
        self.h_pt = nn.ModuleDict(dict(vis=nn.Linear(d, N_CAM), region=nn.Linear(d, N_CAM * 9)))
        self.ego = mlp(4 + 12 + 3, d, d)
        self.h_dec = mlp(2 * d, d, n_pair)
        self.act = nn.ModuleDict(dict(lon=nn.Embedding(n_lon, d), lat=nn.Embedding(n_lat, d)))
        self.risk_dec = Decoder(d, 2)
        self.h_risk = mlp(d, d, n_risk + 1)

    # ------------------------------------------------------------------ scene
    def tokens(self, front, side, rays):
        """front (B,8,576,1024), side (B,7,3,576,1024), rays (B,8,576,6) -> (B, 8*576, d)."""
        B = front.shape[0]
        f = self.inp(front) + self.t_front[None, :, None]                      # B,8,576,d
        s = self.inp(side) + self.t_side[None, None, :, None]                  # B,7,3,576,d
        f = self.temporal(f.permute(0, 2, 1, 3).reshape(B * 576, 8, -1))[:, -1].reshape(B, 1, 576, -1)
        s = self.temporal(s.permute(0, 1, 3, 2, 4).reshape(B * 7 * 576, 3, -1))[:, -1].reshape(B, 7, 576, -1)
        x = torch.cat([f, s], 1) + self.ray(rays) + self.cam.weight[None, :, None]
        x = x.reshape(B * N_CAM, 576, -1)
        for blk in self.cam_enc:
            x = blk(x)
        return x.reshape(B, N_CAM * 576, -1)

    def forward_scene(self, front, side, rays, cam_ok):
        """cam_ok (B, 8) bool: cameras whose images exist; the tokens of the others are not attended."""
        tok = self.tokens(front, side, rays)
        B = tok.shape[0]
        q = torch.cat([self.q_obj, self.q_ctx])[None].expand(B, -1, -1)
        mem = self.scene(q, tok, (~cam_ok).repeat_interleave(576, 1))
        obj, ctx = mem[:, :self.n_obj], mem[:, self.n_obj:]
        out = {k: h(obj) for k, h in self.h_obj.items()}
        return tok, obj, ctx, out

    # ------------------------------------------------------------------ queries
    def _box(self, tok, obj, ctx, kf_idx, cam_idx, feat, extra=None):
        q = self.box_in(feat) + self.cam(cam_idx)
        if extra is not None:
            q = q + extra
        cam_tok = tok.reshape(tok.shape[0], N_CAM, 576, -1)[kf_idx, cam_idx]   # Q,576,d
        mem = torch.cat([obj[kf_idx], ctx[kf_idx], cam_tok], 1)
        return self.box_dec(q[:, None], mem)[:, 0]

    def query_box(self, tok, obj, ctx, kf_idx, cam_idx, feat):
        """one query per row: kf_idx (Q,), cam_idx (Q,), feat (Q, 18) box geometry -> head outputs (Q, ...)."""
        h = self._box(tok, obj, ctx, kf_idx, cam_idx, feat)
        return {k: m(h) for k, m in self.h_box.items()}

    def query_distance(self, tok, obj, ctx, kf_idx, cam_idx, feat, hyp):
        """hyp (Q, K, 6): K distance hypotheses of one box -> scores (Q, K)."""
        Q, K = hyp.shape[:2]
        rep = lambda x: x.repeat_interleave(K, 0)  # noqa: E731
        h = self._box(tok, obj, ctx, rep(kf_idx), rep(cam_idx), rep(feat), self.hyp_in(hyp.reshape(Q * K, -1)))
        return self.h_hyp(h).reshape(Q, K)

    def query_point(self, obj, ctx, kf_idx, feat):
        q = self.pt_in(feat)[:, None]
        h = self.pt_dec(q, torch.cat([obj[kf_idx], ctx[kf_idx]], 1))[:, 0]
        return {'vis': self.h_pt['vis'](h), 'region': self.h_pt['region'](h).reshape(-1, N_CAM, 9)}

    def ego_token(self, ego, drop=0.0):
        e = self.ego(ego)
        if self.training and drop > 0:
            e = e * (torch.rand(e.shape[0], 1, device=e.device) > drop)
        return e

    def decision(self, ctx, e):
        """logits over the valid (lon, lat) pairs."""
        return self.h_dec(torch.cat([ctx.mean(1), e], -1))

    def risk(self, obj, ctx, e, kf_idx, lon, lat):
        """-> (risk logits (Q, 3), most-unsafe score (Q,))."""
        q = (self.act['lon'](lon) + self.act['lat'](lat))[:, None]
        mem = torch.cat([obj[kf_idx], ctx[kf_idx], e[kf_idx][:, None]], 1)
        o = self.h_risk(self.risk_dec(q, mem)[:, 0])
        return o[:, :-1], o[:, -1]


# ============================================================================================ S2 + S3
# S2  action-conditioned interaction reasoning: for every candidate action a = (lon, lat) the ego template rollout
#     tau_a is compared with the predicted 5 s future of every memory object; phi(a, i) = closest distance, time of it,
#     closing speed, object existence -> an additive attention bias of the action query over the memory -> Z(a) ->
#     Safe / Unsafe / Suboptimal + "most unsafe" score (replaces the S1 risk head, same interface).
# S3  path x speed planner: from Z(a) the action query decodes a heading field over the arc fraction (path, 11 knots)
#     and a speed profile over time (10 knots), both as residuals of the action template; the trajectory integrates
#     speed along the path (51 points, 0.1 s).
ACC = (0., -4., -1., -3., -1.2, 2.5, 1.0, 0., 0.)          # template acceleration per longitudinal class (m/s^2)
TURN_R = 10.0                                               # template turn radius (m)
T51 = 51                                                    # 0 .. 5 s at 0.1 s


def _cumtrapz(f, dt=0.1):
    return torch.cat([torch.zeros_like(f[:, :1]), torch.cumsum((f[:, 1:] + f[:, :-1]) * (dt / 2), 1)], 1)


def _interp(knots, u):
    """knots (Q, K) on [0, 1], u (Q, T) -> (Q, T) linear interpolation."""
    K = knots.shape[1]
    x = u.clamp(0, 1) * (K - 1)
    lo = x.floor().long().clamp(max=K - 2)
    w = x - lo
    return knots.gather(1, lo) * (1 - w) + knots.gather(1, lo + 1) * w


def rollout(v, H):
    """speed v (Q, 51) along a path given by heading knots H (Q, 11) over the arc fraction -> (Q, 51, 3) x, y, heading."""
    s = _cumtrapz(v)
    u = s.abs() / s[:, -1:].abs().clamp(min=1e-3)
    th = _interp(H, u)
    return torch.stack([_cumtrapz(v * torch.cos(th)), _cumtrapz(v * torch.sin(th)), th], -1)


def ego_template(v0, lon, lat):
    """kinematic template of an action: speed (Q, 51) and heading knots over the arc fraction (Q, 11)."""
    t = torch.arange(T51, device=v0.device, dtype=torch.float32) * 0.1
    a = torch.tensor(ACC, device=v0.device)[lon]
    a = torch.where(lon == 2, -torch.clamp(v0 / 4, min=1.0), a)
    v = torch.clamp(v0[:, None] + a[:, None] * t[None], min=0.0)
    v = torch.where((lon == 0)[:, None], torch.zeros_like(v), v)
    v = torch.where((lon == 8)[:, None], torch.full_like(v, -1.5), v)
    s = _cumtrapz(v).abs()
    smooth = lambda x: (3 * x ** 2 - 2 * x ** 3)  # noqa: E731
    amp = torch.tensor([.8, -.8, 3.5, -3.5, 0., 0., 0.], device=v0.device)[lat]
    dur = torch.tensor([3., 3., 4., 4., 1., 1., 1.], device=v0.device)[lat]
    y_lane = amp[:, None] * smooth((t[None] / dur[:, None]).clamp(0, 1))
    phi = torch.clamp(s / TURN_R, max=math.pi / 2)
    sign = torch.where(lat == 4, 1.0, -1.0)[:, None]
    turn = (lat == 4) | (lat == 5)
    x = torch.where(turn[:, None], TURN_R * torch.sin(phi) + (s - TURN_R * phi) * torch.cos(phi), s)
    y = torch.where(turn[:, None], sign * (TURN_R * (1 - torch.cos(phi)) + (s - TURN_R * phi) * torch.sin(phi)), y_lane)
    dx, dy = x[:, 1:] - x[:, :-1], y[:, 1:] - y[:, :-1]
    head = torch.atan2(dy, dx.clamp(min=1e-4))
    head = torch.where(torch.hypot(dx, dy) > 1e-4, head, torch.zeros_like(head))
    head = torch.cat([head[:, :1], head], 1)                               # heading at each of the 51 times
    head = torch.where((lon == 8)[:, None], torch.zeros_like(head), head)
    u_t = s / s[:, -1:].clamp(min=1e-3)
    u_k = torch.linspace(0, 1, 11, device=v0.device)[None].expand(len(v0), -1).contiguous()
    idx = torch.searchsorted(u_t.contiguous(), u_k).clamp(max=T51 - 1)
    return v, head.gather(1, idx)


class BiasedDecoder(Decoder):
    def forward(self, q, mem, bias):
        """bias (Q, S, heads) added to the cross-attention logits."""
        m = bias.permute(0, 2, 1).reshape(-1, 1, bias.shape[1])
        for blk in self.layers:
            q = blk(q, mem, memory_mask=m.to(q.dtype))
        return self.norm(q)


class VLRPlan(VLR):
    """S1 model + S2 action-conditioned reasoner (replaces risk) + S3 path x speed planner; initialised from S1."""

    def __init__(self, *args, d=256, heads=8, **kw):
        super().__init__(*args, d=d, **kw)
        self.heads = heads
        self.phi = mlp(6, 64, heads)
        self.risk2 = BiasedDecoder(d, 2, heads)
        self.h_risk2 = mlp(d, d, 4)
        self.plan_q = mlp(d, d, d)
        self.plan_dec = Decoder(d, 2, heads)
        self.h_speed = mlp(d, d, 10)
        self.h_head = mlp(d, d, 11)
        for h in (self.h_speed, self.h_head, self.phi):    # start from the action template / an unbiased S1 reasoner
            nn.init.zeros_(h[-1].weight); nn.init.zeros_(h[-1].bias)
        self._scene = self._v0 = self._z = None

    def forward_scene(self, front, side, rays, cam_ok):
        tok, obj, ctx, out = super().forward_scene(front, side, rays, cam_ok)
        self._scene = {k: out[k].detach().float() for k in ('center', 'fut', 'cls')}
        return tok, obj, ctx, out

    def ego_token(self, ego, drop=0.0):
        self._v0 = (ego[:, 0] * 20).float()                # ego_feat: speed / 20
        return super().ego_token(ego, drop)

    def interaction(self, kf_idx, lon, lat):
        """phi(a, i) of each action query against the 64 memory objects -> attention bias (Q, 64 + 4 + 1, heads)."""
        sc = self._scene
        v, H = ego_template(self._v0[kf_idx], lon, lat)
        ego = rollout(v, H)[:, ::5, :2]                                   # Q, 11, 2 at 0, 0.5 .. 5 s
        c = sc['center'][kf_idx][..., :2]                                 # Q, 64, 2
        obj = torch.cat([c[:, :, None], c[:, :, None] + sc['fut'][kf_idx].reshape(len(kf_idx), -1, 10, 2)], 2)
        diff = ego[:, None] - obj                                         # Q, 64, 11, 2
        d = diff.norm(dim=-1)
        dmin, imin = d.min(-1)
        rel = (diff[:, :, 1:] - diff[:, :, :-1]).norm(dim=-1) / 0.5       # closing speed per interval
        dv = rel.gather(2, (imin.clamp(1, 10) - 1)[..., None])[..., 0]
        p = 1 - sc['cls'][kf_idx].softmax(-1)[..., -1]
        f = torch.stack([dmin / 20, torch.exp(-dmin / 2), torch.exp(-dmin / 5), imin / 10, dv / 10, p], -1)
        b = self.phi(f)
        return torch.cat([b, torch.zeros(len(kf_idx), 5, self.heads, device=b.device, dtype=b.dtype)], 1)

    def risk(self, obj, ctx, e, kf_idx, lon, lat):
        q = (self.act['lon'](lon) + self.act['lat'](lat))[:, None]
        mem = torch.cat([obj[kf_idx], ctx[kf_idx], e[kf_idx][:, None]], 1)
        self._z = self.risk2(q, mem, self.interaction(kf_idx, lon, lat))[:, 0]
        o = self.h_risk2(self._z)
        return o[:, :-1], o[:, -1]

    def plan(self, obj, ctx, e, kf_idx, lon, lat):
        """-> trajectory (Q, 51, 3), speed (Q, 51), heading knots (Q, 11), risk logits (Q, 3)."""
        lo, _ = self.risk(obj, ctx, e, kf_idx, lon, lat)
        q = (self.act['lon'](lon) + self.act['lat'](lat) + self.plan_q(self._z))[:, None]
        mem = torch.cat([obj[kf_idx], ctx[kf_idx], e[kf_idx][:, None]], 1)
        h = self.plan_dec(q, mem)[:, 0].float()
        v_t, H_t = ego_template(self._v0[kf_idx], lon, lat)
        knots = torch.cat([v_t[:, :1], v_t[:, 5::5] + self.h_speed(h)], 1)          # 0, 0.5 .. 5 s
        v = _interp(knots, torch.linspace(0, 1, T51, device=h.device)[None].expand(len(h), -1))
        H = H_t + self.h_head(h)
        return rollout(v, H), v, H, lo