Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

perf(moe): multi-token router kernel, float4 k=10 combine and float4 sigmoid scale (#783 PR-c)

Niko1221822251bef63c
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 8937b0bbb..5cd06a5e4 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -805,6 +805,11 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
target_include_directories(router_top10_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(router_top10_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME router_top10_parity COMMAND router_top10_parity --selftest)
+ # #783 PR-c: the multi-token router and the k = 10 float4 combine, bitwise against the single-token contracts
+ add_executable(native_multi_parity src/kernels/native_multi_parity.cpp)
+ target_include_directories(native_multi_parity PRIVATE ${_strata_gpu_include_directories})
+ target_link_libraries(native_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
+ add_test(NAME native_multi_parity COMMAND native_multi_parity)
if(STRATA_HIP_GFX906)
# the S6 router (STRATA_HIP_ROUTER_FAST=1 on gfx906) against the portable kernel, bitwise, on wave64
add_executable(hip_router_fast tests/hip/router_fast.cpp)
diff --git a/src/kernels/cuda/native_moe.cu b/src/kernels/cuda/native_moe.cu
index ab3950d91..fb4818feb 100644
--- a/src/kernels/cuda/native_moe.cu
+++ b/src/kernels/cuda/native_moe.cu
@@ -63,6 +63,35 @@ __global__ void combine(const float* __restrict__ parts, const float* __restrict
}
output[col] = sum;
}
+__global__ void combine_k10_vec4(const float4* __restrict__ parts4, const float* __restrict__ weights,
+ const float4* __restrict__ shared4, float4* __restrict__ output4,
+ int64_t n4) {
+ const int64_t tk = blockIdx.y;
+ parts4 += tk * 10 * n4;
+ weights += tk * 10;
+ shared4 += tk * n4;
+ output4 += tk * n4;
+ const int64_t c4 = int64_t(blockIdx.x) * blockDim.x + threadIdx.x;
+ if (c4 >= n4) return;
+ const float w0 = __ldg(weights + 0);
+ const float4 p0 = parts4[c4];
+ float4 sum = make_float4(p0.x * w0, p0.y * w0, p0.z * w0, p0.w * w0);
+#pragma unroll
+ for (int expert = 1; expert < 10; ++expert) {
+ const float w = __ldg(weights + expert);
+ const float4 p = parts4[int64_t(expert) * n4 + c4];
+ sum.x += p.x * w;
+ sum.y += p.y * w;
+ sum.z += p.z * w;
+ sum.w += p.w * w;
+ }
+ const float4 sh = shared4[c4];
+ sum.x += sh.x;
+ sum.y += sh.y;
+ sum.z += sh.z;
+ sum.w += sh.w;
+ output4[c4] = sum;
+}
bool valid_span(const void* p, size_t bytes) {
const auto address = reinterpret_cast<uintptr_t>(p);
return p && address % alignof(float) == 0 && bytes <= UINTPTR_MAX - address;
@@ -86,8 +115,16 @@ void native_moe_combine(const float* parts, const float* weights, const float* s
|| overlap(output, row_bytes, weights, weight_bytes)
|| (shared && overlap(output, row_bytes, shared, row_bytes)))
throw std::invalid_argument("native MoE combine requires aligned spans and disjoint output");
- combine<<<unsigned((n_embd + 255) / 256), 256, 0, static_cast<cudaStream_t>(stream)>>>(
- parts, weights, shared, output, n_embd, int(k));
+ if (k == 10 && shared != nullptr && (n_embd & 3) == 0 &&
+ (((uintptr_t) parts | (uintptr_t) shared | (uintptr_t) output) & 15u) == 0) {
+ const int64_t n4 = n_embd >> 2;
+ combine_k10_vec4<<<unsigned((n4 + 127) / 128), 128, 0, static_cast<cudaStream_t>(stream)>>>(
+ reinterpret_cast<const float4*>(parts), weights, reinterpret_cast<const float4*>(shared),
+ reinterpret_cast<float4*>(output), n4);
+ } else {
+ combine<<<unsigned((n_embd + 255) / 256), 256, 0, static_cast<cudaStream_t>(stream)>>>(
+ parts, weights, shared, output, n_embd, int(k));
+ }
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
@@ -95,8 +132,16 @@ void native_moe_combine_multi(const float* parts, const float* weights, const fl
int64_t n_embd, int64_t k, int n_tok, void* stream) {
if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1)
throw std::invalid_argument("native MoE combine (multi) requires a stream, width, 1..15 experts, tokens");
- combine<<<dim3(unsigned((n_embd + 255) / 256), (unsigned) n_tok), 256, 0, static_cast<cudaStream_t>(stream)>>>(
- parts, weights, shared, output, n_embd, int(k));
+ if (k == 10 && shared != nullptr && (n_embd & 3) == 0 &&
+ (((uintptr_t) parts | (uintptr_t) shared | (uintptr_t) output) & 15u) == 0) {
+ const int64_t n4 = n_embd >> 2;
+ combine_k10_vec4<<<dim3(unsigned((n4 + 127) / 128), (unsigned) n_tok), 128, 0, static_cast<cudaStream_t>(stream)>>>(
+ reinterpret_cast<const float4*>(parts), weights, reinterpret_cast<const float4*>(shared),
+ reinterpret_cast<float4*>(output), n4);
+ } else {
+ combine<<<dim3(unsigned((n_embd + 255) / 256), (unsigned) n_tok), 256, 0, static_cast<cudaStream_t>(stream)>>>(
+ parts, weights, shared, output, n_embd, int(k));
+ }
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
diff --git a/src/kernels/cuda/native_router.cu b/src/kernels/cuda/native_router.cu
index 3f8b69ce2..9f6b7022c 100644
--- a/src/kernels/cuda/native_router.cu
+++ b/src/kernels/cuda/native_router.cu
@@ -96,6 +96,58 @@ __global__ void route(const float* __restrict__ logits, int32_t* __restrict__ id
const float inverse_selected_sum = 1.0f / selected_sum;
if (lane < 10) weights[lane] = selected * inverse_selected_sum;
}
+__launch_bounds__(256, 1)
+__global__ void route_multi(const float* __restrict__ logits, int32_t* __restrict__ ids,
+ float* __restrict__ weights, int n_tok) {
+ const int tk = (int) blockIdx.x * 8 + (int) threadIdx.y;
+ if (tk >= n_tok) return;
+ logits += (size_t) tk * 512; ids += (size_t) tk * 10; weights += (size_t) tk * 10;
+ const int lane = threadIdx.x;
+ float values[16];
+#pragma unroll
+ for (int i = 0; i < 16; ++i) values[i] = logits[lane + i * 32];
+ __syncwarp();
+ float maximum = -INFINITY;
+#pragma unroll
+ for (int i = 0; i < 16; ++i) maximum = max(maximum, values[i]);
+ maximum = warp_max(maximum);
+ float sum = 0.0f;
+#pragma unroll
+ for (int i = 0; i < 16; ++i) {
+ values[i] = expf(values[i] - maximum);
+ sum += values[i];
+ }
+ const float reciprocal = 1.0f / warp_sum(sum);
+#pragma unroll
+ for (int i = 0; i < 16; ++i) {
+ values[i] *= reciprocal;
+ if (__isnanf(values[i])) values[i] = -FLT_MAX;
+ }
+ float selected = 0.0f, selected_sum = 0.0f;
+ for (int rank = 0; rank < 10; ++rank) {
+ float best = values[0];
+ int expert = lane;
+#pragma unroll
+ for (int i = 1; i < 16; ++i) {
+ if (values[i] > best) { best = values[i]; expert = lane + i * 32; }
+ }
+#pragma unroll
+ for (int mask = 16; mask; mask >>= 1) {
+ const float other = __shfl_xor_sync(0xffffffffu, best, mask, 32);
+ const int other_id = __shfl_xor_sync(0xffffffffu, expert, mask, 32);
+ if (other > best || (other == best && other_id < expert)) { best = other; expert = other_id; }
+ }
+ if ((expert & 31) == lane) {
+ values[expert / 32] = -INFINITY;
+ ids[rank] = expert;
+ selected_sum += best;
+ }
+ if (rank == lane) selected = best;
+ }
+ selected_sum = max(warp_sum(selected_sum), 6.103515625e-5f);
+ const float inverse_selected_sum = 1.0f / selected_sum;
+ if (lane < 10) weights[lane] = selected * inverse_selected_sum;
+}
bool valid(const void* p, size_t bytes) {
const auto address = reinterpret_cast<uintptr_t>(p);
return p && address % 4 == 0 && bytes <= UINTPTR_MAX - address;
@@ -120,7 +172,7 @@ void native_router_top10_multi(const float* logits, int32_t* ids, float* weights
if (!stream || n_tok < 1 || !valid(logits, (size_t) n_tok * 512 * 4) || !valid(ids, (size_t) n_tok * 10 * 4) ||
!valid(weights, (size_t) n_tok * 10 * 4))
throw std::invalid_argument("native router (multi) requires a stream and aligned [n,512]/[n,10] buffers");
- route<<<(unsigned) n_tok, dim3(32, 8), 0, static_cast<cudaStream_t>(stream)>>>(logits, ids, weights);
+ route_multi<<<(unsigned) ((n_tok + 7) / 8), dim3(32, 8), 0, static_cast<cudaStream_t>(stream)>>>(logits, ids, weights, n_tok);
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
diff --git a/src/kernels/cuda/shared_expert.cu b/src/kernels/cuda/shared_expert.cu
index 2214c7f90..450fe24a9 100644
--- a/src/kernels/cuda/shared_expert.cu
+++ b/src/kernels/cuda/shared_expert.cu
@@ -177,6 +177,31 @@ __global__ void sigmoid_scale_rows_kernel(float* __restrict__ out, const float*
}
}
+__global__ void sigmoid_scale_rows_vec4_kernel(float4* __restrict__ out4, const float* __restrict__ g, int n4) {
+ const int t = blockIdx.y;
+ const int i = blockIdx.x * blockDim.x + threadIdx.x;
+ if (i < n4) {
+ const float gt = __fdividef(1.0f, 1.0f + __expf(-__ldg(g + t)));
+ float4 v = out4[(size_t) t * n4 + i];
+ v.x *= gt;
+ v.y *= gt;
+ v.z *= gt;
+ v.w *= gt;
+ out4[(size_t) t * n4 + i] = v;
+ }
+}
+
+void launch_sigmoid_scale_rows(float* out, const float* g, int n_embd, int n_tok, cudaStream_t cs) {
+ if ((n_embd & 3) == 0 && ((uintptr_t) out & 15u) == 0) {
+ const int n4 = n_embd >> 2;
+ sigmoid_scale_rows_vec4_kernel<<<dim3((unsigned) ((n4 + THREADS - 1) / THREADS), (unsigned) n_tok), THREADS, 0, cs>>>(
+ reinterpret_cast<float4*>(out), g, n4);
+ } else {
+ sigmoid_scale_rows_kernel<<<dim3((unsigned) ((n_embd + THREADS - 1) / THREADS), (unsigned) n_tok), THREADS, 0, cs>>>(
+ out, g, n_embd);
+ }
+}
+
bool fused_swiglu_q81_enabled() {
static const bool on = [] {
const char* v = std::getenv("STRATA_FUSED_SWIGLU_Q81");
@@ -221,12 +246,10 @@ void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, cons
static const bool batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }();
if (native_bf16 && batch && n_tok > 1) { // one gemv for all rows (outputs identical), fused sigmoid+scale
bf16_gemv_fp32_mmvf_multi(x, n_embd, gate_inp_bf16, g, 1, n_embd, 1, n_tok, stream);
- sigmoid_scale_rows_kernel<<<dim3((unsigned) ((n_embd + THREADS - 1) / THREADS), (unsigned) n_tok), THREADS, 0, cs>>>(
- out, g, (int) n_embd);
+ launch_sigmoid_scale_rows(out, g, (int) n_embd, n_tok, cs);
} else if (native_bf16 && n_tok == 1) {
bf16_gemv_fp32_mmvf(x, gate_inp_bf16, g, n_embd, 1, stream);
- sigmoid_scale_rows_kernel<<<dim3((unsigned) ((n_embd + THREADS - 1) / THREADS), 1u), THREADS, 0, cs>>>(
- out, g, (int) n_embd);
+ launch_sigmoid_scale_rows(out, g, (int) n_embd, 1, cs);
} else {
for (int t = 0; t < n_tok; ++t) {
if (native_bf16) {
@@ -357,7 +380,7 @@ void shared_expert(const uint8_t* x_q8_0, const uint8_t* x_q8k, const uint16_t*
// round trip. 256 threads is the reduction's width, not the problem's size.
if (use_native) {
bf16_gemv_fp32_mmvf(x_f32, gate_inp_bf16, g, n_embd, 1, stream);
- sigmoid_scale_rows_kernel<<<dim3(g_embd, 1u), THREADS, 0, (cudaStream_t) stream>>>(out, g, (int) n_embd);
+ launch_sigmoid_scale_rows(out, g, (int) n_embd, 1, (cudaStream_t) stream);
} else {
scalar_gate_kernel<<<1, 256, 0, (cudaStream_t) stream>>>(x_bf16, gate_inp_bf16, g, (int) n_embd);
scale_kernel<<<g_embd, THREADS, 0, (cudaStream_t) stream>>>(out, g, (int) n_embd);
diff --git a/src/kernels/native_multi_parity.cpp b/src/kernels/native_multi_parity.cpp
new file mode 100644
index 000000000..6c88b50b0
--- /dev/null
+++ b/src/kernels/native_multi_parity.cpp
@@ -0,0 +1,155 @@
+// src/kernels/native_multi_parity.cpp - the multi-token router and the k = 10 combine, bitwise against their
+// single-token contracts (#783 PR-c: route_multi, combine_k10_vec4).
+//
+// * native_router_top10_multi (one warp per token, 8 tokens per CTA) against native_router_top10 token by token,
+// for n = 1..19 (a partial last CTA, and more than one CTA), on plain logits, on logits with exact ties and on
+// logits with NaN (the router maps NaN to -FLT_MAX): ids and weights are compared with memcmp;
+// * native_moe_combine / native_moe_combine_multi (k = 10 with a shared row takes the float4 kernel; a misaligned
+// output, k = 9 and a null shared row take the scalar one) against a host replay of the documented contract:
+// the first product rounds to F32, the next ones accumulate with FMA in expert order, the shared row is added
+// once: memcmp.
+#include "strata/kernels/native_moe.hpp"
+#include "strata/kernels/native_router.hpp"
+
+#include <cuda_runtime.h>
+
+#include <cmath>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <random>
+#include <string>
+#include <vector>
+
+namespace {
+
+void check(cudaError_t e, const char* what) {
+ if (e != cudaSuccess) {
+ std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));
+ std::exit(1);
+ }
+}
+
+template <typename T>
+T* up(const std::vector<T>& h) {
+ void* p = nullptr;
+ check(cudaMalloc(&p, h.size() * sizeof(T) + 64), "malloc");
+ check(cudaMemcpy(p, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "h2d");
+ return (T*) p;
+}
+template <typename T>
+std::vector<T> down(const T* d, size_t n) {
+ std::vector<T> h(n);
+ check(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "d2h");
+ return h;
+}
+
+} // namespace
+
+int main(int argc, char**) {
+ (void) argc;
+ using namespace strata::kernels;
+ std::mt19937 rng(783);
+ std::normal_distribution<float> gauss(0.0f, 1.0f);
+ int bad = 0;
+ cudaStream_t st = nullptr;
+ check(cudaStreamCreate(&st), "stream");
+
+ // ---- the multi-token router
+ for (int mode = 0; mode < 3; ++mode) {
+ const char* names[] = {"random logits", "exact ties", "NaN logits"};
+ int mode_bad = 0, cases = 0;
+ for (int n = 1; n <= 19; ++n) {
+ std::vector<float> lg((size_t) n * 512);
+ for (auto& v : lg) v = gauss(rng) * 2.0f;
+ if (mode == 1)
+ for (size_t i = 0; i < lg.size(); ++i) lg[i] = (float) (int) (lg[i] * 2.0f) * 0.5f; // coarse: many exact ties
+ if (mode == 2)
+ for (int t = 0; t < n; ++t) lg[(size_t) t * 512 + (size_t) (rng() % 512)] = std::nanf("");
+ float* d_l = up(lg);
+ int32_t *d_i, *d_ir;
+ float *d_w, *d_wr;
+ check(cudaMalloc(&d_i, (size_t) n * 10 * 4), "i");
+ check(cudaMalloc(&d_ir, (size_t) n * 10 * 4), "ir");
+ check(cudaMalloc(&d_w, (size_t) n * 10 * 4), "w");
+ check(cudaMalloc(&d_wr, (size_t) n * 10 * 4), "wr");
+ native_router_top10_multi(d_l, d_i, d_w, n, st);
+ for (int t = 0; t < n; ++t) native_router_top10(d_l + (size_t) t * 512, d_ir + t * 10, d_wr + t * 10, st);
+ check(cudaDeviceSynchronize(), "sync");
+ const auto i1 = down(d_i, (size_t) n * 10), i2 = down(d_ir, (size_t) n * 10);
+ const auto w1 = down(d_w, (size_t) n * 10), w2 = down(d_wr, (size_t) n * 10);
+ ++cases;
+ if (std::memcmp(i1.data(), i2.data(), i1.size() * 4) != 0 || std::memcmp(w1.data(), w2.data(), w1.size() * 4) != 0) {
+ std::printf(" *** native_router_top10_multi n=%d (%s) differs from native_router_top10 ***\n", n, names[mode]);
+ ++mode_bad;
+ }
+ cudaFree(d_l); cudaFree(d_i); cudaFree(d_ir); cudaFree(d_w); cudaFree(d_wr);
+ }
+ std::printf(" %-52s %s (%d cases)\n", (std::string("router multi == single, ") + names[mode]).c_str(),
+ mode_bad ? "*** NO ***" : "bitwise", cases);
+ bad += mode_bad;
+ }
+
+ // ---- the combine
+ struct Cfg { const char* name; int k; bool shared; int out_off; };
+ const Cfg cfgs[] = {{"k=10 + shared (float4 kernel)", 10, true, 0}, {"k=10 + shared, output misaligned", 10, true, 1},
+ {"k=10 without shared", 10, false, 0}, {"k=9 + shared", 9, true, 0}};
+ const int N = 2048;
+ for (const Cfg& c : cfgs) {
+ int cfg_bad = 0, cases = 0;
+ for (int n = 1; n <= 8; ++n) {
+ std::vector<float> parts((size_t) n * c.k * N), w((size_t) n * c.k), sh((size_t) n * N);
+ for (auto& v : parts) v = gauss(rng);
+ for (auto& v : w) v = (float) (rng() % 1000) / 1000.0f;
+ for (auto& v : sh) v = gauss(rng);
+ float* d_p = up(parts);
+ float* d_w = up(w);
+ float* d_s = up(sh);
+ float* d_o = nullptr;
+ check(cudaMalloc(&d_o, (size_t) n * N * 4 + 64), "o");
+ float* out = d_o + c.out_off;
+ if (c.out_off) {
+ // a misaligned output cannot take a multi launch of rows with the 4-float stride contract either way:
+ // the rows are still n*N floats from `out`
+ }
+ native_moe_combine_multi(d_p, d_w, c.shared ? d_s : nullptr, out, N, c.k, n, st);
+ check(cudaDeviceSynchronize(), "sync");
+ const auto got = down(out, (size_t) n * N);
+ std::vector<float> want((size_t) n * N);
+ for (int t = 0; t < n; ++t)
+ for (int col = 0; col < N; ++col) {
+ float s = parts[((size_t) t * c.k) * N + col] * w[(size_t) t * c.k];
+ for (int e = 1; e < c.k; ++e)
+ s = std::fmaf(parts[((size_t) t * c.k + e) * N + col], w[(size_t) t * c.k + e], s);
+ if (c.shared) s += sh[(size_t) t * N + col];
+ want[(size_t) t * N + col] = s;
+ }
+ ++cases;
+ if (std::memcmp(got.data(), want.data(), got.size() * 4) != 0) {
+ std::printf(" *** native_moe_combine_multi n=%d (%s) differs from the contract's host replay ***\n", n, c.name);
+ ++cfg_bad;
+ }
+ // the single-token call is the same arithmetic
+ if (n == 1) {
+ check(cudaMemset(d_o, 0, (size_t) N * 4 + 64), "z");
+ native_moe_combine(d_p, d_w, c.shared ? d_s : nullptr, out, N, c.k, st);
+ check(cudaDeviceSynchronize(), "sync");
+ const auto g1 = down(out, (size_t) N);
+ ++cases;
+ if (std::memcmp(g1.data(), want.data(), g1.size() * 4) != 0) {
+ std::printf(" *** native_moe_combine (%s) differs from the contract's host replay ***\n", c.name);
+ ++cfg_bad;
+ }
+ }
+ cudaFree(d_p); cudaFree(d_w); cudaFree(d_s); cudaFree(d_o);
+ }
+ std::printf(" %-52s %s (%d cases)\n", (std::string("combine ") + c.name).c_str(), cfg_bad ? "*** NO ***" : "bitwise", cases);
+ bad += cfg_bad;
+ }
+
+ std::printf("\nnative_multi: %d failures\n", bad);
+ if (bad) return 1;
+ std::printf("native_multi_parity OK\n");
+ return 0;
+}