File size: 37,011 Bytes
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
7b01b36
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
 
 
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
 
 
 
 
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
 
31ffdfe
 
7b01b36
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
31ffdfe
 
 
7b01b36
 
 
 
31ffdfe
7b01b36
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31ffdfe
7b01b36
 
 
 
 
31ffdfe
 
 
 
 
7b01b36
31ffdfe
 
 
7b01b36
 
 
31ffdfe
 
7b01b36
 
 
 
31ffdfe
 
 
 
7b01b36
 
 
 
 
 
 
 
 
 
31ffdfe
 
 
 
7b01b36
31ffdfe
 
 
 
 
 
7b01b36
 
 
31ffdfe
 
 
 
7b01b36
31ffdfe
7b01b36
 
 
31ffdfe
 
 
7b01b36
 
 
 
 
 
 
 
 
31ffdfe
7b01b36
 
 
 
 
31ffdfe
 
7b01b36
31ffdfe
 
 
7b01b36
 
 
 
 
 
 
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31ffdfe
 
 
 
 
 
7b01b36
 
31ffdfe
 
 
7b01b36
31ffdfe
 
 
 
 
 
 
 
7b01b36
 
 
 
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
31ffdfe
 
 
 
 
 
 
 
 
7b01b36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31ffdfe
 
 
 
7b01b36
 
 
 
 
 
31ffdfe
7b01b36
 
 
 
31ffdfe
7b01b36
 
 
31ffdfe
7b01b36
31ffdfe
 
7b01b36
 
 
 
 
31ffdfe
7b01b36
31ffdfe
7b01b36
31ffdfe
 
 
 
 
 
 
 
 
7b01b36
 
 
 
 
 
 
 
31ffdfe
7b01b36
 
 
 
31ffdfe
 
 
 
7b01b36
 
 
31ffdfe
7b01b36
 
 
 
31ffdfe
 
 
 
 
 
 
 
7b01b36
31ffdfe
 
 
7b01b36
 
 
 
 
 
 
31ffdfe
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
// SPDX-License-Identifier: Apache-2.0
// Vendored from the BEVFormer-small p150 port (tt_bevformer/tt/kernels/msda_k_reader.cpp) and extended for AutoE2E
// (tt_autoe2e/tt/msda_k.py): HDIV (head blocks sharing a value map: the t1 self-attention's two queue entries),
// ATT_COL0 (the level's point columns inside a 32-column softmax block: the 4-level cross-attention), LOC_OFF (the
// level's columns inside the merged sampling projection) and NSEG / SEG_END (value-map segments of unequal block
// counts: the per-camera row capacities of the rebatched cross-attention).
// msda_k (tt/msda_k.py, OPT_PLAN #1 / #2 / #10): the data-movement half of the fixed-point MSDA kernel. The same
// source runs on both data-movement RISC-Vs; PART 0 (NCRISC, "reader") owns the points [0, P/2), PART 1 (BRISC,
// "writer") the points [P/2, P) and also writes the output tiles. Each RISC has its own CBs (cb_geo, cb_in, cb_loc),
// so there is no cross-RISC handshake.
//
// Work item w (contiguous range per core, core index from the logical coordinates: common RT args only, probe P3):
//   b = w / H (32-query block), j = w % H (head block; head-minor order); value map m = j * SUB + segment(b);
//   loc  int32 TILE [1, H, NB * 32, 32], tile j * NB + b: row r, column 2p / 2p + 1 = x / y of point p as
//        round(pixel * 2^16) (pixel = (g + 1) size / 2 - 0.5, align_corners=False);
//   attn fp32 TILE  [1, H, NB * 32, 32], tile j * NB + b: the softmax weight of point p in column p;
//   out  bf16 TILE  [1, 1, NB * 32, H * 32], tile b * H + j.
// value: VSRC 0 = (N, h, w, 32) ROW_MAJOR, page m * h * w + y * w + x; VSRC 1 = the head split [B, heads, rows, 32]
// TILE as nlp_create_qkv_heads writes it (map m = j * SUB + s: slice j, rows s * h * w ..; TPH tiles per slice), the
// stick of a pixel = row r of its tile: two 32-byte face rows (faces 2 (r / 16) and + 1), no untilize needed.
// Per item and RISC: cb_geo <- 3 fp32 tiles (fx, fy, attn with the other RISC's point columns zeroed) and
// cb_in <- 2P bf16 tiles (step k = (p - p0) * 4 + corner; corners NW, NE, SW, SE): row r of step k is the 32-channel
// value stick of that corner, read as two 32-byte halves straight into the tile's face rows; corners outside the map
// (and padding rows) read the zeros page. The compute kernel turns geo into the 4 corner weights on the SFPU.
#include <stdint.h>

#include "api/dataflow/dataflow_api.h"
#ifdef MSDA_K_TIMING
#include "tools/profiler/kernel_profiler.hpp"
#define TNOW() reg_read(RISCV_DEBUG_REG_WALL_CLOCK_L)
#endif
#include "ttnn/cpp/ttnn/kernel_lib/reduce_helpers_dataflow.hpp"

constexpr uint32_t PART = get_compile_time_arg_val(1);
constexpr uint32_t cb_in = get_compile_time_arg_val(2);
constexpr uint32_t cb_geo = get_compile_time_arg_val(3);
constexpr uint32_t cb_loc = get_compile_time_arg_val(4);
constexpr uint32_t cb_e = get_compile_time_arg_val(5);
constexpr uint32_t cb_out = get_compile_time_arg_val(6);
constexpr int32_t HV = get_compile_time_arg_val(7);
constexpr int32_t WV = get_compile_time_arg_val(8);
constexpr uint32_t NQ = get_compile_time_arg_val(9);
constexpr uint32_t NB = get_compile_time_arg_val(10);
constexpr uint32_t H = get_compile_time_arg_val(11);
constexpr uint32_t SUB = get_compile_time_arg_val(12);
constexpr uint32_t P = get_compile_time_arg_val(13);
constexpr uint32_t NWORK = get_compile_time_arg_val(14);
constexpr uint32_t NC = get_compile_time_arg_val(15);
constexpr uint32_t GX = get_compile_time_arg_val(16);
constexpr uint32_t WRITES_OUT = get_compile_time_arg_val(17);
constexpr uint32_t MAKES_E = get_compile_time_arg_val(18);
// 0: ROW_MAJOR maps (64-byte pages); 1: TILE heads; 2 (BEVFORMER_MSDA_PAIRS): pixel-pair maps [N, h, w + 1, 64]
// (tt/pairmap_k.py: 128-byte page (m, y, i) = the sticks of x = i - 1 and x = i): ONE read per point and row lands
// the NW + NE (or SW + SE) sticks as a row of a [32 x 64] row-major staging block (tilized by the compute kernel)
constexpr uint32_t VSRC = get_compile_time_arg_val(19);
constexpr uint32_t TPH = get_compile_time_arg_val(20);    // VSRC 1: tiles per head slice (SUB maps of HV x WV rows)
// SKIP: items strided over the cores (w = core, core + NC, ..: padding blocks spread evenly) and points with all four
// corners outside the map (or rows past NQ) issue no reads: their weight is set to 0, and their tile rows keep
// earlier (finite) gathers; the step tiles are zeroed once. 0: contiguous item ranges, zeros-page reads.
constexpr uint32_t SKIP = get_compile_time_arg_val(21);
// LOC_HS 0: loc is the head split [1, H, NB * 32, 32] (tile j * NB + b, columns 2p / 2p + 1); LOC_HS > 0
// (BEVFORMER_MSDA_LOC=compact): loc is the merged [1, 1, NB * 32, H * LOC_HS] map (the sampling projection's own
// layout: head j in columns j * LOC_HS .. + 2P), LOC_TW tiles per row block: tile b * LOC_TW + j * LOC_HS / 32,
// column (j * LOC_HS) % 32 + 2p
constexpr uint32_t LOC_HS = get_compile_time_arg_val(22);
constexpr uint32_t LOC_TW = get_compile_time_arg_val(23);
// SM 1 (BEVFORMER_MSDA_SOFTMAX=kernel): attn is the compact attention-logit map [1, 1, NB * 32, H * P] (head j in
// columns j * P ..; AT_TW tiles per row block); the PART-0 RISC rebuilds the head's logit tile (columns 0..P-1 the
// logits, the rest PAD_LOGIT: what the head-block projection writes) into cb_lg for the compute kernel's softmax,
// and makes the reduce scalers and the two half masks once. Rows past NQ get logits 0 (finite; their values are 0).
constexpr uint32_t SM = get_compile_time_arg_val(24);
constexpr uint32_t AT_TW = get_compile_time_arg_val(25);
constexpr uint32_t PAD_BITS = get_compile_time_arg_val(26);   // fp32 bits of PAD_LOGIT
constexpr uint32_t cb_lg = 9, cb_scmax = 10, cb_scsum = 11, cb_msk = 12, cb_scr = 18;
constexpr uint32_t HDIV = get_compile_time_arg_val(27);     // head blocks per value-map head (1; 2 for the t1 TSA)
constexpr uint32_t ATT_COL0 = get_compile_time_arg_val(28); // attn: point p is column ATT_COL0 + p (non-SM)
constexpr uint32_t LOC_OFF = get_compile_time_arg_val(29);  // LOC_HS > 0: head j's columns start at j * LOC_HS + LOC_OFF
constexpr uint32_t NSEG = get_compile_time_arg_val(30);     // > 0: SUB = NSEG segments, segment s = blocks [END(s-1), END(s))
constexpr uint32_t SEG_CT[8] = {get_compile_time_arg_val(31), get_compile_time_arg_val(32), get_compile_time_arg_val(33),
                                get_compile_time_arg_val(34), get_compile_time_arg_val(35), get_compile_time_arg_val(36),
                                get_compile_time_arg_val(37), get_compile_time_arg_val(38)};
// SEG_RT 1: the segment ends are read at start from page 0 of a uint32 tensor (common RT arg 4; the first NSEG words,
// cumulative block ends), so a trace replays with per-frame segments (the host rewrites that tensor); else SEG_CT
constexpr uint32_t SEG_RT = get_compile_time_arg_val(39);
// LOCF 1: loc is the fp32 sampling projection itself (offsets in Q16.16 units, the merged LOC_HS layout) and a base
// tensor [1, 1, NB * 32, 64] fp32 (common RT arg 5; per row block 2 tiles, column LOC_OFF % 64 + 2p + (x, y): the
// level's anchor positions in Q16.16 units) is added in integers: pos = f2i(offset) + f2i(base) (each rounded to the
// nearest 2^-16 px), so no device-side add / typecast / repeat of the [R, H * 64] map is needed.
constexpr uint32_t LOCF = get_compile_time_arg_val(40);
// SM 2 (joint): the head's logits are all 32 columns of its tile (4 levels x 8 points); the softmax runs over all of
// them and this call's points are the columns ECOL + p (ECOL = ATT_COL0): fx / fy, the E rows and the half masks
// move to those columns, so the weights are the joint softmax restricted to this level.
constexpr uint32_t ECOL = SM == 2 ? ATT_COL0 : 0;
constexpr auto v_args = TensorAccessorArgs<41>();
constexpr auto l_args = TensorAccessorArgs<v_args.next_compile_time_args_offset()>();
constexpr auto a_args = TensorAccessorArgs<l_args.next_compile_time_args_offset()>();
constexpr auto o_args = TensorAccessorArgs<a_args.next_compile_time_args_offset()>();
constexpr auto s_args = TensorAccessorArgs<o_args.next_compile_time_args_offset()>();
constexpr auto b_args = TensorAccessorArgs<s_args.next_compile_time_args_offset()>();
constexpr uint32_t cb_base = 21 + PART;   // one page per RISC (the two RISCs run their items independently)

constexpr uint32_t PH = P / 2;
constexpr uint32_t P0 = PART * PH;
constexpr uint32_t NS = PH * 4;  // steps (tiles) per item and RISC
constexpr uint32_t TB16 = 2048, TB32 = 4096;
// VSRC 4 (AutoE2E): quad maps [N, h + 1, w + 1, 128] (tt/pairmap.py quad=True): the 256-byte page (m, Y, i) holds the
// NW | NE | SW | SE sticks of the point whose top-left corner is (Y - 1, i - 1): ONE read per point and row lands a row
// of the point's [32 x 128] row-major staging block (tilized into the 4 corner tiles by the compute kernel)
constexpr uint32_t VPAGE = VSRC == 0 ? 64 : (VSRC == 2 ? 128 : (VSRC == 4 ? 256 : 2048));
constexpr uint32_t VPAGE_AL = VPAGE;   // L1 page stride (128 B: already a multiple of the L1 alignment)
static_assert((VSRC != 2 && VSRC != 4) || !SKIP, "msda_k: pair / quad maps and SKIP are exclusive");
// MSDA_K_SKIPP (pair maps, no in-kernel softmax): a point with all four corners outside the map (or a row past NQ)
// issues no reads; its weight in this RISC's attn copy is set to 0 and its staging rows keep earlier finite sticks
// (zeroed once at start), so it adds 0 (the zeros-page reads it replaces cost as much as real ones)
#ifdef MSDA_K_SKIPP
constexpr bool SKIPP = true;
#else
constexpr bool SKIPP = false;
#endif
static_assert(!SKIPP || ((VSRC == 2 || VSRC == 4) && SM == 0), "msda_k: SKIPP needs pair / quad maps and host-side weights");
constexpr uint32_t BPS = NB / SUB;
constexpr uint32_t MAP = static_cast<uint32_t>(HV * WV);
constexpr int32_t LOC_LIM = 1 << 28;  // |pixel| < 4096 after the clamp: no overflow below
static_assert(P % 2 == 0 && P <= 8, "msda_k: P even, <= 8 (x / y of a point share a face)");
static_assert(NSEG > 0 || NB % SUB == 0, "msda_k: blocks split evenly over the value maps of a head");
static_assert(NSEG == 0 || NSEG == SUB, "msda_k: NSEG segments are the SUB maps of a head");
static_assert(ATT_COL0 + P <= 32, "msda_k: the level's point columns fit the attn tile");
static_assert(LOC_HS == 0 || (LOC_HS >= 2 * P && (32 % LOC_HS == 0 || LOC_HS % 32 == 0)),
              "msda_k: LOC_HS holds 2P columns, divides 32 or is a multiple of 32");
static_assert(LOC_HS == 0 || (LOC_OFF % 32) + 2 * P <= 32, "msda_k: a head's 2P loc columns stay in one tile");

static inline uint32_t tile_elem(uint32_t r, uint32_t c) {
    return (((r >> 4) << 1) + (c >> 4)) * 256 + ((r & 15) << 4) + (c & 15);
}

// q in [0, 65536): the fp32 bit pattern of q / 65536 (exact)
// fp32 bit pattern -> int32, rounded to nearest (ties away from zero); |x| < 2^30 (Q16.16 positions: |px| < 2^14)
static inline int32_t f2i(uint32_t bits) {
    const int32_t e = static_cast<int32_t>((bits >> 23) & 0xFF) - 127;
    if (e < -1) {
        return 0;
    }
    const uint32_t m = (bits & 0x7FFFFF) | 0x800000;
    const uint32_t v = e >= 23 ? (m << (e - 23)) : ((m + (1u << (22 - e))) >> (23 - e));
    return (bits >> 31) ? -static_cast<int32_t>(v) : static_cast<int32_t>(v);
}

static inline uint32_t q16_to_f32(uint32_t q) {
    if (q == 0) {
        return 0;
    }
    const uint32_t n = 31 - __builtin_clz(q);
    return ((127 - 16 + n) << 23) | ((q << (23 - n)) & 0x7FFFFF);
}
// the fraction q (16 bits) as the fp32 2^23 + q: one OR instead of a normalisation (no clz on these RISC-Vs); the
// compute kernel's weight function takes (f - 2^23) * 2^-16, exact. FRAC0 is the encoding of 0.
constexpr uint32_t FRAC0 = 0x4B000000u;
static inline uint32_t q16_frac(uint32_t q) { return FRAC0 | q; }

// lean 128-byte reads of pixel-pair pages (interleaved L1): the bank and its NOC coordinate from the firmware
// tables, and only the registers that change per read (the length and the chip-local address high bits are set
// once per item by noc_async_read_one_packet_set_state)
static inline void pair_read_state() {
    noc_async_read_one_packet_set_state(get_noc_addr(MEM_ZEROS_BASE), VPAGE);
}
static inline void pair_read(uint32_t xy, uint32_t src, uint32_t dst) {
    while (!noc_cmd_buf_ready(noc_index, read_cmd_buf));
    NOC_CMD_BUF_WRITE_REG(noc_index, read_cmd_buf, NOC_RET_ADDR_LO, dst);
    NOC_CMD_BUF_WRITE_REG(noc_index, read_cmd_buf, NOC_TARG_ADDR_LO, src);
    NOC_CMD_BUF_WRITE_REG(noc_index, read_cmd_buf, NOC_TARG_ADDR_COORDINATE, xy);
    NOC_CMD_BUF_WRITE_REG(noc_index, read_cmd_buf, NOC_CMD_CTRL, NOC_CTRL_SEND_REQ);
}

// one corner stick (32 channels) -> the face rows at dst (channels 0..15) and dst + 512 (16..31). pos: RM page
// (VSRC 0) or slice * TPH * 32 + row (VSRC 1).
// VSRC 3 (BEVFORMER_DEC_VALUE=fused, D20 round 3): the value is the projection itself, TILE [1, 1, SUB h w, H * 32]
// (no head split): the head block j of map row pos is tile (pos / 32) * H + j; g_hj = the current item's head
static uint32_t g_hj = 0;
static uint32_t g_seg[8] = {SEG_CT[0], SEG_CT[1], SEG_CT[2], SEG_CT[3], SEG_CT[4], SEG_CT[5], SEG_CT[6], SEG_CT[7]};

static inline uint32_t segment(uint32_t b) {
    if constexpr (NSEG == 0) {
        return b / BPS;
    } else {
        uint32_t s = 0;
        while (s + 1 < NSEG && b >= g_seg[s]) {
            ++s;
        }
        return s;
    }
}

template <typename A>
static inline void gather(const A& v_acc, uint32_t pos, bool ok, uint64_t zeros, uint32_t dst) {
    if (!ok) {
        noc_async_read(zeros, dst, 32);
        noc_async_read(zeros, dst + 512, 32);
        return;
    }
    uint64_t s;
    uint32_t hi;
    if constexpr (VSRC == 0) {
        s = v_acc.get_noc_addr(pos);
        hi = 32;
    } else {
        const uint32_t r = pos & 31;
        const uint32_t t = VSRC == 3 ? (pos >> 5) * H + g_hj : pos >> 5;
        s = v_acc.get_noc_addr(t, ((r >> 4) << 10) + ((r & 15) << 5));
        hi = 512;
    }
#ifndef MSDA_K_NOREAD
    noc_async_read(s, dst, 32);
    noc_async_read(s + hi, dst + 512, 32);
#endif
}

static inline void zero_l1(uint32_t addr, uint32_t bytes) {
    const uint64_t z = get_noc_addr(MEM_ZEROS_BASE);
    for (uint32_t o = 0; o < bytes; o += MEM_ZEROS_SIZE) {
        noc_async_read(z, addr + o, MEM_ZEROS_SIZE);
    }
}

void kernel_main() {
    const uint32_t ci = get_absolute_logical_y() * GX + get_absolute_logical_x();
    if (ci >= NC) {
        return;
    }
    // strided items (w = core, core + NC, ..) whenever per-item work varies (skipped points, padding blocks): every
    // core gets a sample of all segments / heads instead of one contiguous range
    constexpr bool STRIDE = SKIP || SKIPP;
    const uint32_t w0 = STRIDE ? ci : ci * NWORK / NC;
    const uint32_t w1 = STRIDE ? NWORK : (ci + 1) * NWORK / NC;
    const uint32_t wstep = STRIDE ? NC : 1;
    if (w0 >= w1) {
        return;
    }
    const auto v_acc = TensorAccessor(v_args, get_common_arg_val<uint32_t>(0), VPAGE);
    const auto l_acc = TensorAccessor(l_args, get_common_arg_val<uint32_t>(1), TB32);
    const auto a_acc = TensorAccessor(a_args, get_common_arg_val<uint32_t>(2), TB32);
    const auto o_acc = TensorAccessor(o_args, get_common_arg_val<uint32_t>(3), TB16);
    const uint64_t zeros = get_noc_addr(MEM_ZEROS_BASE);
    if constexpr (SEG_RT) {
        const auto s_acc = TensorAccessor(s_args, get_common_arg_val<uint32_t>(4), 32);
        cb_reserve_back(cb_loc, 1);
        const uint32_t sbuf = get_write_ptr(cb_loc);
        noc_async_read(s_acc.get_noc_addr(0), sbuf, 32);
        noc_async_read_barrier();
        volatile tt_l1_ptr uint32_t* sv = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(sbuf);
        for (uint32_t i = 0; i < 8; ++i) {
            g_seg[i] = sv[i];
        }
    }

    if constexpr (MAKES_E) {
        // E_p (bf16): row p all ones, so W @ E_p broadcasts column p of W over the 32 channels
        cb_reserve_back(cb_e, P);
        const uint32_t e_addr = get_write_ptr(cb_e);
        zero_l1(e_addr, P * TB16);
        noc_async_read_barrier();
        volatile tt_l1_ptr uint16_t* e = reinterpret_cast<volatile tt_l1_ptr uint16_t*>(e_addr);
        for (uint32_t p = 0; p < P; ++p) {
            for (uint32_t c = 0; c < 32; ++c) {
                e[p * (TB16 / 2) + tile_elem(ECOL + p, c)] = 0x3F80;
            }
        }
        cb_push_back(cb_e, P);
    }
    if constexpr (SM && MAKES_E) {
        // the softmax's reduce scalers, as ttnn's softmax reader makes them; the half masks (fp32 1 / 0 per column:
        // RISC h owns the points [h P / 2, (h + 1) P / 2)); the logit pages pre-filled with PAD_LOGIT
        dataflow_kernel_lib::calculate_and_prepare_reduce_scaler<cb_scmax, ckernel::PoolType::MAX,
                                                                 ckernel::ReduceDim::REDUCE_ROW>();
        dataflow_kernel_lib::calculate_and_prepare_reduce_scaler<cb_scsum, ckernel::PoolType::SUM,
                                                                 ckernel::ReduceDim::REDUCE_ROW>();
        cb_reserve_back(cb_msk, 2);
        volatile tt_l1_ptr uint32_t* m = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(get_write_ptr(cb_msk));
        for (uint32_t h = 0; h < 2; ++h) {
            for (uint32_t r = 0; r < 32; ++r) {
                for (uint32_t c = 0; c < 32; ++c) {
#ifdef MSDA_K_COLB
                    m[h * 1024 + tile_elem(r, c)] = (c % 4 == 0 && c / 4 >= h * PH && c / 4 < (h + 1) * PH) ? 0x3F800000u : 0u;
#else
                    m[h * 1024 + tile_elem(r, c)] =
                        (c >= ECOL + h * PH && c < ECOL + (h + 1) * PH) ? 0x3F800000u : 0u;
#endif
                }
            }
        }
        cb_push_back(cb_msk, 2);
        cb_reserve_back(cb_lg, 2);
        volatile tt_l1_ptr uint32_t* lg = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(get_write_ptr(cb_lg));
        for (uint32_t i = 0; i < 2048; ++i) {
            lg[i] = PAD_BITS;
        }
    }
    // the geo pages: zero once (columns >= P and the right faces stay zero / finite forever)
    cb_reserve_back(cb_geo, 6);
    zero_l1(get_write_ptr(cb_geo), 6 * TB32);
    if constexpr (SKIP || SKIPP) {
        cb_reserve_back(cb_in, 2 * NS);
        zero_l1(get_write_ptr(cb_in), 2 * NS * TB16);
    }
    // PREF (the in-kernel softmax with pair maps: the t1 self-attention): the next item's loc and logit tiles are read
    // while the current item's points are processed (two buffers each), hiding their DRAM latency
    constexpr bool PREF = SM == 1 && VSRC == 2 && LOC_HS > 0 && !LOCF && ECOL == 0;
    cb_reserve_back(cb_loc, PREF ? 2 : 1);
    const uint32_t lbuf = get_write_ptr(cb_loc);
    const uint32_t sbuf0 = (SM && MAKES_E) ? get_write_ptr(cb_scr) : 0;
    uint32_t bbuf = 0;
    if constexpr (LOCF) {
        cb_reserve_back(cb_base, 1);
        bbuf = get_write_ptr(cb_base);
    }
    const auto bs_acc = TensorAccessor(b_args, get_common_arg_val<uint32_t>(LOCF ? 5 : 3), TB32);
    volatile tt_l1_ptr uint32_t* bbits = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(bbuf);
    volatile tt_l1_ptr uint32_t* lbits = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(lbuf);
    constexpr uint32_t BCOL = LOC_OFF % 32;
    noc_async_read_barrier();
    volatile tt_l1_ptr int32_t* loc = reinterpret_cast<volatile tt_l1_ptr int32_t*>(lbuf);

    uint32_t prev = 0xFFFFFFFF;
    auto head_reads = [&](uint32_t wq, uint32_t lb, uint32_t sb) {
        const uint32_t bq = wq / H;
        const uint32_t jq = wq - bq * H;
        noc_async_read(l_acc.get_noc_addr(bq * LOC_TW + (jq * LOC_HS + LOC_OFF) / 32), lb, TB32);
        if constexpr (SM && MAKES_E) {
            noc_async_read(a_acc.get_noc_addr(bq * AT_TW + (jq * P) / 32), sb, TB32);
        }
    };
    uint32_t cur = 0;
    if constexpr (PREF) {
        if (w0 < w1) {
            head_reads(w0, lbuf, sbuf0);
            noc_async_read_barrier();
        }
    }
    uint32_t nrd = 0;
    const uint32_t vaddr = get_common_arg_val<uint32_t>(0);
    const uint32_t my_xy = NOC_XY_ENCODING(my_x[noc_index], my_y[noc_index]);
#ifdef MSDA_K_TIMING
    uint32_t t_res = 0, t_bar = 0, t_loop = 0, t_out = 0, t_hdr = 0, t0, t1;
#endif
    for (uint32_t w = w0; w < w1; w += wstep) {
        // head-minor items (w = b * H + j): the cores running at the same time cover all the heads' maps of a camera,
        // not one map (a small level's map is ~100 pages: one map at a time made hot spots of its banks); the output
        // tile of item w is tile w
        const uint32_t b = w / H;
        const uint32_t j = w - b * H;
        // VSRC 0: page of the map's pixel 0; VSRC 1: the slice's first tile row + the map's first row in it
        const uint32_t jm = j / HDIV;
        const uint32_t sg = segment(b);
        const uint32_t vbase = VSRC == 0   ? (jm * SUB + sg) * MAP
                               : VSRC == 2 ? (jm * SUB + sg) * HV * (WV + 1)
                               : VSRC == 4 ? (jm * SUB + sg) * (HV + 1) * (WV + 1)
                               : VSRC == 3 ? sg * MAP
                                           : jm * TPH * 32 + sg * MAP;
        g_hj = j;
#ifdef MSDA_K_TIMING
        t0 = TNOW();
#endif
        cb_reserve_back(cb_geo, 3);
        cb_reserve_back(cb_in, NS);
#ifdef MSDA_K_TIMING
        t1 = TNOW();
        t_res += t1 - t0;
#endif
        const uint32_t g_addr = get_write_ptr(cb_geo);
        const uint32_t in_base = get_write_ptr(cb_in);
        const uint32_t ltile = LOC_HS == 0 ? j * NB + b : b * LOC_TW + (j * LOC_HS + LOC_OFF) / 32;
        const uint32_t lcol = LOC_HS == 0 ? 0 : (j * LOC_HS + LOC_OFF) % 32;
        const uint32_t lcur = PREF ? lbuf + cur * TB32 : lbuf;
        const uint32_t scur = PREF ? sbuf0 + cur * TB32 : sbuf0;
        if constexpr (PREF) {
            if (w + wstep < w1) {
                head_reads(w + wstep, lbuf + (cur ^ 1) * TB32, sbuf0 + (cur ^ 1) * TB32);
            }
            cur ^= 1;
        } else {
            noc_async_read(l_acc.get_noc_addr(ltile), lbuf, TB32);
        }
        if constexpr (LOCF) {
            noc_async_read(bs_acc.get_noc_addr(b * 2 + (LOC_OFF % 64) / 32), bbuf, TB32);
        }
        if constexpr (SM) {
            if constexpr (MAKES_E && !PREF) {
                noc_async_read(a_acc.get_noc_addr(b * AT_TW + (SM == 2 ? j : (j * P) / 32)), get_write_ptr(cb_scr),
                               TB32);
            }
        } else {
            noc_async_read(a_acc.get_noc_addr(j * NB + b), g_addr + 2 * TB32, TB32);
        }
        if constexpr (!PREF) {
            noc_async_read_barrier();
        }
        if constexpr (SM && MAKES_E) {
            // the head's logit tile: columns 0..P-1 <- compact columns (j P) % 32 + p; columns >= P keep PAD
            cb_reserve_back(cb_lg, 1);
            volatile tt_l1_ptr uint32_t* lg = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(get_write_ptr(cb_lg));
            volatile tt_l1_ptr uint32_t* src = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(scur);
            const uint32_t acol = (j * P) % 32;
            if constexpr (SM == 2) {
                for (uint32_t r = 0; r < 32; ++r) {
                    const bool ok = b * 32 + r < NQ;
                    for (uint32_t c = 0; c < 32; ++c) {
                        lg[tile_elem(r, c)] = ok ? src[tile_elem(r, c)] : 0u;
                    }
                }
            } else {
                // the P compact columns of a head sit in one face row ((j P) % 16 + P <= 16): row base + offsets
                uint32_t* lgn = const_cast<uint32_t*>(lg);
                const uint32_t* srn = const_cast<const uint32_t*>(src) + ((acol >> 4) << 8) + (acol & 15);
                for (uint32_t r = 0; r < 32; ++r) {
                    const uint32_t rb = ((r >> 4) << 9) + ((r & 15) << 4);
                    const bool ok = b * 32 + r < NQ;
#pragma GCC unroll 8
                    for (uint32_t p = 0; p < P; ++p) {
#ifdef MSDA_K_COLB
                        lgn[rb + 4 * p] = ok ? srn[rb + p] : 0u;     // point p in column 4 p (the rest PAD)
#else
                        lgn[rb + p] = ok ? srn[rb + p] : 0u;
#endif
                    }
                }
                asm volatile("" ::: "memory");
            }
            cb_push_back(cb_lg, 1);
        }
#ifdef MSDA_K_TIMING
        t0 = TNOW();
        t_hdr += t0 - t1;
#endif
        if constexpr (VSRC == 2 || VSRC == 4) {
            pair_read_state();
        }
        volatile tt_l1_ptr uint32_t* fx = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(g_addr);
        volatile tt_l1_ptr uint32_t* fy = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(g_addr + TB32);
        volatile tt_l1_ptr uint32_t* at = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(g_addr + 2 * TB32);
        // the other RISC's points carry zero weight in this copy (their fx / fy here are stale but finite); SM: the
        // compute kernel applies the half mask to the softmax instead
        if constexpr (!SM) {
            for (uint32_t r = 0; r < 32; ++r) {
                for (uint32_t p = 0; p < P; ++p) {
                    if (p < P0 || p >= P0 + PH) {
                        at[tile_elem(r, p)] = 0;
                    } else if constexpr (ATT_COL0 > 0) {
                        at[tile_elem(r, p)] = at[tile_elem(r, ATT_COL0 + p)];   // ATT_COL0 >= P: no overlap
                    }
                }
            }
        }
        // fast path (pair maps, the merged loc layout, no fp32 offsets): row bases instead of per-element tile
        // indexing; a head's 2P loc columns lie in one face row ((j LOC_HS + LOC_OFF) % 16 + 2P <= 16 in every use)
        constexpr bool FAST = VSRC == 2 && LOC_HS > 0 && !LOCF && ECOL == 0;
#ifdef MSDA_K_COLB
        constexpr uint32_t GC = 4;      // geo column of point p: 4 p (the compute kernel's column broadcast)
        static_assert(FAST && SM == 1 && P <= 4, "msda_k: COLB is the compact-softmax pair-map fast path");
#else
        constexpr uint32_t GC = 1;
#endif
        if constexpr (FAST) {
            const int32_t* Ln = reinterpret_cast<const int32_t*>(lcur) + ((lcol >> 4) << 8) + (lcol & 15);
            uint32_t* fxn = const_cast<uint32_t*>(fx);
            uint32_t* fyn = const_cast<uint32_t*>(fy);
            uint32_t* atn = const_cast<uint32_t*>(at);
            for (uint32_t r = 0; r < 32; ++r) {
                const uint32_t rb = ((r >> 4) << 9) + ((r & 15) << 4);
                const uint32_t sb = in_base + r * 128;
                if (b * 32 + r >= NQ) {
#pragma GCC unroll 4
                    for (uint32_t p = P0; p < P0 + PH; ++p) {
                        fxn[rb + GC * p] = FRAC0;
                        fyn[rb + GC * p] = FRAC0;
                        if constexpr (!SM) {
                            atn[rb + p] = 0;
                        }
                        if constexpr (!SKIPP) {
                            pair_read(my_xy, MEM_ZEROS_BASE, sb + (p - P0) * 4 * TB16);
                            pair_read(my_xy, MEM_ZEROS_BASE, sb + (p - P0) * 4 * TB16 + 2 * TB16);
                            nrd += 2;
                        }
                    }
                    continue;
                }
                const int32_t* lr = Ln + rb;
#pragma GCC unroll 4
                for (uint32_t p = P0; p < P0 + PH; ++p) {
                    const int32_t vx = lr[2 * p];
                    const int32_t vy = lr[2 * p + 1];
                    const int32_t x0 = vx >> 16;
                    const int32_t y0 = vy >> 16;
                    const uint32_t blk = sb + (p - P0) * 4 * TB16;
                    const bool xp = static_cast<uint32_t>(x0 + 1) <= static_cast<uint32_t>(WV);
                    const bool yv0 = static_cast<uint32_t>(y0) < static_cast<uint32_t>(HV);
                    const bool yv1 = static_cast<uint32_t>(y0 + 1) < static_cast<uint32_t>(HV);
                    if constexpr (SKIPP) {
                        if (!(xp && (yv0 || yv1))) {
                            atn[rb + p] = 0;
                            continue;
                        }
                    }
                    fxn[rb + GC * p] = q16_frac(static_cast<uint32_t>(vx) & 0xFFFF);
                    fyn[rb + GC * p] = q16_frac(static_cast<uint32_t>(vy) & 0xFFFF);
#ifdef MSDA_K_NOREAD
                    continue;
#endif
                    const uint32_t pg = vbase + static_cast<uint32_t>(y0) * (WV + 1) + static_cast<uint32_t>(x0 + 1);
                    if (xp && yv0) {
                        const uint32_t row = udivsi3_const_divisor<NUM_L1_BANKS>(pg);
                        const uint32_t bank = pg - row * NUM_L1_BANKS;
                        pair_read(l1_bank_to_noc_xy[noc_index][bank], vaddr + row * VPAGE_AL + bank_to_l1_offset[bank], blk);
                    } else {
                        pair_read(my_xy, MEM_ZEROS_BASE, blk);
                    }
                    if (xp && yv1) {
                        const uint32_t pb = pg + WV + 1;
                        const uint32_t row = udivsi3_const_divisor<NUM_L1_BANKS>(pb);
                        const uint32_t bank = pb - row * NUM_L1_BANKS;
                        pair_read(l1_bank_to_noc_xy[noc_index][bank], vaddr + row * VPAGE_AL + bank_to_l1_offset[bank],
                                  blk + 2 * TB16);
                    } else {
                        pair_read(my_xy, MEM_ZEROS_BASE, blk + 2 * TB16);
                    }
                    nrd += 2;
                }
            }
            asm volatile("" ::: "memory");
        }
        for (uint32_t r = 0; r < (FAST ? 0u : 32u); ++r) {
            const uint32_t roff = (((r >> 4) << 1) << 9) + ((r & 15) << 5);  // face (r / 16, 0), row r % 16
            const bool row_ok = b * 32 + r < NQ;
            for (uint32_t p = P0; p < P0 + PH; ++p) {
                const uint32_t dst = in_base + (p - P0) * 4 * TB16 + roff;
                const uint32_t ew = tile_elem(r, ECOL + p);
                if (!row_ok) {
                    fx[ew] = FRAC0;
                    fy[ew] = FRAC0;
                    if constexpr (!SM) {
                        at[ew] = 0;
                    }
                    if constexpr (SKIP || SKIPP) {
                        continue;
                    }
                    if constexpr (VSRC == 2) {
                        const uint32_t blk = in_base + (p - P0) * 4 * TB16 + r * 128;
                        noc_async_read(zeros, blk, 128);
                        noc_async_read(zeros, blk + 2 * TB16, 128);
                        continue;
                    }
                    if constexpr (VSRC == 4) {
                        noc_async_read(zeros, in_base + (p - P0) * 4 * TB16 + r * 256, 256);
                        continue;
                    }
                    for (uint32_t c = 0; c < 4; ++c) {
                        noc_async_read(zeros, dst + c * TB16, 32);
                        noc_async_read(zeros, dst + c * TB16 + 512, 32);
                    }
                    continue;
                }
                int32_t vx, vy;
                if constexpr (LOCF) {
                    vx = f2i(lbits[tile_elem(r, lcol + 2 * p)]) + f2i(bbits[tile_elem(r, BCOL + 2 * p)]);
                    vy = f2i(lbits[tile_elem(r, lcol + 2 * p + 1)]) + f2i(bbits[tile_elem(r, BCOL + 2 * p + 1)]);
                } else {
                    vx = loc[tile_elem(r, lcol + 2 * p)];
                    vy = loc[tile_elem(r, lcol + 2 * p + 1)];
                }
                vx = vx > LOC_LIM ? LOC_LIM : (vx < -LOC_LIM ? -LOC_LIM : vx);
                vy = vy > LOC_LIM ? LOC_LIM : (vy < -LOC_LIM ? -LOC_LIM : vy);
                const int32_t x0 = vx >> 16;
                const int32_t y0 = vy >> 16;
                fx[ew] = q16_frac(static_cast<uint32_t>(vx) & 0xFFFF);
                fy[ew] = q16_frac(static_cast<uint32_t>(vy) & 0xFFFF);
                const bool xv0 = x0 >= 0 && x0 < WV, xv1 = x0 + 1 >= 0 && x0 + 1 < WV;
                const bool yv0 = y0 >= 0 && y0 < HV, yv1 = y0 + 1 >= 0 && y0 + 1 < HV;
                if constexpr (SKIP) {
                    static_assert(!(SKIP && SM), "msda_k: SKIP and SM are exclusive");
                    if (!((yv0 || yv1) && (xv0 || xv1))) {
                        at[ew] = 0;
                        continue;
                    }
                }
                if constexpr (VSRC == 4) {
                    // staging block of point p: [32 x 128] row-major at + 0 (4 tiles); row r: 256 B = NW | NE | SW | SE
                    const uint32_t blk = in_base + (p - P0) * 4 * TB16 + r * 256;
                    if (!(x0 >= -1 && x0 < WV && y0 >= -1 && y0 < HV)) {
                        if constexpr (SKIPP) {
                            at[ew] = 0;
                        } else {
                            pair_read(my_xy, MEM_ZEROS_BASE, blk);
                            nrd += 1;
                        }
                        continue;
                    }
#ifdef MSDA_K_NOREAD
                    continue;
#endif
                    const uint32_t pg = vbase + static_cast<uint32_t>((y0 + 1) * (WV + 1) + x0 + 1);
                    const uint32_t row = udivsi3_const_divisor<NUM_L1_BANKS>(pg);
                    const uint32_t bank = pg - row * NUM_L1_BANKS;
                    pair_read(l1_bank_to_noc_xy[noc_index][bank], vaddr + row * VPAGE_AL + bank_to_l1_offset[bank], blk);
                    nrd += 1;
                    continue;
                }
                if constexpr (VSRC == 2) {
                    // staging blocks of point p: top (NW | NE) at + 0, bottom (SW | SE) at + 2 tiles; row r: 128 B
                    const uint32_t blk = in_base + (p - P0) * 4 * TB16 + r * 128;
                    const bool xp = x0 >= -1 && x0 < WV;                 // page i = x0 + 1 in [0, WV]
                    if constexpr (SKIPP) {
                        if (!(xp && (yv0 || yv1))) {
                            at[ew] = 0;
                            continue;
                        }
                    }
                    const uint32_t pg = vbase + static_cast<uint32_t>(y0 * (WV + 1) + x0 + 1);
#ifdef MSDA_K_NOREAD
                    continue;
#endif
                    // top page pg, bottom page pg + WV + 1 (bank = page % NUM_L1_BANKS, row = page / NUM_L1_BANKS)
                    if (xp && yv0) {
                        const uint32_t row = udivsi3_const_divisor<NUM_L1_BANKS>(pg);
                        const uint32_t bank = pg - row * NUM_L1_BANKS;
                        pair_read(l1_bank_to_noc_xy[noc_index][bank], vaddr + row * VPAGE_AL + bank_to_l1_offset[bank], blk);
                    } else {
                        pair_read(my_xy, MEM_ZEROS_BASE, blk);
                    }
                    if (xp && yv1) {
                        const uint32_t pb = pg + WV + 1;
                        const uint32_t row = udivsi3_const_divisor<NUM_L1_BANKS>(pb);
                        const uint32_t bank = pb - row * NUM_L1_BANKS;
                        pair_read(l1_bank_to_noc_xy[noc_index][bank], vaddr + row * VPAGE_AL + bank_to_l1_offset[bank],
                                  blk + 2 * TB16);
                    } else {
                        pair_read(my_xy, MEM_ZEROS_BASE, blk + 2 * TB16);
                    }
                    nrd += 2;
                    continue;
                }
                const uint32_t pos = vbase + static_cast<uint32_t>(y0 * WV + x0);
                gather(v_acc, pos, yv0 && xv0, zeros, dst);
                gather(v_acc, pos + 1, yv0 && xv1, zeros, dst + TB16);
                gather(v_acc, pos + WV, yv1 && xv0, zeros, dst + 2 * TB16);
                gather(v_acc, pos + WV + 1, yv1 && xv1, zeros, dst + 3 * TB16);
            }
        }
        if constexpr (VSRC == 2 || VSRC == 4) {
            noc_reads_num_issued[noc_index] += nrd;   // the lean reads do not count themselves
            nrd = 0;
        }
#ifdef MSDA_K_TIMING
        t1 = TNOW();
        t_loop += t1 - t0;
#endif
        noc_async_read_barrier();
#ifdef MSDA_K_TIMING
        t0 = TNOW();
        t_bar += t0 - t1;
#endif
        cb_push_back(cb_geo, 3);
        cb_push_back(cb_in, NS);
        if constexpr (WRITES_OUT) {
            if (prev != 0xFFFFFFFF) {
#ifdef MSDA_K_TIMING
                t0 = TNOW();
#endif
                cb_wait_front(cb_out, 1);
#ifdef MSDA_K_TIMING
                t_out += TNOW() - t0;
#endif
                noc_async_write(get_read_ptr(cb_out), o_acc.get_noc_addr(prev), TB16);
                noc_async_writes_flushed();
                cb_pop_front(cb_out, 1);
            }
        }
        prev = w;
    }
    if constexpr (WRITES_OUT) {
        cb_wait_front(cb_out, 1);
        noc_async_write(get_read_ptr(cb_out), o_acc.get_noc_addr(prev), TB16);
        noc_async_write_barrier();
        cb_pop_front(cb_out, 1);
    }
#ifdef MSDA_K_TIMING
    DeviceTimestampedData("res", t_res);
    DeviceTimestampedData("hdr", t_hdr);
    DeviceTimestampedData("loop", t_loop);
    DeviceTimestampedData("bar", t_bar);
    DeviceTimestampedData("out", t_out);
#endif
}