File size: 20,854 Bytes
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5afa0d
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5afa0d
b7e49b8
d5afa0d
 
 
 
b7e49b8
 
 
 
d5afa0d
 
 
 
 
b7e49b8
 
 
 
d5afa0d
 
 
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5afa0d
 
b7e49b8
 
 
 
 
 
 
 
d5afa0d
 
 
 
 
b7e49b8
 
 
 
 
 
 
 
 
d5afa0d
 
 
 
 
b7e49b8
 
 
 
 
 
 
 
 
 
d5afa0d
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
// SPDX-License-Identifier: Apache-2.0
//
// DepthPro2 ENC megakernel, BRISC (NoC 1): the boot barrier, the global hub barriers, every DRAM read of the op
// inputs (constants, rope tables, patches, x, q / K / V, attention output), every DRAM write (q / k / v staging, the
// attention output, taps, x), and the row gathers:
//   IA  patches / attention output: each core reads its share of the K tiles of the row's slots from DRAM and
//       multicasts it to the row (-> CB_INF, k * RB + s)
//   IX  LN input: the packed partial statistics (-> slot x of CB_STAT) and bf16(x) (-> CB_INX, k * RB + s)
//   IF  FC1 output blocks (-> CB_INF, f * RB + s)
// Every gather is a loopback multicast of the slice plus one flag word set to a per-type generation; the landing CB is
// pushed at full capacity once every flag of the round reached it. WAR safety of the landing buffers follows from the
// dataflow (MK_LOG 1.3): a core sends round g + 1 of a buffer only after it received data that every row core sends
// after its last read of round g.
#include "me_dm.hpp"

using namespace mex;

namespace {

constexpr auto acc_dram = TensorAccessorArgs<CT_ACC0>();
#define ME_NOINL __attribute__((noinline))

struct Me {
    uint32_t idx, role, x, y, h0, nh, n0, nx, f0, nf, ks0, ks1, pk0, pk1, rowx0, rowx1, rowy, poolx, pooly;
    uint32_t ax0, ay0, ax1, ay1, nall, hubx, huby, nl, dump;
    uint32_t kd[RB], ri[RB];
};
Me me;
uint32_t gen_ix = 0, gen_ia = 0, gen_if = 0, gen_bar = 0, gen_pool = 0, gen_fd = 0;

FORCE_INLINE void dbg(uint32_t a, uint32_t b) {
    *sync_ptr(W_DBG) = a;
    *sync_ptr(W_DBG + 1) = b;
}
ME_NOINL void wait_ge(uint32_t w, uint32_t v) {
    WAYPOINT("BWGE");
    *sync_ptr(W_DBG + 2) = w;
    *sync_ptr(W_DBG + 3) = v;
    while (sync_read(w) < v) {
    }
}
ME_NOINL void wait_all(uint32_t w0, uint32_t n, uint32_t v) {
    for (uint32_t i = 0; i < n; ++i) {
        wait_ge(w0 + i, v);
    }
}
FORCE_INLINE void land(uint32_t cb, uint32_t cap) {
    cb_reserve_back(cb, cap);
    cb_push_back(cb, cap);
}

FORCE_INLINE auto dram(uint32_t addr, uint32_t page_bytes) { return TensorAccessor(acc_dram, addr, page_bytes); }
ME_NOINL void rd16(uint32_t addr, uint32_t page, uint32_t l1) { noc_async_read_page(page, dram(addr, T16), l1); }
ME_NOINL void rd32(uint32_t addr, uint32_t page, uint32_t l1) { noc_async_read_page(page, dram(addr, T32), l1); }
ME_NOINL void wr16(uint32_t addr, uint32_t page, uint32_t l1) { noc_async_write_page(page, dram(addr, T16), l1); }
ME_NOINL void wr32(uint32_t addr, uint32_t page, uint32_t l1) { noc_async_write_page(page, dram(addr, T32), l1); }

// multicast [src, src + bytes) to the same-offset address dst on every core of my grid row (loopback)
ME_NOINL void row_data(uint32_t src, uint32_t dst, uint32_t bytes, bool linked) {
    noc_async_write_multicast_loopback_src(src, mcast_addr(me.rowx0, me.rowy, me.rowx1, me.rowy, dst), bytes, C,
                                           linked);
}
ME_NOINL void row_flag(uint32_t flag_word, uint32_t src_word, uint32_t v) {
    const uint32_t srcw = sync_addr(W_SRC + src_word);
    *reinterpret_cast<volatile tt_l1_ptr uint32_t*>(srcw) = v;
    noc_semaphore_set_multicast_loopback_src(
        srcw, mcast_addr(me.rowx0, me.rowy, me.rowx1, me.rowy, sync_addr(flag_word)), C);
    noc_async_writes_flushed();
}

void load_args() {
    me.idx = rt(A_IDX);
    me.role = rt(A_ROLE);
    me.x = rt(A_X);
    me.y = rt(A_Y);
    me.h0 = rt(A_H0);
    me.nh = rt(A_NH);
    me.n0 = rt(A_N0);
    me.nx = rt(A_NX);
    me.f0 = rt(A_F0);
    me.nf = rt(A_NF);
    me.ks0 = rt(A_KS0);
    me.ks1 = rt(A_KS1);
    me.pk0 = rt(A_PK0);
    me.pk1 = rt(A_PK1);
    me.rowx0 = rt(A_ROWX0);
    me.rowx1 = rt(A_ROWX1);
    me.rowy = rt(A_ROWY);
    me.poolx = rt(A_POOLX);
    me.pooly = rt(A_POOLY);
    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.hubx = ca(K_HUB_X);
    me.huby = ca(K_HUB_Y);
    me.nl = ca(K_NL);
    me.dump = ca(K_DUMP);
}

void kinds(uint32_t w) {
    for (uint32_t s = 0; s < RB; ++s) {
        me.ri[s] = ri_of(w, me.y, s);
        me.kd[s] = kind_of(me.ri[s]);
    }
}

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(me.hubx, me.huby, sem_boot), 1);
    noc_async_atomic_barrier();
    if (me.role & R_HUB) {
        volatile tt_l1_ptr uint32_t* b = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(sem_boot);
        WAYPOINT("BOOT");
        while (true) {
            invalidate_l1_cache();
            if (*b >= me.nall) {
                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(me.ax0, me.ay0, me.ax1, me.ay1, sem_go), me.nall);
        noc_async_writes_flushed();
    }
    wait_go(sem_go);
}

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

// ------------------------------------------------------------------ init
void init_consts() {
    cb_reserve_back(CB_CONST, N_CONST);
    for (uint32_t i = 0; i < N_CONST; ++i) {
        rd16(ca(K_CONST), i, get_write_ptr(CB_CONST) + i * T16);
    }
    cb_reserve_back(CB_CF32, N_CF32);
    for (uint32_t i = 0; i < N_CF32; ++i) {
        rd32(ca(K_CF32), i, get_write_ptr(CB_CF32) + i * T32);
    }
    cb_reserve_back(CB_PFX, NXM);
    for (uint32_t j = 0; j < me.nx; ++j) {
        rd32(ca(K_PFX), me.n0 + j, get_write_ptr(CB_PFX) + j * T32);
    }
    noc_async_read_barrier();
    if constexpr (POOL) {  // valid frames n / bits(1 / n) of this run (VF tile elements 0, 1), for the TRISC too
        cb_reserve_back(CB_PL, NXM);
        const uint32_t a = get_write_ptr(CB_PL);
        rd32(ca(K_VF), 0, a);
        noc_async_read_barrier();
        invalidate_l1_cache();
        volatile tt_l1_ptr uint32_t* v = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(a);
        uint32_t n = v[0];
        n = n < 1 ? 1 : (n > T ? T : n);
        g_nv = n;
        *sync_ptr(W_NV) = n;
        *sync_ptr(W_INVN) = v[1];
    }
    cb_push_back(CB_CONST, N_CONST);  // the TRISC reads W_NV / W_INVN after this push
    cb_push_back(CB_CF32, N_CF32);
    cb_push_back(CB_PFX, NXM);
}

// ------------------------------------------------------------------ per wave
// rope tables of the wave's patch slots
void rope_tab() {
    cb_reserve_back(CB_TAB, 2 * RB);
    const uint32_t a = get_write_ptr(CB_TAB);
    for (uint32_t s = 0; s < RB; ++s) {
        if (me.kd[s] == KD_PATCH) {
            const uint32_t p = (me.ri[s] - T) % PT;
            rd32(ca(K_ROPE), 2 * p, a + (2 * s) * T32);
            rd32(ca(K_ROPE), 2 * p + 1, a + (2 * s + 1) * T32);
        }
    }
    noc_async_read_barrier();
    cb_push_back(CB_TAB, 2 * RB);
}

// x of the wave from XD (NW > 1)
void x_load() {
    cb_reserve_back(CB_XL, RB * NXM);
    const uint32_t a = get_write_ptr(CB_XL);
    for (uint32_t s = 0; s < RB; ++s) {
        if (me.kd[s] == KD_PREFIX || me.kd[s] == KD_PATCH) {
            for (uint32_t j = 0; j < me.nx; ++j) {
                rd32(ca(K_XD), me.ri[s] * DT + me.n0 + j, a + (s * NXM + j) * T32);
            }
        }
    }
    noc_async_read_barrier();
    cb_push_back(CB_XL, RB * NXM);
}

// IA: the row's slots' K tiles [k0, k1) of a DRAM tile tensor (Kt tiles per row tile) -> CB_INF (k * RB + s), my
// share read from DRAM and multicast to the row. mode 0: patches (row tile = patch index), 1: attention output.
ME_NOINL void ia_gather(uint32_t mode, uint32_t act) {
    ++gen_ia;
    const uint32_t k0 = mode == 0 ? me.pk0 : me.ks0, k1 = mode == 0 ? me.pk1 : me.ks1;
    const uint32_t Kt = mode == 0 ? PE_T : DT;
    const uint32_t addr = ca(mode == 0 ? K_PATCH : K_O);
    const uint32_t base = cb_base(CB_INF);
    for (uint32_t s = 0; s < RB; ++s) {
        if (!(act & (1u << s))) {
            continue;
        }
        const uint32_t row = mode == 0 ? me.ri[s] - T : me.ri[s];
        for (uint32_t k = k0; k < k1; ++k) {
            rd16(addr, row * Kt + k, base + (k * RB + s) * T16);
        }
    }
    noc_async_read_barrier();
    if (k1 > k0) {
        row_data(base + k0 * RB * T16, base + k0 * RB * T16, (k1 - k0) * RB * T16, true);
    }
    row_flag(W_IA + me.x, SRC_IA, gen_ia);
    wait_all(W_IA, C, gen_ia);
    land(CB_INF, INF_CAP);
}

// IX: packed statistics + bf16(x) slice
ME_NOINL void ln_gather() {
    ++gen_ix;
    cb_wait_front(CB_STO, 1);
    cb_wait_front(CB_OUTX, NXM * RB);
    row_data(get_read_ptr(CB_STO), cb_base(CB_STAT) + me.x * T32, T32, true);
    row_data(get_read_ptr(CB_OUTX), cb_base(CB_INX) + me.n0 * RB * TIX, me.nx * RB * TIX, true);
    row_flag(W_IX + me.x, SRC_IX, gen_ix);
    cb_pop_front(CB_STO, 1);
    cb_pop_front(CB_OUTX, NXM * RB);
    wait_all(W_IX, C, gen_ix);
    land(CB_STAT, C);
    land(CB_INX, INX_CAP);
}

// IF: FC1 output blocks (FB hidden tiles x RB slots each)
ME_NOINL void fc1_gather() {
    ++gen_if;
    const uint32_t base = cb_base(CB_INF);
    for (uint32_t fb = 0; fb < me.nf;) {
        uint32_t nb = 1;  // the TRISC's power-of-two blocks (pow2_floor)
        while (nb * 2 <= me.nf - fb && nb * 2 <= FB) {
            nb *= 2;
        }
        cb_wait_front(CB_FO, FB * RB);
        const uint32_t dst = base + (me.f0 + fb) * RB * T16;
        row_data(get_read_ptr(CB_FO), dst, nb * RB * T16, false);
        noc_async_writes_flushed();
        cb_pop_front(CB_FO, FB * RB);
        fb += nb;
    }
    noc_async_write_barrier();
    row_flag(W_IF + me.x, SRC_IF, gen_if);
    wait_all(W_IF, C, gen_if);
    land(CB_INF, INF_CAP);
}

ME_NOINL void store_x(uint32_t s) {
    cb_wait_front(CB_XO, NXM);
    const uint32_t a = get_read_ptr(CB_XO);
    for (uint32_t j = 0; j < me.nx; ++j) {
        wr32(ca(K_XD), me.ri[s] * DT + me.n0 + j, a + j * T32);
    }
    noc_async_writes_flushed();
    cb_pop_front(CB_XO, NXM);
}

void tap_dm(uint32_t k) {
    for (uint32_t s = 0; s < RB; ++s) {
        if (!tap_on(me.kd[s])) {
            continue;
        }
        cb_wait_front(CB_TAP, NXM);
        const uint32_t a = get_read_ptr(CB_TAP), row = tap_row(me.ri[s]);
        for (uint32_t j = 0; j < me.nx; ++j) {
            wr16(ca(K_TAP0 + k), row * DT + me.n0 + j, a + j * T16);
        }
        noc_async_writes_flushed();
        cb_pop_front(CB_TAP, NXM);
    }
}

// before LN1 of a joint block: prefix slots -> XD + signal the pool owner; the pool owner reads the T slices
void pool_dm() {
    bool own = false;
    for (uint32_t s = 0; s < RB; ++s) {
        if (me.kd[s] == KD_PREFIX) {
            store_x(s);
            noc_async_write_barrier();
            noc_semaphore_inc(get_noc_addr(me.poolx, me.pooly, sync_addr(W_POOL)), 1);
            noc_async_atomic_barrier();
        }
        own = own || me.kd[s] == KD_POOL;
    }
    if (!own) {
        return;
    }
    ++gen_pool;
    wait_ge(W_POOL, gen_pool * T);  // every frame's prefix slots report; the mean takes frames < n
    for (uint32_t t = 0; t < g_nv; ++t) {
        cb_reserve_back(CB_PL, NXM);
        const uint32_t a = get_write_ptr(CB_PL);
        for (uint32_t j = 0; j < me.nx; ++j) {
            rd32(ca(K_XD), t * DT + me.n0 + j, a + j * T32);
        }
        noc_async_read_barrier();
        cb_push_back(CB_PL, NXM);
    }
}

// q / k / v of block l: one OUT push (2 RB tiles) per head unit
void qkv_dm(uint32_t l) {
    for (uint32_t jh = 0; jh < me.nh; ++jh) {
        const uint32_t u = me.h0 + jh, ty = unit_type(u), h = unit_head(u);
        const uint32_t addr = ca(ty == 0 ? K_Q : ty == 1 ? K_K : K_V);
        const bool lo = ty == 1 && klo_wave(l, me.kd);
        cb_wait_front(CB_OUT, 2 * RB);
        if (lo) {
            cb_wait_front(CB_OUTLO, 2 * RB);
        }
        const uint32_t a = get_read_ptr(CB_OUT), alo = lo ? get_read_ptr(CB_OUTLO) : 0;
        for (uint32_t s = 0; s < RB; ++s) {
            if ((qkv_mask(l, me.kd[s]) >> ty) & 1u) {
                wr16(addr, me.ri[s] * DT + 2 * h, a + (2 * s) * T16);
                wr16(addr, me.ri[s] * DT + 2 * h + 1, a + (2 * s + 1) * T16);
                if (lo && (KLO == 2 || me.kd[s] != KD_PATCH)) {
                    const uint32_t r = klo_row(me.ri[s]);
                    wr16(ca(K_KLO), r * DT + 2 * h, alo + (2 * s) * T16);
                    wr16(ca(K_KLO), r * DT + 2 * h + 1, alo + (2 * s + 1) * T16);
                }
            }
        }
        noc_async_writes_flushed();
        cb_pop_front(CB_OUT, 2 * RB);
        if (lo) {
            cb_pop_front(CB_OUTLO, 2 * RB);
        }
    }
}

void tail_dm(int l) {
    const uint32_t l1 = (uint32_t)(l + 1);
    if (l1 >= NL) {  // QKV(l + 1) runs even past a debug stop (nl < L): the staging then holds block nl's q / k / v
        return;
    }
    if (POOL && joint(l1)) {
        pool_dm();
    }
    ln_gather();
    qkv_dm(l1);
}

void wave_end_dm(bool store) {
    if (store) {
        for (uint32_t s = 0; s < RB; ++s) {
            if (me.kd[s] == KD_PREFIX || me.kd[s] == KD_PATCH) {
                store_x(s);
            }
        }
    }
}

// ------------------------------------------------------------------ attention of block l
// Jobs (me_sched.hpp): the grid column x runs jobs x, x + C, ... ; its reader (last row) reads each K / V chunk of
// the job's segment from DRAM once and multicasts it down the column; every core grants a CB_KV slot (credit)
// before the reader may fill it. Job g's q reads and K / V chunks are issued before job g - 1's outputs are
// collected (CB_AQ holds 2 jobs' q, CB_AO one job's outputs).
uint32_t kv_count = 0;  // K / V chunks of this column so far (identical on its cores)

void kv_chunk(const Item& it, uint32_t p0, uint32_t nk) {
    cb_reserve_back(CB_KV, CHT);
    const uint32_t ak = get_write_ptr(CB_KV), av = ak + 2 * KC * T16, al = av + 2 * KC * T16;
    if (me.role & R_KVR) {
        const uint32_t ka = ca(K_K), va = ca(K_V);
        for (uint32_t j = 0; j < nk; ++j) {
            const uint32_t key = seg_key(it, p0 + j);
            rd16(ka, key * DT + 2 * it.h, ak + (2 * j) * T16);
            rd16(ka, key * DT + 2 * it.h + 1, ak + (2 * j + 1) * T16);
            rd16(va, key * DT + 2 * it.h, av + (2 * j) * T16);
            rd16(va, key * DT + 2 * it.h + 1, av + (2 * j + 1) * T16);
            if (KLO == 2 || (KLO == 1 && p0 + j == 0)) {
                const uint32_t r = klo_row(key), o = KLO == 2 ? 2 * j : 0;
                rd16(ca(K_KLO), r * DT + 2 * it.h, al + o * T16);
                rd16(ca(K_KLO), r * DT + 2 * it.h + 1, al + (o + 1) * T16);
            }
        }
        for (uint32_t y = 0; y + 1 < R; ++y) {
            wait_ge(W_KCRED + y, kv_count + 1);
        }
        noc_async_read_barrier();
        if (R > 1) {
            const uint32_t kx = rt(A_KRX), y0 = rt(A_KY0), y1 = rt(A_KY1);
            noc_async_write_multicast(ak, mcast_addr(kx, y0, kx, y1, ak), 2 * nk * T16, R - 1, true);
            noc_async_write_multicast(av, mcast_addr(kx, y0, kx, y1, av), 2 * nk * T16, R - 1, true);
            if (KLO == 2) {
                noc_async_write_multicast(al, mcast_addr(kx, y0, kx, y1, al), 2 * nk * T16, R - 1, true);
            } else if (KLO == 1 && p0 == 0) {
                noc_async_write_multicast(al, mcast_addr(kx, y0, kx, y1, al), 2 * T16, R - 1, true);
            }
            const uint32_t srcw = sync_addr(W_KSRC);
            *reinterpret_cast<volatile tt_l1_ptr uint32_t*>(srcw) = kv_count + 1;
            noc_semaphore_set_multicast(srcw, mcast_addr(kx, y0, kx, y1, sync_addr(W_KV)), R - 1);
            noc_async_writes_flushed();
        }
    } else {
        noc_semaphore_inc(get_noc_addr(rt(A_KRX), rt(A_KRY), sync_addr(W_KCRED + me.y)), 1);
        wait_ge(W_KV, kv_count + 1);
    }
    ++kv_count;
    cb_push_back(CB_KV, CHT);
}

void att_reads(const Item& it) {
    const uint32_t qa = ca(K_Q);
    cb_reserve_back(CB_AQ, QB * 2);
    {
        const uint32_t a = get_write_ptr(CB_AQ);
        for (uint32_t j = 0; j < it.nq; ++j) {
            rd16(qa, it.q[j] * DT + 2 * it.h, a + (2 * j) * T16);
            rd16(qa, it.q[j] * DT + 2 * it.h + 1, a + (2 * j + 1) * T16);
        }
    }
    noc_async_read_barrier();
    cb_push_back(CB_AQ, QB * 2);
    const uint32_t L = seg_len(it);
    for (uint32_t p0 = 0; p0 < L; p0 += KC) {
        kv_chunk(it, p0, L - p0 < KC ? L - p0 : KC);
    }
}
void att_writes(const Item& it) {
    const uint32_t oa = ca(K_O);
    for (uint32_t j = 0; j < it.nq; ++j) {
        cb_wait_front(CB_AO, 2);
        const uint32_t a = get_read_ptr(CB_AO);
        wr16(oa, it.q[j] * DT + 2 * it.h, a);
        wr16(oa, it.q[j] * DT + 2 * it.h + 1, a + T16);
        noc_async_writes_flushed();
        cb_pop_front(CB_AO, 2);
    }
}
void att_dm(uint32_t l) {
    Item it[2];
    const uint32_t n = n_jobs(l);
    uint32_t k = 0;
    for (uint32_t g = me.x; g < n; g += C, ++k) {
        job_of(l, g, me.y, it[k & 1]);
        att_reads(it[k & 1]);
        if (k > 0) {
            att_writes(it[(k - 1) & 1]);
        }
    }
    if (k > 0) {
        att_writes(it[(k - 1) & 1]);
    }
    noc_async_atomic_barrier();
}

}  // namespace

void kernel_main() {
    load_args();
    for (uint32_t w = 0; w < N_SYNC; ++w) {
        *sync_ptr(w) = 0;
    }
#if ME_PROF
    for (uint32_t w = 0; w < PROF_WORDS; ++w) {
        prof_ptr()[w] = 0;
    }
#endif
    boot_barrier();
    PROF(0);
    init_consts();
    const uint32_t nl = me.nl;
    dbg(1, 0);
    // E: embedding (+ LN1 / QKV of block 0)
    for (uint32_t w = 0; w < NW; ++w) {
        kinds(w);
        rope_tab();
        uint32_t act = 0;
        for (uint32_t s = 0; s < RB; ++s) {
            act |= (me.kd[s] == KD_PATCH ? 1u : 0u) << s;
        }
        ia_gather(0, act);
        tail_dm(-1);
        wave_end_dm(NW > 1 || (me.dump && nl == 0));
    }
    PROF(1);
    for (uint32_t l = 0; l < nl; ++l) {
        barrier();
        PROF(2 + 4 * l);
        dbg(2, l);
        att_dm(l);
        PROF(3 + 4 * l);
        barrier();
        PROF(4 + 4 * l);
        dbg(3, l);
        for (uint32_t w = 0; w < NW; ++w) {
            kinds(w);
            rope_tab();
            if (NW > 1) {
                x_load();
            }
            uint32_t act = 0;
            for (uint32_t s = 0; s < RB; ++s) {
                act |= (mlp_on(l, me.kd[s]) ? 1u : 0u) << s;
            }
            const bool wp = l == 1 && w == 0;
            if (wp) PROF(320);
            if (NW > 1 && l + 1 >= NL && w > 0) {
                // a block without a QKV tail: before this wave's attention output lands in CB_INF, every row core must
                // have finished the previous wave's FC2 reads of it (the tail's LN1 gather orders this otherwise)
                wait_all(W_FD, C, gen_fd);
            }
            ia_gather(1, act);
            if (wp) PROF(321);
            ln_gather();
            if (wp) PROF(322);
            fc1_gather();
            if (NW > 1 && l + 1 >= NL && w + 1 < NW) {
                cb_wait_front(CB_TOK, 1);
                cb_pop_front(CB_TOK, 1);
                row_flag(W_FD + me.x, SRC_FD, ++gen_fd);
            }
            if (wp) PROF(323);
            const int tk = tap_of(l);
            if (tk >= 0) {
                tap_dm((uint32_t)tk);
            }
            tail_dm((int)l);
            if (wp) PROF(324);
            wave_end_dm(NW > 1 || (me.dump && l + 1 == nl));
        }
        PROF(5 + 4 * l);
    }
#if ME_PROBE
    if (me.idx == 0 && nl > 0) {
        cb_wait_front(CB_PRB, N_PROBE);
        const uint32_t a = get_read_ptr(CB_PRB);
        for (uint32_t i = 0; i < N_PROBE; ++i) {
            wr32(ca(K_PROBE), i, a + i * T32);
        }
        noc_async_write_barrier();
        cb_pop_front(CB_PRB, N_PROBE);
    }
#endif
    dbg(0xD0, 0xD0);
    noc_async_full_barrier();
#if ME_PROF
    for (volatile uint32_t spin = 0; spin < 20000; spin = spin + 1) {  // let the TRISC's last stamps land
    }
    noc_async_write_page(me.idx, TensorAccessor(acc_dram, ca(K_PROF), PROF_WORDS * 4), cb_base(CB_SYNC) + SYNC_PROF);
    noc_async_write_barrier();
#endif
}