File size: 27,480 Bytes
9d8d25c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// SPDX-License-Identifier: Apache-2.0
// K1 segment_reduce (ttaw.ops.segment, PLAN.md 1.3): per-segment MAX over the rows of a tensor sorted by segment.
//
//   out[s, :] = max(x[off[s] : off[s + 1], :])      for s in [0, NUM_SEG); empty segments -> FILL_BITS
//
// x: [1, 1, NUM_ROWS, C] interleaved DRAM, TILE (IN_TILE = 1) or ROW_MAJOR, bf16 or fp32; off: uint32 ROW_MAJOR
// [1, >= NUM_SEG + 1] interleaved DRAM (one page; CSR offsets, non-decreasing); out: [1, 1, NUM_SEG, C] ROW_MAJOR
// interleaved DRAM, bf16 (round to nearest even) or fp32. Exact: the maximum is taken on integer keys of the
// float bit patterns (key = bits ^ ((bits >> 31) & 0x7fffffff), signed order == float order, -0 < +0), so no float
// arithmetic happens on the RISC-V (no F extension) and bf16 / fp32 inputs come out bit-exact (fp32 -> bf16 is a
// monotonic rounding, so max-then-round == round-then-max). NaN is not supported (not produced by the models).
//
// Work split (deterministic, data-dependent, no per-core runtime args): NUM_WORKERS workers = SLOTS data-movement
// RISC-Vs per core on a GW-wide core rectangle starting at (X0, Y0); worker w = core_index * SLOTS + SLOT. The cost
// of segment s is off[s] + s (its rows plus one output row; strictly increasing in s), T = off[S] + S. Worker w owns
// the segments whose cost lies in [w T / W, (w + 1) T / W): it finds them by two binary searches over off (64-byte
// probes from DRAM), then streams its contiguous row range in units of 32 rows (one tile-row in TILE mode) with
// double buffering, reduces each segment into an L1 accumulator and writes one output row per segment (a ring of
// OUT_RING staging rows). Every segment is written by exactly one worker; nothing is shared between workers.
//
// Runtime args: COMMON only [x_addr, off_addr, out_addr] (P3 rule: per-core work derives from the core coordinates;
// the arg layout is fixed by the compile-time args). Hang-protocol notes (PLAN.md 4.4): no CB is pushed or popped
// (CBs are plain L1 scratch: data 2 units, offsets window, probe block, accumulator, output ring; sizes checked by
// the host builder), no multicast, no semaphores; every DRAM read has matching 64-byte alignment of source and
// destination (Blackhole NOC_DRAM_READ_ALIGNMENT_BYTES), every read is waited on by noc_async_read_barrier (which
// also invalidates the Blackhole L1 data cache) before the data are used, staging rows are reused only after
// noc_async_writes_flushed, and the kernel ends with noc_async_write_barrier. Offsets are clamped to [0, NUM_ROWS]
// and to non-decreasing order, so a corrupt table can never make the kernel read outside x.
#include <cstdint>

#include "api/dataflow/dataflow_api.h"

constexpr uint32_t IN_TILE = get_compile_time_arg_val(0);      // 1: TILE input, 0: ROW_MAJOR input
constexpr uint32_t IN_BYTES = get_compile_time_arg_val(1);     // input element bytes: 2 (bf16) or 4 (fp32)
constexpr uint32_t OUT_BYTES = get_compile_time_arg_val(2);    // output element bytes: 2 (bf16, RNE) or 4 (fp32)
constexpr uint32_t C = get_compile_time_arg_val(3);            // channels (multiple of 32)
constexpr uint32_t NUM_ROWS = get_compile_time_arg_val(4);     // input rows (multiple of 32): the read bound
constexpr uint32_t NUM_SEG = get_compile_time_arg_val(5);      // output rows (segments)
constexpr uint32_t NUM_WORKERS = get_compile_time_arg_val(6);  // workers of the program
constexpr uint32_t SLOTS = get_compile_time_arg_val(7);        // workers per core (1 or 2)
constexpr uint32_t SLOT = get_compile_time_arg_val(8);         // this kernel's slot on its core
constexpr uint32_t X0 = get_compile_time_arg_val(9);           // core rectangle: first logical x
constexpr uint32_t Y0 = get_compile_time_arg_val(10);          //                 first logical y
constexpr uint32_t GW = get_compile_time_arg_val(11);          //                 width in cores
constexpr uint32_t CB_DATA = get_compile_time_arg_val(12);     // 2 units of input rows (+ 64 B alignment slack)
constexpr uint32_t CB_OFF = get_compile_time_arg_val(13);      // offsets window: OFF_CHUNK uint32 (+ 64 B)
constexpr uint32_t CB_PROBE = get_compile_time_arg_val(14);    // one 64-byte probe block (+ 64 B)
constexpr uint32_t CB_ACC = get_compile_time_arg_val(15);      // C int32 keys
constexpr uint32_t CB_OUT = get_compile_time_arg_val(16);      // OUT_RING output rows (+ 64 B)
constexpr uint32_t OUT_RING = get_compile_time_arg_val(17);    // staging rows in flight
constexpr uint32_t OFF_CHUNK = get_compile_time_arg_val(18);   // offsets per window (multiple of 16)
constexpr uint32_t FILL_BITS = get_compile_time_arg_val(19);   // fp32 bits written for an empty segment
constexpr uint32_t OFF_PAGE_BYTES = get_compile_time_arg_val(20);  // page (= tensor) size of off, bytes
constexpr uint32_t UNIT_PATH = get_compile_time_arg_val(21);  // 1: in-register path for one-unit segments (0.23.4)
constexpr auto x_args = TensorAccessorArgs<22>();
constexpr auto off_args = TensorAccessorArgs<x_args.next_compile_time_args_offset()>();
constexpr auto out_args = TensorAccessorArgs<off_args.next_compile_time_args_offset()>();

constexpr uint32_t UNIT_ROWS = 32;                              // rows per streamed unit (one tile-row)
constexpr uint32_t CT = C / 32;                                 // 32-column tiles per row
constexpr uint32_t TILE_ELEMS = 1024;
constexpr uint32_t IN_PAGE_BYTES = IN_TILE ? TILE_ELEMS * IN_BYTES : C * IN_BYTES;
constexpr uint32_t PAGES_PER_UNIT = IN_TILE ? CT : UNIT_ROWS;
constexpr uint32_t UNIT_BYTES = PAGES_PER_UNIT * IN_PAGE_BYTES;
constexpr uint32_t OUT_ROW_BYTES = C * OUT_BYTES;
constexpr uint32_t OFF_ALIGNED_BYTES = (OFF_PAGE_BYTES + 63u) & ~63u;
constexpr uint32_t NUM_UNITS = NUM_ROWS / UNIT_ROWS;

static_assert(C % 32 == 0, "C must be a multiple of 32");
static_assert(NUM_ROWS % UNIT_ROWS == 0, "NUM_ROWS must be a multiple of 32");
static_assert(IN_BYTES == 2 || IN_BYTES == 4, "bf16 or fp32 input");
static_assert(OUT_BYTES == 2 || OUT_BYTES == 4, "bf16 or fp32 output");
static_assert(OFF_CHUNK % 16 == 0 && OFF_CHUNK >= 16, "OFF_CHUNK must be a multiple of 16");
static_assert(OUT_RING >= 1, "OUT_RING >= 1");
static_assert(IN_PAGE_BYTES % 64 == 0, "input pages must be 64-byte multiples (DRAM read alignment)");
static_assert(OUT_ROW_BYTES % 16 == 0, "output rows must be 16-byte multiples (DRAM write alignment)");

#define COMPILER_BARRIER() asm volatile("" ::: "memory")

#define ACC_LOCAL (C <= 256)
#if ACC_LOCAL
static int32_t acc_local[C];
#endif

static inline uint32_t align64(uint32_t a) { return (a + 63u) & ~63u; }

// float bits <-> signed key (an involution); signed comparison of keys == float comparison (no NaN)
static inline int32_t to_key(uint32_t bits) {
    const int32_t b = static_cast<int32_t>(bits);
    return b ^ ((b >> 31) & 0x7fffffff);
}
static inline uint32_t from_key(int32_t k) { return static_cast<uint32_t>(k ^ ((k >> 31) & 0x7fffffff)); }

static inline uint16_t to_bf16_rne(uint32_t bits) {
    return static_cast<uint16_t>((bits + 0x7fffu + ((bits >> 16) & 1u)) >> 16);
}

void kernel_main() {
    const uint32_t x_addr = get_common_arg_val<uint32_t>(0);
    const uint32_t off_addr = get_common_arg_val<uint32_t>(1);
    const uint32_t out_addr = get_common_arg_val<uint32_t>(2);

    const uint32_t core = (get_absolute_logical_y() - Y0) * GW + (get_absolute_logical_x() - X0);
    const uint32_t w = core * SLOTS + SLOT;
    if (w >= NUM_WORKERS) {
        return;
    }

    const auto xa = TensorAccessor(x_args, x_addr, IN_PAGE_BYTES);
    const auto oa = TensorAccessor(off_args, off_addr, OFF_PAGE_BYTES);
    const auto ya = TensorAccessor(out_args, out_addr, OUT_ROW_BYTES);

    const uint32_t data_l1 = align64(get_write_ptr(CB_DATA));
    const uint32_t off_l1 = align64(get_write_ptr(CB_OFF));
    const uint32_t probe_l1 = align64(get_write_ptr(CB_PROBE));
    const uint32_t out_l1 = align64(get_write_ptr(CB_OUT));
    // accumulator: in the RISC-V's local data memory (ACC_LOCAL, C <= 256: 1 KiB of .bss; 0.23.3) instead of L1 --
    // every input element costs one accumulator load and one store, which L1 makes the bottleneck
#if ACC_LOCAL
    int32_t* acc = acc_local;
#else
    int32_t* acc = reinterpret_cast<int32_t*>(get_write_ptr(CB_ACC));
#endif

    // ---- offsets: single 64-byte probes (binary search) and a streamed window (the worker's segments)
    auto probe = [&](uint32_t s) -> uint32_t {
        const uint32_t byte = s * 4u;
        noc_async_read(oa.get_noc_addr(0, byte & ~63u), probe_l1, 64);
        noc_async_read_barrier();
        COMPILER_BARRIER();
        const uint32_t v = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(probe_l1)[(byte & 63u) >> 2];
        return v < NUM_ROWS ? v : NUM_ROWS;
    };
    uint32_t win0 = 0xffffffffu;  // first offset index held in the window (multiple of 16)
    auto off_at = [&](uint32_t s) -> uint32_t {
        if (win0 == 0xffffffffu || s < win0 || s >= win0 + OFF_CHUNK) {
            win0 = s & ~15u;
            const uint32_t start = win0 * 4u;
            uint32_t bytes = OFF_CHUNK * 4u;
            if (start + bytes > OFF_ALIGNED_BYTES) {
                bytes = OFF_ALIGNED_BYTES - start;
            }
            noc_async_read(oa.get_noc_addr(0, start), off_l1, bytes);
            noc_async_read_barrier();
            COMPILER_BARRIER();
        }
        const uint32_t v = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(off_l1)[s - win0];
        return v < NUM_ROWS ? v : NUM_ROWS;
    };

    // ---- this worker's segments [s_lo, s_hi): costs off[s] + s in [w T / W, (w + 1) T / W)
    const uint32_t total = probe(NUM_SEG) + NUM_SEG;
    auto search = [&](uint32_t target) -> uint32_t {  // smallest s in [0, NUM_SEG] with off[s] + s >= target
        uint32_t lo = 0, hi = NUM_SEG;
        while (lo < hi) {
            const uint32_t mid = (lo + hi) >> 1;
            if (probe(mid) + mid >= target) {
                hi = mid;
            } else {
                lo = mid + 1;
            }
        }
        return lo;
    };
    const uint32_t t0 = static_cast<uint32_t>((static_cast<uint64_t>(w) * total) / NUM_WORKERS);
    const uint32_t t1 = static_cast<uint32_t>((static_cast<uint64_t>(w + 1) * total) / NUM_WORKERS);
    const uint32_t s_lo = (w == 0) ? 0 : search(t0);
    const uint32_t s_hi = (w + 1 == NUM_WORKERS) ? NUM_SEG : search(t1);
    if (s_lo >= s_hi) {
        return;
    }

    // ---- input rows: units of 32 rows, two L1 slots, the next unit prefetched while the current one is reduced
    uint32_t row_last = off_at(s_lo);  // largest row this worker reads (+1), monotone over its segments
    {
        const uint32_t r_end = off_at(s_hi);
        if (r_end > row_last) {
            row_last = r_end;
        }
    }
    const uint32_t unit_last = row_last > 0 ? (row_last - 1) / UNIT_ROWS : 0;
    auto issue_unit = [&](uint32_t u, uint32_t slot) {
        const uint32_t dst = data_l1 + slot * UNIT_BYTES;
        const uint32_t first_page = IN_TILE ? u * CT : u * UNIT_ROWS;
        for (uint32_t p = 0; p < PAGES_PER_UNIT; ++p) {
            noc_async_read(xa.get_noc_addr(first_page + p), dst + p * IN_PAGE_BYTES, IN_PAGE_BYTES);
        }
    };
    uint32_t cur_unit = 0xffffffffu, cur_slot = 0;
    bool next_ready = false;  // the unit cur_unit + 1 is in flight into slot cur_slot ^ 1
    auto ensure_unit = [&](uint32_t u) {
        if (u == cur_unit) {
            return;
        }
        if (next_ready && u == cur_unit + 1) {
            noc_async_read_barrier();
            cur_slot ^= 1u;
        } else {
            noc_async_read_barrier();  // drain a stale prefetch before its slot is reused
            issue_unit(u, cur_slot);
            noc_async_read_barrier();
        }
        COMPILER_BARRIER();
        cur_unit = u;
        next_ready = false;
        if (u + 1 <= unit_last && u + 1 < NUM_UNITS) {
            issue_unit(u + 1, cur_slot ^ 1u);
            next_ready = true;
        }
    };

    // acc = max(acc, x[r, :]) on keys; FIRST: acc = keys of x[r, :] (the first row of a segment: the same result as
    // max(INT32_MIN, key), without the reset pass; 0.23.3). The data slot is plain memory here: the reads that filled
    // it were waited on by noc_async_read_barrier (which also invalidates the Blackhole L1 data cache) and the
    // COMPILER_BARRIER after it orders the loads, so the loads need not be volatile (0.23.3: lets them pipeline).
    auto accumulate_row = [&](uint32_t r, bool first) {
        const uint32_t i = r - cur_unit * UNIT_ROWS;
        const uint32_t base = data_l1 + cur_slot * UNIT_BYTES;
        if constexpr (IN_TILE) {
            const uint32_t face_row = (i >> 4) << 1;  // faces 0/1 (rows 0-15) or 2/3 (rows 16-31)
            for (uint32_t tc = 0; tc < CT; ++tc) {
                for (uint32_t h = 0; h < 2; ++h) {
                    const uint32_t e0 = tc * TILE_ELEMS + (face_row + h) * 256 + (i & 15u) * 16;
                    int32_t* a = acc + tc * 32 + h * 16;
                    if constexpr (IN_BYTES == 4) {
                        const uint32_t* src = reinterpret_cast<const uint32_t*>(base) + e0;
                        if (first) {
#pragma GCC unroll 16
                            for (uint32_t k = 0; k < 16; ++k) {
                                a[k] = to_key(src[k]);
                            }
                        } else {
#pragma GCC unroll 16
                            for (uint32_t k = 0; k < 16; ++k) {
                                const int32_t key = to_key(src[k]);
                                a[k] = key > a[k] ? key : a[k];
                            }
                        }
                    } else {
                        const uint16_t* src = reinterpret_cast<const uint16_t*>(base) + e0;
                        if (first) {
#pragma GCC unroll 16
                            for (uint32_t k = 0; k < 16; ++k) {
                                a[k] = to_key(static_cast<uint32_t>(src[k]) << 16);
                            }
                        } else {
#pragma GCC unroll 16
                            for (uint32_t k = 0; k < 16; ++k) {
                                const int32_t key = to_key(static_cast<uint32_t>(src[k]) << 16);
                                a[k] = key > a[k] ? key : a[k];
                            }
                        }
                    }
                }
            }
        } else {
            if constexpr (IN_BYTES == 4) {
                const uint32_t* src = reinterpret_cast<const uint32_t*>(base) + i * C;
                for (uint32_t c = 0; c < C; ++c) {
                    const int32_t key = to_key(src[c]);
                    acc[c] = (first || key > acc[c]) ? key : acc[c];
                }
            } else {
                const uint16_t* src = reinterpret_cast<const uint16_t*>(base) + i * C;
                for (uint32_t c = 0; c < C; ++c) {
                    const int32_t key = to_key(static_cast<uint32_t>(src[c]) << 16);
                    acc[c] = (first || key > acc[c]) ? key : acc[c];
                }
            }
        }
    };

    // ---- output rows: a ring of OUT_RING staging rows, reused after noc_async_writes_flushed. fill_mask (0.23.4):
    // the ring slots that already hold the empty-segment row, so a run of empty segments (every segment past the
    // frame's M) is written from L1 without re-filling the row
    static_assert(OUT_RING <= 32, "fill_mask holds 32 ring slots");
    uint32_t emitted = 0;
    uint32_t fill_mask = 0;
    auto stage = [&]() -> uint32_t {
        const uint32_t ring = emitted % OUT_RING;
        if (ring == 0 && emitted > 0) {
            noc_async_writes_flushed();
        }
        fill_mask &= ~(1u << ring);
        return out_l1 + ring * OUT_ROW_BYTES;
    };
    auto send = [&](uint32_t dst, uint32_t s) {
        COMPILER_BARRIER();
        noc_async_write(dst, ya.get_noc_addr(s), OUT_ROW_BYTES);
        ++emitted;
    };
    auto emit = [&](uint32_t s, bool empty) {
        const uint32_t ring = emitted % OUT_RING;
        if (empty && (fill_mask & (1u << ring))) {  // the slot still holds the fill row (0.23.4)
            if (ring == 0 && emitted > 0) {
                noc_async_writes_flushed();
            }
            send(out_l1 + ring * OUT_ROW_BYTES, s);
            return;
        }
        const uint32_t dst = stage();
        if (empty) {
            fill_mask |= 1u << ring;
        }
        if constexpr (OUT_BYTES == 4) {
            volatile tt_l1_ptr uint32_t* o = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(dst);
            for (uint32_t c = 0; c < C; ++c) {
                o[c] = empty ? FILL_BITS : from_key(acc[c]);
            }
        } else {
            volatile tt_l1_ptr uint16_t* o = reinterpret_cast<volatile tt_l1_ptr uint16_t*>(dst);
            const uint16_t fill = to_bf16_rne(FILL_BITS);
            for (uint32_t c = 0; c < C; ++c) {
                o[c] = empty ? fill : to_bf16_rne(from_key(acc[c]));
            }
        }
        send(dst, s);
    };
    // one-row segment (0.23.3): its max is the row itself (from_key(to_key(b)) == b), so the row is converted to the
    // output dtype straight from the data slot (the same RNE for bf16 outputs), without the accumulator
    auto emit_row = [&](uint32_t s, uint32_t r) {
        ensure_unit(r / UNIT_ROWS);
        const uint32_t i = r - cur_unit * UNIT_ROWS;
        const uint32_t base = data_l1 + cur_slot * UNIT_BYTES;
        const uint32_t dst = stage();
        auto put = [&](uint32_t c, uint32_t bits32) {
            if constexpr (OUT_BYTES == 4) {
                reinterpret_cast<volatile tt_l1_ptr uint32_t*>(dst)[c] = bits32;
            } else {
                reinterpret_cast<volatile tt_l1_ptr uint16_t*>(dst)[c] = to_bf16_rne(bits32);
            }
        };
        if constexpr (IN_TILE) {
            const uint32_t face_row = (i >> 4) << 1;
            for (uint32_t tc = 0; tc < CT; ++tc) {
                for (uint32_t h = 0; h < 2; ++h) {
                    const uint32_t e0 = tc * TILE_ELEMS + (face_row + h) * 256 + (i & 15u) * 16;
                    const uint32_t c0 = tc * 32 + h * 16;
                    if constexpr (OUT_BYTES == 2 && UNIT_PATH) {
                        // 0.23.4: bf16 outputs as packed pairs (one 32-bit store per two channels); a bf16 input
                        // pair is its own output word (RNE of a bf16-exact value is the value)
                        volatile tt_l1_ptr uint32_t* o = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(dst) + (c0 >> 1);
                        if constexpr (IN_BYTES == 4) {
                            const uint32_t* src = reinterpret_cast<const uint32_t*>(base) + e0;
#pragma GCC unroll 8
                            for (uint32_t k = 0; k < 8; ++k) {
                                o[k] = static_cast<uint32_t>(to_bf16_rne(src[2 * k])) |
                                       (static_cast<uint32_t>(to_bf16_rne(src[2 * k + 1])) << 16);
                            }
                        } else {
                            const uint32_t* src = reinterpret_cast<const uint32_t*>(base) + (e0 >> 1);
#pragma GCC unroll 8
                            for (uint32_t k = 0; k < 8; ++k) {
                                o[k] = src[k];
                            }
                        }
                    } else if constexpr (IN_BYTES == 4) {
                        const uint32_t* src = reinterpret_cast<const uint32_t*>(base) + e0;
#pragma GCC unroll 16
                        for (uint32_t k = 0; k < 16; ++k) {
                            put(c0 + k, src[k]);
                        }
                    } else {
                        const uint16_t* src = reinterpret_cast<const uint16_t*>(base) + e0;
#pragma GCC unroll 16
                        for (uint32_t k = 0; k < 16; ++k) {
                            put(c0 + k, static_cast<uint32_t>(src[k]) << 16);
                        }
                    }
                }
            }
        } else {
            if constexpr (IN_BYTES == 4) {
                const uint32_t* src = reinterpret_cast<const uint32_t*>(base) + i * C;
                for (uint32_t c = 0; c < C; ++c) {
                    put(c, src[c]);
                }
            } else {
                const uint16_t* src = reinterpret_cast<const uint16_t*>(base) + i * C;
                for (uint32_t c = 0; c < C; ++c) {
                    put(c, static_cast<uint32_t>(src[c]) << 16);
                }
            }
        }
        send(dst, s);
    };

    // keys of the max over rows [i0, i1) of one 8-column group (element offset eq within a row's face row) of the TILE
    // data: rows < UNIT_ROWS in slot base0, the next unit's rows in base1 (0.23.4). The maximum stays in registers
    // (8 independent loads per row, no accumulator traffic); the same integer keys as accumulate_row.
    auto group_keys = [&](uint32_t base0, uint32_t base1, uint32_t i0, uint32_t i1, uint32_t eq, int32_t* k)
        __attribute__((always_inline)) {
        {
            const uint32_t base = i0 < UNIT_ROWS ? base0 : base1;
            const uint32_t ii = i0 & (UNIT_ROWS - 1);
            const uint32_t e = eq + ((ii >> 4) << 9) + (ii & 15u) * 16;
            if constexpr (IN_BYTES == 4) {
                const uint32_t* src = reinterpret_cast<const uint32_t*>(base) + e;
#pragma GCC unroll 8
                for (uint32_t j = 0; j < 8; ++j) {
                    k[j] = to_key(src[j]);
                }
            } else {
                const uint16_t* src = reinterpret_cast<const uint16_t*>(base) + e;
#pragma GCC unroll 8
                for (uint32_t j = 0; j < 8; ++j) {
                    k[j] = to_key(static_cast<uint32_t>(src[j]) << 16);
                }
            }
        }
        for (uint32_t i = i0 + 1; i < i1; ++i) {
            const uint32_t base = i < UNIT_ROWS ? base0 : base1;
            const uint32_t ii = i & (UNIT_ROWS - 1);
            const uint32_t e = eq + ((ii >> 4) << 9) + (ii & 15u) * 16;
            uint32_t v[8];
            if constexpr (IN_BYTES == 4) {
                const uint32_t* src = reinterpret_cast<const uint32_t*>(base) + e;
#pragma GCC unroll 8
                for (uint32_t j = 0; j < 8; ++j) {
                    v[j] = src[j];
                }
            } else {
                const uint16_t* src = reinterpret_cast<const uint16_t*>(base) + e;
#pragma GCC unroll 8
                for (uint32_t j = 0; j < 8; ++j) {
                    v[j] = static_cast<uint32_t>(src[j]) << 16;
                }
            }
#pragma GCC unroll 8
            for (uint32_t j = 0; j < 8; ++j) {
                const int32_t key = to_key(v[j]);
                k[j] = key > k[j] ? key : k[j];
            }
        }
    };

    // a segment whose rows lie in one 32-row unit or in two consecutive ones (TILE input; 0.23.4): group_keys per
    // 8-column group, converted straight into the output row (bf16 outputs as packed pairs, one 32-bit store per two
    // channels). A segment reaching into the next unit uses its prefetch, waited on here (ensure_unit issued it into
    // the other slot; the next ensure_unit flips to it as usual). The same integer-key max and the same RNE as the
    // accumulator path: bit-identical.
    auto emit_seg_unit = [&](uint32_t s, uint32_t r0, uint32_t r1) {
        ensure_unit(r0 / UNIT_ROWS);
        if ((r1 - 1) / UNIT_ROWS != cur_unit) {
            noc_async_read_barrier();  // the prefetch of cur_unit + 1 into slot cur_slot ^ 1
            COMPILER_BARRIER();
        }
        const uint32_t i0 = r0 - cur_unit * UNIT_ROWS;
        const uint32_t i1 = r1 - cur_unit * UNIT_ROWS;  // <= 2 * UNIT_ROWS
        const uint32_t base0 = data_l1 + cur_slot * UNIT_BYTES;
        const uint32_t base1 = data_l1 + (cur_slot ^ 1u) * UNIT_BYTES;
        const uint32_t dst = stage();
        for (uint32_t tc = 0; tc < CT; ++tc) {
            for (uint32_t h = 0; h < 2; ++h) {
#pragma GCC unroll 2
                for (uint32_t q = 0; q < 2; ++q) {
                    const uint32_t col = tc * 32 + h * 16 + q * 8;
                    int32_t k[8];
                    group_keys(base0, base1, i0, i1, tc * TILE_ELEMS + h * 256 + q * 8, k);
                    if constexpr (OUT_BYTES == 4) {
                        volatile tt_l1_ptr uint32_t* o = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(dst) + col;
#pragma GCC unroll 8
                        for (uint32_t j = 0; j < 8; ++j) {
                            o[j] = from_key(k[j]);
                        }
                    } else {
                        volatile tt_l1_ptr uint32_t* o =
                            reinterpret_cast<volatile tt_l1_ptr uint32_t*>(dst) + (col >> 1);
#pragma GCC unroll 4
                        for (uint32_t j = 0; j < 4; ++j) {
                            o[j] = static_cast<uint32_t>(to_bf16_rne(from_key(k[2 * j]))) |
                                   (static_cast<uint32_t>(to_bf16_rne(from_key(k[2 * j + 1]))) << 16);
                        }
                    }
                }
            }
        }
        send(dst, s);
    };

    // a longer segment (TILE input; 0.23.4): group_keys over each unit's part of it, merged into the accumulator
    // (the first part initialises it), then emitted as before
    auto reduce_long = [&](uint32_t r0, uint32_t r1) {
        for (uint32_t r = r0; r < r1;) {
            const uint32_t u = r / UNIT_ROWS;
            const uint32_t re = r1 < (u + 1) * UNIT_ROWS ? r1 : (u + 1) * UNIT_ROWS;
            ensure_unit(u);
            const uint32_t base = data_l1 + cur_slot * UNIT_BYTES;
            const bool first = r == r0;
            for (uint32_t tc = 0; tc < CT; ++tc) {
                for (uint32_t h = 0; h < 2; ++h) {
#pragma GCC unroll 2
                    for (uint32_t q = 0; q < 2; ++q) {
                        int32_t k[8];
                        group_keys(base, base, r - u * UNIT_ROWS, re - u * UNIT_ROWS, tc * TILE_ELEMS + h * 256 + q * 8,
                                   k);
                        int32_t* a = acc + tc * 32 + h * 16 + q * 8;
#pragma GCC unroll 8
                        for (uint32_t j = 0; j < 8; ++j) {
                            a[j] = (first || k[j] > a[j]) ? k[j] : a[j];
                        }
                    }
                }
            }
            r = re;
        }
    };

    // ---- the reduction
    uint32_t seg_begin = off_at(s_lo);
    for (uint32_t s = s_lo; s < s_hi; ++s) {
        uint32_t seg_end = off_at(s + 1);
        if (seg_end < seg_begin) {
            seg_end = seg_begin;  // non-decreasing offsets (a corrupt table reads nothing extra)
        }
        if (seg_end == seg_begin) {
            emit(s, true);
        } else if (seg_end == seg_begin + 1) {
            emit_row(s, seg_begin);
        } else if (IN_TILE && UNIT_PATH && (seg_end - 1) / UNIT_ROWS - seg_begin / UNIT_ROWS <= 1u) {
            emit_seg_unit(s, seg_begin, seg_end);
        } else if (IN_TILE && UNIT_PATH) {
            reduce_long(seg_begin, seg_end);
            emit(s, false);
        } else {
            for (uint32_t r = seg_begin; r < seg_end; ++r) {
                ensure_unit(r / UNIT_ROWS);
                accumulate_row(r, r == seg_begin);
            }
            emit(s, false);
        }
        seg_begin = seg_end;
    }
    noc_async_read_barrier();  // a prefetch past the last row may still be in flight
    noc_async_write_barrier();
}