File size: 22,433 Bytes
aa204f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// SPDX-License-Identifier: Apache-2.0
//
// GLM-OCR decode megakernel (DEC), BRISC. Adapted from this workspace's Qwen3-ASR DEC (bundles/qwen3-asr
// tt/mk_dec/kernels/md_brisc.cpp, Apache-2.0), itself from the Qwen3-TTS talker megakernel: boot barrier, every
// exchange between cores, the small DRAM reads (STATE, the embedding row, constants, tables, seen bitmap) and writes
// (KV append, logits, STATE, seen bitmap).
//   boot : every active core counts in at the HUB (semaphore 0); the HUB reads STATE (p = L + ntok - 1; done when no
//          token yet / stopped / KV full), then multicasts the go word (p + 1) | done << 31 into semaphore 1.
//   MM   : x0 = embed_tokens[S_LAST] (its slice; zero for the padded columns), per layer: the post-norm gamma slices,
//          norm gathers (bf16 x slice -> CB_H of every MM core + flag W_NH[w] = gen), the q head -> every active key
//          slot of its group / the k, v rows -> the slot holding the last block, the merged attention outputs (flags
//          W_AO) -> CB_O, the y gathers (-> CB_YG, flags W_YG), the SwiGLU gathers (-> CB_F, flags W_F); final: the
//          logits slice -> DRAM page w, the repetition penalty on the seen ids, the local candidate list -> HUB.
//   ATT  : q heads -> CB_Q; the slot's K / V blocks landed by the NCRISC -> CB_KR / CB_VR (the last block patched with
//          the new k / v row and written back); slots s > 0 send their partial (O, mz, lz: 1 KB each) to slot 0's
//          CB_MRG + flag W_MG + s; slot 0 pushes CB_MRG and sends the merged o to every MM core's CB_O + flag.
//   HUB  : merge of the 32 lists, selection (greedy / Philox(seed, ntok) sampling), STATE: circular token ring,
//          last token, ntok + 1, EOS / max-token / KV stop; the seen bitmap (penalty on): + the new token.
// Every gather is single-buffered; the WAR argument is the dataflow (md_trisc.cpp).
#include "md_dm.hpp"
#define MKS_MAX_LISTS 32
#include "sampler.hpp"

using namespace mtx;

namespace {

constexpr auto acc = TensorAccessorArgs<CT_ACC0>();
constexpr uint32_t DT = MT_DT, IT = MT_IT, XS = MT_XS, FS = MT_FS, NHD = MT_NHD, D = MT_D;
constexpr uint32_t CAP_MRG = MT_CAP_MRG;
constexpr uint32_t FS_CAP = MT_FS_CAP;
#define NOINL __attribute__((noinline))

struct Me {
    uint32_t idx, role, w, hk, slot, attx, atty;
    uint32_t ax0, ay0, ax1, ay1, nall, nact, hubx, huby, nl, flags;
    uint32_t p, nb, done, nohead;
    uint32_t attk, nbl, sact;  // key slots, blocks per slot, active slots
};
Me me;
// NoC (x, y) of ATT core (group g, key slot s)
FORCE_INLINE void att_xy(uint32_t g, uint32_t s, uint32_t& x, uint32_t& y) {
    const uint32_t xy = ca(K_ATT0 + g * me.attk + s);
    x = xy >> 16;
    y = xy & 0xFFFF;
}

FORCE_INLINE auto dram(uint32_t addr, uint32_t page) { return TensorAccessor(acc, addr, page); }
// time stamps of layer 1 (and the step) at SYNC_PROF word i (always on; a few stores per step)
FORCE_INLINE void tstamp(uint32_t l, uint32_t i) {
    if (l == 1) {
        reinterpret_cast<volatile tt_l1_ptr uint32_t*>(cb_base(CB_SYNC) + SYNC_PROF)[i] = get_timestamp_32b();
    }
}
FORCE_INLINE uint32_t stg(uint32_t k) { return cb_base(CB_SYNC) + SYNC_STG + k * 16; }  // 16 B flag sources

// all-gather send: [src, src + bytes) -> dst on every MM core (incl. this one), then flag word w = v there.
// Unicast loop, data first then the flag per destination (same NoC, same command buffer: in order). No multicast:
// 32 concurrent multicasts to overlapping 2D rectangles hung the NoC (hang #2, 2026-11-30); unicasts cannot.
NOINL void mcast_flag(uint32_t src, uint32_t dst, uint32_t bytes, uint32_t flag_word, uint32_t v, uint32_t k) {
    const uint32_t srcw = stg(k);
    *reinterpret_cast<volatile tt_l1_ptr uint32_t*>(srcw) = v;
    const uint32_t fa = sync_addr(flag_word);
    for (uint32_t i = 0; i < NW; ++i) {
        const uint32_t xy = ca(K_MM0 + i);
        const uint32_t x = xy >> 16, y = xy & 0xFFFF;
        noc_async_write(src, uni_addr(x, y, dst), bytes);
        noc_async_write(srcw, uni_addr(x, y, fa), 4);
    }
    wr_flush();
}
// unicast [src, src + bytes) to dst on (x, y), then flag word w = v there (same NoC, same command buffer: in order)
NOINL void uni_flag(uint32_t x, uint32_t y, uint32_t src, uint32_t dst, uint32_t bytes, uint32_t flag_word,
                    uint32_t v, uint32_t k) {
    const uint32_t srcw = stg(k);
    *reinterpret_cast<volatile tt_l1_ptr uint32_t*>(srcw) = v;
    noc_async_write(src, uni_addr(x, y, dst), bytes);
    noc_async_write(srcw, uni_addr(x, y, sync_addr(flag_word)), 4);
    wr_flush();
}

// ------------------------------------------------------------------ boot
void boot() {
    const uint32_t sem_boot = get_semaphore(0);
    const uint32_t sem_go = get_semaphore(1);
    if (me.role == R_HUB) {
        // STATE -> staging (ring A memory of the hub, past the H gather; CB_F / CB_E receive the f multicasts)
        const uint32_t s = cb_base(CB_HG) + 16384;
        noc_async_read_page(0, dram(ca(K_STATE), 8192), s);
        rd_bar();
        volatile tt_l1_ptr uint32_t* st = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(s);
        const uint32_t L = st[S_L], ntok = st[S_NTOK];
        uint32_t done = st[S_DONE], nohead = 0;
        uint32_t p = L + ntok - 1;
        if (ntok == 0) {
            done = 1;  // the prefill has not produced token 0
        }
        if (p >= ca(K_MAXP) || (me.flags & F_BOOTONLY)) {
            done = 1;
        }
        if (done) {
            p = 0;
        }
        spin_l1_ge(sem_boot, me.nact - 1);
        const uint32_t go = (p + 1) | (nohead ? GO_NOHEAD : 0u) | (done ? GO_DONE : 0u);
        *reinterpret_cast<volatile tt_l1_ptr uint32_t*>(sem_go) = go;
        noc_semaphore_set_multicast_loopback_src(sem_go, mcast_addr(me.ax0, me.ay0, me.ax1, me.ay1, sem_go), me.nall);
        wr_flush();
    } else {
        noc_semaphore_inc(uni_addr(me.hubx, me.huby, sem_boot), 1);
        at_bar();
    }
    const uint32_t g = spin_l1_ge(sem_go, 1);
    me.done = (g == 0) || (g & GO_DONE);
    me.nohead = (g & GO_NOHEAD) != 0;
    me.p = (g & GO_P) - 1;
    me.nb = me.p / 32 + 1;
}

// ------------------------------------------------------------------ MM
NOINL void norm_gather(uint32_t gen) {
    cbw_front(CB_XB, 1);
    mcast_flag(get_read_ptr(CB_XB), cb_base(CB_H) + me.w * XS * TINY16, XS * TINY16, W_NH + me.w, gen, 0);
    cb_pop_front(CB_XB, 1);
    spin_all(W_NH, NW, gen);
    cbr_back(CB_H, DT);
    cb_push_back(CB_H, DT);
    cbr_back(CB_HD, NHD);
    cb_push_back(CB_HD, NHD);
}

NOINL void send_head(uint32_t l) {
    cbw_front(CB_QO, 1);
    const uint32_t src = get_read_ptr(CB_QO);
    const uint32_t g = rt(A_ATT2_X);  // kv group of this head
    uint32_t x, y;
    if (me.hk == HK_Q) {  // every active key slot needs both q heads of the group
        for (uint32_t s = 0; s < me.sact; ++s) {
            att_xy(g, s, x, y);
            uni_flag(x, y, src, cb_base(CB_Q) + me.slot * HD_T * TINY16, HD_T * TINY16, W_Q + me.slot, l + 1, 1);
        }
    } else {  // the new k / v row -> the slot holding the last block
        att_xy(g, me.sact - 1, x, y);
        if (me.hk == HK_K) {
            uni_flag(x, y, src, cb_base(CB_KVN), HD_T * TINY16, W_K, l + 1, 1);
        } else {
            uni_flag(x, y, src, cb_base(CB_KVN) + 256, HD_T * TINY16, W_V, l + 1, 1);
        }
    }
    cb_pop_front(CB_QO, 1);
}

// y gather (sandwich norms): bf16 y slice (CB_XB) -> CB_YG of every MM core + flag W_YG[w] = gen
NOINL void y_gather(uint32_t gen) {
    cbw_front(CB_XB, 1);
    mcast_flag(get_read_ptr(CB_XB), cb_base(CB_YG) + me.w * XS * TINY16, XS * TINY16, W_YG + me.w, gen, 3);
    cb_pop_front(CB_XB, 1);
    spin_all(W_YG, NW, gen);
    cbr_back(CB_YG, DT);
    cb_push_back(CB_YG, DT);
    cbr_back(CB_YGD, NHD);
    cb_push_back(CB_YGD, NHD);
}

NOINL void read_pages(uint32_t cb, uint32_t addr, uint32_t page_bytes, uint32_t page0, uint32_t n) {
    cbr_back(cb, n);
    const uint32_t a = get_write_ptr(cb);
    const auto s = dram(addr, page_bytes);
    for (uint32_t i = 0; i < n; ++i) {
        noc_async_read_page(page0 + i, s, a + i * page_bytes);
    }
    rd_bar();
    cb_push_back(cb, n);
}

void mm_main() {
    // zero the dense tails (reductions read them) and the residual tile
    l1_fill(cb_base(CB_ACC) + 512, (T32 - 512) / 4, 0);
    l1_fill(cb_base(CB_ACS) + 512, (T32 - 512) / 4, 0);
    read_pages(CB_CONST, ca(K_CONST), T16, 0, N_CONST);
    // STATE (sampler words, last token) -> SYNC_SMP; x0 slice <- embed_tokens[S_LAST] (bf16 row, D * 2 B page)
    {
        const uint32_t s = cb_base(CB_E);
        noc_async_read_page(0, dram(ca(K_STATE), 8192), s);
        rd_bar();
        volatile tt_l1_ptr uint32_t* st = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(s);
        volatile tt_l1_ptr uint32_t* sm = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(cb_base(CB_SYNC) + SYNC_SMP);
        for (uint32_t i = 0; i < 18; ++i) {
            sm[i] = st[i];
        }
        sm[18] = st[S_NTOK];
        const uint32_t tok = st[S_LAST];
        const uint32_t e = s + 8192;
        noc_async_read_page(tok, dram(ca(K_EMBED), D * 2), e);
        rd_bar();
        cbr_back(CB_X0, 1);
        const uint32_t x0 = get_write_ptr(CB_X0);
        l1_fill(x0, T32 / 4, 0);
        if (me.w * XS * 32 < D) {  // cores 24..31 own the zero-padded columns
            volatile tt_l1_ptr uint16_t* src = reinterpret_cast<volatile tt_l1_ptr uint16_t*>(e) + me.w * XS * 32;
            volatile tt_l1_ptr uint32_t* dst = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(x0);
            for (uint32_t i = 0; i < XS * 32; ++i) {
                dst[i] = ((uint32_t)src[i]) << 16;  // bf16 -> fp32 (exact)
            }
        }
        cb_push_back(CB_X0, 1);
    }
    const bool qk = me.hk != HK_V;
    if (qk) {  // rope rows of position p + delta (M-RoPE); the q table carries 128^-0.5
        volatile tt_l1_ptr uint32_t* sm = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(cb_base(CB_SYNC) + SYNC_SMP);
        const uint32_t rp = me.p + sm[S_DELTA];  // uint32 wrap = signed add
        read_pages(CB_TAB, ca(me.hk == HK_Q ? K_ROPEQ : K_ROPE), T32, 2 * rp, 2);
    }
    const uint32_t nl = me.nl;
    for (uint32_t l = 0; l < nl; ++l) {
        {  // post-norm gamma slices of layer l (psa, pm): pages (l * 2 + k) * NW + w
            cbr_back(CB_G, 2);
            const uint32_t a = get_write_ptr(CB_G);
            const auto sg = dram(ca(K_GAM), T32);
            noc_async_read_page((l * 2 + 0) * NW + me.w, sg, a);
            noc_async_read_page((l * 2 + 1) * NW + me.w, sg, a + T32);
            rd_bar();
            cb_push_back(CB_G, 2);
        }
        tstamp(l, 0);
        norm_gather(4 * l + 1);
        tstamp(l, 1);
        if (ca(K_STOP) == 1) {
            return;
        }
        send_head(l);
        tstamp(l, 2);
        spin_all(W_AO, NG, l + 1);
        tstamp(l, 3);
        cbr_back(CB_O, AT);
        cb_push_back(CB_O, AT);
        if (ca(K_STOP) == 2) {
            return;
        }
        y_gather(2 * l + 1);
        norm_gather(4 * l + 2);
        tstamp(l, 4);
        // SwiGLU gather
        cbw_front(CB_FS, FS_CAP);
        mcast_flag(get_read_ptr(CB_FS), cb_base(CB_F) + me.w * FS * TINY16, FS * TINY16, W_F + me.w, l + 1, 2);
        cb_pop_front(CB_FS, FS_CAP);
        spin_all(W_F, NW, l + 1);
        tstamp(l, 5);
        cbr_back(CB_F, IT);
        cb_push_back(CB_F, IT);
        y_gather(2 * l + 2);
    }
    tstamp(1, 8);
    const bool dump = me.flags & F_DUMP;
    const bool full = nl == N_LAYERS_FULL && !dump && !me.nohead;
    norm_gather(4 * nl + 1);
    if (dump) {  // debug: the raw residual slice -> the logits page w (no head)
        cbw_front(CB_HS, 1);
        noc_async_write_page(me.w, dram(ca(K_LOGITS), MT_HC * TINY32), get_read_ptr(CB_HS));
        wr_flush();
        cb_pop_front(CB_HS, 1);
    }
    if (full) {
        cbw_front(CB_LS, MT_HC);
        const uint32_t lg = get_read_ptr(CB_LS);
        // the raw logits of this core's columns (the logits output, host tests / host sampling) ...
        noc_async_write_page(me.w, dram(ca(K_LOGITS), MT_HC * TINY32), lg);
        if (!(me.flags & F_NOSAMPLE)) {
            // ... and the local candidate list of ids w * HC * 32 .. (valid vocabulary only)
            volatile tt_l1_ptr uint32_t* sm = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(cb_base(CB_SYNC) + SYNC_SMP);
            volatile tt_l1_ptr uint32_t* bits = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(lg);
            const uint32_t id0 = me.w * MT_HC * 32;
            const uint32_t nv = sm[S_NVOCAB];
            const uint32_t n = id0 >= nv ? 0u : (nv - id0 < MT_HC * 32 ? nv - id0 : MT_HC * 32);
            const uint32_t cap = sm[S_DOSAMPLE] ? (ca(K_KMAX) > 64 ? 64 : ca(K_KMAX)) : 1u;
            const uint32_t lst = cb_base(CB_SYNC) + SYNC_LIST;
            mks::Entry* ent = reinterpret_cast<mks::Entry*>(lst + 16);
            const uint32_t pen = sm[S_PEN];
            if (pen != mks::F32_ONE && pen != 0) {  // repetition penalty on the seen ids of this slice (HF order)
                const uint32_t sb = cb_base(CB_G);  // free after the last post-norm (the TRISC popped CB_G)
                wr_flush();  // the raw logits page left L1 before the in-place penalty
                noc_async_read_page(0, dram(ca(K_SEEN), 8192), sb);
                rd_bar();
                mks::glm_penalty(bits, n, id0, reinterpret_cast<volatile tt_l1_ptr uint32_t*>(sb), pen);
            }
            const uint32_t cnt = mks::local_sorted(bits, n, id0, ent, cap);
            *reinterpret_cast<volatile tt_l1_ptr uint32_t*>(lst) = cnt;
            noc_async_write(lst, uni_addr(me.hubx, me.huby, cb_base(CB_LG) + LIST0 + me.w * LIST_B), 16 + 8 * cnt);
        }
        const uint32_t srcw = stg(4);
        *reinterpret_cast<volatile tt_l1_ptr uint32_t*>(srcw) = 1;
        noc_async_write(srcw, uni_addr(me.hubx, me.huby, sync_addr(W_LS + me.w)), 4);
        wr_flush();
        cb_pop_front(CB_LS, MT_HC);
    }
}

// ------------------------------------------------------------------ ATT
// row r of a 32-position block (4 bf16 tiles of 32 positions x 32 dims) <- the 128 bf16 values at src
FORCE_INLINE void patch_row(uint32_t blk, uint32_t src, uint32_t r) {
    for (uint32_t d = 0; d < HD_T; ++d) {
        for (uint32_t c2 = 0; c2 < 2; ++c2) {
            const uint32_t face = (r / 16) * 2 + c2;
            const uint32_t dst = blk + d * T16 + (face * 256 + (r % 16) * 16) * 2;
            l1_copy(src + (32 * d + 16 * c2) * 2, dst, 8);
        }
    }
}

void att_main() {
    if (ca(K_STOP) == 1) {
        return;
    }
    const uint32_t g = me.w, s = me.slot;
    const uint32_t nb = me.nb, r = me.p % 32;
    const uint32_t NB = ca(K_NB);
    read_pages(CB_CONST, ca(K_CONST), T16, 0, N_CONST);
    read_pages(CB_MSK, ca(K_MASK), T16, r, 1);
    const uint32_t j0 = s * me.nbl;
    if (j0 >= nb) {
        return;  // inactive key slot: no q, no blocks, no partial
    }
    const uint32_t my = (j0 + me.nbl < nb ? j0 + me.nbl : nb) - j0;
    const bool last = j0 + my == nb;
    const uint32_t jb = my - 1;  // local index of the global last block (when last)
    const uint32_t kbase = cb_base(CB_KR), vbase = cb_base(CB_VR);
    const uint32_t rb = MT_KV_RING_BLOCKS;
    const auto kv = dram(ca(K_KV), T16);
    uint32_t kt = 0, vt = 0;
    uint32_t x0 = 0, y0 = 0;
    att_xy(g, 0, x0, y0);
    for (uint32_t l = 0; l < me.nl; ++l) {
        tstamp(l, 10);
        spin_ge(W_Q, l + 1);
        spin_ge(W_Q + 1, l + 1);
        tstamp(l, 11);
        cbr_back(CB_Q, 2 * HD_T);  // full-capacity cycle: the q heads land at the CB base (fixed layout)
        cb_push_back(CB_Q, 2 * HD_T);
        for (uint32_t j = 0; j < my; ++j, ++kt) {
            spin_ge(W_KL, kt + 1);
            if (last && j == jb) {
                const uint32_t blk = kbase + (kt % rb) * KV_PAGE;
                spin_ge(W_K, l + 1);
                patch_row(blk, cb_base(CB_KVN), r);
                for (uint32_t d = 0; d < HD_T; ++d) {
                    noc_async_write_page((((l * 2 + 0) * NG + g) * NB + (nb - 1)) * HD_T + d, kv, blk + d * T16);
                }
                wr_flush();
            }
            cbr_back(CB_KR, HD_T);
            cb_push_back(CB_KR, HD_T);
        }
        for (uint32_t j = 0; j < my; ++j, ++vt) {
            spin_ge(W_VL, vt + 1);
            if (last && j == jb) {
                const uint32_t blk = vbase + (vt % rb) * KV_PAGE;
                spin_ge(W_V, l + 1);
                patch_row(blk, cb_base(CB_KVN) + 256, r);
                for (uint32_t d = 0; d < HD_T; ++d) {
                    noc_async_write_page((((l * 2 + 1) * NG + g) * NB + (nb - 1)) * HD_T + d, kv, blk + d * T16);
                }
                wr_flush();
            }
            cbr_back(CB_VR, HD_T);
            cb_push_back(CB_VR, HD_T);
        }
        tstamp(l, 12);
        if (s != 0) {  // the partial (O, mz, lz: the first 256 fp32 values of each) -> slot 0's CB_MRG + flag
            const uint32_t dst = cb_base(CB_MRG) + 3 * (s - 1) * T32;
            cbw_front(CB_PRO, 1);
            cbw_front(CB_PRM, 1);
            cbw_front(CB_PRL, 1);
            noc_async_write(get_read_ptr(CB_PRO), uni_addr(x0, y0, dst), 1024);
            noc_async_write(get_read_ptr(CB_PRM), uni_addr(x0, y0, dst + T32), 1024);
            uni_flag(x0, y0, get_read_ptr(CB_PRL), dst + 2 * T32, 1024, W_MG + s, l + 1, 6);
            cb_pop_front(CB_PRO, 1);
            cb_pop_front(CB_PRM, 1);
            cb_pop_front(CB_PRL, 1);
        } else {
            if (me.sact > 1) {
                for (uint32_t k = 1; k < me.sact; ++k) {
                    spin_ge(W_MG + k, l + 1);
                }
                cbr_back(CB_MRG, CAP_MRG);  // full-capacity cycle: the partials land at the CB base
                cb_push_back(CB_MRG, CAP_MRG);
            }
            cbw_front(CB_QO, 1);
            tstamp(l, 13);
            mcast_flag(get_read_ptr(CB_QO), cb_base(CB_O) + g * 2 * HD_T * TINY16, 2 * HD_T * TINY16, W_AO + g, l + 1,
                       5);
            tstamp(l, 14);
            cb_pop_front(CB_QO, 1);
        }
        if (ca(K_STOP) == 2) {
            return;
        }
    }
}

// ------------------------------------------------------------------ HUB
void hub_main() {
    if (ca(K_STOP)) {
        return;
    }
    const bool dump = me.flags & F_DUMP;
    const bool full = me.nl == N_LAYERS_FULL && !dump && !me.nohead;
    if (!full) {
        wr_bar();
        return;
    }
    spin_all(W_LS, NW, 1);
    const uint32_t s = cb_base(CB_HG) + 16384;  // STATE staged at boot
    volatile tt_l1_ptr uint32_t* st = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(s);
    const uint32_t ntok = st[S_NTOK];
    if (!(me.flags & F_NOSAMPLE)) {
        const mks::Entry* lists[NW];
        uint32_t counts[NW];
        for (uint32_t w = 0; w < NW; ++w) {
            const uint32_t a = cb_base(CB_LG) + LIST0 + w * LIST_B;
            counts[w] = *reinterpret_cast<volatile tt_l1_ptr uint32_t*>(a);
            lists[w] = reinterpret_cast<const mks::Entry*>(a + 16);
        }
        mks::Merger mg;
        mg.init(lists, counts, NW);
        mks::Entry best[64];
        uint32_t wts[64];
        const uint32_t kmax = st[S_DOSAMPLE] ? (ca(K_KMAX) > 64 ? 64 : ca(K_KMAX)) : 1u;
        const uint32_t cnt = mks::merge_take(mg, best, kmax);
        mks::Params pr{st[S_DOSAMPLE], st[S_INVT], st[S_TOPK], st[S_TOPP]};
        const uint32_t u = mks::philox_u24(st[S_SEED_LO], st[S_SEED_HI], ntok, 0);
        uint32_t t = mks::select_topk(best, cnt, pr, u, kmax, wts, nullptr);
        if (t == mks::INVALID) {
            t = st[S_EOS1];
        }
        st[S_TOKENS + ntok % S_TOKENS_MAX] = t;
        if (st[S_PEN] != mks::F32_ONE && st[S_PEN] != 0) {  // the seen bitmap += t (RMW of its 8 KB page)
            const uint32_t sb = cb_base(CB_HG) + 32768;
            noc_async_read_page(0, dram(ca(K_SEEN), 8192), sb);
            rd_bar();
            reinterpret_cast<volatile tt_l1_ptr uint32_t*>(sb)[t >> 5] |= 1u << (t & 31);
            noc_async_write_page(0, dram(ca(K_SEEN), 8192), sb);
            wr_flush();
        }
        st[S_LAST] = t;
        const uint32_t n1 = ntok + 1;
        st[S_NTOK] = n1;
        if (t == st[S_EOS0] || t == st[S_EOS1]) {
            st[S_DONE] = 1;
            st[S_STOP] = 1;
        } else if (n1 >= st[S_MAXNEW]) {
            st[S_DONE] = 1;
            st[S_STOP] = 2;
        } else if (st[S_L] + n1 - 1 >= ca(K_MAXP)) {
            st[S_DONE] = 1;
            st[S_STOP] = 3;
        }
    } else {
        st[S_NTOK] = ntok + 1;  // logits only: the host samples and rewrites S_LAST / the ring
    }
    noc_async_write_page(0, dram(ca(K_STATE), 8192), s);
    wr_bar();
}

}  // namespace

void kernel_main() {
    me.idx = rt(A_IDX);
    me.role = rt(A_ROLE);
    if (me.role == R_IDLE) {
        return;
    }
    me.w = rt(A_W);
    me.hk = rt(A_HK);
    me.slot = rt(A_SLOT);
    me.attx = rt(A_ATT_X);
    me.atty = rt(A_ATT_Y);
    me.ax0 = ca(K_ALL_X0);
    me.ay0 = ca(K_ALL_Y0);
    me.ax1 = ca(K_ALL_X1);
    me.ay1 = ca(K_ALL_Y1);
    me.nall = ca(K_N_ALL);
    me.nact = ca(K_N_ACT);
    me.hubx = ca(K_HUB_X);
    me.huby = ca(K_HUB_Y);
    me.nl = ca(K_NL);
    me.flags = ca(K_FLAGS);
    g_spin = ca(K_SPIN);
    g_dbg_word = W_DBG;
    for (uint32_t w = 0; w < N_SYNC; ++w) {
        *sync_ptr(w) = 0;
    }
    boot();
    me.attk = ca(K_ATTK);
    me.nbl = (me.nb + me.attk - 1) / me.attk;
    me.sact = (me.nb + me.nbl - 1) / me.nbl;
    if (me.role == R_MM || me.role == R_ATT) {  // the go word -> the TRISC
        const uint32_t gw = me.done ? GO_DONE : ((me.p + 1) | (me.nohead ? GO_NOHEAD : 0u));
        cbr_back(CB_GO, 1);
        *reinterpret_cast<volatile tt_l1_ptr uint32_t*>(get_write_ptr(CB_GO)) = gw;
        cb_push_back(CB_GO, 1);
    }
    if (!me.done && !g_abort && !(me.flags & F_ARM_STREAM)) {
        if (me.role == R_MM) {
            mm_main();
        } else if (me.role == R_ATT) {
            att_main();
        } else {
            hub_main();
        }
    }
    // diagnostics: the first 4 KB of the sync area (every sync word) -> debug page idx
    {
        *sync_ptr(W_DBG + 8) = me.p;
        *sync_ptr(W_DBG + 9) = me.done;
        noc_async_write_page(me.idx, dram(ca(K_DBG), SYNC_BYTES), cb_base(CB_SYNC));
    }
    exit_barriers(1);
}