okami.mom/strata

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

Niko1221Merge f-qwen36 into f-144-rel (geometry: #2179's read_geometry guard kept for qwen4exp, Qwen3.6's family guard on top)4cfeaa0f4

main
15.6 KiB329 linesraw
1// Adapted from topk-moe.cu/common.cuh in llama.cpp
2// 3cf03257f219afbe7334045ff7c6a06ac68c627d; finite F32, 512-expert/10-output path.
3// MIT License
4// Copyright (c) 2023-2026 The ggml authors
5//
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12//
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15//
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23#include "strata/kernels/native_router.hpp"
24#include <cuda_runtime.h>
25#include <atomic>
26#include <cfloat>
27#include <cstddef>
28#include <cstdint>
29#include <stdexcept>
30
31namespace strata::kernels {
32namespace {
33std::atomic<bool> enabled{false};
34__device__ __forceinline__ float warp_sum(float value) {
35#pragma unroll
36    for (int mask = 16; mask; mask >>= 1) value += __shfl_xor_sync(0xffffffffu, value, mask, 32);
37    return value;
38}
39__device__ __forceinline__ float warp_max(float value) {
40#pragma unroll
41    for (int mask = 16; mask; mask >>= 1) value = fmaxf(value, __shfl_xor_sync(0xffffffffu, value, mask, 32));
42    return value;
43}
44__launch_bounds__(256, 1)
45__global__ void route(const float* __restrict__ logits, int32_t* __restrict__ ids,
46                      float* __restrict__ weights) {
47    // Preserve the pinned 32x8 block geometry; only row zero is active here.
48    // blockIdx.x = the token (a multi-token launch; 0 for the single one)
49    logits += (size_t) blockIdx.x * 512; ids += (size_t) blockIdx.x * 10; weights += (size_t) blockIdx.x * 10;
50    if (threadIdx.y != 0) return;
51    const int lane = threadIdx.x;
52    float values[16];
53#pragma unroll
54    for (int i = 0; i < 16; ++i) values[i] = logits[lane + i * 32];
55    __syncthreads();
56    float maximum = -INFINITY;
57#pragma unroll
58    for (int i = 0; i < 16; ++i) maximum = max(maximum, values[i]);
59    maximum = warp_max(maximum);
60    float sum = 0.0f;
61#pragma unroll
62    for (int i = 0; i < 16; ++i) {
63        values[i] = expf(values[i] - maximum);
64        sum += values[i];
65    }
66    const float reciprocal = 1.0f / warp_sum(sum);
67#pragma unroll
68    for (int i = 0; i < 16; ++i) {
69        values[i] *= reciprocal;
70        if (__isnanf(values[i])) values[i] = -FLT_MAX;
71    }
72    float selected = 0.0f, selected_sum = 0.0f;
73    for (int rank = 0; rank < 10; ++rank) {
74        float best = values[0];
75        int expert = lane;
76#pragma unroll
77        for (int i = 1; i < 16; ++i) {
78            if (values[i] > best) { best = values[i]; expert = lane + i * 32; }
79        }
80#pragma unroll
81        for (int mask = 16; mask; mask >>= 1) {
82            const float other = __shfl_xor_sync(0xffffffffu, best, mask, 32);
83            const int other_id = __shfl_xor_sync(0xffffffffu, expert, mask, 32);
84            if (other > best || (other == best && other_id < expert)) { best = other; expert = other_id; }
85        }
86        if ((expert & 31) == lane) {
87            values[expert / 32] = -INFINITY;
88            ids[rank] = expert;
89            // Deliberately accumulate by WINNING EXPERT lane, not output rank.
90            // Multiple selected experts in one lane add in selection order.
91            selected_sum += best;
92        }
93        if (rank == lane) selected = best;
94    }
95    selected_sum = max(warp_sum(selected_sum), 6.103515625e-5f);
96    const float inverse_selected_sum = 1.0f / selected_sum;
97    if (lane < 10) weights[lane] = selected * inverse_selected_sum;
98}
99__launch_bounds__(256, 1)
100__global__ void route_multi(const float* __restrict__ logits, int32_t* __restrict__ ids,
101                            float* __restrict__ weights, int n_tok) {
102    const int tk = (int) blockIdx.x * 8 + (int) threadIdx.y;
103    if (tk >= n_tok) return;
104    logits += (size_t) tk * 512; ids += (size_t) tk * 10; weights += (size_t) tk * 10;
105    const int lane = threadIdx.x;
106    float values[16];
107#pragma unroll
108    for (int i = 0; i < 16; ++i) values[i] = logits[lane + i * 32];
109    __syncwarp();
110    float maximum = -INFINITY;
111#pragma unroll
112    for (int i = 0; i < 16; ++i) maximum = max(maximum, values[i]);
113    maximum = warp_max(maximum);
114    float sum = 0.0f;
115#pragma unroll
116    for (int i = 0; i < 16; ++i) {
117        values[i] = expf(values[i] - maximum);
118        sum += values[i];
119    }
120    const float reciprocal = 1.0f / warp_sum(sum);
121#pragma unroll
122    for (int i = 0; i < 16; ++i) {
123        values[i] *= reciprocal;
124        if (__isnanf(values[i])) values[i] = -FLT_MAX;
125    }
126    float selected = 0.0f, selected_sum = 0.0f;
127    for (int rank = 0; rank < 10; ++rank) {
128        float best = values[0];
129        int expert = lane;
130#pragma unroll
131        for (int i = 1; i < 16; ++i) {
132            if (values[i] > best) { best = values[i]; expert = lane + i * 32; }
133        }
134#pragma unroll
135        for (int mask = 16; mask; mask >>= 1) {
136            const float other = __shfl_xor_sync(0xffffffffu, best, mask, 32);
137            const int other_id = __shfl_xor_sync(0xffffffffu, expert, mask, 32);
138            if (other > best || (other == best && other_id < expert)) { best = other; expert = other_id; }
139        }
140        if ((expert & 31) == lane) {
141            values[expert / 32] = -INFINITY;
142            ids[rank] = expert;
143            selected_sum += best;
144        }
145        if (rank == lane) selected = best;
146    }
147    selected_sum = max(warp_sum(selected_sum), 6.103515625e-5f);
148    const float inverse_selected_sum = 1.0f / selected_sum;
149    if (lane < 10) weights[lane] = selected * inverse_selected_sum;
150}
151// The same contract for other (experts, top-k) shapes - Qwen3.6-35B-A3B's 256 / 8 - one warp per token, n_tok tokens
152// (8 per block).  The 512 / 10 path keeps its own kernels above (the Flash-Next bits), this template is only used
153// for the other shapes.
154template <int NE, int K>
155__launch_bounds__(256, 1)
156__global__ void route_topk(const float* __restrict__ logits, int32_t* __restrict__ ids, float* __restrict__ weights,
157                           int n_tok) {
158    static_assert(NE % 32 == 0 && K <= 32, "experts in whole warps, at most 32 picks");
159    constexpr int V = NE / 32;
160    const int tk = (int) blockIdx.x * 8 + (int) threadIdx.y;
161    if (tk >= n_tok) return;
162    logits += (size_t) tk * NE; ids += (size_t) tk * K; weights += (size_t) tk * K;
163    const int lane = threadIdx.x;
164    float values[V];
165#pragma unroll
166    for (int i = 0; i < V; ++i) values[i] = logits[lane + i * 32];
167    float maximum = -INFINITY;
168#pragma unroll
169    for (int i = 0; i < V; ++i) maximum = max(maximum, values[i]);
170    maximum = warp_max(maximum);
171    float sum = 0.0f;
172#pragma unroll
173    for (int i = 0; i < V; ++i) {
174        values[i] = expf(values[i] - maximum);
175        sum += values[i];
176    }
177    const float reciprocal = 1.0f / warp_sum(sum);
178#pragma unroll
179    for (int i = 0; i < V; ++i) {
180        values[i] *= reciprocal;
181        if (__isnanf(values[i])) values[i] = -FLT_MAX;
182    }
183    float selected = 0.0f, selected_sum = 0.0f;
184    for (int rank = 0; rank < K; ++rank) {
185        float best = values[0];
186        int expert = lane;
187#pragma unroll
188        for (int i = 1; i < V; ++i) {
189            if (values[i] > best) { best = values[i]; expert = lane + i * 32; }
190        }
191#pragma unroll
192        for (int mask = 16; mask; mask >>= 1) {
193            const float other = __shfl_xor_sync(0xffffffffu, best, mask, 32);
194            const int other_id = __shfl_xor_sync(0xffffffffu, expert, mask, 32);
195            if (other > best || (other == best && other_id < expert)) { best = other; expert = other_id; }
196        }
197        if ((expert & 31) == lane) {
198            values[expert / 32] = -INFINITY;
199            ids[rank] = expert;
200            selected_sum += best;
201        }
202        if (rank == lane) selected = best;
203    }
204    selected_sum = max(warp_sum(selected_sum), 6.103515625e-5f);
205    const float inverse_selected_sum = 1.0f / selected_sum;
206    if (lane < K) weights[lane] = selected * inverse_selected_sum;
207}
208bool valid(const void* p, size_t bytes) {
209    const auto address = reinterpret_cast<uintptr_t>(p);
210    return p && address % 4 == 0 && bytes <= UINTPTR_MAX - address;
211}
212bool overlap(const void* a, size_t an, const void* b, size_t bn) {
213    const auto ap = reinterpret_cast<uintptr_t>(a), bp = reinterpret_cast<uintptr_t>(b);
214    return ap < bp + bn && bp < ap + an;
215}
216}
217void native_router_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); }
218bool native_router_enabled() { return enabled.load(std::memory_order_relaxed); }
219void native_router_top10(const float* logits, int32_t* ids, float* weights, void* stream) {
220    if (!stream || !valid(logits, 512 * 4) || !valid(ids, 10 * 4) || !valid(weights, 10 * 4)
221        || overlap(logits, 512 * 4, ids, 10 * 4) || overlap(logits, 512 * 4, weights, 10 * 4)
222        || overlap(ids, 10 * 4, weights, 10 * 4))
223        throw std::invalid_argument("native router requires a stream, aligned spans, and disjoint outputs");
224    route<<<1, dim3(32, 8), 0, static_cast<cudaStream_t>(stream)>>>(logits, ids, weights);
225    const auto error = cudaGetLastError();
226    if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
227}
228void native_router_top10_multi(const float* logits, int32_t* ids, float* weights, int n_tok, void* stream) {
229    if (!stream || n_tok < 1 || !valid(logits, (size_t) n_tok * 512 * 4) || !valid(ids, (size_t) n_tok * 10 * 4) ||
230        !valid(weights, (size_t) n_tok * 10 * 4))
231        throw std::invalid_argument("native router (multi) requires a stream and aligned [n,512]/[n,10] buffers");
232    route_multi<<<(unsigned) ((n_tok + 7) / 8), dim3(32, 8), 0, static_cast<cudaStream_t>(stream)>>>(logits, ids, weights, n_tok);
233    const auto error = cudaGetLastError();
234    if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
235}
236bool native_router_topk_supported(int n_expert, int k) { return (n_expert == 512 && k == 10) || (n_expert == 256 && k == 8); }
237void native_router_topk(const float* logits, int32_t* ids, float* weights, int n_expert, int k, int n_tok, void* stream) {
238    if (n_expert == 512 && k == 10) {   // Flash-Next: the pinned kernels above, unchanged
239        if (n_tok == 1) native_router_top10(logits, ids, weights, stream);
240        else native_router_top10_multi(logits, ids, weights, n_tok, stream);
241        return;
242    }
243    if (!stream || n_tok < 1 || !native_router_topk_supported(n_expert, k) ||
244        !valid(logits, (size_t) n_tok * n_expert * 4) || !valid(ids, (size_t) n_tok * k * 4) ||
245        !valid(weights, (size_t) n_tok * k * 4))
246        throw std::invalid_argument("native_router_topk: a stream, a supported (experts, k) and aligned buffers");
247    route_topk<256, 8><<<(unsigned) ((n_tok + 7) / 8), dim3(32, 8), 0, static_cast<cudaStream_t>(stream)>>>(
248        logits, ids, weights, n_tok);
249    const auto error = cudaGetLastError();
250    if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
251}
252
253// STRATA_ROUTE_RESIDENT (EXPERIMENTAL, opt-in, changes the output): residency-biased routing for 512 x 10.
254// After the top-10: for the ranks lo..hi a non-resident expert is replaced by the best resident expert not already
255// picked when its logit is within `margin` of the replaced one; the weights are then the softmax of the selected
256// logits (the router's renormalisation).  Tokens without a swap keep the router's exact bits.
257// stats (device, 4 x uint64): [0] tail entries seen, [1] swaps, [2] non-resident entries before, [3] after.
258//
259// One warp per token.  This used to be one THREAD per token scanning all 512 experts (4 ranks x 512 x 12 scalar
260// ops on up to 6 threads): 45 us per layer, 2.2 ms of a 19.4 ms window, which is exactly what the option saved in
261// PCIe experts (~2.4 ms) - the swap cost as much as the misses it removed.  The ranks are still visited in order
262// (a swap changes the set already picked), but the scan is coalesced (lane j reads f = j, j + 32, ...) and reduced
263// within the warp.  The bits are unchanged: a strictly greater logit wins, the smallest expert index breaks ties,
264// and the softmax is the same expression.
265__global__ void route_resident_k(const float* __restrict__ logits, int32_t* __restrict__ ids, float* __restrict__ weights,
266                                 const int32_t* __restrict__ res, int n_tok, float margin, int lo, int hi,
267                                 unsigned long long* __restrict__ stats) {
268    const int t = blockIdx.x;
269    if (t >= n_tok) return;
270    const int lane = (int) threadIdx.x;
271    const float* l = logits + (size_t) t * 512;
272    int32_t* id = ids + (size_t) t * 10;
273    int32_t my[10];
274    for (int r = 0; r < 10; ++r) my[r] = id[r];
275    int swaps = 0, tail = 0, before = 0;
276    if (lane == 0)
277        for (int r = 0; r < 10; ++r) before += res[my[r]] < 0;
278    for (int r = lo; r <= hi && r < 10; ++r) {
279        const int e = my[r];
280        if (res[e] >= 0) continue;                      // already resident: uniform across the warp
281        if (lane == 0) ++tail;
282        float bv = -INFINITY;
283        int bi = -1;
284        for (int f = lane; f < 512; f += 32) {
285            if (res[f] < 0) continue;
286            bool used = false;
287            for (int q = 0; q < 10; ++q) used |= my[q] == f;
288            if (used) continue;
289            if (l[f] > bv) { bv = l[f]; bi = f; }
290        }
291        #pragma unroll
292        for (int off = 16; off > 0; off >>= 1) {
293            const float ov = __shfl_down_sync(0xffffffffu, bv, off);
294            const int oi = __shfl_down_sync(0xffffffffu, bi, off);
295            if (ov > bv || (ov == bv && oi >= 0 && (bi < 0 || oi < bi))) { bv = ov; bi = oi; }
296        }
297        if (lane == 0 && bi >= 0 && l[e] - bv <= margin) { my[r] = bi; ++swaps; }
298        my[r] = __shfl_sync(0xffffffffu, my[r], 0);     // all lanes keep the same picked set
299    }
300    int after = 0;
301    if (lane == 0)
302        for (int r = 0; r < 10; ++r) after += res[my[r]] < 0;
303    const int sw = __shfl_sync(0xffffffffu, swaps, 0);
304    if (sw) {
305        float m = -INFINITY;
306        for (int r = 0; r < 10; ++r) m = fmaxf(m, l[my[r]]);
307        float ex[10], sum = 0.0f;
308        for (int r = 0; r < 10; ++r) { ex[r] = expf(l[my[r]] - m); sum += ex[r]; }
309        for (int r = 0; r < 10; ++r) weights[(size_t) t * 10 + r] = ex[r] / sum;
310    }
311    if (lane == 0) {
312        for (int r = 0; r < 10; ++r) id[r] = my[r];
313        if (stats) {
314            atomicAdd(stats + 0, (unsigned long long) tail);
315            atomicAdd(stats + 1, (unsigned long long) sw);
316            atomicAdd(stats + 2, (unsigned long long) before);
317            atomicAdd(stats + 3, (unsigned long long) after);
318        }
319    }
320}
321void native_route_resident(const float* logits, int32_t* ids, float* weights, const int32_t* res_layer, int n_tok, float margin,
322                           int rank_lo, int rank_hi, unsigned long long* stats, void* stream) {
323    if (!stream || n_tok < 1 || !res_layer) throw std::invalid_argument("native_route_resident: bad arguments");
324    route_resident_k<<<(unsigned) n_tok, 32, 0, static_cast<cudaStream_t>(stream)>>>(
325        logits, ids, weights, res_layer, n_tok, margin, rank_lo, rank_hi, stats);
326    const auto error = cudaGetLastError();
327    if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
328}
329}