File size: 31,655 Bytes
31ffdfe
 
 
 
 
 
 
 
 
7b01b36
 
 
 
 
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
31ffdfe
 
7b01b36
31ffdfe
 
 
 
 
 
7b01b36
 
 
 
 
 
 
 
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
31ffdfe
 
 
 
 
 
 
7b01b36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31ffdfe
 
 
7b01b36
31ffdfe
 
 
7b01b36
 
 
 
 
 
 
31ffdfe
 
7b01b36
 
 
 
31ffdfe
 
 
 
 
7b01b36
 
31ffdfe
 
 
7b01b36
 
 
 
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
31ffdfe
 
 
 
7b01b36
 
 
 
31ffdfe
 
 
 
 
 
 
 
7b01b36
 
 
 
 
 
31ffdfe
 
 
7b01b36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31ffdfe
 
 
 
 
 
 
 
 
7b01b36
 
 
 
 
 
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
31ffdfe
 
 
 
 
 
 
 
 
 
7b01b36
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
31ffdfe
 
 
7b01b36
 
 
31ffdfe
 
 
 
 
7b01b36
 
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
31ffdfe
 
 
 
 
7b01b36
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31ffdfe
 
 
 
 
7b01b36
 
 
 
 
 
 
 
 
 
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
31ffdfe
 
 
 
 
 
 
 
7b01b36
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
31ffdfe
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
# SPDX-License-Identifier: Apache-2.0
"""One AutoE2E BEV frame on the device: 6 x (t1 TSA -> LN -> rebatched 4-level SCA -> LN -> FFN -> LN), in the
schedule of ``reference/port_form.py`` (layer 0's TSA + LN is a constant).

Every tensor of the BEV stream is TILE ``[1, 1, 60000, 256]`` bf16 in DRAM. Per frame the host geometry
(``host/geometry.py``) is uploaded: ``sca_index``, ``base`` (Q16.16 anchors per level), ``seg`` (the kernel's camera
segments), ``gather`` (K scatter gathers), ``scale``, ``observed``. The FPN levels arrive as rows ``[1, 1, 6 h w, 256]``
(camera-major) bf16 TILE.

TSA (layers 1-5): upstream projects ``pin = [q | q + pos]``; with ``W = [Wa | Wb]`` that is ``(Wa + Wb) q`` plus
the per-layer constant ``Wb pos + b`` (``pos`` is fixed), so the device projects ``q`` alone (K = 256) and adds the
constant (fp32, the cell-centre base folded in for the positions): one fp32 sampling projection in the merged layout
of 16 head blocks (block ``2 head + queue``: 4 points x (x, y), scaled by 2^16) -> int32 positions; one fp32
attention projection to the compact logits (4 per block) for the kernel's own softmax; the value
projection as 8 maps 300 x 200 in L1 shared by the two blocks of a head (``hdiv`` 2); the queue mean (x 0.5) folded
into the output projection over the 16 merged blocks.

SCA: the query rows of every camera gathered by ``sca_index`` (``ttnn.embedding`` from the query + a zero row); fp32
sampling projection (2^16-scaled, upstream's column order head, level, point, xy) + ``base`` repeated over the heads
-> int32 positions; fp32 attention projection -> head split -> softmax over the 32 (level, point) columns of a head;
per level one kernel call (``loc_off`` 16 l, ``att_col0`` 8 l) on that level's 48 value maps (map ``head * 6 +
camera``, the runtime camera segments) and the 4 level outputs summed; the scatter over cameras as K gathers of the
stacked rows + a zero row, times ``scale``; output projection, residual + LN.
"""
from __future__ import annotations

from typing import Any, Dict, List, Optional, Sequence

import numpy as np

from ..host.geometry import K_CAMS, R_CAP, CmGeometry, level_sizes, tsa_base, use_cm
from ..reference.port_form import BEV_H, BEV_W, E, HEADS, LEVELS, LN_EPS, Q
from ..ttaw.models.second import RowLinear
from .msda_cm import msda_cm
from .msda_k import PAD_LOGIT, msda

PREC = "HiFi4+fp32+l1acc:w=fp32"
SCALE = 65536.0


def prec(group: str, default: str = PREC) -> str:
    """Precision of a linear group (``AE_PREC_<GROUP>`` overrides, for experiments): OFF / ATT (sampling offsets and
    attention logits), VAL (value projections), OUT (output projections), FFN."""
    import os

    return os.environ.get(f"AE_PREC_{group}", default)


def _np(t) -> np.ndarray:
    return t.detach().float().cpu().numpy()


def _free(*ts):
    import ttnn

    for t in ts:
        if t is not None:
            ttnn.deallocate(t)


class _LN:
    def __init__(self, norm):
        self.g = _np(norm.weight).reshape(1, -1)
        self.b = _np(norm.bias).reshape(1, -1)
        self.dev = None

    def __call__(self, x, residual=None, cfg=None):
        import torch
        import ttnn

        d = x.device()
        if self.dev is None:
            up = lambda a: ttnn.from_torch(torch.from_numpy(a), dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT,
                                           device=d, memory_config=ttnn.DRAM_MEMORY_CONFIG)
            self.dev = (up(self.g), up(self.b))
        kw = {} if residual is None else {"residual_input_tensor": residual}
        return ttnn.layer_norm(x, weight=self.dev[0], bias=self.dev[1], epsilon=LN_EPS, compute_kernel_config=cfg,
                               memory_config=ttnn.DRAM_MEMORY_CONFIG, **kw)


_DTYPE_KW = {"ok": None}


def add_f32(a, b):
    """``a + b`` as float32 (bf16 inputs welcome): ``ttnn.add(..., dtype=float32)`` when this ttnn takes an output
    dtype (decided on the first, eager call), else typecasts + add."""
    import ttnn

    if _DTYPE_KW["ok"] is not False:
        try:
            out = ttnn.add(a, b, dtype=ttnn.float32, memory_config=ttnn.DRAM_MEMORY_CONFIG)
            _DTYPE_KW["ok"] = True
            return out
        except TypeError:
            _DTYPE_KW["ok"] = False
    fa = a if a.dtype == ttnn.float32 else ttnn.typecast(a, ttnn.float32)
    fb = b if b.dtype == ttnn.float32 else ttnn.typecast(b, ttnn.float32)
    out = ttnn.add(fa, fb, memory_config=ttnn.DRAM_MEMORY_CONFIG)
    if fa is not a:
        _free(fa)
    if fb is not b:
        _free(fb)
    return out


def linear_l1(lin, x):
    """``lin(x)`` (a RowLinear) with its output in L1 interleaved (the same ttnn.linear call otherwise)."""
    import ttnn

    if isinstance(lin, PcLinear):
        return lin(x, memory_config=ttnn.L1_MEMORY_CONFIG)
    from ..ttaw.tensors import ttnn_dtype

    weight, bias, grid, cfg = lin._device or lin._upload(x.device())
    return ttnn.linear(x, weight, bias=bias, activation=lin.activation, compute_kernel_config=cfg, core_grid=grid,
                       memory_config=ttnn.L1_MEMORY_CONFIG, dtype=ttnn_dtype(lin.output_dtype))


# Explicit matmul program configs per (K tiles, N tiles, fp32 out, relu), from the sweep of tests/dev_layer_ops.py on
# 60,000 BEV rows (1.2-1.8x faster than ttnn's choice for core_grid; the same fp32 accumulation, results within one
# rounding step), kept under an L1 budget for their circular buffers (L1 tensors such as the value maps live beside
# them): ("1d", in0_block_w, out_block_h, subblock h, subblock w) = in1 multicast, rows split over the grid;
# ("2d", grid x, in0_block_w, out_block_h, subblock h, subblock w)
_MM_SPECS = {
    (8, 16, True, False): ("2d", 8, 4, 4, 2, 2),     # sampling offsets 256 -> 512 (fp32)
    (8, 8, True, False): ("1d", 4, 4, 1, 4),         # attention logits 256 -> 256 (fp32)
    (8, 8, False, False): ("1d", 4, 4, 1, 4),        # output / value projections
    (8, 16, False, True): ("2d", 8, 4, 4, 2, 2),     # FFN 1 (relu)
    (8, 16, False, False): ("2d", 8, 4, 4, 2, 2),
    (16, 8, False, False): ("1d", 4, 2, 1, 4),       # FFN 2, TSA output (512 -> 256)
    (16, 8, True, False): ("1d", 4, 2, 1, 4),
    (8, 4, True, False): ("1d", 8, 4, 1, 4),         # TSA offsets 256 -> 128 (fp32)
    (8, 24, True, False): ("2d", 8, 4, 4, 1, 3),     # SCA offsets + logits 256 -> 768 (fp32)
}
_MM_BUDGET = {"dram": 600 << 10, "l1": 260 << 10}


def _mm_footprint(spec, k: int, n: int, fp32_out: bool) -> int:
    """Circular-buffer bytes of a spec (bf16 activations, fp32 weights): in0 / in1 double-buffered, out, fp32 partials."""
    if spec[0] == "1d":
        _, ibw, obh, _, _ = spec
        pcn = n
    else:
        _, nx, ibw, obh, _, _ = spec
        pcn = n // nx
    return (2 * obh * ibw * 2048 + 2 * ibw * pcn * 4096 + obh * pcn * (4096 if fp32_out else 2048)
            + (obh * pcn * 4096 if k // ibw > 1 else 0))


def mm_program_config(device, rows: int, k: int, n: int, fp32_out: bool, relu: bool, budget: str = "dram"):
    """The matmul program config of a ``[rows, 32 k] x [32 k, 32 n]`` linear (``None``: ttnn's own choice, as
    ``AE_MM_PC=0`` forces)."""
    import os

    import ttnn

    if os.environ.get("AE_MM_PC", "1") == "0":
        return None
    sbw0 = next(w for w in (4, 2, 1) if n % w == 0)
    spec = _MM_SPECS.get((k, n, fp32_out, relu)) or ("1d", next(b for b in (4, 2, 1) if k % b == 0), 4, 1, sbw0)
    if budget == "l1":
        spec = ("1d", next(b for b in (2, 1) if k % b == 0), 2, 1, sbw0)
    while _mm_footprint(spec, k, n, fp32_out) > _MM_BUDGET[budget]:
        if spec[0] == "2d":
            spec = ("1d", min(spec[2], 4), spec[3], 1, sbw0)
        elif spec[2] > 1:
            spec = (spec[0], spec[1], spec[2] // 2, 1, spec[4])
        elif spec[1] > 1:
            spec = (spec[0], spec[1] // 2, spec[2], spec[3], spec[4])
        else:
            return None
    g = device.compute_with_storage_grid_size()
    gx, gy = int(g.x), int(g.y)
    mt = -(-int(rows) // 32)
    act = ttnn.UnaryWithParam(ttnn.UnaryOpType.RELU) if relu else None
    if spec[0] == "2d":
        _, nx, ibw, obh, sbh, sbw = spec
        pcm = -(-mt // gy)
        if pcm % obh or n % nx:
            return None
        return ttnn.MatmulMultiCoreReuseMultiCastProgramConfig(
            compute_with_storage_grid_size=ttnn.CoreCoord(nx, gy), in0_block_w=ibw, out_subblock_h=sbh,
            out_subblock_w=sbw, out_block_h=obh, out_block_w=n // nx, per_core_M=pcm, per_core_N=n // nx,
            transpose_mcast=False, fused_activation=act)
    _, ibw, obh, sbh, sbw = spec
    pcm = -(-mt // (gx * gy))
    obh = min(obh, pcm)
    while pcm % obh:
        obh -= 1
    while obh % sbh:
        sbh -= 1
    return ttnn.MatmulMultiCoreReuseMultiCast1DProgramConfig(
        compute_with_storage_grid_size=ttnn.CoreCoord(gx, gy), in0_block_w=ibw, out_subblock_h=sbh,
        out_subblock_w=sbw, out_block_h=obh, out_block_w=n, per_core_M=pcm, per_core_N=n, fuse_batch=True,
        fused_activation=act, mcast_in0=False)


class PcLinear(RowLinear):
    """A RowLinear run with an explicit program config (:func:`mm_program_config`, cached per row count)."""

    def __call__(self, x: Any, memory_config: Any = None) -> Any:
        import ttnn

        from ..ttaw.tensors import ttnn_dtype

        if int(x.shape[-1]) != self.in_channels:
            raise ValueError(f"{self.name}: input has {int(x.shape[-1])} channels, expected {self.in_channels}")
        weight, bias, grid, cfg = self._device or self._upload(x.device())
        rows = 1
        for i in range(len(x.shape) - 1):
            rows *= int(x.shape[i])
        mc = memory_config or ttnn.DRAM_MEMORY_CONFIG
        budget = "l1" if mc.buffer_type == ttnn.BufferType.L1 else "dram"
        cache = self.__dict__.setdefault("_pcs", {})
        if (rows, budget) not in cache:
            cache[(rows, budget)] = mm_program_config(x.device(), rows, self.in_channels // 32,
                                                      self.out_channels // 32, self.output_dtype == "float32",
                                                      self.activation == "relu", budget)
        pc = cache[(rows, budget)]
        if pc is None or self.in_channels % 32 or self.out_channels % 32:
            return ttnn.linear(x, weight, bias=bias, activation=self.activation, compute_kernel_config=cfg,
                               core_grid=grid, memory_config=mc, dtype=ttnn_dtype(self.output_dtype))
        return ttnn.linear(x, weight, bias=bias, program_config=pc, compute_kernel_config=cfg, memory_config=mc,
                           dtype=ttnn_dtype(self.output_dtype))


def _lin(w_out_in: np.ndarray, b: Optional[np.ndarray], *, out="bfloat16", act=None, name="linear",
         group: str = "OFF") -> RowLinear:
    """nn.Linear weight ``[out, in]`` -> PcLinear (``[in, out]``)."""
    return PcLinear(np.ascontiguousarray(w_out_in.T), b, activation=act, precision=prec(group), output_dtype=out,
                    name=name)


def cm_column_orders():
    """Column orders of the sampling offsets / attention logits for ``msda_cm`` (its reader RISC h reads only its own
    points 4 h .. 4 h + 3): offsets ``j * 64 + h * 32 + l * 8 + 2 q + xy`` (upstream ``j * 64 + l * 16 + 2 p + xy``,
    ``p = 4 h + q``), logits ``j * 32 + h * 16 + l * 4 + q`` (upstream ``j * 32 + l * 8 + p``; the softmax over a
    head's 32 columns does not depend on their order). Returns the two index arrays ``new -> upstream``."""
    po = np.zeros(HEADS * 64, np.int64)
    pa = np.zeros(HEADS * 32, np.int64)
    for j in range(HEADS):
        for h in range(2):
            for l in range(LEVELS):
                for q in range(4):
                    p = 4 * h + q
                    for xy in range(2):
                        po[j * 64 + h * 32 + l * 8 + 2 * q + xy] = j * 64 + l * 16 + 2 * p + xy
                    pa[j * 32 + h * 16 + l * 4 + q] = j * 32 + l * 8 + p
    return po, pa


def _permuted(lin: RowLinear, perm: np.ndarray) -> "PcLinear":
    """``lin`` with its output columns reordered (``out[:, n] = lin_out[:, perm[n]]``)."""
    return PcLinear(lin.weight_host[:, perm], lin.bias_host[perm], activation=lin.activation, precision=lin.precision,
                    output_dtype=lin.output_dtype, name=lin.name)


class _Layer:
    def __init__(self, layer, i: int, pos: np.ndarray):
        sa, ca, ffn = layer.self_attention, layer.cross_attention, layer.ffn
        self.i = i
        if i > 0:
            self.tsa_v = _lin(_np(sa.value_proj.weight), _np(sa.value_proj.bias), name=f"l{i}.tsa.value", group="VAL")
            # pin = [q | q + pos] -> (Wa + Wb) q + (Wb pos + b): the second term is a per-layer constant
            p64 = pos.astype(np.float64)
            w, b = _np(sa.sampling_offsets.weight).astype(np.float64), _np(sa.sampling_offsets.bias).astype(np.float64)
            self.tsa_off = _lin(((w[:, :E] + w[:, E:]) * SCALE).astype(np.float32), None, out="float32",
                                name=f"l{i}.tsa.off")
            self.tsa_off_c = ((p64 @ w[:, E:].T + b) * SCALE + tsa_base().astype(np.float64)).astype(np.float32)
            # [64, 512]: column h * 8 + q * 4 + p = head block 2 h + q, point p: the compact logits of the in-kernel
            # softmax (4 per block) as they come
            w, b = _np(sa.attention_weights.weight).astype(np.float64), _np(sa.attention_weights.bias).astype(np.float64)
            self.tsa_att = _lin((w[:, :E] + w[:, E:]).astype(np.float32), None, out="float32", name=f"l{i}.tsa.att",
                                group="ATT")
            self.tsa_att_c = (p64 @ w[:, E:].T + b).astype(np.float32)
            wo = _np(sa.output_proj.weight)             # [256, 256] (out, in = head * 32 + d)
            wo2 = np.zeros((E, 16 * 32), np.float32)
            for h in range(HEADS):
                for q in range(2):
                    wo2[:, (2 * h + q) * 32:(2 * h + q + 1) * 32] = 0.5 * wo[:, h * 32:(h + 1) * 32]
            self.tsa_out = _lin(wo2, _np(sa.output_proj.bias), name=f"l{i}.tsa.out", group="OUT")
        self.sca_v = _lin(_np(ca.value_proj.weight), _np(ca.value_proj.bias), name=f"l{i}.sca.value", group="VAL")
        self.sca_off = _lin(_np(ca.sampling_offsets.weight) * SCALE, _np(ca.sampling_offsets.bias) * SCALE,
                            out="float32", name=f"l{i}.sca.off")
        self.sca_att = _lin(_np(ca.attention_weights.weight), _np(ca.attention_weights.bias), out="float32",
                            name=f"l{i}.sca.att", group="ATT")
        self.sca_out = _lin(_np(ca.output_proj.weight), _np(ca.output_proj.bias), name=f"l{i}.sca.out", group="OUT")
        self.ffn1 = _lin(_np(ffn[0].weight), _np(ffn[0].bias), act="relu", name=f"l{i}.ffn1", group="FFN")
        self.ffn2 = _lin(_np(ffn[3].weight), _np(ffn[3].bias), name=f"l{i}.ffn2", group="FFN")
        self.norms = [_LN(n) for n in layer.norms]


class TtBevEncoder:
    """``TtBevEncoder(device, model)`` (``model`` the loaded upstream AutoE2E); ``frame(levels, geo)``."""

    def __init__(self, device: Any, model: Any, *, image: int = 512):
        import torch
        import ttnn

        from ..reference.port_form import PortForm

        self.device = device
        self.image = image
        self.sizes = level_sizes(image)
        pf = PortForm(model)
        vf = pf.vf
        pos = pf.position.numpy()
        self.layers = [_Layer(l, i, pos) for i, l in enumerate(vf.layers)]
        up = lambda a, dt=ttnn.bfloat16: ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(a, np.float32)),
                                                         dtype=dt, layout=ttnn.TILE_LAYOUT, device=device,
                                                         memory_config=ttnn.DRAM_MEMORY_CONFIG)
        self.layer0 = up(pf.layer0.numpy().reshape(1, 1, Q, E))
        for L in self.layers[1:]:
            L.tsa_off_dev = up(L.tsa_off_c.reshape(1, 1, Q, 128), ttnn.float32)
            L.tsa_att_dev = up(L.tsa_att_c.reshape(1, 1, Q, 64), ttnn.float32)
            del L.tsa_off_c, L.tsa_att_c
        # level + camera embeddings of the value input, per level [1, 1, 6 h w, 256] (camera-major rows)
        lvl, cam = pf.level_emb.numpy(), pf.camera_emb.numpy()
        self.emb = []
        for l, (h, w) in enumerate(self.sizes):
            e = np.repeat((lvl[l][None] + cam[:6])[:, None, :], h * w, axis=1).reshape(1, 1, 6 * h * w, E)
            self.emb.append(up(e))
        self.prof: Optional[Dict[str, float]] = None   # set to {} to time the blocks (synchronizes the device)
        self.pairs = True                               # pixel-pair value maps (2x faster SCA kernel, same values)
        import os

        # cross-attention value maps as quads (the 4 corners of a point in one 256-byte read; the same values)
        self.quads = self.pairs and os.environ.get("AE_QUADS", "1") != "0"
        # cell-major cross-attention (one kernel per layer, no gather / scatter / level sum); layer 0's query is the
        # constant LN0(TSA0(bev_queries)), so its sampling offsets and weights are constants too
        self.cfg = ttnn.init_device_compute_kernel_config(device.arch(), math_fidelity=ttnn.MathFidelity.HiFi4,
                                                          math_approx_mode=False, fp32_dest_acc_en=True,
                                                          packer_l1_acc=True)
        self.cm = self.quads and use_cm()
        # intermediates read once by the next linear kept in L1 interleaved (no DRAM round trip) where they fit beside
        # the value maps and the kernel buffers: the FFN hidden (AE_L1_FFN), the TSA / SCA kernel outputs (AE_L1_TSA /
        # AE_L1_SCA; the SCA output does not fit beside its maps)
        l1 = lambda k, d: ttnn.L1_MEMORY_CONFIG if os.environ.get(k, d) != "0" else ttnn.DRAM_MEMORY_CONFIG
        self._mid_ffn = l1("AE_L1_FFN", "1")
        self._mid_tsa = l1("AE_L1_TSA", "0")
        self._mid_sca = l1("AE_L1_SCA", "0")
        self._cm0 = None
        if self.cm:
            po, pa = cm_column_orders()
            # the offsets and logits as ONE 256 -> 768 projection (the query read once; AE_SCA_MERGE=0: two)
            self.sca_merge = os.environ.get("AE_SCA_MERGE", "1") != "0"
            for L in self.layers:
                L.sca_off = _permuted(L.sca_off, po)
                L.sca_att = _permuted(L.sca_att, pa)
                if self.sca_merge:
                    L.sca_proj = PcLinear(np.concatenate([L.sca_off.weight_host, L.sca_att.weight_host], axis=1),
                                          np.concatenate([L.sca_off.bias_host, L.sca_att.bias_host]),
                                          precision=L.sca_off.precision, output_dtype="float32",
                                          name=f"l{L.i}.sca.proj")
            L0 = self.layers[0]
            # the raw projections (msda_cm converts them in the kernel)
            if self.sca_merge:
                self._cm0 = (L0.sca_proj(self.layer0), None)
            else:
                self._cm0 = (L0.sca_off(self.layer0), L0.sca_att(self.layer0))

    # ------------------------------------------------------------------ inputs
    def upload_geometry(self, geo) -> Dict[str, Any]:
        """Host :class:`FrameGeometry` -> device tensors (fresh; a traced runner copies into persistent ones)."""
        import torch
        import ttnn

        d = self.device
        t = {}
        if isinstance(geo, CmGeometry):
            t["table"] = ttnn.from_torch(torch.from_numpy(geo.table.reshape(1, 1, Q, 32)), dtype=ttnn.int32,
                                         layout=ttnn.TILE_LAYOUT, device=d)
            t["observed"] = ttnn.from_torch(torch.from_numpy(geo.observed.reshape(1, 1, Q, 1)), dtype=ttnn.bfloat16,
                                            layout=ttnn.TILE_LAYOUT, device=d)
            return t
        t["sca_index"] = ttnn.from_torch(torch.from_numpy(geo.sca_index.astype(np.int64)).to(torch.int32),
                                         dtype=ttnn.uint32, layout=ttnn.ROW_MAJOR_LAYOUT, device=d)
        t["base"] = ttnn.from_torch(torch.from_numpy(geo.base.reshape(1, 1, geo.base.shape[0], -1)), dtype=ttnn.float32,
                                    layout=ttnn.TILE_LAYOUT, device=d)
        t["seg"] = ttnn.from_torch(torch.from_numpy(geo.seg.astype(np.int64)).to(torch.int32), dtype=ttnn.uint32,
                                   layout=ttnn.ROW_MAJOR_LAYOUT, device=d)
        t["gather"] = [ttnn.from_torch(torch.from_numpy(geo.gather[k:k + 1].astype(np.int64)).to(torch.int32),
                                       dtype=ttnn.uint32, layout=ttnn.ROW_MAJOR_LAYOUT, device=d)
                       for k in range(geo.gather.shape[0])]
        t["scale"] = ttnn.from_torch(torch.from_numpy(geo.scale.reshape(1, 1, Q, 1)), dtype=ttnn.float32,
                                     layout=ttnn.TILE_LAYOUT, device=d)
        t["observed"] = ttnn.from_torch(torch.from_numpy(geo.observed.reshape(1, 1, Q, 1)), dtype=ttnn.bfloat16,
                                        layout=ttnn.TILE_LAYOUT, device=d)
        t["nseg"] = len(geo.seg_rows)
        return t

    # ------------------------------------------------------------------ blocks
    def _t(self, name, t0):
        """Profiling: add the time since ``t0`` to block ``name`` (device synchronized); returns the new t0."""
        import time

        import ttnn

        if self.prof is None:
            return t0
        ttnn.synchronize_device(self.device)
        t = time.perf_counter()
        self.prof[name] = self.prof.get(name, 0.0) + (t - t0)
        return t

    def _heads(self, x, n, mc=None):
        import ttnn

        out, _, _ = ttnn.experimental.nlp_create_qkv_heads(x, num_heads=int(n), num_kv_heads=0,
                                                           transpose_k_heads=False,
                                                           memory_config=mc or ttnn.DRAM_MEMORY_CONFIG)
        return out

    def _maps(self, proj, n_maps, h, w, quad=False):
        """value projection ``[1, 1, S h w, 256]`` -> the ``msda`` value of the 8 S maps (map head * S + s): pixel-pair
        maps ``(8 S, h, w + 1, 64)`` in L1 (``tt/pairmap.py``; one 128-byte read per two corners) when ``self.pairs``,
        else stick maps ``(8 S, h, w, 32)`` in L1."""
        import ttnn

        if self.pairs:
            from .pairmap import pair_maps

            p1 = proj if proj.memory_config().buffer_type == ttnn.BufferType.L1 else \
                ttnn.to_memory_config(proj, ttnn.L1_MEMORY_CONFIG)
            out = pair_maps(p1, heads=HEADS, sub=int(n_maps) // HEADS, hw=(h, w), quad=quad)
            if p1 is not proj:
                _free(p1)
            return out
        heads = self._heads(proj, HEADS)
        rm = ttnn.to_layout(heads, ttnn.ROW_MAJOR_LAYOUT, memory_config=ttnn.L1_MEMORY_CONFIG)
        _free(heads)
        return ttnn.reshape(rm, (int(n_maps), int(h), int(w), 32))

    def _tsa(self, L: _Layer, query):
        import time

        import ttnn

        t0 = self._t('-', time.perf_counter())
        off = L.tsa_off(query)                                                  # [1, 1, Q, 128] fp32
        loc_f = ttnn.add(off, L.tsa_off_dev, memory_config=ttnn.DRAM_MEMORY_CONFIG)   # + Wb pos + b + base
        _free(off)
        loc = ttnn.typecast(loc_f, ttnn.int32)
        _free(loc_f)
        lg = L.tsa_att(query)                                                   # [1, 1, Q, 64] fp32
        logits = ttnn.add(lg, L.tsa_att_dev, memory_config=ttnn.DRAM_MEMORY_CONFIG)
        _free(lg)
        t0 = self._t('tsa.proj_loc_att', t0)
        vproj = linear_l1(L.tsa_v, query) if self.pairs else L.tsa_v(query)
        maps = self._maps(vproj, HEADS, BEV_H, BEV_W)
        _free(vproj)
        t0 = self._t('tsa.value_maps', t0)
        out = msda(maps, loc, logits, points=4, nq=Q, sub=1, hdiv=2, loc_hs=8, softmax=True,
                   memory_config=self._mid_tsa)                                 # [1, 1, Q, 512]
        _free(maps, loc, logits)
        t0 = self._t('tsa.msda', t0)
        y = L.tsa_out(out)
        _free(out)
        self._t('tsa.out', t0)
        return y

    def _sca(self, L: _Layer, query, xs, g):
        import time

        import ttnn

        from ..ttaw.ops.gather import with_zero_rows

        t0 = self._t('-', time.perf_counter())
        table = with_zero_rows(query)                                           # [1, 1, Q + 1, 256] RM
        rows = ttnn.embedding(g["sca_index"], table, layout=ttnn.TILE_LAYOUT, padding_idx=Q,
                              embeddings_type=ttnn.EmbeddingsType.PADDED)
        _free(table)
        rows = ttnn.reshape(rows, (1, 1, R_CAP, E))
        t0 = self._t('sca.gather_rows', t0)
        # positions = fp32 offsets (Q16.16 units) + the anchors repeated over the heads, as int32 (msda's LOCF mode
        # adds the anchors in the kernel instead, but its per-point float -> int conversions on the reader RISC-Vs
        # cost more than this add + typecast: e16_base, SCA kernel 88 -> 131 ms per frame); the softmax over a
        # head's 4 levels x 8 points once per layer (in-kernel it would repeat in each of the 4 level calls: 2x slower)
        off = L.sca_off(rows)                                                   # [1, 1, R, 512] fp32
        loc_f = ttnn.add(off, g["base512"], memory_config=ttnn.DRAM_MEMORY_CONFIG)
        _free(off)
        loc = ttnn.typecast(loc_f, ttnn.int32)
        _free(loc_f)
        logits = L.sca_att(rows)                                                # [1, 1, R, 256] fp32
        _free(rows)
        lh = self._heads(logits, HEADS)
        _free(logits)
        att = ttnn.softmax(lh, dim=-1, compute_kernel_config=self.cfg)          # per head over (level, point)
        _free(lh)
        t0 = self._t('sca.proj_loc_att', t0)
        acc = None
        for l, (h, w) in enumerate(self.sizes):
            vproj = linear_l1(L.sca_v, xs[l]) if self.pairs else L.sca_v(xs[l])
            maps = self._maps(vproj, HEADS * 6, h, w, quad=self.quads)
            _free(vproj)
            t0 = self._t('sca.value_maps', t0)
            o = msda(maps, loc, att, points=8, nq=R_CAP, segments=[0] * g["nseg"], seg_table=g["seg"],
                     loc_hs=64, loc_off=16 * l, att_col0=8 * l)
            _free(maps)
            t0 = self._t(f'sca.msda.l{l}', t0)
            if acc is None:
                acc = o                                                         # bf16; the sums are fp32
            else:
                nxt = add_f32(acc, o)
                _free(acc, o)
                acc = nxt
        _free(loc, att)
        t0 = self._t('sca.level_sum', t0)
        stacked = ttnn.typecast(acc, ttnn.bfloat16)
        _free(acc)
        st = with_zero_rows(stacked)                                            # [1, 1, R + 1, 256] RM
        _free(stacked)
        tot = None
        for gi in g["gather"]:
            part = ttnn.embedding(gi, st, layout=ttnn.TILE_LAYOUT, padding_idx=R_CAP,
                                  embeddings_type=ttnn.EmbeddingsType.PADDED)
            part = ttnn.reshape(part, (1, 1, Q, E))
            if tot is None:
                tot = part
            else:
                nxt = add_f32(tot, part)
                _free(tot, part)
                tot = nxt
        _free(st)
        if tot.dtype != ttnn.float32:                                           # K = 1: no sum
            t32 = ttnn.typecast(tot, ttnn.float32)
            _free(tot)
            tot = t32
        att_mean = ttnn.multiply(tot, g["scale"], memory_config=ttnn.DRAM_MEMORY_CONFIG)
        _free(tot)
        attended = ttnn.typecast(att_mean, ttnn.bfloat16)
        _free(att_mean)
        t0 = self._t('sca.scatter', t0)
        y = L.sca_out(attended)
        _free(attended)
        self._t('sca.out', t0)
        return y

    def _sca_cm(self, L: _Layer, query, xs, g):
        """The cell-major cross-attention (``msda_cm``): offsets / weights on the Q cells, the 4 levels' quad maps, one
        kernel; ``g["table"]`` the frame's cell table."""
        import time

        import ttnn

        t0 = self._t('-', time.perf_counter())
        const = L.i == 0 and self._cm0 is not None
        if const:
            loc, att = self._cm0
        else:
            # raw fp32 projections: msda_cm makes the offsets int32 and runs the softmax per head in the kernel
            if self.sca_merge:
                loc, att = L.sca_proj(query), None                              # [1, 1, Q, 768] fp32
            else:
                loc = L.sca_off(query)                                          # [1, 1, Q, 512] fp32
                att = L.sca_att(query)                                          # [1, 1, Q, 256] fp32
        t0 = self._t('sca.proj_loc_att', t0)
        maps = []
        for l, (h, w) in enumerate(self.sizes):
            vproj = linear_l1(L.sca_v, xs[l])
            maps.append(self._maps(vproj, HEADS * 6, h, w, quad=True))
            _free(vproj)
        t0 = self._t('sca.value_maps', t0)
        o = msda_cm(maps, loc, att, g["table"], memory_config=self._mid_sca)
        _free(*maps)
        if not const:
            _free(loc, att)
        t0 = self._t('sca.msda', t0)
        y = L.sca_out(o)
        _free(o)
        self._t('sca.out', t0)
        return y

    def frame(self, levels: Sequence[Any], g: Dict[str, Any], *, trace: Optional[List] = None):
        """``levels``: 4 x ``[1, 1, 6 h w, 256]`` bf16 TILE FPN rows; ``g`` from :meth:`upload_geometry` -> the BEV
        ``[1, 1, Q, 256]`` bf16 (zero where no camera sees the cell)."""
        import ttnn

        cm = "table" in g
        if cm and "observed" not in g:
            # 1 where a camera sees the cell: the count column of the cell table (per frame, on the device)
            cnt = ttnn.typecast(ttnn.slice(g["table"], [0, 0, 0, 18], [1, 1, Q, 19]), ttnn.bfloat16)
            g = dict(g, observed=ttnn.gtz(cnt))
            _free(cnt)
            own_obs = True
        else:
            own_obs = False
        own_base = not cm and "base512" not in g
        if own_base:
            g["base512"] = ttnn.repeat(g["base"], ttnn.Shape([1, 1, 1, HEADS]), memory_config=ttnn.DRAM_MEMORY_CONFIG)
        xs = [ttnn.add(levels[l], self.emb[l], memory_config=ttnn.DRAM_MEMORY_CONFIG) for l in range(LEVELS)]
        query = self.layer0
        own = False
        for L in self.layers:
            if L.i > 0:
                y = self._tsa(L, query)
                q2 = L.norms[0](y, residual=query, cfg=self.cfg)
                _free(y)
                if own:
                    _free(query)
                query, own = q2, True
            y = self._sca_cm(L, query, xs, g) if cm else self._sca(L, query, xs, g)
            q2 = L.norms[1](y, residual=query, cfg=self.cfg)
            _free(y)
            if own:
                _free(query)
            query, own = q2, True
            import time

            t0 = self._t('-', time.perf_counter())
            h1 = L.ffn1(query, memory_config=self._mid_ffn)
            y = L.ffn2(h1)
            _free(h1)
            q2 = L.norms[2](y, residual=query, cfg=self.cfg)
            _free(y)
            self._t('ffn_ln', t0)
            _free(query)
            query = q2
            if trace is not None:
                trace.append(ttnn.to_torch(query).float().numpy().reshape(Q, E))
        _free(*xs)
        if own_base:
            _free(g.pop("base512"))
        out = ttnn.multiply(query, g["observed"], memory_config=ttnn.DRAM_MEMORY_CONFIG)
        _free(query)
        if own_obs:
            _free(g["observed"])
        return out