okami.mom/strata

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

Niko1221Merge branch 'f-139b-old' into f-139-relbd34d0d87

main
24.1 KiB497 linesraw
1// src/kernels/cuda/router_top10.cu - P2.S2: the MoE router.
2//
3// P2.S2's spec: "BF16 GEMV, softmax / top-k / renormalize per docs/semantics.md; emits (expert_id, weight) x 10
4// per token".  This is the softmax/top-k/renormalize half; the BF16 GEMV that produces the logits is a
5// separate kernel and is NOT here.
6//
7// The semantics are transcribed from `ref/moe.py::router`, which is itself transcribed from llama-graph.cpp:
8//
9//     p   = softmax(logits)                       over ALL experts, not over the selected subset
10//     ids = stable argsort(-p)[:k]                ties break by INDEX, ascending
11//     w   = gather(p, ids)
12//     s   = max(sum(w), 2**-14)                   ggml_clamp(..., 2**-14, INF)
13//     return ids, w / s
14//
15// The two-step structure matters and is not cosmetic: computing softmax over the selected subset instead is
16// mathematically identical (softmax is shift-invariant) but it moves the renormalisation, and the CLAMP is
17// part of the renormalisation.  Reproducing the gather form is what makes the clamp land in the same place.
18//
19// WHY THIS IS NO LONGER "NAIVE BY DESIGN", AND WHAT THE OLD REASONING GOT WRONG.
20//
21// The first version was ONE THREAD PER TOKEN: k passes over the experts, each pass recomputing
22// `exp((double) l[e] - mx)` for every expert.  Its comment justified that with
23//
24//     "5,120 operations per token against 2.36e9 weights of expert matvec - three orders of magnitude smaller
25//      than the thing it feeds, so the simplest correct version is also fast enough"
26//
27// **That is a statement about OPERATION COUNT and it says nothing about TIME, because all 5,120 operations were
28// on ONE THREAD while the matvec has thousands.**  Measured (round 218, stage-by-stage inside one block):
29//
30//     moe_layer   4.077 ms      router_top10   3.387 ms      bf16 gemv   0.270 ms
31//
32// 3.39 ms per layer x 48 layers = 163 ms of a 289 ms token - **56% of the whole forward pass, in a kernel that
33// reads 2.6 MB.**  It was invisible in `router_top10_parity` because that test runs the kernel ONCE and checks
34// the right ids, and invisible in every per-layer test for the same reason.
35//
36// WHAT IS PARALLELISED AND WHAT IS DELIBERATELY NOT:
37//
38//   * the MAX is a tree reduction of `fmaxf`, which is exact and order-independent - bit-identical to the
39//     serial scan it replaces;
40//   * the 512 EXPONENTIALS are computed ONCE each, in parallel.  The old kernel computed them ELEVEN TIMES
41//     (once for the softmax, then again inside every one of the k passes).  This is where the 3.4 ms was;
42//   * the DOUBLE SUM is still accumulated on ONE thread in ASCENDING order.  512 double adds is about a
43//     microsecond and it keeps the accumulation order - and therefore the last bits - identical to the
44//     reference-faithful serial version.  Parallelising it would be a free speedup and a silent change to the
45//     values, and the exp was the cost, not this;
46//   * the SELECTION is by RANK rather than by k repeated maxima:
47//
48//         rank(e) = #{ f : p[f] > p[e] }  +  #{ f < e : p[f] == p[e] }
49//
50//     which IS "stable descending argsort, ties by ascending index" - the same order the repeated-maximum loop
51//     produced - computed in ONE parallel pass over the experts instead of k serial ones.  It is O(n^2)
52//     comparisons and that is the right trade here: n = 512, every comparison is independent, and the old
53//     version was O(k*n) with a serial `exp` inside.
54#include "strata/kernels/router_top10.hpp"
55
56#include <cuda_runtime.h>
57
58#include <cmath>
59#include <cstdio>
60#include <cstdlib>
61
62namespace strata::kernels {
63namespace {
64
65constexpr int RT_MAX_THREADS = 512;
66
67/// One BLOCK per token, so the reductions have somewhere to happen.  `n_tokens` is 1 in decode; the grid keeps
68/// the batch case working without a second code path.
69__global__ void router_top10_kernel(const float* __restrict__ logits, int n_tokens, int n_expert, int k,
70                                    int* __restrict__ ids, float* __restrict__ weights) {
71    // **`s_taken` IS FIRST SO THE OTHER TWO KEEP THEIR ALIGNMENT WITHOUT AN OFFSET PARAMETER**, and `s_p`'s
72    // existing `s_ex + n_expert` stays correct because it is relative to `s_ex`.  One byte per expert.
73    extern __shared__ unsigned char s_raw[];
74    const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u;
75    unsigned char* s_taken = s_raw;
76    double* s_ex = (double*) (s_raw + taken_bytes);
77    __shared__ float s_red[RT_MAX_THREADS / 32];
78    __shared__ int s_rid[RT_MAX_THREADS / 32];
79    __shared__ double s_sum;
80
81    const int t = blockIdx.x;
82    if (t >= n_tokens) return;
83    const int tid = threadIdx.x;
84    const int nt = blockDim.x;
85    const float* l = logits + (size_t) t * n_expert;
86
87    // ---- softmax over ALL experts, for stability: the max.  A tree of `fmaxf` is EXACT and order-independent,
88    // so this is bit-identical to the serial scan.
89    float mx = -INFINITY;
90    for (int e = tid; e < n_expert; e += nt) mx = fmaxf(mx, l[e]);
91    for (int off = 16; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_down_sync(0xffffffffu, mx, off));
92    if ((tid & 31) == 0) s_red[tid >> 5] = mx;
93    __syncthreads();
94    if (tid < 32) {
95        const int nw = (nt + 31) >> 5;
96        float v = (tid < nw) ? s_red[tid] : -INFINITY;
97        for (int off = 16; off > 0; off >>= 1) v = fmaxf(v, __shfl_down_sync(0xffffffffu, v, off));
98        if (tid == 0) s_red[0] = v;
99    }
100    __syncthreads();
101    mx = s_red[0];
102
103    // ---- THE 512 EXPONENTIALS, ONCE EACH AND IN PARALLEL.  `exp` in double is software-emulated on this die
104    // and was 5,632 serial calls before; it is 512 parallel ones now.
105    for (int e = tid; e < n_expert; e += nt) s_ex[e] = exp((double) l[e] - (double) mx);
106    __syncthreads();
107
108    // ---- the sum, ascending, on one thread: see the note above on why this is NOT parallelised.
109    if (tid == 0) {
110        double sum = 0.0;
111        for (int e = 0; e < n_expert; ++e) sum += s_ex[e];
112        s_sum = sum;
113    }
114    __syncthreads();
115    const float inv = (float) (1.0 / s_sum);
116
117    // ---- the selection, by rank.  `p[e] = (float)(s_ex[e] * inv)` reproduces the old expression exactly:
118    // `(float)(exp((double) l[e] - (double) mx) * inv)` with `inv` a FLOAT.
119    // ---- p[] ONCE.  The rank loop below compares every expert against every other, so computing
120    // `(float) (s_ex[f] * inv)` INSIDE it did **512 x 512 = 262,144** double multiplies and float converts per
121    // token per layer instead of 512 - and a consumer die runs FP64 at a small fraction of FP32, which is why
122    // this was worth more than the branch.  The shared load stays either way; the ARITHMETIC is what goes.
123    //
124    // THIS IS BIT-IDENTICAL, not merely equivalent: `p[e]` is the same expression it was, computed once instead
125    // of 513 times, and the comparisons then see exactly the same floats.
126    float* s_p = (float*) (s_ex + n_expert);
127    for (int e = tid; e < n_expert; e += nt) s_p[e] = (float) (s_ex[e] * inv);
128    __syncthreads();
129
130    // ================================ THE SELECTION, IN k PASSES ================================
131    //
132    // **THE RANK-BY-COUNTING LOOP COMPARED EVERY EXPERT AGAINST EVERY OTHER**: 512 x 512 = 262,144 shared
133    // loads and compares per token per layer, to choose ten things out of 512 - measured at 34.35 us, 63% of
134    // `moe_route`'s accounted cost and the largest single item in the R3 plan.  The comment above records that
135    // the FP64 ARITHMETIC inside that loop was hoisted out once already ("262,144 double multiplies per token
136    // per layer instead of 512"); **the O(n^2) STRUCTURE was left, and it is the structure that costs.**
137    //
138    // `k` passes of a block-wide argmax is 10 x 512 = 5,120 compares - **51x less work** - and it produces the
139    // SAME ORDER.  That is the whole correctness argument: scanning `e` ascending with a strict `>` keeps the
140    // LOWEST index on a tie, which is exactly the rule the rank loop spelled out as
141    // `else if (f < e && pf == pe) ++rank`.  A stable descending top-k, ties by index.
142    for (int e = tid; e < n_expert; e += nt) s_taken[e] = 0;
143    __syncthreads();
144
145    for (int i = 0; i < k; ++i) {
146        float bv = -INFINITY;
147        int bi = n_expert;               // a sentinel that loses to every real index
148        for (int e = tid; e < n_expert; e += nt) {
149            if (s_taken[e]) continue;
150            const float pe = s_p[e];
151            if (pe > bv) { bv = pe; bi = e; }
152        }
153        for (int off = 16; off > 0; off >>= 1) {
154            const float ov = __shfl_down_sync(0xffffffffu, bv, off);
155            const int oi = __shfl_down_sync(0xffffffffu, bi, off);
156            if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
157        }
158        if ((tid & 31) == 0) { s_red[tid >> 5] = bv; s_rid[tid >> 5] = bi; }
159        __syncthreads();
160        if (tid < 32) {
161            const int nw = (nt + 31) >> 5;
162            float v = (tid < nw) ? s_red[tid] : -INFINITY;
163            int ix = (tid < nw) ? s_rid[tid] : n_expert;
164            for (int off = 16; off > 0; off >>= 1) {
165                const float ov = __shfl_down_sync(0xffffffffu, v, off);
166                const int oi = __shfl_down_sync(0xffffffffu, ix, off);
167                if (ov > v || (ov == v && oi < ix)) { v = ov; ix = oi; }
168            }
169            if (tid == 0 && ix < n_expert) {
170                ids[(size_t) t * k + i] = ix;
171                weights[(size_t) t * k + i] = v;
172                s_taken[ix] = 1;
173            }
174        }
175        __syncthreads();
176    }
177    __syncthreads();
178
179    // ---- renormalise, with ggml's lower clamp.  Order preserved.
180    if (tid == 0) {
181        double s = 0.0;
182        for (int i = 0; i < k; ++i) s += (double) weights[(size_t) t * k + i];
183        const double sc = fmax(s, 6.103515625e-05);       // 2**-14
184        for (int i = 0; i < k; ++i)
185            weights[(size_t) t * k + i] = (float) ((double) weights[(size_t) t * k + i] / sc);
186    }
187}
188
189
190#if defined(STRATA_HIP_GFX906)
191// AMD (wave64): the same routing in ONE wavefront per token.  The block-wide kernel above spends its time in
192// barriers - 10 selection passes with two __syncthreads each over 8 logical warps - not in arithmetic (43 us per
193// token on gfx906).  Here every lane holds up to RW_PER probabilities in registers and each pass is a 64-lane
194// butterfly argmax: no LDS round trip, no block barrier.  Bit-identical to the kernel above: fmaxf trees are
195// exact, the exponentials and the (float) products are the same expressions, the sum stays one serial ascending
196// scan, and the argmax keeps the lowest index on a tie (a total order, so the butterfly's association is free).
197constexpr int RW_PER = 8;   // n_expert <= 64 * 8
198__global__ void __launch_bounds__(64) router_top10_wave_kernel(const float* __restrict__ logits, int n_tokens,
199                                                               int n_expert, int k, int* __restrict__ ids,
200                                                               float* __restrict__ weights) {
201    __shared__ double s_ex[64 * RW_PER];
202    __shared__ double s_sum;
203    const int t = blockIdx.x;
204    if (t >= n_tokens) return;
205    const int lane = threadIdx.x;
206    const float* l = logits + (size_t) t * n_expert;
207    float lv[RW_PER];
208    float mx = -INFINITY;
209#pragma unroll
210    for (int j = 0; j < RW_PER; ++j) {
211        const int e = lane + 64 * j;
212        lv[j] = e < n_expert ? l[e] : -INFINITY;
213        mx = fmaxf(mx, lv[j]);
214    }
215#pragma unroll
216    for (int off = 32; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_xor(mx, off, 64));
217#pragma unroll
218    for (int j = 0; j < RW_PER; ++j) {
219        const int e = lane + 64 * j;
220        if (e < n_expert) s_ex[e] = exp((double) lv[j] - (double) mx);
221    }
222    __syncthreads();
223    if (lane == 0) {
224        double sum = 0.0;
225        for (int e = 0; e < n_expert; ++e) sum += s_ex[e];
226        s_sum = sum;
227    }
228    __syncthreads();
229    const float inv = (float) (1.0 / s_sum);
230    float p[RW_PER];
231#pragma unroll
232    for (int j = 0; j < RW_PER; ++j) {
233        const int e = lane + 64 * j;
234        p[j] = e < n_expert ? (float) (s_ex[e] * inv) : -INFINITY;
235    }
236    unsigned taken = 0;
237    for (int i = 0; i < k; ++i) {
238        float bv = -INFINITY;
239        int bi = n_expert;
240#pragma unroll
241        for (int j = 0; j < RW_PER; ++j) {
242            const int e = lane + 64 * j;
243            if (e >= n_expert || (taken >> j & 1u)) continue;
244            if (p[j] > bv || (p[j] == bv && e < bi)) { bv = p[j]; bi = e; }
245        }
246#pragma unroll
247        for (int off = 32; off > 0; off >>= 1) {
248            const float ov = __shfl_xor(bv, off, 64);
249            const int oi = __shfl_xor(bi, off, 64);
250            if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
251        }
252        if (bi >= n_expert) break;
253        if ((bi & 63) == lane) taken |= 1u << (bi >> 6);
254        if (lane == 0) { ids[(size_t) t * k + i] = bi; weights[(size_t) t * k + i] = bv; }
255    }
256    if (lane == 0) {
257        double s = 0.0;
258        for (int i = 0; i < k; ++i) s += (double) weights[(size_t) t * k + i];
259        const double sc = fmax(s, 6.103515625e-05);       // 2**-14
260        for (int i = 0; i < k; ++i)
261            weights[(size_t) t * k + i] = (float) ((double) weights[(size_t) t * k + i] / sc);
262    }
263}
264#endif  // STRATA_HIP_GFX906
265
266#if defined(__HIPCC__)
267// ---- S6, AMD: the same router, BIT-IDENTICAL, without its serial parts. Measured on RDNA4 (gfx1201) the kernel
268// above took 39 us per call in decode (16% of the GPU's decode time): the ascending double sum is 512 dependent FP64
269// adds (~50 cycles each there), the ten selection passes are 20 block barriers, and the renormalisation re-reads its
270// ten weights from global memory one by one.  Here:
271//   * the sum's ONLY use is inv = (float) (1.0 / sum).  Every term is positive and the largest is exactly 1
272//     (exp(0)), so the serial sum and any other summation order both lie within 2^-43 (relative) of the exact sum
273//     (|serial - exact| <= 511u, |tree - exact| <= 21u, u = 2^-53).  1.0 / x and the float cast are monotone: when
274//     the bracket [tree (1 - 2^-40), tree (1 + 2^-40)] maps to ONE float, that float is the serial sum's.  Otherwise
275//     (about 1 row in 1000 in the parity test, or a non-finite sum) thread 0 runs the serial sum as before;
276//   * the selection runs on wave 0 alone with the probabilities in registers (16 per lane): the largest p with the
277//     lowest index on ties is unique, so the butterfly finds the same expert as the block reduction did;
278//   * the renormalisation sums the ten weights in rank order from registers and divides them in parallel.
279// Same expressions, same operands: the ids and weights are bitwise those of router_top10_kernel (hip_router_fast
280// checks it on 65,536 rows with ties, near-ties, NaN rows and the forced serial path). STRATA_HIP_ROUTER_OLD=1: the
281// kernel above.
282template <bool FORCE_SERIAL>
283__global__ void router_top10_fast_kernel(const float* __restrict__ logits, int n_tokens, int n_expert, int k,
284                                         int* __restrict__ ids, float* __restrict__ weights) {
285    extern __shared__ unsigned char s_raw[];
286    const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u;
287    double* s_ex = (double*) (s_raw + taken_bytes);
288    __shared__ float s_red[RT_MAX_THREADS / 32];
289    __shared__ double s_dred[RT_MAX_THREADS / 32];
290    __shared__ float s_inv;
291    const int t = blockIdx.x;
292    if (t >= n_tokens) return;
293    const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
294    const int nt = blockDim.x, nw = (nt + 31) >> 5;
295    const float* l = logits + (size_t) t * n_expert;
296    // the max: as router_top10_kernel (exact, order-independent)
297    float mx = -INFINITY;
298    for (int e = tid; e < n_expert; e += nt) mx = fmaxf(mx, l[e]);
299    for (int off = 16; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_down_sync(0xffffffffu, mx, off));
300    if (lane == 0) s_red[warp] = mx;
301    __syncthreads();
302    if (tid < 32) {
303        float v = (tid < nw) ? s_red[tid] : -INFINITY;
304        for (int off = 16; off > 0; off >>= 1) v = fmaxf(v, __shfl_down_sync(0xffffffffu, v, off));
305        if (tid == 0) s_red[0] = v;
306    }
307    __syncthreads();
308    mx = s_red[0];
309    // the exponentials (the same expression), and a tree sum of them for the bracket
310    double part = 0.0;
311    for (int e = tid; e < n_expert; e += nt) {
312        const double x = exp((double) l[e] - (double) mx);
313        s_ex[e] = x;
314        part += x;
315    }
316    for (int off = 16; off > 0; off >>= 1) part += __shfl_xor_sync(0xffffffffu, part, off);
317    if (lane == 0) s_dred[warp] = part;
318    __syncthreads();
319    double tot = 0.0;
320    for (int w = 0; w < nw; ++w) tot += s_dred[w];
321    const double lo = tot * (1.0 - 0x1p-40), hi = tot * (1.0 + 0x1p-40);
322    const float f_lo = (float) (1.0 / hi), f_hi = (float) (1.0 / lo);
323    float inv;
324    if (!FORCE_SERIAL && tot >= 1.0 && hi < 1e300 && f_lo == f_hi) {
325        inv = f_lo;
326    } else {   // block-uniform (every thread computed the same tot): the serial sum, exactly as router_top10_kernel
327        if (tid == 0) {
328            double sum = 0.0;
329            for (int e = 0; e < n_expert; ++e) sum += s_ex[e];
330            s_inv = (float) (1.0 / sum);
331        }
332        __syncthreads();
333        inv = s_inv;
334    }
335    if (warp != 0) return;
336    // wave 0: lane holds experts lane + 32 j; p is router_top10_kernel's expression
337    constexpr int PER = 16;
338    float pv[PER];
339    unsigned live = 0;
340#pragma unroll
341    for (int j = 0; j < PER; ++j) {
342        const int e = lane + 32 * j;
343        pv[j] = -INFINITY;
344        if (e < n_expert) { pv[j] = (float) (s_ex[e] * inv); live |= 1u << j; }
345    }
346    float my_w = 0.0f;
347    int my_id = 0, nsel = 0;
348    for (int i = 0; i < k; ++i) {
349        float bv = -INFINITY;
350        int bi = n_expert;   // a sentinel that loses to every real index
351#pragma unroll
352        for (int j = 0; j < PER; ++j)
353            if (((live >> j) & 1u) && pv[j] > bv) { bv = pv[j]; bi = lane + 32 * j; }
354        for (int off = 16; off > 0; off >>= 1) {
355            const float ov = __shfl_xor_sync(0xffffffffu, bv, off);
356            const int oi = __shfl_xor_sync(0xffffffffu, bi, off);
357            if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
358        }
359        if (bi >= n_expert) break;   // as router_top10_kernel: no rank i or later is written (every p left is NaN)
360        if ((bi & 31) == lane) live &= ~(1u << (bi >> 5));
361        if (lane == i) { my_w = bv; my_id = bi; }
362        nsel = i + 1;
363    }
364    if (nsel == k) {
365        double s = 0.0;
366        for (int i = 0; i < k; ++i) s += (double) __shfl_sync(0xffffffffu, my_w, i);
367        const double sc = fmax(s, 6.103515625e-05);       // 2**-14
368        if (lane < k) {
369            ids[(size_t) t * k + lane] = my_id;
370            weights[(size_t) t * k + lane] = (float) ((double) my_w / sc);
371        }
372    } else {   // router_top10_kernel's tail exactly: unwritten ranks keep what the buffer held and are renormalised too
373        if (lane < nsel) { ids[(size_t) t * k + lane] = my_id; weights[(size_t) t * k + lane] = my_w; }
374        __threadfence();
375        if (lane == 0) {
376            double s = 0.0;
377            for (int i = 0; i < k; ++i) s += (double) weights[(size_t) t * k + i];
378            const double sc = fmax(s, 6.103515625e-05);
379            for (int i = 0; i < k; ++i)
380                weights[(size_t) t * k + i] = (float) ((double) weights[(size_t) t * k + i] / sc);
381        }
382    }
383}
384
385void launch_generic(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights, void* stream,
386                    int mode) {   // mode 0: router_top10_kernel, 1: the HIP fast kernel, 2: the fast kernel's serial path
387    int threads = n_expert < RT_MAX_THREADS ? n_expert : RT_MAX_THREADS;
388    threads = (threads + 31) & ~31;
389    const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u;
390    const size_t smem = taken_bytes + (size_t) n_expert * sizeof(double) + (size_t) n_expert * sizeof(float);
391    if (mode == 1) {
392        router_top10_fast_kernel<false><<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>(
393            logits, n_tokens, n_expert, k, ids, weights);
394        return;
395    }
396    if (mode == 2) {
397        router_top10_fast_kernel<true><<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>(
398            logits, n_tokens, n_expert, k, ids, weights);
399        return;
400    }
401    router_top10_kernel<<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>(
402        logits, n_tokens, n_expert, k, ids, weights);
403}
404#endif
405
406}  // namespace
407
408bool router_top10_variant(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights,
409                          void* stream, int variant) {
410#if defined(__HIPCC__)
411    if (n_tokens <= 0 || n_expert <= 64 || n_expert > 512 || k <= 0 || k > 32) return false;
412    if (variant < 0 || variant > 2) return false;
413    launch_generic(logits, n_tokens, n_expert, k, ids, weights, stream, variant);
414    return cudaGetLastError() == cudaSuccess;
415#else
416    (void) logits; (void) n_tokens; (void) n_expert; (void) k; (void) ids; (void) weights; (void) stream;
417    (void) variant;
418    return false;
419#endif
420}
421
422void router_top10(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights,
423                  void* stream) {
424#if defined(__HIPCC__)
425    {
426#if defined(STRATA_HIP_GFX906)
427        // gfx906 (wave64): the one-wavefront kernel below stays the default; the S6 kernel is wave32-shaped and only
428        // runs here on request (STRATA_HIP_ROUTER_FAST=1) until it is measured on this card
429        static const bool old = std::getenv("STRATA_HIP_ROUTER_FAST") == nullptr;
430#else
431        static const bool old = std::getenv("STRATA_HIP_ROUTER_OLD") != nullptr;
432#endif
433        if (!old && n_tokens > 0 && n_expert > 64 && n_expert <= 512 && k > 0 && k <= 32) {
434            launch_generic(logits, n_tokens, n_expert, k, ids, weights, stream, 1);
435            const cudaError_t e = cudaGetLastError();
436            if (e != cudaSuccess) {
437                std::fprintf(stderr, "router_top10 launch: %s\n", cudaGetErrorString(e));
438                std::exit(1);
439            }
440            if (stream == nullptr) {
441                const cudaError_t s = cudaDeviceSynchronize();
442                if (s != cudaSuccess) {
443                    std::fprintf(stderr, "router_top10: %s\n", cudaGetErrorString(s));
444                    std::exit(1);
445                }
446            }
447            return;
448        }
449    }
450#endif
451    if (n_tokens <= 0 || n_expert <= 0 || k <= 0) return;
452    if (k > 64) {
453        std::fprintf(stderr, "router_top10: k %d exceeds the kernel's 64\n", k);
454        std::exit(1);
455    }
456    if (n_expert > RT_MAX_THREADS * 64) {
457        std::fprintf(stderr, "router_top10: n_expert %d is past the kernel's %d\n", n_expert,
458                     RT_MAX_THREADS * 64);
459        std::exit(1);
460    }
461#if defined(STRATA_HIP_GFX906)
462    if (n_expert <= 64 * RW_PER && !std::getenv("STRATA_ROUTER_BLOCK")) {
463        router_top10_wave_kernel<<<(unsigned) n_tokens, 64, 0, (cudaStream_t) stream>>>(logits, n_tokens, n_expert, k,
464                                                                                       ids, weights);
465        const cudaError_t e = cudaGetLastError();
466        if (e != cudaSuccess) {
467            std::fprintf(stderr, "router_top10 launch: %s\n", cudaGetErrorString(e));
468            std::exit(1);
469        }
470        if (stream == nullptr && cudaDeviceSynchronize() != cudaSuccess) std::exit(1);
471        return;
472    }
473#endif
474    int threads = n_expert < RT_MAX_THREADS ? n_expert : RT_MAX_THREADS;
475    threads = (threads + 31) & ~31;                  // at least one full warp, for the reductions
476    // the selection's taken-mask, then n_expert doubles for the exponentials, then n_expert floats for the
477    // probabilities.  The mask is first so the two aligned arrays need no offset parameter.
478    const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u;
479    const size_t smem =
480        taken_bytes + (size_t) n_expert * sizeof(double) + (size_t) n_expert * sizeof(float);
481    router_top10_kernel<<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>(
482        logits, n_tokens, n_expert, k, ids, weights);
483    const cudaError_t e = cudaGetLastError();
484    if (e != cudaSuccess) {
485        std::fprintf(stderr, "router_top10 launch: %s\n", cudaGetErrorString(e));
486        std::exit(1);
487    }
488    if (stream == nullptr) {
489        const cudaError_t s = cudaDeviceSynchronize();
490        if (s != cudaSuccess) {
491            std::fprintf(stderr, "router_top10: %s\n", cudaGetErrorString(s));
492            std::exit(1);
493        }
494    }
495}
496
497}  // namespace strata::kernels