File size: 23,336 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
// SPDX-License-Identifier: Apache-2.0
//
// DepthPro2 DEC megakernel, BRISC (NoC 1): boot + global hub barriers, the plan table and constants, every DRAM
// read of a unit's inputs (ROW_MAJOR bands of the input / residual maps, HC selector tiles, RA tap tiles) and every
// DRAM write of its outputs (ROW_MAJOR map runs incl. depth-to-space, the float32 inverse depth tiles).
// Map storage (plan.py MapG): storage pixel of (y, x) = B0 + y * WP + x, pages of 32 storage pixels x C channels;
// pads / guard rows are zero and never written.
#include "md_dm.hpp"

using namespace mdx;

namespace {

constexpr auto acc_dram = TensorAccessorArgs<CT_ACC0>();
constexpr uint32_t OUT_BLK = 8;  // CB_OUT pages per output block (the TRISC pushes whole 8-page blocks)
#define MD_NOINL __attribute__((noinline))

Plan pl;
uint32_t me_x, me_y, role, nall, hubx, huby, ax0, ay0, ax1, ay1;
uint32_t gen_bar = 0;

FORCE_INLINE auto dram(uint32_t addr, uint32_t page_bytes) { return TensorAccessor(acc_dram, addr, page_bytes); }

MD_NOINL void wait_ge(uint32_t w, uint32_t v) {
    WAYPOINT("BWGE");
    spin_ge(w, v);
}

void boot_barrier() {
    const uint32_t sem_boot = get_semaphore(0);
    const uint32_t sem_go = get_semaphore(1);
    noc_semaphore_inc(get_noc_addr(hubx, huby, sem_boot), 1);
    at_bar();
    if (role & R_HUB) {
        volatile tt_l1_ptr uint32_t* b = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(sem_boot);
        WAYPOINT("BOOT");
        uint32_t it = 0;
        while (true) {
            invalidate_l1_cache();
            if (*b >= nall) {
                break;
            }
            if (++it > g_spin) {
                abort_note(AB_SYNC, 998);
                break;
            }
        }
        volatile tt_l1_ptr uint32_t* go = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(sem_go);
        *go = 1;
        noc_semaphore_set_multicast_loopback_src(sem_go, mcast_addr(ax0, ay0, ax1, ay1, sem_go), nall);
        wr_flush();
    }
    wait_go(sem_go);
}

// global barrier: every write of this core landed, then the hub counts arrivals and multicasts the generation
MD_NOINL void barrier() {
    ++gen_bar;
    wr_bar();
    noc_semaphore_inc(get_noc_addr(hubx, huby, sync_addr(W_BCNT)), 1);
    at_bar();
    if (role & R_HUB) {
        wait_ge(W_BCNT, gen_bar * nall);
        const uint32_t srcw = sync_addr(W_SRC);
        *reinterpret_cast<volatile tt_l1_ptr uint32_t*>(srcw) = gen_bar;
        noc_semaphore_set_multicast_loopback_src(srcw, mcast_addr(ax0, ay0, ax1, ay1, sync_addr(W_BAR)), nall);
        wr_flush();
    }
    wait_ge(W_BAR, gen_bar);
}

// ------------------------------------------------------------------ map access
// DRAM request discipline (Blackhole SYS-1419, mk_enc's never-hung pattern): every DRAM request of the map / output
// traffic is >= 2 KB. Map rows start on 32-pixel pages (plan.py MapG), so a unit's tile columns are whole pages; the
// C3 / HC band halo pixels come from 2 KB edge chunks; outputs are staged in L1 (CB_RES memory) and leave as whole
// pages (C3, UP, RA) or 2 KB fp32 face pairs (HC). Gathers into the staging area are local L1 -> L1 NoC copies.
struct MapA {
    uint32_t addr, C, wp, b0, fpix, bpx;  // bpx = bytes per storage pixel
};
FORCE_INLINE MapA map_of(uint32_t m) {
    MapA a;
    a.addr = ca(pl.mf(m, M_ARG));
    a.C = pl.mf(m, M_C);
    a.wp = pl.mf(m, M_WP);
    a.b0 = pl.mf(m, M_B0);
    a.fpix = pl.mf(m, M_FPG) * 32;
    a.bpx = a.C * 2;
    return a;
}
// storage pixel of (f, y, x) (y, x may be -1)
FORCE_INLINE uint32_t spx(const MapA& a, uint32_t f, int32_t y, int32_t x) {
    return f * a.fpix + (uint32_t)((int32_t)a.b0 + y * (int32_t)a.wp + x);
}
// one DRAM read of npx storage pixels from g (the run stays inside one 32-pixel page)
FORCE_INLINE void rd_run(const MapA& a, uint32_t g, uint32_t npx, uint32_t dst) {
    noc_async_read(dram(a.addr, 32 * a.bpx).get_noc_addr(g >> 5, (g & 31) * a.bpx), dst, npx * a.bpx);
}
// read n storage pixels from a page-aligned g (whole pages) to dst
MD_NOINL void read_px(const MapA& a, uint32_t g, uint32_t n, uint32_t dst) {
    while (n) {
        const uint32_t off = g & 31;
        const uint32_t cnt = 32 - off < n ? 32 - off : n;
        rd_run(a, g, cnt, dst);
        dst += cnt * a.bpx;
        g += cnt;
        n -= cnt;
    }
}
// one whole page (32 pixels x C) from L1 src to the page-aligned storage pixel g
FORCE_INLINE void wr_page(const MapA& a, uint32_t g, uint32_t src) {
    noc_async_write(src, dram(a.addr, 32 * a.bpx).get_noc_addr(g >> 5, 0), 32 * a.bpx);
}
FORCE_INLINE uint32_t stage_base() { return cb_base(CB_RES); }
MD_NOINL void zero_l1(uint32_t addr, uint32_t bytes) {
    volatile tt_l1_ptr uint32_t* p = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(addr);
    for (uint32_t i = 0; i < (bytes >> 2); ++i) {
        p[i] = 0;
    }
}
// local L1 -> L1 copy through the NoC (gathers into the staging area; no DRAM traffic)
FORCE_INLINE void lcopy(uint32_t src, uint32_t dst, uint32_t bytes) { noc_async_write(src, get_noc_addr(dst), bytes); }

// ------------------------------------------------------------------ units
struct Lay {
    uint32_t l, op, s, nbw, nbi, n, bh, bw, ct, kc, flags, nres, ho, wo, kxo, bandp, boff, kpx;
    uint32_t src, dst, res0, res1;
};
FORCE_INLINE void lay_of(uint32_t l, Lay& L) {
    L.l = l;
    L.op = pl.lf(l, L_OP);
    L.s = pl.lf(l, L_S);
    L.nbw = pl.lf(l, L_NBW);
    L.nbi = pl.lf(l, L_NBI);
    L.n = pl.lf(l, L_N);
    L.bh = pl.lf(l, L_BH);
    L.bw = pl.lf(l, L_BW);
    L.ct = pl.lf(l, L_CT);
    L.kc = pl.lf(l, L_KC);
    L.flags = pl.lf(l, L_FLAGS);
    L.nres = pl.lf(l, L_NRES);
    L.ho = pl.lf(l, L_HO);
    L.wo = pl.lf(l, L_WO);
    L.kxo = pl.lf(l, L_KXO);
    L.bandp = pl.lf(l, L_BANDP);
    L.boff = pl.lf(l, L_BOFF);
    L.kpx = pl.lf(l, L_KPX);
    L.src = pl.lf(l, L_SRC);
    L.dst = pl.lf(l, L_DST);
    L.res0 = pl.lf(l, L_RES0);
    L.res1 = pl.lf(l, L_RES1);
}

// C3 / HC / UP band of unit un -> CB_BAND (one page)
MD_NOINL void load_band(const Lay& L, const Unit& un) {
    const MapA a = map_of(L.src);
    cbr_back(CB_BAND, 1);
    const uint32_t dst = get_write_ptr(CB_BAND);
    if (L.op == OP_UP) {
        for (uint32_t j = 0; j < un.bh; ++j) {
            read_px(a, spx(a, un.f, un.y0 + j, 32 * un.kx0), 32 * un.bw, dst + j * L.bandp);
        }
    } else {
        // row j: [kpx - 1 slack px][x0 = s 32 kx0 - 1][s 32 bw px (whole pages)][s == 1: x0 + 32 bw + 1 .. + kpx - 1]
        const uint32_t s = L.s, kpx = L.kpx, pxb = a.bpx;
        const uint32_t rows = s * (un.bh - 1) + 3;
        const uint32_t npx = s * 32 * un.bw;
        for (uint32_t j = 0; j < rows; ++j) {
            const uint32_t d = dst + L.boff + j * L.bandp;
            const uint32_t g = spx(a, un.f, (int32_t)(s * un.y0 + j) - 1, (int32_t)(s * 32 * un.kx0));
            rd_run(a, g - kpx, kpx, d - (kpx - 1) * pxb);  // left edge chunk: ends at x0 (last pixels of a page)
            read_px(a, g, npx, d + pxb);
            if (s == 1) {
                rd_run(a, g + npx, kpx, d + (npx + 1) * pxb);  // right edge chunk: starts at x0 + 32 bw + 1
            }
        }
    }
    rd_bar();
    cb_push_back(CB_BAND, 1);
}

// residual map m: the unit's output pixels (bh rows x 32 bw pixels, row pitch 32 BW pixels) -> CB_RES (one page)
MD_NOINL void load_res(const Lay& L, const Unit& un, uint32_t m) {
    const MapA a = map_of(m);
    cbr_back(CB_RES, 1);
    const uint32_t dst = get_write_ptr(CB_RES);
    const uint32_t pitch = 32 * L.bw * a.bpx;
    for (uint32_t r = 0; r < un.bh; ++r) {
        read_px(a, spx(a, un.f, un.y0 + r, 32 * un.kx0), 32 * un.bw, dst + r * pitch);
    }
    rd_bar();
    cb_push_back(CB_RES, 1);
}

// HC bias selector tiles of the unit (row class x tile column) -> CB_SEL (r * bw + kx)
MD_NOINL void load_sel(const Lay& L, const Unit& un, uint32_t cap) {
    const auto acc = dram(ca(K_SEL), T16);
    const uint32_t kxh = pl.hdr(H_KX_HC);
    cbr_back(CB_SEL, cap);
    const uint32_t dst = get_write_ptr(CB_SEL);
    for (uint32_t r = 0; r < un.bh; ++r) {
        const uint32_t y = un.y0 + r;
        const uint32_t ycls = y == 0 ? 0 : (y == L.ho - 1 ? 2 : 1);
        for (uint32_t kx = 0; kx < un.bw; ++kx) {
            noc_async_read_page(ycls * kxh + un.kx0 + kx, acc, dst + (r * un.bw + kx) * T16);
        }
    }
    rd_bar();
    cb_push_back(CB_SEL, cap);
}

// RA: tap tiles of token tiles [m0, m0 + mt) (K tiles each) -> CB_TAPA (mi * Kt + c)
MD_NOINL void load_taps(const Lay& L, uint32_t grp, uint32_t m0, uint32_t mt, uint32_t cap) {
    const auto acc = dram(ca(K_TAP0 + L.src), T16);
    const uint32_t pt = pl.hdr(H_PT), G = pl.hdr(H_G);
    cbr_back(CB_TAPA, cap);
    const uint32_t dst = get_write_ptr(CB_TAPA);
    for (uint32_t mi = 0; mi < mt; ++mi) {
        const uint32_t m = m0 + mi;
        const uint32_t f = m / pt, p = m - f * pt;
        const uint32_t row = (grp * G + f) * pt + p;
        for (uint32_t c = 0; c < L.ct; ++c) {
            noc_async_read_page(row * L.ct + c, acc, dst + (mi * L.ct + c) * T16);
        }
    }
    rd_bar();
    cb_push_back(CB_TAPA, cap);
}

// ------------------------------------------------------------------ outputs
// C3 with one n-block (whole pixels): output block (unit row r, tile kx) = 32 rows x C (ROW_MAJOR) = one page
MD_NOINL void write_c3(const Lay& L, const Unit& un, uint32_t r, uint32_t kx, uint32_t src) {
    const MapA a = map_of(L.dst);
    const uint32_t x0 = 32 * (un.kx0 + kx);
    const uint32_t nv = L.wo - x0 < 32 ? L.wo - x0 : 32;
    if (nv < 32) {
        zero_l1(src + nv * a.bpx, (32 - nv) * a.bpx);  // the pad columns stay zero
    }
    wr_page(a, spx(a, un.f, un.y0 + r, x0), src);
}

// HC: fp32 tile (rows s = 2a + b, column i = pixel x0 + i) -> staging of tile column kx: output rows 2r + a (of the
// unit's 16), columns 2i + b (of 64) in the tile face layout of the two output tiles (2 x [16 x 16 | 16 x 16] fp32)
MD_NOINL void stage_hc(const Lay& L, const Unit& un, uint32_t r, uint32_t kx, uint32_t src, uint32_t st) {
    const uint32_t x0 = 32 * (un.kx0 + kx);
    const uint32_t nv = L.wo - x0 < 32 ? L.wo - x0 : 32;
    invalidate_l1_cache();
    const volatile tt_l1_ptr uint32_t* t = reinterpret_cast<const volatile tt_l1_ptr uint32_t*>(src);
    volatile tt_l1_ptr uint32_t* o = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(st);
    for (uint32_t a = 0; a < 2; ++a) {
        const uint32_t R = 2 * r + a;
        for (uint32_t i = 0; i < nv; ++i) {
            const uint32_t base = (i >> 4) * 256 + (i & 15);
            for (uint32_t b = 0; b < 2; ++b) {
                const uint32_t X = 2 * i + b;
                o[(X >> 5) * 512 + ((X >> 4) & 1) * 256 + R * 16 + (X & 15)] = t[base + (2 * a + b) * 16];
            }
        }
    }
}
// HC unit done (8 input rows = 16 output rows, one half tile row): 2 KB face-pair writes per output tile
MD_NOINL void write_hc(const Lay& L, const Unit& un, uint32_t grp, uint32_t st) {
    const uint32_t hp = pl.hdr(H_HP), wpx = pl.hdr(H_WP);
    const uint32_t fr = grp * pl.hdr(H_G) + un.f;
    const auto acc = dram(ca(K_OUT), T32);
    const uint32_t Y0 = 2 * un.y0;  // multiple of 16 (plan: HC units of 8 rows)
    for (uint32_t kx = 0; kx < un.bw; ++kx) {
        const uint32_t x0 = 32 * (un.kx0 + kx);
        const uint32_t nv = L.wo - x0 < 32 ? L.wo - x0 : 32;
        const uint32_t nt = (2 * nv + 31) / 32;
        for (uint32_t t = 0; t < nt; ++t) {
            const uint32_t X = 2 * x0 + 32 * t;
            const uint32_t page = (fr * (hp >> 5) + (Y0 >> 5)) * (wpx >> 5) + (X >> 5);
            noc_async_write(st + kx * 4096 + t * 2048, acc.get_noc_addr(page, ((Y0 & 31) >> 4) * 2048), 2048);
        }
    }
    wr_flush();
}

// ------------------------------------------------------------------ layer
// C3 / HC / UP inputs of unit un
MD_NOINL void load_inputs(const Lay& L, const Unit& un) {
    if (L.op == OP_UP) {
        load_band(L, un);
        return;
    }
    if (L.nres > 0) {
        load_res(L, un, L.res0);
    }
    if (L.nres > 1) {
        load_res(L, un, L.res1);
    }
    load_band(L, un);
    if (L.op == OP_HC) {
        load_sel(L, un, MD_SEL_CAP);
    }
}

// UP outputs of unit un, n-block group g. Block (nb, r, kx) = 32 input pixels x chn channels of output a-row a; per
// input pixel i its channels land contiguously at output pixel k i + b (a-row channel order (b, co)). Each (r, kx)
// stages its a-row (k * 32 output pixels x cout) and leaves as whole pages once the a-row's last n-block landed.
MD_NOINL void drain_up(const Lay& L, const Unit& un, uint32_t g) {
    const MapA a = map_of(L.dst);
    const uint32_t k = L.s, cob = a.bpx, chb = L.nbw * 64;
    const uint32_t rowb = k * cob;     // bytes of one input pixel's a-row (k output pixels x cout)
    const uint32_t segb = 32 * rowb;  // staging bytes of one (r, kx)
    const uint32_t win = pl.mf(L.src, M_W);
    const uint32_t st = stage_base();
    for (uint32_t nbi = 0; nbi < L.nbi; ++nbi) {
        const uint32_t c0b = (g * L.nbi + nbi) * chb;  // byte offset of the block in the output channel order
        const uint32_t ar = c0b / rowb, cinb = c0b - ar * rowb;
        for (uint32_t r = 0; r < un.bh; ++r) {
            for (uint32_t kx = 0; kx < un.bw; ++kx) {
                cbw_front(CB_OUT, OUT_BLK);
                const uint32_t src = get_read_ptr(CB_OUT);
                const uint32_t x0 = 32 * (un.kx0 + kx);
                const uint32_t nv = win - x0 < 32 ? win - x0 : 32;
                const uint32_t seg = st + (r * un.bw + kx) * segb;
                if (chb == rowb) {
                    lcopy(src, seg, nv * chb);
                } else {
                    for (uint32_t i = 0; i < nv; ++i) {
                        lcopy(src + i * chb, seg + i * rowb + cinb, chb);
                    }
                }
                wr_flush();
                cb_pop_front(CB_OUT, OUT_BLK);
            }
        }
        if (cinb + chb == rowb) {  // a-row ar complete for every (r, kx): whole output pages
            wr_bar();
            for (uint32_t r = 0; r < un.bh; ++r) {
                for (uint32_t kx = 0; kx < un.bw; ++kx) {
                    const uint32_t x0 = 32 * (un.kx0 + kx);
                    const uint32_t nv = win - x0 < 32 ? win - x0 : 32;
                    const uint32_t seg = st + (r * un.bw + kx) * segb;
                    if (nv < 32) {
                        zero_l1(seg + nv * rowb, (32 - nv) * rowb);
                    }
                    const uint32_t X0 = k * x0;
                    uint32_t np = (a.wp - X0) / 32;
                    if (np > k) {
                        np = k;
                    }
                    const uint32_t g0 = spx(a, un.f, k * (un.y0 + r) + ar, X0);
                    for (uint32_t p = 0; p < np; ++p) {
                        wr_page(a, g0 + 32 * p, seg + p * 32 * cob);
                    }
                }
            }
            wr_flush();
        }
    }
}

// C3 / HC outputs of unit un (n-block group g)
MD_NOINL void drain(const Lay& L, const Unit& un, uint32_t g, uint32_t grp) {
    if (L.op == OP_UP) {
        drain_up(L, un, g);
        return;
    }
    const uint32_t st = stage_base();
    if (L.op == OP_HC) {
        for (uint32_t r = 0; r < un.bh; ++r) {
            for (uint32_t kx = 0; kx < un.bw; ++kx) {
                cbw_front(CB_HO, 1);
                stage_hc(L, un, r, kx, get_read_ptr(CB_HO), st + kx * 4096);
                cb_pop_front(CB_HO, 1);
            }
        }
        write_hc(L, un, grp, st);
        return;
    }
    if (L.nbi == 1) {  // one n-block = whole pixels: each block is one page
        for (uint32_t r = 0; r < un.bh; ++r) {
            for (uint32_t kx = 0; kx < un.bw; ++kx) {
                cbw_front(CB_OUT, OUT_BLK);
                write_c3(L, un, r, kx, get_read_ptr(CB_OUT));
                wr_flush();
                cb_pop_front(CB_OUT, OUT_BLK);
            }
        }
        return;
    }
    // several n-blocks on this core (nbo == 1): gather whole pixels, then one page per (r, kx)
    const MapA a = map_of(L.dst);
    const uint32_t chb = L.nbw * 64;
    for (uint32_t nbi = 0; nbi < L.nbi; ++nbi) {
        for (uint32_t r = 0; r < un.bh; ++r) {
            for (uint32_t kx = 0; kx < un.bw; ++kx) {
                cbw_front(CB_OUT, OUT_BLK);
                const uint32_t src = get_read_ptr(CB_OUT);
                const uint32_t seg = st + (r * un.bw + kx) * 32 * a.bpx;
                for (uint32_t i = 0; i < 32; ++i) {
                    lcopy(src + i * chb, seg + i * a.bpx + nbi * chb, chb);
                }
                wr_flush();
                cb_pop_front(CB_OUT, OUT_BLK);
            }
        }
    }
    wr_bar();
    for (uint32_t r = 0; r < un.bh; ++r) {
        for (uint32_t kx = 0; kx < un.bw; ++kx) {
            const uint32_t x0 = 32 * (un.kx0 + kx);
            const uint32_t nv = L.wo - x0 < 32 ? L.wo - x0 : 32;
            const uint32_t seg = st + (r * un.bw + kx) * 32 * a.bpx;
            if (nv < 32) {
                zero_l1(seg + nv * a.bpx, (32 - nv) * a.bpx);
            }
            wr_page(a, spx(a, un.f, un.y0 + r, x0), seg);
        }
    }
    wr_flush();
}

// RA page unit u (tokens [t0, t1) of token row y, page pg): every n-block of its token tiles -> the staging page
// (pixel t - t0, channels nb * chn ...) -> one whole page
MD_NOINL void run_ra(const Lay& L, uint32_t grp, uint32_t u) {
    RaPage rp;
    ra_page(pl, L.l, u, rp);
    uint32_t m0, mt;
    ra_unit(pl, L.l, u, m0, mt);
    load_taps(L, grp, m0, mt, MD_TAPA_CAP);
    const MapA a = map_of(L.dst);
    const uint32_t chb = L.nbw * 64;
    const uint32_t st = stage_base();
    const uint32_t tb0 = (m0 - rp.f * pl.hdr(H_PT)) * 32;  // first token of tile m0 (frame-relative)
    for (uint32_t nbi = 0; nbi < L.nbi; ++nbi) {
        for (uint32_t mi = 0; mi < mt; ++mi) {
            cbw_front(CB_OUT, OUT_BLK);
            const uint32_t src = get_read_ptr(CB_OUT);
            const uint32_t tb = tb0 + 32 * mi;
            const uint32_t lo = rp.t0 > tb ? rp.t0 : tb;
            const uint32_t hi = rp.t1 < tb + 32 ? rp.t1 : tb + 32;
            if (chb == a.bpx) {
                if (hi > lo) {
                    lcopy(src + (lo - tb) * chb, st + (lo - rp.t0) * a.bpx, (hi - lo) * chb);
                }
            } else {
                for (uint32_t t = lo; t < hi; ++t) {
                    lcopy(src + (t - tb) * chb, st + (t - rp.t0) * a.bpx + nbi * chb, chb);
                }
            }
            wr_flush();
            cb_pop_front(CB_OUT, OUT_BLK);
        }
    }
    wr_bar();
    const uint32_t nv = rp.t1 - rp.t0;
    if (nv < 32) {
        zero_l1(st + nv * a.bpx, (32 - nv) * a.bpx);
    }
    wr_page(a, spx(a, rp.f, rp.y, 32 * rp.pg), st);
    wr_flush();
}

// Units are software-pipelined: unit k + 1's inputs are read before unit k's outputs are written (the TRISC frees
// the band / residual / selector CBs before it produces outputs). Not for RA (the tap tiles are freed after the
// outputs) nor two-residual layers (the second residual of unit k + 1 lands only once the TRISC started it).
MD_NOINL void run_layer(uint32_t grp, uint32_t l) {
    Lay L;
    lay_of(l, L);
    Sched s;
    sched_of(pl, l, me_x, me_y, s);
    const uint32_t U = pl.lf(l, L_U);
#ifdef MD_PIPE
    const bool pipe = L.op != OP_RA && L.nres < 2;
#else
    const bool pipe = false;  // MD_PIPE (unit pipelining): opt-in, a device hang is not yet ruled out (MK_LOG)
#endif
    bool have = false;
    Unit pu;
    uint32_t pg = 0;
    for (uint32_t gi = 0; gi < s.ng; ++gi) {
        const uint32_t g = s.g0 + gi * s.gstep;
        for (uint32_t k = 0; k < s.rounds; ++k) {
            const uint32_t u = k * s.span + s.off;
            if (u >= U) {
                continue;
            }
            if (L.op == OP_RA) {
                run_ra(L, grp, u);
                continue;
            }
            Unit un;
            unit_of(pl, l, u, un);
            load_inputs(L, un);
            if (!pipe) {
                drain(L, un, g, grp);
                continue;
            }
            if (have) {
                drain(L, pu, pg, grp);
            }
            pu = un;
            pg = g;
            have = true;
        }
    }
    if (have) {
        drain(L, pu, pg, grp);
    }
}

}  // namespace

void kernel_main() {
    me_x = rt(A_X);
    me_y = rt(A_Y);
    g_spin = ca(K_SPIN);
    g_dbg_word = W_DBG;
    role = rt(A_ROLE);
    ax0 = ca(K_ALL_X0);
    ay0 = ca(K_ALL_Y0);
    ax1 = ca(K_ALL_X1);
    ay1 = ca(K_ALL_Y1);
    nall = ca(K_N_ALL);
    hubx = ca(K_HUB_X);
    huby = ca(K_HUB_Y);
    // zero the sync words, then the boot barrier (the NCRISC waits for SEM_GO before touching them)
    for (uint32_t w = 0; w < N_SYNC; ++w) {
        *sync_ptr(w) = 0;
    }
#if MD_PROF
    for (uint32_t w = 0; w < PROF_WORDS; ++w) {
        reinterpret_cast<volatile tt_l1_ptr uint32_t*>(sync_addr(0) + SYNC_PROF)[w] = 0;
    }
#endif
    boot_barrier();
    // the plan table and the constants
    cbr_back(CB_PLAN, 1);
    {
        const uint32_t bytes = ca(K_PLANB);
        noc_async_read(dram(ca(K_PLANA), bytes).get_noc_addr(0), get_write_ptr(CB_PLAN), bytes);
        rd_bar();
    }
    cb_push_back(CB_PLAN, 1);
    invalidate_l1_cache();
    pl.t = reinterpret_cast<const uint32_t*>(cb_base(CB_PLAN));
    pl.nm = pl.t[H_NM];
    cbr_back(CB_CONST, N_CONST);
    {
        const auto acc = dram(ca(K_CONST), T16);
        for (uint32_t i = 0; i < N_CONST; ++i) {
            noc_async_read_page(i, acc, get_write_ptr(CB_CONST) + i * T16);
        }
        rd_bar();
    }
    cb_push_back(CB_CONST, N_CONST);
    uint32_t nl = ca(K_NL);
    if (nl > pl.hdr(H_NL)) {
        nl = pl.hdr(H_NL);
    }
    const uint32_t ngrp = g_abort ? 0 : pl.hdr(H_NGRP);
#if MD_PROF
    volatile tt_l1_ptr uint32_t* pfw = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(sync_addr(0) + SYNC_PROF);
    const uint32_t pf0 = get_timestamp_32b();
#endif
    for (uint32_t grp = 0; grp < ngrp; ++grp) {
        for (uint32_t l = 0; l < nl; ++l) {
            *sync_ptr(W_DBG + 8) = grp * 1000 + l;
            run_layer(grp, l);
#if MD_PROF
            if (grp == 0 && l < 32) {
                pfw[8 * l] = get_timestamp_32b() - pf0;
            }
#endif
            if (pl.lf(l, L_BAR) || l + 1 == nl) {
                barrier();
            }
#if MD_PROF
            if (grp == 0 && l < 32) {
                pfw[8 * l + 1] = get_timestamp_32b() - pf0;
            }
#endif
        }
    }
    wr_bar();
#if MD_PROF
    noc_async_write(sync_addr(0) + SYNC_PROF, dram(ca(K_PROF), PROF_WORDS * 4).get_noc_addr(rt(A_IDX)), PROF_WORDS * 4);
    wr_bar();
#endif
    // diagnostics of this core (abort codes of every RISC, last layer) -> K_DBG page idx
    {
        const uint32_t stg = sync_addr(0) + SYNC_STG;
        volatile tt_l1_ptr uint32_t* o = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(stg);
        for (uint32_t i = 0; i < DBG_WORDS; ++i) {
            o[i] = sync_read(W_DBG + i);
        }
        exit_barriers(1);
        o[11] = sync_read(W_EXIT);  // (the NCRISC's bit may land later; the BRISC's own is final here)
        noc_async_write(stg, dram(ca(K_DBG), DBG_PAGE * 4).get_noc_addr(rt(A_IDX)), DBG_PAGE * 4);  // 2 KB page
        exit_barriers(1);
    }
}