File size: 27,000 Bytes
ca1a504
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// SPDX-License-Identifier: Apache-2.0
//
// DeepSeek-OCR family DEC-MoE megakernel, BRISC. Adapted from this workspace's GLM-OCR DEC (bundles/glm-ocr
// tt/mk_dec/kernels/md_brisc.cpp, Apache-2.0), itself from the Qwen3-ASR DEC / 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 and multicasts the go word.
//   MM    : x0 = embed_tokens[S_LAST] (its owned tiles), per layer: norm gathers (bf16 x slice -> CB_H of every MM core
//           (+ the 2 routers before an MoE MLP) + 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 attention outputs (flags W_AO) -> CB_O, the
//           routing record (W_RT) -> CB_RW (the 6 weights for the TRISC), the SwiGLU gathers (-> CB_F, flags W_F);
//           final: the logits slice -> DRAM page w, the n-gram bans / repetition penalty, the local candidate list.
//   ATT   : q head -> CB_Q; 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 to slot 0; slot 0 sends o to every MM core.
//   ROUTER: per MoE layer the norm gather -> CB_H; router 1 sends its 32 logits to router 0; router 0 assembles the 64
//           logits (CB_RSM), takes the TRISC's softmax (CB_RPR), selects the top 6 (fp32 keys, lower id on ties) and
//           unicasts the record (6 ids, 6 fp32 weights) + flag W_RT = layer to every MM core.
//   HUB   : merge of the 32 lists, selection, STATE: circular token ring, last token, ntok + 1, stop rules.
#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 CAP_MRG = MT_CAP_MRG;
constexpr uint32_t NHD = 2;  // dense bf16 tiles of the D-vector view (1280 values + zero tail)
constexpr uint32_t CAP_FS = 512 / TINY16;  // CB_FS pages (full-capacity cycles, as the TRISC)
// fixed-layout gather views cycle at their FULL capacity so the read pointer is always the CB base (the gathers
// write fixed offsets): CB_H / CB_O hold 64 tiny tiles (4 KB, shared with the 2-tile dense view) of which 40 are used
constexpr uint32_t CAP_H = T32 / TINY16;
constexpr uint32_t CAP_O = T32 / TINY16;
constexpr uint32_t CAP_RL = 512 / TINY32;  // CB_RL pages
#define NOINL __attribute__((noinline))

struct Me {
    uint32_t idx, role, w, hk, slot, grp, xoff, xn;
    uint32_t ax0, ay0, ax1, ay1, nall, nact, hubx, huby, nl, flags;
    uint32_t p, nb, done, nohead;
    uint32_t attk, nbl, sact;
};
Me me;
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); }
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; }

// all-gather send: [src, src + bytes) -> dst on every MM core (incl. this one) (+ the routers), then flag word
// w = v there. Unicast loop, data first then the flag per destination (same NoC, same command buffer: in order).
NOINL void gather_send(uint32_t src, uint32_t dst, uint32_t bytes, uint32_t flag_word, uint32_t v, uint32_t k,
                       bool routers) {
    const uint32_t srcw = stg(k);
    *reinterpret_cast<volatile tt_l1_ptr uint32_t*>(srcw) = v;
    const uint32_t fa = sync_addr(flag_word);
    const uint32_t nd = NW + (routers ? 2u : 0u);
    for (uint32_t i = 0; i < nd; ++i) {
        const uint32_t xy = i < NW ? ca(K_MM0 + i) : ca(i == NW ? K_RT0 : K_RT1);
        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();
}
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) {
        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;
        }
        if (p >= ca(K_MAXP) || (me.flags & F_BOOTONLY)) {
            done = 1;
        }
        if (done && !st[S_DONE] && !(me.flags & F_BOOTONLY)) {
            // decided at boot (KV capacity reached / nothing to do): record it, or the host would relaunch forever
            st[S_DONE] = 1;
            st[S_STOP] = 3;
            noc_async_write_page(0, dram(ca(K_STATE), 8192), s);
            wr_flush();
        }
        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;
}

// the gathered D-vector: its dense view reads 2 x 2048 B; bytes beyond the 40 tiny tiles must be zero
FORCE_INLINE void zero_h_tail() { l1_fill(cb_base(CB_H) + DT * TINY16, (NHD * T16 - DT * TINY16) / 4, 0); }
NOINL void land_h(uint32_t gen) {
    spin_all(W_NH, NW, gen);
    cbr_back(CB_H, CAP_H);
    cb_push_back(CB_H, CAP_H);
    cbr_back(CB_HD, NHD);
    cb_push_back(CB_HD, NHD);
}

// ------------------------------------------------------------------ MM
NOINL void norm_gather(uint32_t gen, bool routers) {
    cbw_front(CB_XB, 1);
    gather_send(get_read_ptr(CB_XB), cb_base(CB_H) + me.xoff * TINY16, me.xn * TINY16, W_NH + me.w, gen, 0, routers);
    cb_pop_front(CB_XB, 1);
    land_h(gen);
}

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 = me.grp;
    uint32_t x, y;
    if (me.hk == HK_Q) {  // every active key slot needs the q head
        for (uint32_t s = 0; s < me.sact; ++s) {
            att_xy(g, s, x, y);
            uni_flag(x, y, src, cb_base(CB_Q), HD_T * TINY16, W_Q, 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);
}

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);
}

// the routing record of MoE layer l -> CB_RW (6 fp32 weight words for the TRISC)
NOINL void land_route(uint32_t l) {
    spin_ge(W_RT, l);
    cbr_back(CB_RW, 1);
    volatile tt_l1_ptr uint32_t* r =
        reinterpret_cast<volatile tt_l1_ptr uint32_t*>(cb_base(CB_SYNC) + SYNC_ROUTE + (l & 1) * 64);
    volatile tt_l1_ptr uint32_t* d = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(get_write_ptr(CB_RW));
    for (uint32_t k = 0; k < NSLOT; ++k) {
        d[k] = r[8 + k];
    }
    cb_push_back(CB_RW, 1);
}

void mm_main() {
    l1_fill(cb_base(CB_ACC) + 512, (T32 - 512) / 4, 0);
    l1_fill(cb_base(CB_ACS) + 512, (T32 - 512) / 4, 0);
    zero_h_tail();
    read_pages(CB_CONST, ca(K_CONST), T16, 0, N_CONST);
    {
        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 < SMP_WORDS; ++i) {
            sm[i] = st[i];
        }
        sm[SMP_WORDS] = st[S_NTOK];
        // a token id outside the vocabulary (garbage after a numerical failure) must not address a DRAM page
        // beyond the embedding table: clamp it (the output is wrong either way, the launch still completes)
        const uint32_t tok = st[S_LAST] < st[S_NVOCAB] ? st[S_LAST] : 0u;
        const uint32_t e = s + 8192;
        noc_async_read_page(tok, dram(ca(K_EMBED), D_MODEL * 2), e);
        rd_bar();
        cbr_back(CB_X0, 1);
        const uint32_t x0 = get_write_ptr(CB_X0);
        l1_fill(x0, T32 / 4, 0);
        volatile tt_l1_ptr uint16_t* src = reinterpret_cast<volatile tt_l1_ptr uint16_t*>(e) + me.xoff * 32;
        volatile tt_l1_ptr uint32_t* dst = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(x0);
        for (uint32_t i = 0; i < me.xn * 32; ++i) {
            dst[i] = ((uint32_t)src[i]) << 16;  // bf16 -> fp32 (exact)
        }
        cb_push_back(CB_X0, 1);
    }
    if (me.hk == HK_Q || me.hk == HK_K) {  // rope rows of position p + delta; 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];
        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) {
        tstamp(l, 0);
        norm_gather(2 * l + 1, false);
        tstamp(l, 1);
        if (ca(K_STOP) == 1) {
            return;
        }
        if (me.hk != HK_NONE) {
            send_head(l);
        }
        tstamp(l, 2);
        spin_all(W_AO, NG, l + 1);
        tstamp(l, 3);
        cbr_back(CB_O, CAP_O);
        cb_push_back(CB_O, CAP_O);
        if (ca(K_STOP) == 2) {
            return;
        }
        norm_gather(2 * l + 2, l >= 1);
        tstamp(l, 4);
        if (l >= 1) {
            land_route(l);
            tstamp(l, 5);
        }
        // SwiGLU gather (7 tiles of every core; CB_FS cycles at its full capacity CAP_FS)
        cbw_front(CB_FS, CAP_FS);
        gather_send(get_read_ptr(CB_FS), cb_base(CB_F) + me.w * FS * TINY16, FS * TINY16, W_F + me.w, l + 1, 2,
                    false);
        cb_pop_front(CB_FS, CAP_FS);
        spin_all(W_F, NW, l + 1);
        tstamp(l, 6);
        cbr_back(CB_F, IT);
        cb_push_back(CB_F, IT);
    }
    tstamp(1, 8);
    const bool dump = me.flags & F_DUMP;
    const bool full = nl == N_LAYERS_FULL && !dump && !me.nohead;
    norm_gather(2 * nl + 1, false);
    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);
        noc_async_write_page(me.w, dram(ca(K_LOGITS), MT_HC * TINY32), lg);
        if (!(me.flags & F_NOSAMPLE)) {
            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);
            wr_flush();  // the raw logits page left L1 before the in-place edits
            const uint32_t nban = sm[S_BAN_N];
            if (nban && sm[SMP_WORDS] == sm[S_BAN_STEP]) {  // n-gram bans of this step (host-computed)
                for (uint32_t b = 0; b < nban && b < S_BAN_MAX; ++b) {
                    const uint32_t id = sm[S_BAN0 + b];
                    if (id >= id0 && id < id0 + n) {
                        bits[id - id0] = mks::F32_NEG_INF;
                    }
                }
            }
            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_E);  // the STATE / embedding staging is free now
                noc_async_read_page(0, dram(ca(K_SEEN), SEEN_WORDS * 4), 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
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;
    }
    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;
    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);
        tstamp(l, 11);
        cbr_back(CB_Q, 8);  // full-capacity cycle: the q head lands at the CB base (fixed layout)
        cb_push_back(CB_Q, 8);
        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 128 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), 512);
            noc_async_write(get_read_ptr(CB_PRM), uni_addr(x0, y0, dst + T32), 512);
            uni_flag(x0, y0, get_read_ptr(CB_PRL), dst + 2 * T32, 512, 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);
                cb_push_back(CB_MRG, CAP_MRG);
            }
            cbw_front(CB_QO, 1);
            tstamp(l, 13);
            gather_send(get_read_ptr(CB_QO), cb_base(CB_O) + g * HD_T * TINY16, HD_T * TINY16, W_AO + g, l + 1, 5,
                        false);
            tstamp(l, 14);
            cb_pop_front(CB_QO, 1);
        }
        if (ca(K_STOP) == 2) {
            return;
        }
    }
}

// ------------------------------------------------------------------ ROUTER
void rt_main() {
    if (ca(K_STOP) || me.nl < 2) {
        return;
    }
    const uint32_t r = me.w;
    const bool force = me.flags & F_FORCE_ROUTE;
    if (r == 1 && force) {
        return;
    }
    zero_h_tail();
    read_pages(CB_CONST, ca(K_CONST), T16, 0, N_CONST);  // the TRISC's ONES / masks
    if (r == 0) {  // CB_RSM: elements 64 .. 1023 = NEG (the softmax tail); 0..63 written per layer
        const uint32_t neg = ca(K_NEG);
        l1_fill(cb_base(CB_RSM) + 256, (T32 - 256) / 4, neg);
    }
    uint32_t x1 = 0, y1 = 0;
    {
        const uint32_t xy = ca(K_RT0);
        x1 = xy >> 16;
        y1 = xy & 0xFFFF;
    }
    for (uint32_t l = 1; l < me.nl; ++l) {
        uint32_t rec[16];
        if (!force) {
            land_h(2 * l + 2);
            cbw_front(CB_RL, CAP_RL);
            if (r == 1) {
                uni_flag(x1, y1, get_read_ptr(CB_RL), cb_base(CB_RSM) + 128, 128, W_RL, l, 3);
                cb_pop_front(CB_RL, CAP_RL);
                continue;
            }
            cbr_back(CB_RSM, 1);
            l1_copy(get_read_ptr(CB_RL), get_write_ptr(CB_RSM), 32);
            cb_pop_front(CB_RL, CAP_RL);
            spin_ge(W_RL, l);
            cb_push_back(CB_RSM, 1);
            cbw_front(CB_RPR, 1);
            volatile tt_l1_ptr uint32_t* lg = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(cb_base(CB_RSM));
            volatile tt_l1_ptr uint32_t* pr = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(get_read_ptr(CB_RPR));
            uint64_t taken = 0;
            for (uint32_t k = 0; k < NSLOT; ++k) {  // top-6 by the fp32 logit keys, lower id on ties
                uint32_t best = 0, bk = 0;
                bool have = false;
                for (uint32_t e = 0; e < NEXP; ++e) {
                    if ((taken >> e) & 1) {
                        continue;
                    }
                    const uint32_t key = mks::f32_key(lg[e]);
                    if (!have || key > bk) {
                        best = e;
                        bk = key;
                        have = true;
                    }
                }
                taken |= (uint64_t)1 << best;
                rec[k] = best;
                rec[8 + k] = pr[best];
            }
            cb_pop_front(CB_RPR, 1);
            rec[6] = rec[7] = rec[14] = rec[15] = 0;
        } else {
            const uint32_t s = cb_base(CB_E);
            noc_async_read_page(l, dram(ca(K_FROUTE), 2048), s);
            rd_bar();
            for (uint32_t k = 0; k < 16; ++k) {
                rec[k] = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(s)[k];
            }
        }
        // the record -> every MM core (64 B at SYNC_ROUTE + (l & 1) * 64) + flag W_RT = l
        const uint32_t src = stg(6) - 64;  // 64 B staging below the flag source words
        volatile tt_l1_ptr uint32_t* sp = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(cb_base(CB_E) + 8192);
        for (uint32_t k = 0; k < 16; ++k) {
            sp[k] = rec[k];
        }
        (void)src;
        const uint32_t srcw = stg(7);
        *reinterpret_cast<volatile tt_l1_ptr uint32_t*>(srcw) = l;
        const uint32_t dsto = cb_base(CB_SYNC) + SYNC_ROUTE + (l & 1) * 64;
        const uint32_t fa = sync_addr(W_RT);
        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(cb_base(CB_E) + 8192, uni_addr(x, y, dsto), 64);
            noc_async_write(srcw, uni_addr(x, y, fa), 4);
        }
        wr_flush();
        if (me.flags & F_ROUTE_LOG) {
            noc_async_write_page(l, dram(ca(K_ROUTE), 2048), cb_base(CB_E) + 8192);
            wr_flush();
        }
    }
}

// ------------------------------------------------------------------ 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;
    volatile tt_l1_ptr uint32_t* st = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(s);
    const uint32_t ntok = st[S_NTOK];
    if (g_abort || sync_read(W_HUBAB) != 0) {
        // a core aborted in this launch (bounded wait expired, dropped read, ...): the candidate lists / KV row of
        // this step may be garbage. Do not commit: STATE keeps ntok, the host sees no progress and relaunches the
        // same step (it rewrites the same KV rows); S_ABORTS counts the retries (the host gives up after a few)
        st[S_ABORTS] = st[S_ABORTS] + 1;
        noc_async_write_page(0, dram(ca(K_STATE), 8192), s);
        wr_bar();
        return;
    }
    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 16 KB page)
            const uint32_t sb = cb_base(CB_HG) + 32768;
            noc_async_read_page(0, dram(ca(K_SEEN), SEEN_WORDS * 4), 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), SEEN_WORDS * 4), 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;
    }
    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.grp = rt(A_GRP);
    me.xoff = rt(A_XOFF);
    me.xn = rt(A_XN);
    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 || me.role == R_RT) {  // the go word -> the TRISC
        // an abort before the main loop (boot) skips the role's protocol: the TRISC must not start it either
        const uint32_t gw = (me.done || g_abort) ? 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 if (me.role == R_RT) {
            rt_main();
        } else {
            hub_main();
        }
    }
    {
        *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);
}