File size: 30,172 Bytes
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
# SPDX-License-Identifier: Apache-2.0
"""DEC megakernel plan (host mirror of ``kernels/md_defs.hpp`` + the plan table in the compile-time args).

Feature maps live in DRAM as ROW_MAJOR NHWC "padded raster" storage (see :class:`MapG`): every image row has one
zero pad pixel after it (pitch ``W' = W + 1``), there is a zero guard row above and below the image and the pads /
guards are zero-initialized once and never written. A 3x3 tap ``(dy, dx)`` of 32 consecutive output pixels of one
image row is then 32 consecutive storage pixels (the x borders read pad pixels = the zero padding), so the A
operand of every tap is a contiguous ROW_MAJOR run that the TRISC tilizes straight out of the unit's L1 band.

Layers (one barrier-separated phase each; the whole list runs once per frame group of ``G`` frames):

* ``RA``  reassemble.i.0 (1x1) on the tapped tokens (TILE) -> map;
* ``UP``  conv-transpose k x k stride k (reassemble.0.1 k=4, reassemble.1.1 k=2, the fusion deconv with the 1x1
  out_conv folded in) = per-pixel matmul with N ordered (a, b, c) + depth-to-space writes;
* ``C3``  3x3 conv (stride 1, or 2 for reassemble.3.1) with optional input ReLU (applied by the packer when the
  input is tilized), output ReLU, bias and up to two residual maps (added in fp32 before the single bf16 rounding);
* ``HC``  head.1 (convT k2s2) o head.2 (3x3) folded into one 3x3 conv on the half-resolution map with 4 sub-pixel
  output tiles (each uses 4 of the 9 half-res neighbours), + bias (per-pixel class: head.1's bias does not pass the
  zero padding), ReLU, head.4 (1x1, 32 -> 1) + ReLU -> the float32 inverse depth (TILE).

Work decomposition of a layer: units (2D blocks of BH output rows x BW tiles of 32 pixels; RA: BH token tiles) x
n-blocks (NBW output tiles). The n-blocks form NBO groups (split over groups of grid rows) of NBI blocks (iterated
inside a unit). Every grid row shares one weight stream (the row feeder multicasts it); a row group's cores take
the group's units round-robin, one unit per core per round, and every core of the row consumes the stream once
per round.
"""

from __future__ import annotations

import math
import os
import re
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Sequence, Tuple

KDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kernels")
DEFS_PATH = os.path.join(KDIR, "md_defs.hpp")


def _parse_defs(path: str = DEFS_PATH) -> Dict[str, int]:
    out = {}
    pat = re.compile(r"^\s*constexpr\s+uint32_t\s+([A-Z0-9_]+)\s*=\s*([0-9]+)\s*;")
    with open(path) as f:
        for line in f:
            m = pat.match(line)
            if m:
                out[m.group(1)] = int(m.group(2))
    return out


D = _parse_defs()
globals().update(D)

NONE = 0xFFFF
#: reference model dims (reference/model.py SIZES)
DIMS = {"S": ((48, 96, 192, 384), 64, 384), "B": ((96, 192, 384, 768), 128, 768),
        "L": ((256, 512, 1024, 1024), 256, 1024), "H": ((256, 512, 1024, 1024), 256, 1280)}

#: L1 caps per CB (bytes); the program allocates exactly the max over layers (<= cap)
CAPS = dict(band=400 << 10, a=160 << 10, res=136 << 10, acc=256 << 10, sel=32 << 10)
RING_PAGES = 20
FEED_BW = float(os.environ.get("DEPTHPRO2_MK_DEC_FEED_GBS", "16")) * 1e9  # bytes / s per row feeder
#: opt-in (not yet cleared on the device, MK_LOG round 3): narrow n-blocks for weight-heavy layers split over row
#: groups, UP n-block groups over row groups, feeder bandwidth in the cost model
NSPLIT = os.environ.get("DEPTHPRO2_MK_DEC_NSPLIT", "0") == "1"
BLK_MAX = RING_PAGES * PAGE_TILES // 2  # tiles per weight block (double-buffered ring)
L1_BUDGET = 1400 * 1024


def c32(n: int) -> int:
    return -(-n // 32) * 32


def cdiv(a: int, b: int) -> int:
    return -(-a // b)


def pow2_div(n: int, cap: int = 8) -> int:
    """largest power of two <= cap dividing n"""
    p = 1
    while p * 2 <= cap and n % (p * 2) == 0:
        p *= 2
    return p


@dataclass
class MapG:
    """Padded-raster ROW_MAJOR storage of an H x W x C map (``frames`` frames). Storage pixel of (y, x) =
    ``b0 + y * wp + x`` for y in [-1, H], x in [-1, W] (x = -1 / W fall into the zero pad columns [W, wp), y = -1 / H
    are the zero guard rows); a DRAM page holds 32 storage pixels x C channels (>= 2 KB). ``wp`` and ``b0`` are
    multiples of 32, so every image row starts on a page: a unit's tile columns are whole pages (DRAM requests >= 2 KB,
    Blackhole SYS-1419)."""

    name: str
    H: int
    W: int
    C: int
    frames: int = 1
    idx: int = -1

    @property
    def wp(self) -> int:
        return c32(self.W + 1)

    @property
    def b0(self) -> int:
        return self.wp + 32  # guard row -1 plus one page in front of it (left edge chunk of row -1)

    @property
    def fpix(self) -> int:
        return c32(self.b0 + (self.H + 3) * self.wp + 64)  # rows -1 .. H, one overshoot row, edge chunks

    @property
    def fpg(self) -> int:
        return self.fpix // 32

    @property
    def page_bytes(self) -> int:
        return 64 * self.C

    @property
    def pages(self) -> int:
        return self.frames * self.fpg

    @property
    def bytes(self) -> int:
        return self.pages * self.page_bytes

    def g(self, y: int, x: int) -> int:
        return self.b0 + y * self.wp + x


@dataclass
class Layer:
    op: int
    name: str
    src: int  # map id (RA: tap index)
    dst: int  # map id (HC: -1)
    res: Tuple[int, ...] = ()
    flags: int = 0
    s: int = 1  # C3 stride / UP k
    cin: int = 0  # input channels (padded)
    n: int = 0  # output tiles
    # weight keys (wprep)
    wkey: str = ""
    # chosen config
    kc: int = 0
    nkb: int = 1
    nbw: int = 0
    nbo: int = 1
    nbi: int = 1
    bh: int = 1
    bw: int = 1
    yb: int = 1
    xb: int = 1
    u: int = 0
    ho: int = 0
    wo: int = 0
    kxo: int = 0
    bandp: int = 0
    boff: int = 0  # C3 / HC: byte offset of the band row data (x = -1) behind the left edge chunk slack
    kpx: int = 1  # C3 / HC: pixels of one band edge chunk (>= 2 KB)
    nbias: int = 0
    acc: int = 0
    wpg: int = 0
    bp0: int = 0
    bp: int = 0
    row0: int = 0  # grid rows [row0, row0 + nrows) run this layer (phase merging); 0 = all rows
    nrows: int = 0
    bar: int = 1  # 1: global barrier after this layer (end of its phase)
    est: Dict[str, float] = field(default_factory=dict)

    @property
    def ct(self) -> int:
        return self.cin // 32


class Plan:
    """Maps + layers + per-layer configs of one DEC program (size, T, hp, wp) on a ``gx x gy`` grid."""

    def __init__(self, size: str, T: int, hp: int, wp: int, gx: int, gy: int, group: Optional[int] = None,
                 map_budget: Optional[int] = None, merge: Optional[bool] = None):
        if hp % 32 or wp % 32:
            raise ValueError("hp, wp must be multiples of 32")
        self.size, self.T, self.hp, self.wp = size, T, hp, wp
        self.C, self.R = gx, gy
        self.NC = gx * gy
        dr, d, cdim = DIMS[size]
        self.dr = tuple(c32(v) for v in dr)
        self.dr_raw = dr
        self.d = d
        self.cdim = cdim
        self.gh, self.gw = hp // 16, wp // 16
        self.n = self.gh * self.gw
        self.np_ = c32(self.n)
        self.pt = self.np_ // 32
        budget = map_budget or int(os.environ.get("DEPTHPRO2_MK_DEC_MAP_MB", "1536")) << 20
        if group is None:
            per = self._map_bytes(1)
            group = 1
            for g in range(T, 0, -1):
                if T % g == 0 and per * g <= budget:
                    group = g
                    break
        if T % group:
            raise ValueError("group must divide T")
        self.G = group
        self.ngrp = T // group
        self.maps: List[MapG] = []
        self.layers: List[Layer] = []
        self._build()
        for L in self.layers:
            self._config(L)
        if merge is None:
            merge = os.environ.get("DEPTHPRO2_MK_DEC_MERGE", "0") == "1"
        self.phases = self._phases() if merge else [[i] for i in range(len(self.layers))]
        self.weight_pages = assign_pages(self.layers)
        self.kx_hc = cdiv(self.wp // 2, 32)

    # ------------------------------------------------------------------ structure
    def _map_bytes(self, frames: int) -> int:
        saved = getattr(self, "maps", None)
        self.maps = []
        self.layers = []
        self.G = frames
        self._build()
        b = sum(m.bytes for m in self.maps)
        self.maps, self.layers = [], []
        return b

    def _map(self, name: str, H: int, W: int, C: int) -> int:
        m = MapG(name, H, W, C, self.G, len(self.maps))
        self.maps.append(m)
        return m.idx

    def _layer(self, **kw) -> Layer:
        L = Layer(**kw)
        self.layers.append(L)
        return L

    def _build(self):
        gh, gw, d = self.gh, self.gw, self.d
        dr = self.dr
        M = self._map
        lv = {3: (gh // 2, gw // 2), 2: (gh, gw), 1: (2 * gh, 2 * gw), 0: (4 * gh, 4 * gw), -1: (8 * gh, 8 * gw)}
        R0 = M("R0", gh, gw, dr[0])
        R1 = M("R1", gh, gw, dr[1])
        P2 = M("P2", gh, gw, dr[2])
        R3 = M("R3", gh, gw, dr[3])
        P0 = M("P0", *lv[0], dr[0])
        P1 = M("P1", *lv[1], dr[1])
        P3 = M("P3", *lv[3], dr[3])
        P = {0: P0, 1: P1, 2: P2, 3: P3}
        Ls = self._layer
        cd = self.cdim
        for i, (src, dst) in enumerate(((0, R0), (1, R1), (2, P2), (3, R3))):
            Ls(op=OP_RA, name=f"ra{i}", src=src, dst=dst, flags=F_BIAS, cin=cd, n=dr[i] // 32,
               wkey=f"encoder.reassemble.{i}.0")
        Ls(op=OP_UP, name="up0", src=R0, dst=P0, flags=F_BIAS, s=4, cin=dr[0], n=16 * dr[0] // 32,
           wkey="encoder.reassemble.0.1")
        Ls(op=OP_UP, name="up1", src=R1, dst=P1, flags=F_BIAS, s=2, cin=dr[1], n=4 * dr[1] // 32,
           wkey="encoder.reassemble.1.1")
        Ls(op=OP_C3, name="s2", src=R3, dst=P3, flags=F_BIAS, s=2, cin=dr[3], n=dr[3] // 32,
           wkey="encoder.reassemble.3.1")
        S, Tm, Y, Z, X = {}, {}, {}, {}, {}
        for i in (3, 2, 1, 0):
            H, W = lv[i]
            S[i] = M(f"S{i}", H, W, d)
            Tm[i] = M(f"T{i}", H, W, d)
            Y[i] = M(f"Y{i}", H, W, d)
            Z[i] = M(f"Z{i}", *lv[i - 1], d)
            if i < 3:
                X[i] = M(f"X{i}", H, W, d)
        Hh = M("Hh", *lv[-1], d // 2)
        fp = lambda i: f"decoder.fusions.{i}"  # noqa: E731
        c1 = F_RELU_IN | F_RELU_OUT | F_BIAS
        # order: independent layers adjacent (phase merging, _phases), then the serial fusion chain
        Ls(op=OP_C3, name="cv2", src=P[2], dst=S[2], flags=0, cin=dr[2], n=d // 32, wkey="decoder.convs.2")
        for i in (3, 1, 0):
            Ls(op=OP_C3, name=f"cv{i}", src=P[i], dst=S[i], flags=0, cin=dr[i], n=d // 32, wkey=f"decoder.convs.{i}")
        for i in (2, 1, 0):
            Ls(op=OP_C3, name=f"f{i}r1c1", src=S[i], dst=Tm[i], flags=c1, cin=d, n=d // 32,
               wkey=fp(i) + ".resnet1.residual.1")
        for i in (3, 2, 1, 0):
            x = S[3]
            if i < 3:
                Ls(op=OP_C3, name=f"f{i}r1c3", src=Tm[i], dst=X[i], res=(Z[i + 1], S[i]), flags=F_BIAS, cin=d,
                   n=d // 32, wkey=fp(i) + ".resnet1.residual.3")
                x = X[i]
            Ls(op=OP_C3, name=f"f{i}r2c1", src=x, dst=Tm[i], flags=c1, cin=d, n=d // 32,
               wkey=fp(i) + ".resnet2.residual.1")
            Ls(op=OP_C3, name=f"f{i}r2c3", src=Tm[i], dst=Y[i], res=(x,), flags=F_BIAS, cin=d, n=d // 32,
               wkey=fp(i) + ".resnet2.residual.3")
            Ls(op=OP_UP, name=f"f{i}up", src=Y[i], dst=Z[i], flags=F_BIAS, s=2, cin=d, n=4 * d // 32, wkey=fp(i) + ".up")
        Ls(op=OP_C3, name="h0", src=Z[0], dst=Hh, flags=F_BIAS, cin=d, n=d // 64, wkey="head.0")
        Ls(op=OP_HC, name="hc", src=Hh, dst=-1, flags=F_BIAS, cin=d // 2, n=4, wkey="head.hc")

    # ------------------------------------------------------------------ phases (layer merging)
    def _phases(self) -> List[List[int]]:
        """Consecutive independent layers (none reads or writes a map another one of the phase writes) share one
        barrier-separated phase; each gets a contiguous slice of grid rows ~ its estimated time (>= 1 row)."""
        phases: List[List[int]] = []
        cur: List[int] = []
        wr: set = set()
        rd: set = set()
        for i, L in enumerate(self.layers):
            ins = set(L.res) | ({L.src} if L.op != OP_RA else set())
            outs = {L.dst} if L.dst >= 0 else set()
            if cur and (ins & wr or outs & (wr | rd) or len(cur) >= self.R):
                phases.append(cur)
                cur, wr, rd = [], set(), set()
            cur.append(i)
            wr |= outs
            rd |= ins
        if cur:
            phases.append(cur)
        for ph in phases:
            for i in ph:
                self.layers[i].bar = 0
            self.layers[ph[-1]].bar = 1
            if len(ph) == 1:
                continue
            est = [max(self.layers[i].est.get("ms", 0.0), 1e-4) for i in ph]
            rows = [1] * len(ph)
            for _ in range(self.R - len(ph)):  # greedy: give the next row to the slowest layer (time / rows)
                j = max(range(len(ph)), key=lambda k: est[k] / rows[k])
                rows[j] += 1
            r0 = 0
            for i, nr in zip(ph, rows):
                L = self.layers[i]
                L.row0, L.nrows = r0, nr
                r0 += nr
                self._config(L)
        return phases

    # ------------------------------------------------------------------ per-layer config
    def _rows(self, L: Layer) -> int:
        return L.nrows or self.R

    def _span(self, L: Layer) -> int:
        """cores sharing a group's units"""
        R = self._rows(L)
        if L.nbo <= R:
            return (R // L.nbo) * self.C
        return self.C

    def _rounds(self, L: Layer) -> int:
        R = self._rows(L)
        rounds = cdiv(L.u, self._span(L))
        if L.nbo > R:
            rounds *= cdiv(L.nbo, R)
        return rounds

    def _config(self, L: Layer):
        static_cfg(L)
        src = self.maps[L.src] if L.op != OP_RA else None
        if L.op == OP_RA:
            self._cfg_ra(L)
        elif L.op == OP_UP:
            self._cfg_up(L, src)
        else:
            self._cfg_c3(L, src)

    def _cost(self, L: Layer, mm: int, tz: int, pk: int, nkb_tot: int, dram: int) -> float:
        """cycles of one unit (compute) and bytes moved per unit"""
        cyc = mm * 64 + tz * 70 + pk * 40 + nkb_tot * 1500 + 4000
        return cyc

    def _round_time(self, L: Layer, unit_cyc: float, unit_bytes: float, wbytes: float) -> float:
        """seconds of one round of the whole grid: compute vs DRAM (all active cores)"""
        R = self._rows(L)
        active = min(R * self.C, L.u * L.nbo if L.nbo <= R else L.u * R)
        comp = unit_cyc / 1.35e9
        dram = (unit_bytes * active + wbytes * R) / 380e9
        feed = wbytes / FEED_BW if NSPLIT else 0.0  # every row streams its blocks through one feeder (~11 GB/s)
        return max(comp, dram, feed)

    def _cfg_ra(self, L: Layer):
        """RA units are output map pages: (frame, token row y, page p) = tokens [y gw + 32 p, y gw + min(32 p + 32, gw))
        (<= 2 token tiles, mb = 2). One core computes every n-block of its unit (nbo = 1) into an L1 staging page
        and writes the whole 32-pixel page (>= 2 KB DRAM write)."""
        kt = self.cdim // 32
        n = L.n
        nb = n // L.nbw
        mb = 2
        if mb * kt * T16 > CAPS["band"] or mb * L.nbw * T32 > CAPS["acc"] or 32 * n * 64 > CAPS["res"]:
            raise RuntimeError(f"no RA config for {L.name}")
        npg = cdiv(self.gw, 32)
        L.nbo, L.nbi, L.bh, L.bw = 1, nb, mb, 1
        L.u = self.G * self.gh * npg
        L.kc, L.nkb, L.acc = L.kc, kt // L.kc, 1
        rounds = self._rounds(L)
        mm = mb * kt * L.nbw * nb + mb * L.nbw * nb
        cyc = self._cost(L, mm, 0, mb * L.nbw * nb * (L.nkb + 1), L.nkb * nb, 0)
        ub = mb * kt * T16 + 32 * n * 64
        wb = (kt * L.nbw + L.nbw) * nb * T16
        t = rounds * self._round_time(L, cyc, ub, wb)
        L.yb, L.xb = L.u, 1
        L.ho, L.wo, L.kxo = self.gh, self.gw, self.pt
        L.nbias = L.nbw
        L.est = {"ms": t * 1e3, "rounds": rounds}
        L.cin = self.cdim

    def _cfg_up(self, L: Layer, src: MapG):
        ct = L.ct
        H, W = src.H, src.W
        kx = cdiv(W, 32)
        nbw = L.nbw
        nb = L.n // nbw
        L.acc = 1
        best = None
        k = L.s
        cout = L.n * 32 // (k * k)
        nbpa = (k * cout // 32) // nbw  # n-blocks of one output a-row (whole output pages once all have landed)
        if (k * cout // 32) % nbw:
            raise RuntimeError(f"{L.name}: n-block {nbw} tiles does not divide an output row ({k * cout} channels)")
        for nbo in ([v for v in range(1, nb + 1) if nb % v == 0] if NSPLIT else [1]):
            nbi = nb // nbo
            if nbi % nbpa:
                continue
            for bh in (1, 2, 4, 8, 16):
                for bw in (1, 2, 3, 4, 6, 8):
                    if bw > kx or bh > H:
                        continue
                    band = bh * 32 * bw * src.C * 2
                    stage = bh * bw * k * 32 * cout * 2  # one a-row of every (r, kx) of the unit, L1 staging
                    if (band > CAPS["band"] or bh * bw * ct * T16 > CAPS["a"]
                            or bh * bw * nbw * T32 > CAPS["acc"] or stage > CAPS["res"]):
                        continue
                    L.nbo, L.nbi = nbo, nbi
                    L.bh, L.bw = bh, bw
                    L.yb, L.xb = cdiv(H, bh), cdiv(kx, bw)
                    L.u = self.G * L.yb * L.xb
                    rounds = self._rounds(L)
                    mt = bh * bw
                    mm = mt * (ct + 1) * nbw * nbi
                    cyc = self._cost(L, mm, mt * ct, mt * nbw * nbi, nbi, 0)
                    ub = band + mt * 32 * nbw * nbi * 64
                    wb = (ct + 1) * nbw * nbi * T16
                    t = rounds * self._round_time(L, cyc, ub, wb)
                    key = (t, -mt, nbo)
                    if best is None or key < best[0]:
                        best = (key, (bh, bw, t, nbo, nbi))
        if best is None:
            raise RuntimeError(f"no UP config for {L.name}")
        L.bh, L.bw, t, L.nbo, L.nbi = best[1]
        L.yb, L.xb = cdiv(H, L.bh), cdiv(kx, L.bw)
        L.u = self.G * L.yb * L.xb
        L.ho, L.wo, L.kxo = H, W, kx
        L.bandp = 32 * L.bw * src.C * 2
        L.nbias = L.nbw
        L.est = {"ms": t * 1e3, "rounds": self._rounds(L)}

    def _cfg_c3(self, L: Layer, src: MapG):
        ct, s = L.ct, L.s
        if L.op == OP_HC:
            Ho, Wo = src.H, src.W
            ntap = 16  # 4 sub-pixels x 4 neighbours (per output tile: 4 x ct)
        else:
            Ho, Wo = (src.H // s, src.W // s)
            ntap = 9
        nbw = L.nbw
        nb = L.n // nbw
        kxo = cdiv(Wo, 32)
        nres = len(L.res)
        pxb = src.C * 2
        # band rows: [left edge chunk slack (kpx - 1 px)] x = -1, 32 s bw pixels (whole pages), [right edge chunk]
        kpx = min(32, cdiv(MIN_REQ, pxb))
        if L.op == OP_HC and Ho % 8:
            raise RuntimeError(f"{L.name}: HC needs a multiple of 8 rows ({Ho})")
        best = None
        for kc in (L.kc,):
            nkb = ct // kc
            for nbo in [v for v in range(1, nb + 1) if nb % v == 0]:
                nbi = nb // nbo
                if nbw < L.n and L.op == OP_C3 and not nres:
                    if nbo != 1:  # whole output pixels on one core (L1 staging, whole-page writes)
                        continue
                elif nbi != 1:
                    continue
                for bh in ((8,) if L.op == OP_HC else (1, 2, 3, 4, 6, 8)):
                    for bw in (1, 2, 3, 4, 6, 8):
                        if bw > kxo or bh > Ho:
                            continue
                        rows = s * (bh - 1) + 3
                        bandp = c16((s * 32 * bw + (2 * kpx if s == 1 else kpx)) * pxb)
                        band = rows * bandp
                        stage = bh * bw * 32 * L.n * 64 if nbi > 1 else (bw * 4096 if L.op == OP_HC else 0)
                        # kc == 1 out of a wider row: the k-block pair (kb, kb + 1) is tilized at once (2-tile
                        # fast-tilize chunks, the kernel keeps the A tiles over the two k-blocks: L1 "pair" mode)
                        a_t = 3 * rows * bw * (2 if pair_mode(L) else kc)
                        acc_t = bh * bw * nbw
                        sel_t = bh * bw if L.op == OP_HC else 0
                        res_b = bh * 32 * bw * L.n * 64 if nres else 0
                        if (band > CAPS["band"] or a_t * T16 > CAPS["a"] or acc_t * T32 > CAPS["acc"]
                                or res_b > CAPS["res"] or sel_t * T16 > CAPS["sel"] or stage > CAPS["res"]):
                            continue
                        L.nbo, L.nbi = nbo, nbi
                        L.u = self.G * cdiv(Ho, bh) * cdiv(kxo, bw)
                        rounds = self._rounds(L)
                        mt = bh * bw
                        kpt = (ntap * ct if L.op != OP_HC else 4 * ct)
                        mm = mt * nbw * (kpt + 1) * nbi
                        if L.op == OP_HC:
                            mm += mt * 9
                        tz = a_t * (nkb // 2 if pair_mode(L) else nkb) * nbi + mt * nbw * nres
                        pk = mt * nbw * (nkb + 2) * nbi
                        cyc = self._cost(L, mm, tz, pk, nkb * nbi, 0)
                        ub = band + res_b + mt * 32 * nbw * 64 * nbi * (1 if L.op != OP_HC else 0)
                        wb = (kpt * nbw + nbw) * T16 * nbi
                        t = rounds * self._round_time(L, cyc, ub, wb)
                        key = (t, -mt, -kc)
                        if best is None or key < best[0]:
                            best = (key, dict(kc=kc, nkb=nkb, nbo=nbo, nbi=nbi, bh=bh, bw=bw, bandp=bandp, t=t))
        if best is None:
            raise RuntimeError(f"no C3 config for {L.name} (cin {L.cin}, n {L.n}, map {src.H}x{src.W})")
        c = best[1]
        L.kc, L.nkb, L.nbo, L.nbi, L.bh, L.bw, L.bandp = c["kc"], c["nkb"], c["nbo"], c["nbi"], c["bh"], c["bw"], c["bandp"]
        L.kpx, L.boff = kpx, (kpx - 1) * pxb
        L.ho, L.wo, L.kxo = Ho, Wo, kxo
        L.yb, L.xb = cdiv(Ho, L.bh), cdiv(kxo, L.bw)
        L.u = self.G * L.yb * L.xb
        L.acc = 1
        L.nbias = nbw if L.op != OP_HC else 4
        L.est = {"ms": c["t"] * 1e3, "rounds": self._rounds(L)}

    # ------------------------------------------------------------------ L1
    def cb_sizes(self) -> Dict[str, int]:
        band = a = res = acc = sel = 0
        for L in self.layers:
            res = max(res, stage_bytes(L))  # L1 staging of whole-page outputs lives in the CB_RES memory
            if L.op == OP_RA:
                band = max(band, L.bh * L.cin // 32 * T16)
                acc = max(acc, L.bh * L.nbw * T32)
                continue
            src = self.maps[L.src]
            if L.op == OP_UP:
                band = max(band, L.bh * L.bandp)
                a = max(a, L.bh * L.bw * L.ct * T16)
                acc = max(acc, L.bh * L.bw * L.nbw * T32)
                continue
            rows = L.s * (L.bh - 1) + 3
            band = max(band, rows * L.bandp)
            a = max(a, 3 * rows * L.bw * (2 if pair_mode(L) else L.kc) * T16)
            acc = max(acc, L.bh * L.bw * L.nbw * T32)
            if L.res:
                res = max(res, L.bh * 32 * L.bw * L.n * 64)
            if L.op == OP_HC:
                sel = max(sel, L.bh * L.bw * T16)
        return dict(w=RING_PAGES * PAGE_TILES * T16, band=c16(band), a=max(a, T16), res=c16(max(res, 16)),
                    acc=max(acc, T32), out=OUT_CAP * T16, const=N_CONST * T16, sel=max(sel, T16), z=4 * T16,
                    ho=2 * T32, sync=SYNC_BYTES)

    def l1_bytes(self) -> int:
        return sum(self.cb_sizes().values())

    # ------------------------------------------------------------------ serialization
    def table(self) -> List[int]:
        hdr = [0] * NHF
        hdr[H_NL] = len(self.layers)
        hdr[H_NM] = len(self.maps)
        hdr[H_G] = self.G
        hdr[H_NGRP] = self.ngrp
        hdr[H_PT] = self.pt
        hdr[H_N] = self.n
        hdr[H_GW] = self.gw
        hdr[H_HP] = self.hp
        hdr[H_WP] = self.wp
        hdr[H_RING] = RING_PAGES
        hdr[H_KX_HC] = self.kx_hc
        out = list(hdr)
        for m in self.maps:
            f = [0] * NMF
            f[M_H], f[M_W], f[M_WP], f[M_C], f[M_B0], f[M_FPG], f[M_ARG] = m.H, m.W, m.wp, m.C, m.b0, m.fpg, K_MAP0 + m.idx
            out += f
        for L in self.layers:
            f = [0] * NLF
            f[L_OP], f[L_SRC], f[L_DST] = L.op, L.src, (L.dst if L.dst >= 0 else NONE)
            f[L_RES0] = L.res[0] if len(L.res) > 0 else NONE
            f[L_RES1] = L.res[1] if len(L.res) > 1 else NONE
            f[L_NRES], f[L_FLAGS], f[L_S] = len(L.res), L.flags, L.s
            f[L_CT] = L.cin // 32
            f[L_KC], f[L_NKB], f[L_N], f[L_NBW], f[L_NBO], f[L_NBI] = L.kc, L.nkb, L.n, L.nbw, L.nbo, L.nbi
            f[L_BH], f[L_BW], f[L_YB], f[L_XB], f[L_U] = L.bh, L.bw, L.yb, L.xb, L.u
            f[L_WPG], f[L_BP0], f[L_BP] = L.wpg, L.bp0, L.bp
            f[L_HO], f[L_WO], f[L_KXO], f[L_BANDP], f[L_NBIAS], f[L_ACC] = L.ho, L.wo, L.kxo, L.bandp, L.nbias, L.acc
            f[L_ROW0], f[L_NROWS], f[L_BAR] = L.row0, L.nrows or self.R, L.bar
            f[L_PAIR] = 1 if pair_mode(L) else 0
            f[L_BOFF], f[L_KPX] = L.boff, L.kpx
            out += f
        return out

    def summary(self) -> str:
        lines = [f"plan {self.size} T={self.T} {self.hp}x{self.wp} grid {self.C}x{self.R} G={self.G} groups={self.ngrp} "
                 f"phases={len(self.phases)}"]
        tot = 0.0
        for L in self.layers:
            tot += L.est.get("ms", 0) * self.ngrp
            lines.append(f"  {L.name:7s} op{L.op} cin {L.cin:5d} n {L.n:3d} nbw {L.nbw} nbo {L.nbo} nbi {L.nbi} "
                         f"kc {L.kc:2d} nkb {L.nkb:2d} bh {L.bh} bw {L.bw} u {L.u:5d} rows {L.row0}+{L.nrows or self.R} "
                         f"bar {L.bar} rounds {L.est.get('rounds')} "
                         f"est {L.est.get('ms', 0):.3f} ms")
        sz = self.cb_sizes()
        lines.append(f"  est total {tot:.2f} ms; L1 {sum(sz.values()) / 1024:.0f} KB {{{', '.join(f'{k} {v // 1024}' for k, v in sz.items())}}}; "
                     f"maps {sum(m.bytes for m in self.maps) / 2**20:.0f} MB")
        return "\n".join(lines)


def c16(n: int) -> int:
    return -(-n // 16) * 16


def _divs(n: int) -> List[int]:
    return [k for k in range(n, 0, -1) if n % k == 0]


def static_cfg(L: Layer) -> None:
    """Shape-independent stream parameters (k-block width kc, n-block width nbw, bias tiles): the weight arena of a
    size is shared by every bucket / clip length. Canonical tile order of a k-block (after nbias bias tiles in
    k-block 0): C3 (c, tap, n), HC (c, sub, neighbour), UP / RA (c, n)."""
    ct = L.cin // 32
    if L.op == OP_RA:
        L.nbw = pow2_div(L.n)
        L.kc = next(k for k in _divs(ct) if k * L.nbw + L.nbw <= BLK_MAX)
    elif L.op == OP_UP:
        row = L.n // L.s  # tiles of one output row a (k * cout channels); n-blocks never straddle two a-rows
        nbw = pow2_div(row)
        while ct * nbw + nbw > BLK_MAX and nbw > 1:
            nbw //= 2
        L.nbw, L.kc = nbw, ct
    elif L.op == OP_HC:
        L.nbw = 4
        L.kc = next(k for k in _divs(ct) if k <= 3 and 16 * k + 4 <= BLK_MAX)
    else:
        L.nbw = pow2_div(L.n)
        if NSPLIT and L.cin >= 384:  # weight-heavy: n-blocks <= 2 tiles split over row groups (rows stream 1 / nb)
            L.nbw = max(1, min(L.nbw, 2) if L.cin >= 768 else L.nbw // 2)
        L.kc = next(k for k in _divs(ct) if k <= 3 and 9 * k * L.nbw + L.nbw <= BLK_MAX)
    L.nkb = ct // L.kc
    L.nbias = L.nbw if L.op != OP_HC else 4
    if L.res and L.nbw != L.n:
        raise ValueError(f"{L.name}: residual layers need one n-block (nbw {L.nbw}, n {L.n})")


def stage_bytes(L: Layer) -> int:
    """L1 staging (CB_RES memory) of a layer's whole-page DRAM writes: UP one output a-row of every (r, kx) of the
    unit, RA one 32-pixel output page, C3 with several n-blocks per core the unit's whole pixels, HC per tile column
    two 16 x 32 fp32 output half tiles (face pairs)"""
    if L.op == OP_UP:
        k = L.s
        return L.bh * L.bw * k * 32 * (L.n * 32 // (k * k)) * 2
    if L.op == OP_RA:
        return 32 * L.n * 64
    if L.op == OP_HC:
        return L.bw * 4096
    if L.nbi > 1:
        return L.bh * L.bw * 32 * L.n * 64
    return 0


def pair_mode(L: Layer) -> bool:
    """C3 / HC with one channel tile per k-block out of a wider row and an even number of k-blocks: the kernel
    tilizes channel tiles (kb, kb + 1) together and keeps them for both k-blocks (no wasted half of a 2-tile chunk)"""
    if os.environ.get("DEPTHPRO2_MK_DEC_PAIR", "0") != "1":  # implemented, not yet validated on the device
        return False
    return L.op in (OP_C3, OP_HC) and L.kc == 1 and L.nkb % 2 == 0 and L.s * (L.cin // 32) > 1


def block_tiles(L: Layer) -> Tuple[int, int]:
    """tiles of one k-block (without / with the k-block 0 bias tiles)"""
    if L.op == OP_C3:
        t = 9 * L.kc * L.nbw
    elif L.op == OP_HC:
        t = 16 * L.kc
    else:
        t = L.kc * L.nbw
    return t, t + L.nbias


def assign_pages(layers: Sequence[Layer]) -> int:
    """weight-arena page offsets: per layer, per n-block nb, per k-block kb a page-padded block"""
    page = 0
    for L in layers:
        t, t0 = block_tiles(L)
        L.bp, L.bp0 = cdiv(t, PAGE_TILES), cdiv(t0, PAGE_TILES)
        L.wpg = page
        page += (L.n // L.nbw) * (L.bp0 + (L.nkb - 1) * L.bp)
    return page


def block_page(L: Layer, nb: int, kb: int) -> int:
    """first arena page of block (nb, kb) of layer L"""
    return L.wpg + nb * (L.bp0 + (L.nkb - 1) * L.bp) + (0 if kb == 0 else L.bp0 + (kb - 1) * L.bp)