okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-strix-p1a: P1A prompt experts for Windows gfx1151, on by default there4786a2e7d

main
27.4 KiB531 linesraw
1// src/prefill/moe_p1a.cu - see moe_p1a.hpp.  gfx11 device code; the engine takes it on gfx1151 only, behind STRATA_PF_P1A=1.
2//
3// The routed experts' prompt pass on the F16 matrix cores with F16 activations and H, the weight codes in registers
4// (gufo's RoutedPairF16Kernel / RoutedDownF16Kernel), on fused::group's tables and the native blobs:
5//   gate/up (Q4_K, Q5_K) + SwiGLU -> H as F16 rows [routed row][n_ff]
6//   down (Q5_1, Q8_0) of that H -> the routed rows' outputs as F16 [routed row][n_embd] (what moe_combine16 reads)
7// What differs from moe_f16_kq.cu (gufo's older RoutedF16GEMMKernel): the activations are the FP16 rows of the layer's input
8// (mixed_h), not int8 per 32; H is F16, not int8; each lane decodes only the K16 half of its row that the WMMA reads from it
9// and v_permlanex16 hands over the other half; the codes stay in registers and the activations are the only LDS stage;
10// a work item is 128 rows of one expert (two of fused::group's 64-row tiles).  The kernels are the harness's
11// (tools/hip/strix_bench/k_moe_p1a.cu) line for line except the work-item decode and the blob / geometry arguments;
12// MD / WPE / FL are the harness's knobs, the engine instantiates MD 0, WPE 0.
13//
14// Adapted from gufo 07e1191f36885c144b34566aac8eaa9777d8fa78: src/models/qwen38_flash_next/kernels/rocm/kernels.hip.cpp
15// (RoutedPairF16Kernel, RoutedDownF16Kernel, CodesToHalves, SwapHalves, GatherBit, SpreadHighBits).
16// MIT License
17// Copyright (c) 2026 gufo contributors
18// Permission is hereby granted, free of charge, to any person obtaining a copy
19// of this software and associated documentation files (the "Software"), to deal
20// in the Software without restriction, including without limitation the rights
21// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
22// copies of the Software, and to permit persons to whom the Software is
23// furnished to do so, subject to the following conditions:
24// The above copyright notice and this permission notice shall be included in all
25// copies or substantial portions of the Software.
26// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32// SOFTWARE.
33#include "moe_p1a.hpp"
34
35#include <hip/hip_fp16.h>
36
37#include "ggml.h"
38
39#include <algorithm>
40#include <cstdio>
41#include <cstdlib>
42
43namespace strata::prefill::fused::p1a {
44namespace {
45
46#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__)
47#define P1A_DEVICE 1
48#else
49#define P1A_DEVICE 0
50#endif
51
52using v16h = __attribute__((__vector_size__(16 * sizeof(_Float16)))) _Float16;
53using v8f = __attribute__((__vector_size__(8 * sizeof(float)))) float;
54using v8u = __attribute__((__vector_size__(32))) uint32_t;
55
56constexpr uint32_t kHalfMagic = 0x64646464U;   // the high bytes of 1024.0 as F16
57constexpr int kQ4K = GGML_TYPE_Q4_K, kQ5K = GGML_TYPE_Q5_K, kQ51 = GGML_TYPE_Q5_1, kQ80 = GGML_TYPE_Q8_0;
58
59
60#if P1A_DEVICE
61__device__ __forceinline__ v8f wmma(v16h a, v16h b, v8f c) { return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); }
62__device__ __forceinline__ uint32_t gather_bit(uint32_t w, int s) { return (((w >> s) & 0x01010101U) * 0x01020408U) >> 24U; }
63__device__ __forceinline__ uint32_t spread_high_bits(uint32_t bits) { return (__umul24(bits, 0x00204081U) & 0x01010101U) << 4U; }
64// lane i receives lane i ^ 16's value
65__device__ __forceinline__ uint32_t swap_halves(uint32_t v) {
66    uint32_t old;
67    asm("" : "=v"(old));
68    return (uint32_t) __builtin_amdgcn_permlanex16((int) old, (int) v, 0x76543210, 0xfedcba98, false, false);
69}
70__device__ __forceinline__ void codes_to_halves(uint32_t codes, __half2 magic, __half2 scale2, __half2 bias2, __half2& lo, __half2& hi) {
71    const uint32_t p0 = __builtin_amdgcn_perm(codes, kHalfMagic, 0x01050004U);
72    const uint32_t p1 = __builtin_amdgcn_perm(codes, kHalfMagic, 0x03070206U);
73    lo = __hfma2(__hadd2(__builtin_bit_cast(__half2, p0), magic), scale2, bias2);
74    hi = __hfma2(__hadd2(__builtin_bit_cast(__half2, p1), magic), scale2, bias2);
75}
76#endif
77
78// rows of expert e: [off[e], off[e + 1]); token of row r: src[r]; the outputs go to row r.
79// MD (--set p1a_mode=N, timing only, the output is wrong): 0 the kernel; 1 no WMMA (a cheap op consumes A and B); 2 no dequant (A = the raw
80// codes); 3 no global activation loads (zeros staged); 5 no global weight loads (codes from registers).
81// WPE (--set p1a_wpe=N): the compiler's waves-per-SIMD floor (VGPR cap 1536 / N); 0 = the compiler's choice.
82// FL (bit 0 --set p1a_il=1, bit 1 --set p1a_db=1), both kernels, MD 0 only:
83//   IL: token tiles in pairs j, j + 1: both B fragments read, then lo j, lo j+1, hi j, hi j+1 (two independent accumulators back to back
84//       instead of the dependent lo -> hi pair on one); an odd last live tile also computes its (zero, unused) neighbour.
85//   DB: two activation stage buffers in LDS, one barrier per stage instead of two (the stage written next was last read two stages ago,
86//       behind the barrier after this stage's commit). No +1 padding: column XOR (row << 2) instead, so 2 x 16 KB = 32 KB a block.
87template <int KS, bool DB>
88__device__ __forceinline__ int act_slot(int r, int c) { return r * KS + (DB ? (c ^ ((r & 7) << 2)) : c); }
89template <int WT, int MD = 0, int WPE = 0, int FL = 0>
90__launch_bounds__(256) __attribute__((amdgpu_waves_per_eu(WPE > 0 ? WPE : 1))) __global__ void pair_kernel(Batch b, NativeGeom geo, const int32_t* __restrict__ ts, const int2* __restrict__ tiles, const __half* __restrict__ x,
91                                                   const int32_t* __restrict__ off, const int32_t* __restrict__ src, __half* __restrict__ out,
92                                                   int m, int k) {
93#if P1A_DEVICE
94    constexpr int BN = 128, BK = 2, kTokTiles = BN / 16, kRows = 64;
95    constexpr bool IL = (FL & 1) != 0 && MD == 0, DB = (FL & 2) != 0;
96    constexpr bool Q5K = WT == kQ5K;
97    constexpr int kBlockBytes = Q5K ? 176 : 144;
98    constexpr int kActStride = DB ? BN : BN + 1, kActBuf = BK * 4 * kActStride, kActBytes = (DB ? 2 : 1) * kActBuf * 16;
99    constexpr int kPairStride = kRows + 2, kEpilogueBytes = BN * kPairStride * 2;
100    constexpr int kLdsBytes = kActBytes > kEpilogueBytes ? kActBytes : kEpilogueBytes;
101    __shared__ __attribute__((aligned(16))) uint8_t lds[kLdsBytes];
102    auto* s_act = reinterpret_cast<uint4*>(lds);
103
104    // the work item: fused::group's 64-row tile y of this batch and the next one of the same expert (a 128-row item);
105    // the second tile of a pair has no block of its own
106    const int t0 = ts[b.e0], w = (int) blockIdx.y;
107    if (w >= ts[b.e1] - t0) return;
108    const int2 tl = tiles[t0 + w];
109    const int expert = tl.x;
110    if ((t0 + w - ts[expert]) & 1) return;
111    const int t_local = 0;
112    const int bucket_begin = tl.y;
113    const int bucket_rows = min(BN, off[expert + 1] - bucket_begin);
114    const int live_tok_tiles = min(kTokTiles, (bucket_rows - t_local + 15) / 16);
115    const int num_sb = k / 256;
116
117    const int tid = (int) threadIdx.x, wave_id = tid >> 5, lane_id = tid & 31, sub_lane = lane_id & 15, half_id = lane_id >> 4;
118    const int r_block = (int) blockIdx.x * kRows;
119    const int row = r_block + wave_id * 8 + (sub_lane % 8);   // tile rows 0-7 gate, 8-15 the matching up rows
120    const bool row_live = row < m;
121    const int f_c = half_id ^ (sub_lane & 1);
122    const uint8_t* w_row = b.blob[expert - b.e0] + (sub_lane < 8 ? 0 : geo.up_off) + (size_t) (row_live ? row : m - 1) * geo.gu_row;
123
124    constexpr int kActFetch = BN * BK * 4 / 256;
125    const __half* a_src[kActFetch];
126    int a_slot[kActFetch];
127#pragma unroll
128    for (int i = 0; i < kActFetch; ++i) {
129        const int chunk = tid + i * 256, t = chunk / (BK * 4), sub = chunk % (BK * 4), c_row = t_local + t;
130        const int32_t s = c_row < bucket_rows ? src[bucket_begin + c_row] : -1;
131        a_src[i] = s >= 0 && MD != 3 ? x + (size_t) s * k + sub * 8 : nullptr;
132        a_slot[i] = act_slot<kActStride, DB>(sub, t);
133    }
134    uint4 raw_header, raw_codes[4], raw_qh[2];
135    uint4 header = make_uint4(0u, 0u, 0u, 0u), codes[4], qh[2];
136    uint4 a_data[kActFetch];
137#pragma unroll
138    for (int i = 0; i < kActFetch; ++i) a_data[i] = make_uint4(0u, 0u, 0u, 0u);
139
140    const auto fetch_stage = [&]<int G>(int sb) {
141        if constexpr (G == 0 && MD == 5) {
142            raw_header = make_uint4(0x3C003C00U ^ (uint32_t) sb, (uint32_t) tid, (uint32_t) sb * 7U, (uint32_t) row);
143            if constexpr (Q5K) { raw_qh[0] = make_uint4((uint32_t) sb, 1U, 2U, 3U); raw_qh[1] = make_uint4((uint32_t) tid, 5U, 6U, 7U); }
144#pragma unroll
145            for (int g = 0; g < 4; ++g) raw_codes[g] = make_uint4((uint32_t) (sb * g), (uint32_t) tid, (uint32_t) g, (uint32_t) (sb ^ tid));
146        } else if constexpr (G == 0) {
147            const auto* chunks = reinterpret_cast<const uint4*>(w_row + sb * kBlockBytes);
148            constexpr int kCodeChunk = Q5K ? 3 : 1;
149            raw_header = chunks[0];
150            if constexpr (Q5K) { raw_qh[0] = chunks[1]; raw_qh[1] = chunks[2]; }
151#pragma unroll
152            for (int g = 0; g < 4; ++g) raw_codes[g] = chunks[kCodeChunk + g * 2 + f_c];
153        }
154        const int kb0 = sb * 8 + G * 2;
155#pragma unroll
156        for (int i = 0; i < kActFetch; ++i)
157            if (a_src[i] != nullptr) a_data[i] = *reinterpret_cast<const uint4*>(a_src[i] + kb0 * 32);
158    };
159    uint32_t own_scale = 0, own_high = 0;
160    const auto commit_stage = [&]<int G>() {
161        if constexpr (G == 0) {
162            header = raw_header;
163#pragma unroll
164            for (int g = 0; g < 4; ++g) codes[g] = raw_codes[g];
165            if constexpr (Q5K) { qh[0] = raw_qh[0]; qh[1] = raw_qh[1]; }
166        }
167        const int sb32 = 2 * G + f_c;
168        const unsigned shift = 8U * ((unsigned) sb32 & 3U);
169        const uint32_t scale_byte = header.y >> shift, min_byte = header.z >> shift;
170        uint32_t sc, mn;
171        if (sb32 < 4) {
172            sc = scale_byte & 0x3FU;
173            mn = min_byte & 0x3FU;
174        } else {
175            const uint32_t packed = header.w >> shift;
176            sc = (packed & 0x0FU) | ((scale_byte & 0xC0U) >> 2U);
177            mn = ((packed >> 4U) & 0x0FU) | ((min_byte & 0xC0U) >> 2U);
178        }
179        const __half2 dm = __builtin_bit_cast(__half2, header.x);
180        const float scale = row_live ? __low2float(dm) * (float) sc : 0.0F;
181        const float offset = row_live ? __high2float(dm) * (float) mn : 0.0F;
182        own_scale = __builtin_bit_cast(uint32_t, __floats2half2_rn(scale, -offset));
183        if constexpr (Q5K) {
184            const uint32_t q[8] = {qh[0].x, qh[0].y, qh[0].z, qh[0].w, qh[1].x, qh[1].y, qh[1].z, qh[1].w};
185            uint32_t high = 0;
186#pragma unroll
187            for (int i = 0; i < 8; ++i) high |= gather_bit(q[i], sb32) << (4 * i);
188            own_high = high;
189        }
190        uint4* buf = s_act + (DB ? (G & 1) * kActBuf : 0);
191#pragma unroll
192        for (int i = 0; i < kActFetch; ++i) buf[a_slot[i]] = a_data[i];
193    };
194    const auto load_b = [&](const uint4* buf, int kb, int j, v16h& b_lo, v16h& b_hi) {
195        uint4 b[4];
196#pragma unroll
197        for (int q = 0; q < 4; ++q) b[q] = buf[act_slot<kActStride, DB>(kb * 4 + q, j * 16 + sub_lane)];
198        __builtin_memcpy(&b_lo, &b[0], 32);
199        __builtin_memcpy(&b_hi, &b[2], 32);
200    };
201    v8f acc[kTokTiles];
202#pragma unroll
203    for (int j = 0; j < kTokTiles; ++j) acc[j] = v8f{0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F};
204    const __half2 magic = __floats2half2_rn(-1024.0F, -1024.0F);
205    const auto compute_stage = [&]<int G>() {
206        const uint4 c = codes[G];
207        const uint32_t words[4] = {c.x, c.y, c.z, c.w};
208        const uint32_t peer_scale = swap_halves(own_scale);
209        const uint32_t peer_high = Q5K ? swap_halves(own_high) : 0U;
210#pragma unroll
211        for (int kb = 0; kb < BK; ++kb) {
212            const __half2 sb = __builtin_bit_cast(__half2, f_c == kb ? own_scale : peer_scale);
213            const __half2 scale2 = __low2half2(sb), bias2 = __high2half2(sb);
214            const uint32_t high = Q5K ? ((f_c == kb ? own_high : peer_high) >> (16U * f_c)) : 0U;
215            __half2 h[8];
216            v8u own, peer;
217            if constexpr (MD == 2) {
218#pragma unroll
219                for (int i = 0; i < 4; ++i) {
220                    own[2 * i] = words[i] ^ (uint32_t) kb ^ __builtin_bit_cast(uint32_t, sb);
221                    own[2 * i + 1] = words[i] + high;
222                }
223                peer = own;
224            } else {
225#pragma unroll
226                for (int i = 0; i < 4; ++i) {
227                    uint32_t nib = (words[i] >> (4U * kb)) & 0x0F0F0F0FU;
228                    if constexpr (Q5K) nib |= spread_high_bits((high >> (4 * i)) & 0xFU);
229                    codes_to_halves(nib, magic, scale2, bias2, h[2 * i], h[2 * i + 1]);
230                }
231                __builtin_memcpy(&own, &h[0], 32);
232#pragma unroll
233                for (int i = 0; i < 8; ++i) peer[i] = swap_halves(own[i]);
234            }
235            const v16h a_lo = __builtin_bit_cast(v16h, own), a_hi = __builtin_bit_cast(v16h, peer);
236            const uint4* buf = s_act + (DB ? (G & 1) * kActBuf : 0);
237            if constexpr (IL) {
238#pragma unroll
239                for (int j = 0; j < kTokTiles; j += 2) {
240                    asm volatile("" ::: "memory");   // two token tiles' fragments live at a time
241                    if (j >= live_tok_tiles) continue;
242                    v16h b0_lo, b0_hi, b1_lo, b1_hi;
243                    load_b(buf, kb, j, b0_lo, b0_hi);
244                    load_b(buf, kb, j + 1, b1_lo, b1_hi);
245                    acc[j] = wmma(a_lo, b0_lo, acc[j]);
246                    acc[j + 1] = wmma(a_lo, b1_lo, acc[j + 1]);
247                    acc[j] = wmma(a_hi, b0_hi, acc[j]);
248                    acc[j + 1] = wmma(a_hi, b1_hi, acc[j + 1]);
249                }
250            } else {
251#pragma unroll
252                for (int j = 0; j < kTokTiles; ++j) {
253                    asm volatile("" ::: "memory");   // one token tile's fragments live at a time (hoisting all eight spills)
254                    if (j >= live_tok_tiles) continue;
255                    v16h b_lo, b_hi;
256                    load_b(buf, kb, j, b_lo, b_hi);
257                    if constexpr (MD == 1) {
258                        const v8u bl = __builtin_bit_cast(v8u, b_lo), bh = __builtin_bit_cast(v8u, b_hi);
259                        acc[j][0] += __uint_as_float((own[j & 7] ^ peer[(j + 1) & 7] ^ bl[0] ^ bl[5] ^ bh[2] ^ bh[7]) & 0x3F7FFFFFU);
260                    } else {
261                        acc[j] = wmma(a_lo, b_lo, acc[j]);
262                        acc[j] = wmma(a_hi, b_hi, acc[j]);
263                    }
264                }
265            }
266        }
267    };
268    const auto run_stage = [&]<int G>(int sb) {
269        commit_stage.template operator()<G>();
270        __syncthreads();
271        if constexpr (G < 3) fetch_stage.template operator()<G + 1>(sb);
272        else if (sb + 1 < num_sb) fetch_stage.template operator()<0>(sb + 1);
273        compute_stage.template operator()<G>();
274        if constexpr (!DB) __syncthreads();
275    };
276    fetch_stage.template operator()<0>(0);
277    for (int sb = 0; sb < num_sb; ++sb) {
278        run_stage.template operator()<0>(sb);
279        run_stage.template operator()<1>(sb);
280        run_stage.template operator()<2>(sb);
281        run_stage.template operator()<3>(sb);
282    }
283    if constexpr (DB) __syncthreads();   // the epilogue's scratch overlays the stage buffers
284    // lane (token n, rows 2l + half) holds gate rows in acc[j][l] and the matching up rows in acc[j][l + 4]
285    __half* scratch = reinterpret_cast<__half*>(lds);
286#pragma unroll
287    for (int j = 0; j < kTokTiles; ++j) {
288        if (j >= live_tok_tiles) continue;
289#pragma unroll
290        for (int l = 0; l < 4; ++l) {
291            float product = acc[j][l + 4] * acc[j][l];
292            asm volatile("" : "+v"(product));
293            float value = product * (1.0f / (1.0f + __expf(-acc[j][l])));
294            asm volatile("" : "+v"(value));
295            scratch[(j * 16 + sub_lane) * kPairStride + wave_id * 8 + 2 * l + half_id] = __float2half(value);
296        }
297    }
298    __syncthreads();
299#pragma unroll
300    for (int unit = 0; unit < BN * kRows / (2 * 256); ++unit) {
301        const int flat = (unit * 256 + tid) * 2, t = t_local + flat / kRows, r = r_block + flat % kRows;
302        if (t < bucket_rows && r < m) {
303            const size_t o = (size_t) (bucket_begin + t) * m + r;
304            const int s = (flat / kRows) * kPairStride + flat % kRows;
305            *reinterpret_cast<__half2*>(out + o) = *reinterpret_cast<const __half2*>(scratch + s);
306        }
307    }
308#else
309    (void) b; (void) geo; (void) ts; (void) x; (void) tiles; (void) off; (void) src; (void) out; (void) m; (void) k;
310    __builtin_trap();
311#endif
312}
313
314// down: x = H rows [routed row][k]; the outputs to the same rows, F16 [routed row][m]
315// MD, WPE, FL as for pair_kernel; BKT (--set p1a_dbk=4): K blocks of 32 a stage
316template <int WT, int MD = 0, int WPE = 0, int BKT = 2, int FL = 0>
317__launch_bounds__(256) __attribute__((amdgpu_waves_per_eu(WPE > 0 ? WPE : 1))) __global__ void down_kernel(Batch b, NativeGeom geo, const int32_t* __restrict__ ts, const int2* __restrict__ tiles, const __half* __restrict__ x,
318                                                   const int32_t* __restrict__ off, __half* __restrict__ out, int m, int k) {
319#if P1A_DEVICE
320    constexpr int BN = 128, BK = BKT, kTokTiles = BN / 16;
321    constexpr bool IL = (FL & 1) != 0 && MD == 0, DB = (FL & 2) != 0;
322    constexpr bool Q5 = WT == kQ51;
323    constexpr int kBlockBytes = Q5 ? 24 : 34;
324    constexpr int kActStride = DB ? BN : BN + 1, kActBuf = BK * 4 * kActStride, kActBytes = (DB ? 2 : 1) * kActBuf * 16;
325    constexpr int kOutStride = 128 + 8, kEpiTokens = 64, kEpiBytes = kEpiTokens * kOutStride * 2;
326    constexpr int kLdsBytes = kActBytes > kEpiBytes ? kActBytes : kEpiBytes;
327    __shared__ __attribute__((aligned(16))) uint8_t lds[kLdsBytes];
328    auto* s_act = reinterpret_cast<uint4*>(lds);
329
330    // the work item: fused::group's 64-row tile y of this batch and the next one of the same expert (a 128-row item);
331    // the second tile of a pair has no block of its own
332    const int t0 = ts[b.e0], w = (int) blockIdx.y;
333    if (w >= ts[b.e1] - t0) return;
334    const int2 tl = tiles[t0 + w];
335    const int expert = tl.x;
336    if ((t0 + w - ts[expert]) & 1) return;
337    const int t_local = 0;
338    const int bucket_begin = tl.y;
339    const int bucket_rows = min(BN, off[expert + 1] - bucket_begin);
340    const int live_tok_tiles = min(kTokTiles, (bucket_rows - t_local + 15) / 16);
341    const int num_kb = k / 32;
342
343    const int tid = (int) threadIdx.x, wave_id = tid >> 5, lane_id = tid & 31, sub_lane = lane_id & 15, half_id = lane_id >> 4;
344    const int r_block = (int) blockIdx.x * 128;
345    const int f_c = half_id ^ (sub_lane & 1);
346    const int row = r_block + wave_id * 16 + sub_lane;
347    const bool row_live = row < m;
348    const uint8_t* w_row = b.blob[expert - b.e0] + geo.down_off + (size_t) (row_live ? row : m - 1) * geo.d_row;
349
350    constexpr int kActFetch = BN * BK * 4 / 256;
351    const __half* a_src[kActFetch];
352    int a_slot[kActFetch];
353#pragma unroll
354    for (int i = 0; i < kActFetch; ++i) {
355        const int chunk = tid + i * 256, t = chunk / (BK * 4), sub = chunk % (BK * 4), c_row = t_local + t;
356        a_src[i] = c_row < bucket_rows && MD != 3 ? x + (size_t) (bucket_begin + c_row) * k + sub * 8 : nullptr;
357        a_slot[i] = act_slot<kActStride, DB>(sub, t);
358    }
359    const auto load_b = [&](const uint4* buf, int kb, int j, v16h& b_lo, v16h& b_hi) {
360        uint4 b[4];
361#pragma unroll
362        for (int q = 0; q < 4; ++q) b[q] = buf[act_slot<kActStride, DB>(kb * 4 + q, j * 16 + sub_lane)];
363        __builtin_memcpy(&b_lo, &b[0], 32);
364        __builtin_memcpy(&b_hi, &b[2], 32);
365    };
366    uint4 w_codes[2][BK];
367    uint32_t w_head[2][BK], w_high[2][BK];
368    uint4 a_data[kActFetch];
369#pragma unroll
370    for (int i = 0; i < kActFetch; ++i) a_data[i] = make_uint4(0u, 0u, 0u, 0u);
371    const auto fetch_stage = [&]<int S>(int kb0) {
372#pragma unroll
373        for (int b = 0; b < BK; ++b) {
374            const uint8_t* blk = w_row + (kb0 + b) * kBlockBytes;
375            if constexpr (MD == 5) {
376                w_head[S][b] = 0x3C003C00U ^ (uint32_t) kb0;
377                w_high[S][b] = (uint32_t) (tid + b);
378                w_codes[S][b] = make_uint4((uint32_t) kb0, (uint32_t) tid, (uint32_t) b, (uint32_t) row);
379            } else if constexpr (Q5) {
380                const uint2 head = *reinterpret_cast<const uint2*>(blk);
381                w_head[S][b] = head.x;
382                w_high[S][b] = head.y;
383                w_codes[S][b] = *reinterpret_cast<const uint4*>(blk + 8);
384            } else {
385                w_head[S][b] = *reinterpret_cast<const uint16_t*>(blk);
386                __builtin_memcpy(&w_codes[S][b], blk + 2 + 16 * f_c, 16);
387            }
388        }
389#pragma unroll
390        for (int i = 0; i < kActFetch; ++i)
391            if (a_src[i] != nullptr) a_data[i] = *reinterpret_cast<const uint4*>(a_src[i] + kb0 * 32);
392    };
393    v8f acc[kTokTiles];
394#pragma unroll
395    for (int j = 0; j < kTokTiles; ++j) acc[j] = v8f{0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F};
396    constexpr float kMagic = Q5 ? -1024.0F : -1152.0F;
397    const __half2 magic = __floats2half2_rn(kMagic, kMagic);
398    const auto compute_stage = [&]<int S>() {
399#pragma unroll
400        for (int kb = 0; kb < BK; ++kb) {
401            const uint32_t scale_bias = Q5 ? w_head[S][kb] : (row_live ? w_head[S][kb] : 0U);
402            const __half2 sb = __builtin_bit_cast(__half2, scale_bias);
403            const __half2 scale2 = __low2half2(sb), bias2 = __high2half2(sb);
404            const uint4 c = w_codes[S][kb];
405            const uint32_t words[4] = {c.x, c.y, c.z, c.w};
406            __half2 h[8];
407            v8u own, peer;
408            if constexpr (MD == 2) {
409#pragma unroll
410                for (int i = 0; i < 4; ++i) {
411                    own[2 * i] = words[i] ^ scale_bias;
412                    own[2 * i + 1] = words[i] + w_high[S][kb];
413                }
414                peer = own;
415            } else {
416#pragma unroll
417                for (int i = 0; i < 4; ++i) {
418                    uint32_t nib;
419                    if constexpr (Q5) nib = ((words[i] >> (4U * f_c)) & 0x0F0F0F0FU) | spread_high_bits((w_high[S][kb] >> (16 * f_c + 4 * i)) & 0xFU);
420                    else nib = words[i] ^ 0x80808080U;
421                    codes_to_halves(nib, magic, scale2, bias2, h[2 * i], h[2 * i + 1]);
422                }
423                __builtin_memcpy(&own, &h[0], 32);
424#pragma unroll
425                for (int i = 0; i < 8; ++i) peer[i] = swap_halves(own[i]);
426            }
427            const v16h a_lo = __builtin_bit_cast(v16h, own), a_hi = __builtin_bit_cast(v16h, peer);
428            const uint4* buf = s_act + (DB ? S * kActBuf : 0);
429            if constexpr (IL) {
430#pragma unroll
431                for (int j = 0; j < kTokTiles; j += 2) {
432                    asm volatile("" ::: "memory");
433                    if (j >= live_tok_tiles) continue;
434                    v16h b0_lo, b0_hi, b1_lo, b1_hi;
435                    load_b(buf, kb, j, b0_lo, b0_hi);
436                    load_b(buf, kb, j + 1, b1_lo, b1_hi);
437                    acc[j] = wmma(a_lo, b0_lo, acc[j]);
438                    acc[j + 1] = wmma(a_lo, b1_lo, acc[j + 1]);
439                    acc[j] = wmma(a_hi, b0_hi, acc[j]);
440                    acc[j + 1] = wmma(a_hi, b1_hi, acc[j + 1]);
441                }
442            } else {
443#pragma unroll
444                for (int j = 0; j < kTokTiles; ++j) {
445                    asm volatile("" ::: "memory");
446                    if (j >= live_tok_tiles) continue;
447                    v16h b_lo, b_hi;
448                    load_b(buf, kb, j, b_lo, b_hi);
449                    if constexpr (MD == 1) {
450                        const v8u bl = __builtin_bit_cast(v8u, b_lo), bh = __builtin_bit_cast(v8u, b_hi);
451                        acc[j][0] += __uint_as_float((own[j & 7] ^ peer[(j + 1) & 7] ^ bl[0] ^ bl[5] ^ bh[2] ^ bh[7]) & 0x3F7FFFFFU);
452                    } else {
453                        acc[j] = wmma(a_lo, b_lo, acc[j]);
454                        acc[j] = wmma(a_hi, b_hi, acc[j]);
455                    }
456                }
457            }
458        }
459    };
460    const auto run_stage = [&]<int S>(int kb0) {
461        uint4* wbuf = s_act + (DB ? S * kActBuf : 0);
462#pragma unroll
463        for (int i = 0; i < kActFetch; ++i) wbuf[a_slot[i]] = a_data[i];
464        __syncthreads();
465        if (kb0 + BK < num_kb) fetch_stage.template operator()<1 - S>(kb0 + BK);
466        compute_stage.template operator()<S>();
467        if constexpr (!DB) __syncthreads();
468    };
469    fetch_stage.template operator()<0>(0);
470    for (int kb0 = 0; kb0 < num_kb; kb0 += 2 * BK) {
471        run_stage.template operator()<0>(kb0);
472        if (kb0 + BK < num_kb) run_stage.template operator()<1>(kb0 + BK);
473    }
474    if constexpr (DB) __syncthreads();   // the epilogue's scratch overlays the stage buffers
475    __half* scratch = reinterpret_cast<__half*>(lds);
476#pragma unroll
477    for (int part = 0; part < BN / kEpiTokens; ++part) {
478        if (part * (kEpiTokens / 16) >= live_tok_tiles) break;
479        if (part > 0) __syncthreads();
480#pragma unroll
481        for (int jj = 0; jj < kEpiTokens / 16; ++jj) {
482            const int j = part * (kEpiTokens / 16) + jj;
483#pragma unroll
484            for (int i = 0; i < 8; ++i)
485                scratch[(jj * 16 + sub_lane) * kOutStride + wave_id * 16 + 2 * i + half_id] =
486                    __float2half(fminf(fmaxf(acc[j][i], -65504.0f), 65504.0f));
487        }
488        __syncthreads();
489#pragma unroll
490        for (int unit = 0; unit < kEpiTokens * 16 / 256; ++unit) {
491            const int flat = unit * 256 + tid, tr = flat / 16, chunk = flat % 16;
492            const int t = t_local + part * kEpiTokens + tr, r = r_block + chunk * 8;
493            if (t >= bucket_rows || r >= m) continue;
494            *reinterpret_cast<uint4*>(out + (size_t) (bucket_begin + t) * m + r) =
495                *reinterpret_cast<const uint4*>(scratch + tr * kOutStride + chunk * 8);
496        }
497    }
498#else
499    (void) b; (void) geo; (void) ts; (void) x; (void) tiles; (void) off; (void) out; (void) m; (void) k;
500    __builtin_trap();
501#endif
502}
503
504}  // namespace
505
506static_assert(kMoeFF % 64 == 0 && kMoeEmbd % 256 == 0 && kMoeEmbd % 128 == 0 && kMoeFF % 32 == 0, "Path A's tile and stage sizes");
507
508bool takes(int gu_type, int d_type, bool l2) {
509    if (gu_type == kQ4K && d_type == kQ51) return true;
510    return l2 && (gu_type == kQ4K || gu_type == kQ5K) && (d_type == kQ51 || d_type == kQ80);
511}
512
513void gate_up(const Batch& b, const NativeGeom& g, const int32_t* ts, const int2* tiles, const int32_t* off, int64_t work_bound,
514             const void* x16, const int32_t* src, void* h16, cudaStream_t s) {
515    const dim3 grid((unsigned) (kMoeFF / 64), (unsigned) std::max<int64_t>(1, work_bound));
516    if (g.gu_type == kQ5K)
517        pair_kernel<kQ5K><<<grid, 256, 0, s>>>(b, g, ts, tiles, (const __half*) x16, off, src, (__half*) h16, kMoeFF, kMoeEmbd);
518    else
519        pair_kernel<kQ4K><<<grid, 256, 0, s>>>(b, g, ts, tiles, (const __half*) x16, off, src, (__half*) h16, kMoeFF, kMoeEmbd);
520}
521
522void down(const Batch& b, const NativeGeom& g, const int32_t* ts, const int2* tiles, const int32_t* off, int64_t work_bound,
523          const void* h16, void* d16, cudaStream_t s) {
524    const dim3 grid((unsigned) ((kMoeEmbd + 127) / 128), (unsigned) std::max<int64_t>(1, work_bound));
525    if (g.d_type == kQ80)
526        down_kernel<kQ80><<<grid, 256, 0, s>>>(b, g, ts, tiles, (const __half*) h16, off, (__half*) d16, kMoeEmbd, kMoeFF);
527    else
528        down_kernel<kQ51><<<grid, 256, 0, s>>>(b, g, ts, tiles, (const __half*) h16, off, (__half*) d16, kMoeEmbd, kMoeFF);
529}
530
531}  // namespace strata::prefill::fused::p1a