File size: 31,967 Bytes
314ecfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
"""Stage 2 (v2): StreamPETR-style monocular 3D detector with object-query memory on the FastVLM vision tower.

Image tokens are the FPN stride-8 features of FastViTHD (models/detector.py) with PETR's 3D position
embedding: every token is lifted along its camera ray to DEPTH_BINS depths, the points are normalised
to PC_RANGE and encoded by an MLP gated by the token's own features (PETRv2 feature-guided PE). A set of
learnable 3D reference points becomes object queries; the decoder layers attend to the image tokens and,
through hybrid self-attention, to a memory queue of the top-K queries of the last MEMORY_FRAMES frames.
Memory entries are aligned to the current frame with the ego motion and the objects' own velocity and
re-encoded by motion-aware layer normalisation (StreamPETR); the most recent K of them are propagated
into the current query set, so a track keeps its query across frames.

Every query predicts class scores, the box centre as a sigmoid-space offset from its reference point,
log half extents, heading (sin, cos) and velocity in the ego frame, and Laplace scales for range and
velocity, so decoded detections have the fields of models.detector.decode and feed the same tracker.
Training uses Hungarian set matching with focal + L1 losses on every decoder layer plus denoising
queries (noised ground-truth boxes with a known assignment).
"""
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 dataloader.detection_data import CAMERA_X, CAMERA_Z, FOCAL, GRID_H, GRID_W, IMAGE_H, IMAGE_W, STRIDE
from dataloader.detection_labels import (
    OBJ_BANK_VISIBLE, OBJ_CLASS, OBJ_HALF_H, OBJ_HALF_L, OBJ_HALF_W, OBJ_LIDAR_POINTS, OBJ_SPEED, OBJ_X, OBJ_Y,
    OBJ_YAW, OBJ_Z,
)
from dataloader.object_bank import NUM_CLASSES
from models.detector import FASTVIT_STAGE_INDEX, FPN, build_fastvithd

PC_RANGE = (-5.0, -50.0, -2.0, 60.0, 50.0, 4.0)  # x_min, y_min, z_min, x_max, y_max, z_max (box frame, metres)
DEPTH_BINS, DEPTH_MIN, DEPTH_MAX = 64, 1.0, 61.0
VEL_SCALE = 10.0
# regression code: dx dy dz (sigmoid-space offsets), log half l w h, sin yaw, cos yaw, vx vy (/VEL_SCALE),
# log sigma range, log sigma vx, log sigma vy
CODE_DIM = 13
BOX_DIM = 10  # target code: x y z, log half l w h, sin, cos, vx, vy
POSITIVE_RANGE = 50.0  # boxes the detector must find (as det_v1)
MATCH_RANGE = 55.0  # labelled boxes farther than this are neither matched nor negatives


# ------------------------------------------------------------------------------------------ helpers
def inverse_sigmoid(x, eps=1e-5):
    x = x.clamp(eps, 1 - eps)
    return torch.log(x / (1 - x))


def normalize_xyz(xyz):
    lo, hi = xyz.new_tensor(PC_RANGE[:3]), xyz.new_tensor(PC_RANGE[3:])
    return (xyz - lo) / (hi - lo)


def denormalize_xyz(n):
    lo, hi = n.new_tensor(PC_RANGE[:3]), n.new_tensor(PC_RANGE[3:])
    return n * (hi - lo) + lo


def sine_embedding(pos, num_feats=128, temperature=10000.0):
    """[..., D] in [0, 1] -> [..., D * num_feats] sine/cosine features."""
    pos = pos.float() * 2 * math.pi
    dim_t = torch.arange(num_feats, dtype=torch.float32, device=pos.device)
    dim_t = temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / num_feats)
    out = []
    for i in range(pos.shape[-1]):
        p = pos[..., i, None] / dim_t
        out.append(torch.stack((p[..., 0::2].sin(), p[..., 1::2].cos()), -1).flatten(-2))
    return torch.cat(out, -1)


def mlp(dims, final_bias=None):
    layers = []
    for i in range(len(dims) - 1):
        layers.append(nn.Linear(dims[i], dims[i + 1]))
        if i < len(dims) - 2:
            layers.append(nn.ReLU(inplace=True))
    if final_bias is not None:
        nn.init.constant_(layers[-1].bias, final_bias)
    return nn.Sequential(*layers)


def camera_frustum_points():
    """Box-frame points [GRID_H * GRID_W, DEPTH_BINS, 3] of the stride-8 cell centres at LID depth bins."""
    u = (torch.arange(GRID_W, dtype=torch.float32) + 0.5) * STRIDE
    v = (torch.arange(GRID_H, dtype=torch.float32) + 0.5) * STRIDE
    i = torch.arange(DEPTH_BINS, dtype=torch.float32) + 0.5
    d = DEPTH_MIN + (DEPTH_MAX - DEPTH_MIN) * i * (i + 1) / (DEPTH_BINS * (DEPTH_BINS + 1))
    vv, uu = torch.meshgrid(v, u, indexing="ij")
    uu, vv, d = uu.reshape(-1, 1), vv.reshape(-1, 1), d[None]
    x = (d + CAMERA_X).expand(uu.shape[0], -1)
    y = (uu - IMAGE_W / 2) * d / FOCAL
    z = -(vv - IMAGE_H / 2) * d / FOCAL + CAMERA_Z
    return torch.stack((x, y, z), -1)


def image_grid_uv():
    """Normalised (u, v) of the stride-8 cell centres [GRID_H * GRID_W, 2]."""
    u = (torch.arange(GRID_W, dtype=torch.float32) + 0.5) / GRID_W
    v = (torch.arange(GRID_H, dtype=torch.float32) + 0.5) / GRID_H
    vv, uu = torch.meshgrid(v, u, indexing="ij")
    return torch.stack((uu.reshape(-1), vv.reshape(-1)), -1)


def ego_from_world(w, pose):
    """World points [..., 2] -> ego frame of pose [..., 3] (x, y, yaw); same convention as ego_motion."""
    c, s = torch.cos(pose[..., 2]), torch.sin(pose[..., 2])
    dx, dy = w[..., 0] - pose[..., 0], w[..., 1] - pose[..., 1]
    return torch.stack((c * dx + s * dy, -s * dx + c * dy), -1)


def world_from_ego(p, pose):
    c, s = torch.cos(pose[..., 2]), torch.sin(pose[..., 2])
    return torch.stack((c * p[..., 0] - s * p[..., 1] + pose[..., 0], s * p[..., 0] + c * p[..., 1] + pose[..., 1]), -1)


def rotate(v, angle):
    c, s = torch.cos(angle), torch.sin(angle)
    return torch.stack((c * v[..., 0] - s * v[..., 1], s * v[..., 0] + c * v[..., 1]), -1)


# ------------------------------------------------------------------------------------------ decoder
class DecoderLayer(nn.Module):
    def __init__(self, d=256, heads=8, ffn=1024, dropout=0.0):
        super().__init__()
        self.heads = heads
        self.self_attn = nn.MultiheadAttention(d, heads, dropout=dropout, batch_first=True)
        self.cross_attn = nn.MultiheadAttention(d, heads, dropout=dropout, batch_first=True)
        self.ffn = nn.Sequential(nn.Linear(d, ffn), nn.ReLU(inplace=True), nn.Dropout(dropout), nn.Linear(ffn, d))
        self.norm1, self.norm2, self.norm3 = nn.LayerNorm(d), nn.LayerNorm(d), nn.LayerNorm(d)
        self.drop = nn.Dropout(dropout)

    def forward(self, q, q_pos, mem, mem_pos, attn_mask, img, img_pos):
        """q [B, L, d] queries; mem [B, S_m, d] memory-only keys; attn_mask [B, L, L + S_m] (True = blocked)."""
        k = torch.cat((q + q_pos, mem + mem_pos), 1)
        v = torch.cat((q, mem), 1)
        mask = attn_mask.repeat_interleave(self.heads, 0)
        x = self.self_attn(q + q_pos, k, v, attn_mask=mask, need_weights=False)[0]
        q = self.norm1(q + self.drop(x))
        x = self.cross_attn(q + q_pos, img + img_pos, img, need_weights=False)[0]
        q = self.norm2(q + self.drop(x))
        return self.norm3(q + self.drop(self.ffn(q)))


class StreamPETR(nn.Module):
    def __init__(self, init="pretrained/FastVLM-0.5B", embed=256, num_queries=400, num_propagated=128,
                 memory_frames=4, layers=6, dn_groups=3, dn_noise=(1.0, 1.0, 0.3), dn_label_noise=0.25,
                 freeze_backbone=False, fpn_channels=128):
        """init: FastVLM checkpoint dir, a driving-model .ckpt, or a train_detector.py .pt (backbone + FPN)."""
        super().__init__()
        from_detector = init.endswith(".pt")
        self.backbone = build_fastvithd("pretrained/FastVLM-0.5B" if from_detector else init)
        self.freeze_backbone = bool(freeze_backbone)
        if self.freeze_backbone:
            self.backbone.requires_grad_(False)
        self.fpn = FPN(fpn_channels)
        if from_detector:
            state = torch.load(init, map_location="cpu", weights_only=False)["model"]
            self.backbone.load_state_dict({k[len("backbone."):]: v for k, v in state.items() if k.startswith("backbone.")})
            self.fpn.load_state_dict({k[len("fpn."):]: v for k, v in state.items() if k.startswith("fpn.")})
        self.embed, self.num_queries, self.num_propagated = embed, num_queries, num_propagated
        self.memory_frames, self.dn_groups = memory_frames, dn_groups
        self.dn_noise, self.dn_label_noise = dn_noise, dn_label_noise

        self.in_proj = nn.Conv2d(fpn_channels, embed, 1)
        self.register_buffer("pe3d_input", inverse_sigmoid(normalize_xyz(camera_frustum_points())).flatten(1),
                             persistent=False)
        self.register_buffer("pe2d_input", sine_embedding(image_grid_uv(), embed // 2), persistent=False)
        self.pe3d = mlp([DEPTH_BINS * 3, embed * 4, embed])
        self.pe2d = mlp([embed, embed, embed])
        self.fpe = mlp([embed, embed, embed])
        self.reference_points = nn.Embedding(num_queries, 3)
        nn.init.uniform_(self.reference_points.weight, 0.0, 1.0)
        self.query_pos = mlp([embed // 2 * 3, embed, embed])
        self.dn_label_enc = nn.Embedding(NUM_CLASSES + 1, embed)
        self.mln = mlp([5, embed, 2 * embed])
        self.mln_norm = nn.LayerNorm(embed, elementwise_affine=False)
        self.layers = nn.ModuleList([DecoderLayer(embed) for _ in range(layers)])
        self.cls_heads = nn.ModuleList([mlp([embed, embed, embed, NUM_CLASSES], final_bias=-math.log(99.0))
                                        for _ in range(layers)])
        self.reg_heads = nn.ModuleList([mlp([embed, embed, embed, CODE_DIM]) for _ in range(layers)])
        for h in self.reg_heads:
            nn.init.zeros_(h[-1].weight)
            nn.init.zeros_(h[-1].bias)
        self.memory = None

    # ------------------------------------------------------------------------------ image tokens
    def backbone_features(self, images):
        x = F.interpolate(images.float() / 255.0, size=(IMAGE_H, IMAGE_W), mode="bilinear",
                          align_corners=False, antialias=True)
        x = self.backbone.patch_embed(x)
        feats = {}
        for i, block in enumerate(self.backbone.network):
            x = block(x)
            for s, idx in FASTVIT_STAGE_INDEX.items():
                if idx == i:
                    feats[s] = x
            if i >= FASTVIT_STAGE_INDEX[64]:
                break
        return feats

    def image_tokens(self, images):
        if self.freeze_backbone:
            with torch.no_grad():
                feats = self.backbone_features(images)
        else:
            feats = self.backbone_features(images)
        img = self.in_proj(self.fpn(feats)[8]).flatten(2).transpose(1, 2)  # [B, N, embed]
        pos = self.pe3d(self.pe3d_input)[None] * torch.sigmoid(self.fpe(img)) + self.pe2d(self.pe2d_input)[None]
        return img, pos

    # ------------------------------------------------------------------------------ memory
    def reset_memory(self, keep=None):
        """Clear the memory queue: everything (keep None) or the batch elements where keep is False."""
        if keep is None or self.memory is None:
            self.memory = None
            return
        keep = keep.to(self.memory["valid"].device)
        for k, v in self.memory.items():
            self.memory[k] = torch.where(keep.view(-1, *([1] * (v.dim() - 1))), v, torch.zeros_like(v))

    def _empty_memory(self, b, device):
        n, d = self.memory_frames * self.num_propagated, self.embed
        return dict(embed=torch.zeros(b, n, d, device=device), ref=torch.zeros(b, n, 3, device=device),
                    vel=torch.zeros(b, n, 2, device=device), pose=torch.zeros(b, n, 3, device=device),
                    time=torch.zeros(b, n, device=device), valid=torch.zeros(b, n, dtype=torch.bool, device=device))

    def aligned_memory(self, pose, time):
        """Memory entries moved into the current ego frame: (embed, pos, ref_norm, valid)."""
        m = self.memory
        pose_m = m["pose"]
        pose_b = pose[:, None].expand_as(pose_m)
        dt = (time[:, None] - m["time"]).clamp(min=0.0)
        moved = m["ref"][..., :2] + m["vel"] * dt[..., None]
        ref_xy = ego_from_world(world_from_ego(moved, pose_m), pose_b)
        ref = torch.cat((ref_xy, m["ref"][..., 2:3]), -1)
        rel_t = ego_from_world(pose_m[..., :2], pose_b)
        dyaw = pose_m[..., 2] - pose[:, None, 2]
        motion = torch.stack((rel_t[..., 0] / 10.0, rel_t[..., 1] / 10.0, torch.cos(dyaw), torch.sin(dyaw), dt), -1)
        gamma, beta = self.mln(motion).chunk(2, -1)
        embed = self.mln_norm(m["embed"]) * (1 + gamma) + beta
        ref_norm = normalize_xyz(ref).clamp(0.0, 1.0)
        pos = self.query_pos(sine_embedding(ref_norm, self.embed // 2))
        return embed, pos, ref_norm, m["valid"]

    @torch.no_grad()
    def update_memory(self, embed, center, vel, score, valid, pose, time):
        """Push the top-K current queries (by score) to the front of the memory queue."""
        k = self.num_propagated
        top = score.masked_fill(~valid, -1.0).topk(k, dim=1).indices
        g = lambda x: x.gather(1, top.unsqueeze(-1).expand(-1, -1, x.shape[-1]))  # noqa: E731
        new = dict(embed=g(embed).float(), ref=g(center).float(), vel=g(vel).float(),
                   pose=pose[:, None].expand(-1, k, -1).float(), time=time[:, None].expand(-1, k).float(),
                   valid=valid.gather(1, top))
        for key in self.memory:
            self.memory[key] = torch.cat((new[key], self.memory[key][:, :-k]), 1)

    # ------------------------------------------------------------------------------ denoising queries
    def make_dn(self, gt_rows, gt_count, device):
        """Noised copies of the positive ground-truth boxes: (embed, ref_norm, valid, group, gt_index).

        At least one (invalid, padded) query is always produced so the module graph is the same on
        every rank."""
        b = gt_rows.shape[0]
        pos = positive_mask(gt_rows, gt_count)
        n_max = int(pos.sum(1).max().item())
        n_dn = max(self.dn_groups * n_max, 1)
        ref = torch.full((b, n_dn, 3), 0.5, device=device)
        label = torch.full((b, n_dn), NUM_CLASSES, dtype=torch.long, device=device)
        valid = torch.zeros(b, n_dn, dtype=torch.bool, device=device)
        group = torch.zeros(b, n_dn, dtype=torch.long, device=device)
        gt_index = torch.zeros(b, n_dn, dtype=torch.long, device=device)
        if n_max:
            noise = gt_rows.new_tensor(self.dn_noise)
            for i in range(b):
                idx = pos[i].nonzero()[:, 0]
                n = len(idx)
                if n == 0:
                    continue
                rows = gt_rows[i, idx]
                for g in range(self.dn_groups):
                    sl = slice(g * n_max, g * n_max + n)
                    center = rows[:, [OBJ_X, OBJ_Y, OBJ_Z]] + (torch.rand(n, 3, device=device) * 2 - 1) * noise
                    lab = rows[:, OBJ_CLASS].long()
                    flip = torch.rand(n, device=device) < self.dn_label_noise
                    lab = torch.where(flip, torch.randint(0, NUM_CLASSES, (n,), device=device), lab)
                    ref[i, sl] = normalize_xyz(center).clamp(0.01, 0.99)
                    label[i, sl] = lab
                    valid[i, sl], group[i, sl], gt_index[i, sl] = True, g, idx
        return self.dn_label_enc(label), ref, valid, group, gt_index

    # ------------------------------------------------------------------------------ forward
    def forward(self, images, pose, time, gt_rows=None, gt_count=None):
        """images uint8 [B, 3, H, W]; pose [B, 3] world (x, y, yaw); time [B] seconds; optional labels
        [B, K, OBJ_DIM] / [B] switch denoising queries on.

        Call reset_memory() at the start of a sequence. Returns per-layer predictions for the query set
        [dn | current | propagated] plus the index layout; the memory queue is updated as a side effect."""
        b, device = images.shape[0], images.device
        img, img_pos = self.image_tokens(images)
        img_pos = img_pos.to(img.dtype)
        if self.memory is None or self.memory["embed"].shape[0] != b:
            self.memory = self._empty_memory(b, device)
        pose, time = pose.float(), time.float()
        mem_embed, mem_pos, mem_ref, mem_valid = self.aligned_memory(pose, time)
        k = self.num_propagated
        prop_embed, prop_pos, prop_ref, prop_valid = mem_embed[:, :k], mem_pos[:, :k], mem_ref[:, :k], mem_valid[:, :k]
        rest_embed, rest_pos, rest_valid = mem_embed[:, k:], mem_pos[:, k:], mem_valid[:, k:]

        cur_ref = self.reference_points.weight[None].expand(b, -1, -1)
        cur_pos = self.query_pos(sine_embedding(cur_ref, self.embed // 2))
        cur_embed = torch.zeros_like(cur_pos)

        if gt_rows is not None:
            dn_embed, dn_ref, dn_valid, dn_group, dn_gt = self.make_dn(gt_rows, gt_count, device)
            dn_pos = self.query_pos(sine_embedding(dn_ref, self.embed // 2))
            q = torch.cat((dn_embed, cur_embed, prop_embed), 1)
            q_pos = torch.cat((dn_pos, cur_pos, prop_pos), 1)
            ref = torch.cat((dn_ref, cur_ref, prop_ref), 1)
            n_dn = dn_embed.shape[1]
        else:
            dn_valid = dn_group = dn_gt = None
            q = torch.cat((cur_embed, prop_embed), 1)
            q_pos = torch.cat((cur_pos, prop_pos), 1)
            ref = torch.cat((cur_ref, prop_ref), 1)
            n_dn = 0
        n_cur, n_rest = self.num_queries, rest_embed.shape[1]
        L = q.shape[1]
        # self-attention keys are [dn | cur | prop | rest memory]; True blocks
        key_valid = torch.cat((torch.ones(b, n_dn + n_cur, dtype=torch.bool, device=device), prop_valid, rest_valid), 1)
        mask = ~key_valid[:, None, :].expand(-1, L, -1).clone()
        if n_dn:
            mask[:, n_dn:, :n_dn] = True  # matching queries never see denoising queries
            same = dn_group[:, :, None] == dn_group[:, None, :]
            mask[:, :n_dn, :n_dn] |= ~same | ~dn_valid[:, None, :]
        eye = torch.eye(L, dtype=torch.bool, device=device)[None]
        mask[:, :, :L] &= ~eye  # every query attends to itself (no empty rows)

        ref_logit = inverse_sigmoid(ref.float())
        q, q_pos = q.to(img.dtype), q_pos.to(img.dtype)
        rest_embed, rest_pos = rest_embed.to(img.dtype), rest_pos.to(img.dtype)
        outs = []
        for layer, cls_head, reg_head in zip(self.layers, self.cls_heads, self.reg_heads):
            q = layer(q, q_pos, rest_embed, rest_pos, mask, img, img_pos)
            reg = reg_head(q).float()
            outs.append(dict(cls=cls_head(q).float(), center=denormalize_xyz(torch.sigmoid(ref_logit + reg[..., 0:3])),
                             log_size=reg[..., 3:6], sincos=reg[..., 6:8], vel=reg[..., 8:10] * VEL_SCALE,
                             log_sigma=reg[..., 10:13]))
        valid = torch.cat((torch.ones(b, n_cur, dtype=torch.bool, device=device), prop_valid), 1)
        last = outs[-1]
        score = torch.sigmoid(last["cls"][:, n_dn:]).max(-1).values
        self.update_memory(q[:, n_dn:].detach(), last["center"][:, n_dn:].detach(), last["vel"][:, n_dn:].detach(),
                           score.detach(), valid, pose, time)
        return dict(layers=outs, n_dn=n_dn, n_cur=n_cur, n_prop=k, query_valid=valid, dn_valid=dn_valid,
                    dn_gt=dn_gt)


# ------------------------------------------------------------------------------------------ targets / loss
def positive_mask(rows, count):
    """[B, K] boxes the detector must find: bank-visible, within 50 m of the camera, hit by the lidar."""
    present = torch.arange(rows.shape[1], device=rows.device)[None] < count[:, None]
    rng = torch.hypot(rows[..., OBJ_X] - CAMERA_X, rows[..., OBJ_Y])
    return present & (rows[..., OBJ_BANK_VISIBLE] > 0.5) & (rng <= POSITIVE_RANGE) & (rows[..., OBJ_LIDAR_POINTS] >= 1)


def matchable_mask(rows, count):
    present = torch.arange(rows.shape[1], device=rows.device)[None] < count[:, None]
    rng = torch.hypot(rows[..., OBJ_X] - CAMERA_X, rows[..., OBJ_Y])
    return present & (rng <= MATCH_RANGE)


def box_code(rows):
    """[..., OBJ_DIM] -> target code (centre xyz, log half extents, sin, cos, vx, vy) [..., BOX_DIM]."""
    yaw, speed = rows[..., OBJ_YAW], rows[..., OBJ_SPEED]
    return torch.cat((rows[..., [OBJ_X, OBJ_Y, OBJ_Z]],
                      torch.log(rows[..., [OBJ_HALF_L, OBJ_HALF_W, OBJ_HALF_H]].clamp(min=1e-3)),
                      torch.sin(yaw)[..., None], torch.cos(yaw)[..., None],
                      (speed * torch.cos(yaw))[..., None], (speed * torch.sin(yaw))[..., None]), -1)


def pred_code(layer, sl):
    return torch.cat((layer["center"][:, sl], layer["log_size"][:, sl], layer["sincos"][:, sl], layer["vel"][:, sl]), -1)


def focal_cost(logits, gt_cls, alpha=0.25, gamma=2.0):
    """[L, C] logits, [G] classes -> [L, G] classification matching cost."""
    p = torch.sigmoid(logits)
    neg = (1 - alpha) * p ** gamma * (-(1 - p).clamp(min=1e-8).log())
    pos = alpha * (1 - p) ** gamma * (-p.clamp(min=1e-8).log())
    return pos[:, gt_cls] - neg[:, gt_cls]


def sigmoid_focal(logits, target_onehot, alpha=0.25, gamma=2.0):
    p = torch.sigmoid(logits)
    ce = F.binary_cross_entropy_with_logits(logits, target_onehot, reduction="none")
    p_t = p * target_onehot + (1 - p) * (1 - target_onehot)
    alpha_t = alpha * target_onehot + (1 - alpha) * (1 - target_onehot)
    return alpha_t * ce * (1 - p_t) ** gamma


def laplace_scale_term(err, log_sigma):
    """Trains only the scale (the mean is trained by the L1): err.detach() * exp(-s) + s."""
    log_sigma = log_sigma.clamp(-5.0, 5.0)
    return err.detach() * torch.exp(-log_sigma) + log_sigma


@torch.no_grad()
def hungarian_all(layers, sl, query_valid, gt_code, gt_cls, w_cls, w_box):
    """Assignments for every (layer, sample): list over layers of lists of (q_idx, g_idx) LongTensors (CPU).

    All cost matrices are moved to the CPU in one transfer."""
    b = query_valid.shape[0]
    g_max = max([len(g) for g in gt_code] + [1])
    costs = []
    for layer in layers:
        pc = pred_code(layer, sl)[..., :8]
        cost = pc.new_full((b, pc.shape[1], g_max), 1e6)
        for i in range(b):
            if len(gt_code[i]):
                c = w_cls * focal_cost(layer["cls"][i, sl], gt_cls[i]) + w_box * torch.cdist(pc[i], gt_code[i][:, :8], p=1)
                cost[i, :, :len(gt_code[i])] = c.masked_fill(~query_valid[i][:, None], 1e6)
        costs.append(cost)
    costs = torch.stack(costs).cpu().numpy()
    out = []
    for li in range(len(layers)):
        pairs = []
        for i in range(b):
            n = len(gt_code[i])
            if n == 0:
                pairs.append((torch.zeros(0, dtype=torch.long), torch.zeros(0, dtype=torch.long)))
                continue
            r, c = linear_sum_assignment(costs[li, i, :, :n])
            pairs.append((torch.as_tensor(r, dtype=torch.long), torch.as_tensor(c, dtype=torch.long)))
        out.append(pairs)
    return out


def stream_petr_loss(out, gt_rows, gt_count, w_cls=2.0, w_box=0.25, w_vel=1.0, w_sigma=0.1, w_dn=1.0):
    """Set loss over all decoder layers plus the denoising loss. gt_rows [B, K, OBJ_DIM] float, gt_count [B].

    Queries matched to an uncertain labelled box (not bank-visible / no lidar point / beyond 50 m) get
    no classification target and no negative pressure; boxes beyond MATCH_RANGE are not matched."""
    device = gt_rows.device
    b = gt_rows.shape[0]
    n_dn, n_cur, n_prop = out["n_dn"], out["n_cur"], out["n_prop"]
    sl = slice(n_dn, n_dn + n_cur + n_prop)
    qv = out["query_valid"]
    match = matchable_mask(gt_rows, gt_count)
    pos = positive_mask(gt_rows, gt_count)
    gt_code = [box_code(gt_rows[i, match[i]]) for i in range(b)]
    gt_cls = [gt_rows[i, match[i], OBJ_CLASS].long() for i in range(b)]
    gt_pos = [pos[i, match[i]] for i in range(b)]
    num_pos = max(float(pos.sum().item()), 1.0)
    assignments = hungarian_all(out["layers"], sl, qv, gt_code, gt_cls, w_cls, w_box)
    zero = gt_rows.new_zeros(())
    losses = dict(cls=zero, box=zero, vel=zero, sigma=zero, dn_cls=zero, dn_box=zero)
    dv, dg = out["dn_valid"], out["dn_gt"]
    if n_dn:
        n_dn_valid = max(float(dv.sum().item()), 1.0)
        gt_cls_all = gt_rows[..., OBJ_CLASS].long()
        dn_target = torch.zeros(b, n_dn, NUM_CLASSES, device=device)
        dn_target.scatter_(2, gt_cls_all.gather(1, dg)[..., None], 1.0)
        dn_target = dn_target * dv[..., None]
        dn_gt_code = box_code(gt_rows).gather(1, dg[..., None].expand(-1, -1, BOX_DIM))
    for layer, pairs in zip(out["layers"], assignments):
        logits = layer["cls"][:, sl]
        target = torch.zeros_like(logits)
        weight = qv.float().clone()  # 0 for invalid propagated queries
        pc = pred_code(layer, sl)
        ls = layer["log_sigma"][:, sl]
        box_l = vel_l = sig_l = zero
        for i, (r, c) in enumerate(pairs):
            if len(r) == 0:
                continue
            r, c = r.to(device), c.to(device)
            is_pos = gt_pos[i][c]
            target[i, r[is_pos], gt_cls[i][c[is_pos]]] = 1.0
            weight[i, r[~is_pos]] = 0.0
            rp, cp = r[is_pos], c[is_pos]
            if len(rp) == 0:
                continue
            p, g = pc[i, rp], gt_code[i][cp]
            box_l = box_l + (p[:, :8] - g[:, :8]).abs().sum()
            vel_err = (p[:, 8:10] - g[:, 8:10]).abs()
            vel_l = vel_l + vel_err.sum()
            rng_err = (torch.hypot(p[:, 0] - CAMERA_X, p[:, 1]) - torch.hypot(g[:, 0] - CAMERA_X, g[:, 1])).abs()
            sig_l = sig_l + laplace_scale_term(rng_err, ls[i, rp, 0]).sum() \
                + laplace_scale_term(vel_err, ls[i, rp, 1:3]).sum()
        losses["cls"] = losses["cls"] + (sigmoid_focal(logits, target) * weight[..., None]).sum() / num_pos
        losses["box"] = losses["box"] + box_l / num_pos
        losses["vel"] = losses["vel"] + vel_l / num_pos
        losses["sigma"] = losses["sigma"] + sig_l / num_pos
        if n_dn:
            dn_logits = layer["cls"][:, :n_dn]
            losses["dn_cls"] = losses["dn_cls"] + (sigmoid_focal(dn_logits, dn_target) * dv[..., None]).sum() / n_dn_valid
            pd = pred_code(layer, slice(0, n_dn))
            err = (pd[..., :8] - dn_gt_code[..., :8]).abs().sum(-1) \
                + w_vel * (pd[..., 8:10] - dn_gt_code[..., 8:10]).abs().sum(-1)
            losses["dn_box"] = losses["dn_box"] + (err * dv).sum() / n_dn_valid
    losses["total"] = w_cls * losses["cls"] + w_box * losses["box"] + w_box * w_vel * losses["vel"] \
        + w_sigma * losses["sigma"] + w_dn * (w_cls * losses["dn_cls"] + w_box * losses["dn_box"])
    return losses


# ------------------------------------------------------------------------------------------ decoding
NMS_LATERAL = {0: 1.0, 1: 0.5, 2: 1.0}  # per class: metres across the viewing ray
NMS_RANGE = {0: (1.5, 0.05), 1: (0.75, 0.025), 2: (1.5, 0.05)}  # along the ray: a + b * range


@torch.no_grad()
def bev_nms(x, y, cls, score):
    """Keep mask: a lower-scoring detection of the same class within NMS_LATERAL across and NMS_RANGE along
    the viewing ray of a kept one is a duplicate (the set prediction occasionally puts a current and a
    propagated query on the same object; their offsets are mostly along the ray, i.e. depth)."""
    n = len(score)
    keep = torch.ones(n, dtype=torch.bool, device=score.device)
    if n < 2:
        return keep
    dx, dy = x - CAMERA_X, y
    rng = torch.hypot(dx, dy)
    ux, uy = dx / rng.clamp(min=1e-6), dy / rng.clamp(min=1e-6)
    order = torch.argsort(score, descending=True)
    x, y, cls, rng, ux, uy = x[order], y[order], cls[order], rng[order], ux[order], uy[order]
    lat = torch.tensor([NMS_LATERAL[int(c)] for c in cls.tolist()], device=score.device)
    along = torch.tensor([NMS_RANGE[int(c)][0] + NMS_RANGE[int(c)][1] * r for c, r in zip(cls.tolist(), rng.tolist())],
                         device=score.device)
    ddx, ddy = x[None] - x[:, None], y[None] - y[:, None]  # [i, j]: j relative to i
    d_along = (ddx * ux[:, None] + ddy * uy[:, None]).abs()
    d_lat = (-ddx * uy[:, None] + ddy * ux[:, None]).abs()
    dup = (cls[None] == cls[:, None]) & (d_along <= along[:, None]) & (d_lat <= lat[:, None])
    kept = torch.ones(n, dtype=torch.bool, device=score.device)
    for i in range(n):
        if kept[i]:
            kept &= ~(dup[i] & (torch.arange(n, device=score.device) > i))
    keep[order] = kept
    return keep


@torch.no_grad()
def decode_stream(out, score_threshold=0.2, max_detections=64, nms=True):
    """Last-layer predictions of the matching queries -> per-image dicts with the fields of detector.decode."""
    n_dn = out["n_dn"]
    layer = out["layers"][-1]
    cls = layer["cls"][:, n_dn:]
    score_all = torch.sigmoid(cls).masked_fill(~out["query_valid"][..., None], 0.0)
    scores, flat = score_all.flatten(1).topk(min(max_detections, score_all.shape[1] * score_all.shape[2]), dim=1)
    q_idx, c_idx = flat // NUM_CLASSES, flat % NUM_CLASSES
    results = []
    for i in range(cls.shape[0]):
        keep = scores[i] >= score_threshold
        if nms and int(keep.sum()) > 1:
            q0 = q_idx[i][keep] + n_dn
            c0 = layer["center"][i, q0]
            sel = bev_nms(c0[:, 0], c0[:, 1], c_idx[i][keep], scores[i][keep])
            keep[keep.clone()] = sel
        q = q_idx[i][keep] + n_dn
        center = layer["center"][i, q]
        sincos = layer["sincos"][i, q]
        vel = layer["vel"][i, q]
        yaw = torch.atan2(sincos[:, 0], sincos[:, 1])
        speed = torch.hypot(vel[:, 0], vel[:, 1])
        flip = (speed > 1.0) & (torch.cos(torch.atan2(vel[:, 1], vel[:, 0]) - yaw) < 0)
        yaw = torch.where(flip, yaw + math.pi, yaw)
        yaw = torch.atan2(torch.sin(yaw), torch.cos(yaw))
        ext = torch.exp(layer["log_size"][i, q].clamp(-4, 4))
        ls = layer["log_sigma"][i, q].clamp(-5, 5)
        results.append(dict(
            x=center[:, 0], y=center[:, 1], z=center[:, 2], yaw=yaw, speed=speed, vx=vel[:, 0], vy=vel[:, 1],
            half_l=ext[:, 0], half_w=ext[:, 1], half_h=ext[:, 2], cls=c_idx[i][keep], score=scores[i][keep],
            depth_sigma=torch.exp(ls[:, 0]), velocity_sigma=torch.exp(ls[:, 1:3]),
            query=q_idx[i][keep],
        ))
    return results


def load_stream_petr(path, device):
    """StreamPETR from a train_stream_petr.py checkpoint, in eval mode with an empty memory."""
    ckpt = torch.load(path, map_location="cpu", weights_only=False)
    a = ckpt.get("args", {})
    model = StreamPETR(init="pretrained/FastVLM-0.5B", num_queries=a.get("num_queries", 400),
                       num_propagated=a.get("num_propagated", 128), memory_frames=a.get("memory_frames", 4),
                       layers=a.get("layers", 6), dn_groups=a.get("dn_groups", 3))
    model.load_state_dict(ckpt["model"])
    model.reset_memory()
    return model.to(device).eval()


class StreamDetector:
    """Online wrapper: one call per 4 Hz frame, memory carried across calls (reset() at route start)."""

    def __init__(self, model, device, score_threshold=0.2):
        self.model, self.device, self.score_threshold = model, device, score_threshold
        self.reset()

    def reset(self):
        self.model.reset_memory()

    @torch.no_grad()
    def step(self, image, pose, time):
        """image uint8 [3, H, W] tensor or numpy HWC; pose (x, y, yaw) world; time seconds -> decode dict
        of numpy arrays."""
        if isinstance(image, np.ndarray):
            image = torch.from_numpy(np.ascontiguousarray(image)).permute(2, 0, 1)
        image = image[None].to(self.device, non_blocking=True)
        pose_t = torch.tensor(pose, dtype=torch.float32, device=self.device)[None]
        time_t = torch.tensor([time], dtype=torch.float32, device=self.device)
        with torch.autocast("cuda", dtype=torch.bfloat16):
            out = self.model(image, pose_t, time_t)
        det = decode_stream(out, self.score_threshold)[0]
        return {k: v.float().cpu().numpy() for k, v in det.items()}