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++
HIP (S6): router_top10 without its serial parts on AMD, bitwise the same (default on HIP; STRATA_HIP_ROUTER_OLD=1: old)
Niko1221a2be1670bbae
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 3bc403e50..ef40fd74a 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -414,6 +414,11 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)add_test(NAME hip_prefill_native_batch COMMAND hip_prefill_native_batch)list(APPEND _strata_hip_tests hip_prefill_native_batch)endif()+ # S6: the AMD fast router against the portable kernel, bitwise+ add_executable(hip_router_fast tests/hip/router_fast.cpp)+ target_link_libraries(hip_router_fast PRIVATE strata_kernels strata_hip_runtime)+ add_test(NAME hip_router_fast COMMAND hip_router_fast)+ list(APPEND _strata_hip_tests hip_router_fast)# S6: the RDNA4 matrix-core prompt attention (STRATA_HIP_WMMA) against the FP32 kernel and FP64; skips off gfx12add_executable(hip_prompt_attn_wmma src/kernels/qsa_prompt_attn_parity.cpp)target_link_libraries(hip_prompt_attn_wmma PRIVATE strata_kernels strata_hip_runtime)diff --git a/include/strata/kernels/router_top10.hpp b/include/strata/kernels/router_top10.hppindex 2158c1fdf..e10295e1e 100644--- a/include/strata/kernels/router_top10.hpp+++ b/include/strata/kernels/router_top10.hpp@@ -17,4 +17,10 @@ namespace strata::kernels {void router_top10(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights,void* stream);+/// Tests (S6, HIP only): one router kernel by name - 0 the portable kernel, 1 the AMD fast kernel (the default there+/// for 64 < n_expert <= 512, k <= 32; bitwise the same results), 2 the fast kernel forced onto its serial-sum path.+/// False (nothing launched) on CUDA builds or outside that geometry.+bool router_top10_variant(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights,+ void* stream, int variant);+} // namespace strata::kernelsdiff --git a/src/kernels/cuda/router_top10.cu b/src/kernels/cuda/router_top10.cuindex 1f137e597..88138d5aa 100644--- a/src/kernels/cuda/router_top10.cu+++ b/src/kernels/cuda/router_top10.cu@@ -186,10 +186,186 @@ __global__ void router_top10_kernel(const float* __restrict__ logits, int n_toke}}+#if defined(__HIPCC__)+// ---- S6, AMD: the same router, BIT-IDENTICAL, without its serial parts. Measured on RDNA4 (gfx1201) the kernel+// above took 39 us per call in decode (16% of the GPU's decode time): the ascending double sum is 512 dependent FP64+// adds (~50 cycles each there), the ten selection passes are 20 block barriers, and the renormalisation re-reads its+// ten weights from global memory one by one. Here:+// * the sum's ONLY use is inv = (float) (1.0 / sum). Every term is positive and the largest is exactly 1+// (exp(0)), so the serial sum and any other summation order both lie within 2^-43 (relative) of the exact sum+// (|serial - exact| <= 511u, |tree - exact| <= 21u, u = 2^-53). 1.0 / x and the float cast are monotone: when+// the bracket [tree (1 - 2^-40), tree (1 + 2^-40)] maps to ONE float, that float is the serial sum's. Otherwise+// (about 1 row in 1000 in the parity test, or a non-finite sum) thread 0 runs the serial sum as before;+// * the selection runs on wave 0 alone with the probabilities in registers (16 per lane): the largest p with the+// lowest index on ties is unique, so the butterfly finds the same expert as the block reduction did;+// * the renormalisation sums the ten weights in rank order from registers and divides them in parallel.+// Same expressions, same operands: the ids and weights are bitwise those of router_top10_kernel (hip_router_fast+// checks it on 65,536 rows with ties, near-ties, NaN rows and the forced serial path). STRATA_HIP_ROUTER_OLD=1: the+// kernel above.+template <bool FORCE_SERIAL>+__global__ void router_top10_fast_kernel(const float* __restrict__ logits, int n_tokens, int n_expert, int k,+ int* __restrict__ ids, float* __restrict__ weights) {+ extern __shared__ unsigned char s_raw[];+ const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u;+ double* s_ex = (double*) (s_raw + taken_bytes);+ __shared__ float s_red[RT_MAX_THREADS / 32];+ __shared__ double s_dred[RT_MAX_THREADS / 32];+ __shared__ float s_inv;+ const int t = blockIdx.x;+ if (t >= n_tokens) return;+ const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;+ const int nt = blockDim.x, nw = (nt + 31) >> 5;+ const float* l = logits + (size_t) t * n_expert;+ // the max: as router_top10_kernel (exact, order-independent)+ float mx = -INFINITY;+ for (int e = tid; e < n_expert; e += nt) mx = fmaxf(mx, l[e]);+ for (int off = 16; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_down_sync(0xffffffffu, mx, off));+ if (lane == 0) s_red[warp] = mx;+ __syncthreads();+ if (tid < 32) {+ float v = (tid < nw) ? s_red[tid] : -INFINITY;+ for (int off = 16; off > 0; off >>= 1) v = fmaxf(v, __shfl_down_sync(0xffffffffu, v, off));+ if (tid == 0) s_red[0] = v;+ }+ __syncthreads();+ mx = s_red[0];+ // the exponentials (the same expression), and a tree sum of them for the bracket+ double part = 0.0;+ for (int e = tid; e < n_expert; e += nt) {+ const double x = exp((double) l[e] - (double) mx);+ s_ex[e] = x;+ part += x;+ }+ for (int off = 16; off > 0; off >>= 1) part += __shfl_xor_sync(0xffffffffu, part, off);+ if (lane == 0) s_dred[warp] = part;+ __syncthreads();+ double tot = 0.0;+ for (int w = 0; w < nw; ++w) tot += s_dred[w];+ const double lo = tot * (1.0 - 0x1p-40), hi = tot * (1.0 + 0x1p-40);+ const float f_lo = (float) (1.0 / hi), f_hi = (float) (1.0 / lo);+ float inv;+ if (!FORCE_SERIAL && tot >= 1.0 && hi < 1e300 && f_lo == f_hi) {+ inv = f_lo;+ } else { // block-uniform (every thread computed the same tot): the serial sum, exactly as router_top10_kernel+ if (tid == 0) {+ double sum = 0.0;+ for (int e = 0; e < n_expert; ++e) sum += s_ex[e];+ s_inv = (float) (1.0 / sum);+ }+ __syncthreads();+ inv = s_inv;+ }+ if (warp != 0) return;+ // wave 0: lane holds experts lane + 32 j; p is router_top10_kernel's expression+ constexpr int PER = 16;+ float pv[PER];+ unsigned live = 0;+#pragma unroll+ for (int j = 0; j < PER; ++j) {+ const int e = lane + 32 * j;+ pv[j] = -INFINITY;+ if (e < n_expert) { pv[j] = (float) (s_ex[e] * inv); live |= 1u << j; }+ }+ float my_w = 0.0f;+ int my_id = 0, nsel = 0;+ for (int i = 0; i < k; ++i) {+ float bv = -INFINITY;+ int bi = n_expert; // a sentinel that loses to every real index+#pragma unroll+ for (int j = 0; j < PER; ++j)+ if (((live >> j) & 1u) && pv[j] > bv) { bv = pv[j]; bi = lane + 32 * j; }+ for (int off = 16; off > 0; off >>= 1) {+ const float ov = __shfl_xor_sync(0xffffffffu, bv, off);+ const int oi = __shfl_xor_sync(0xffffffffu, bi, off);+ if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }+ }+ if (bi >= n_expert) break; // as router_top10_kernel: no rank i or later is written (every p left is NaN)+ if ((bi & 31) == lane) live &= ~(1u << (bi >> 5));+ if (lane == i) { my_w = bv; my_id = bi; }+ nsel = i + 1;+ }+ if (nsel == k) {+ double s = 0.0;+ for (int i = 0; i < k; ++i) s += (double) __shfl_sync(0xffffffffu, my_w, i);+ const double sc = fmax(s, 6.103515625e-05); // 2**-14+ if (lane < k) {+ ids[(size_t) t * k + lane] = my_id;+ weights[(size_t) t * k + lane] = (float) ((double) my_w / sc);+ }+ } else { // router_top10_kernel's tail exactly: unwritten ranks keep what the buffer held and are renormalised too+ if (lane < nsel) { ids[(size_t) t * k + lane] = my_id; weights[(size_t) t * k + lane] = my_w; }+ __threadfence();+ if (lane == 0) {+ double s = 0.0;+ for (int i = 0; i < k; ++i) s += (double) weights[(size_t) t * k + i];+ const double sc = fmax(s, 6.103515625e-05);+ for (int i = 0; i < k; ++i)+ weights[(size_t) t * k + i] = (float) ((double) weights[(size_t) t * k + i] / sc);+ }+ }+}++void launch_generic(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights, void* stream,+ int mode) { // mode 0: router_top10_kernel, 1: the HIP fast kernel, 2: the fast kernel's serial path+ int threads = n_expert < RT_MAX_THREADS ? n_expert : RT_MAX_THREADS;+ threads = (threads + 31) & ~31;+ const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u;+ const size_t smem = taken_bytes + (size_t) n_expert * sizeof(double) + (size_t) n_expert * sizeof(float);+#if defined(__HIPCC__)+ if (mode == 1) {+ router_top10_fast_kernel<false><<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>(+ logits, n_tokens, n_expert, k, ids, weights);+ return;+ }+ if (mode == 2) {+ router_top10_fast_kernel<true><<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>(+ logits, n_tokens, n_expert, k, ids, weights);+ return;+ }+ router_top10_kernel<<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>(+ logits, n_tokens, n_expert, k, ids, weights);+}+#endif+} // namespace+bool router_top10_variant(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights,+ void* stream, int variant) {+#if defined(__HIPCC__)+ if (n_tokens <= 0 || n_expert <= 64 || n_expert > 512 || k <= 0 || k > 32) return false;+ if (variant < 0 || variant > 2) return false;+ launch_generic(logits, n_tokens, n_expert, k, ids, weights, stream, variant);+ return cudaGetLastError() == cudaSuccess;+#else+ (void) logits; (void) n_tokens; (void) n_expert; (void) k; (void) ids; (void) weights; (void) stream;+ (void) variant;+ return false;+#endif+}+void router_top10(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights,void* stream) {+#if defined(__HIPCC__)+ {+ static const bool old = std::getenv("STRATA_HIP_ROUTER_OLD") != nullptr;+ if (!old && n_tokens > 0 && n_expert > 64 && n_expert <= 512 && k > 0 && k <= 32) {+ launch_generic(logits, n_tokens, n_expert, k, ids, weights, stream, 1);+ const cudaError_t e = cudaGetLastError();+ if (e != cudaSuccess) {+ std::fprintf(stderr, "router_top10 launch: %s\n", cudaGetErrorString(e));+ std::exit(1);+ }+ if (stream == nullptr) {+ const cudaError_t s = cudaDeviceSynchronize();+ if (s != cudaSuccess) {+ std::fprintf(stderr, "router_top10: %s\n", cudaGetErrorString(s));+ std::exit(1);+ }+ }+ return;+ }+ }+#endifif (n_tokens <= 0 || n_expert <= 0 || k <= 0) return;if (k > 64) {std::fprintf(stderr, "router_top10: k %d exceeds the kernel's 64\n", k);diff --git a/src/kernels/qsa_prompt_attn_parity.cpp b/src/kernels/qsa_prompt_attn_parity.cppindex 9525d0cfc..c5dad7c95 100644--- a/src/kernels/qsa_prompt_attn_parity.cpp+++ b/src/kernels/qsa_prompt_attn_parity.cpp@@ -220,7 +220,9 @@ int main(int argc, char** argv) {const int reps = argc > 3 ? std::atoi(argv[3]) : 5;int fails = 0;fails += run(1, ctx, nq, reps);- fails += run(0, ctx, nq, reps);+#if !defined(__HIP_PLATFORM_AMD__)+ fails += run(0, ctx, nq, reps); // FP16 KV: the RDNA4 kernel takes int8 KV only+#endiffails += run(1, 1500, std::min<int64_t>(nq, 1500), reps); // short context: the selection is every cellfails += run(1, 2100, std::min<int64_t>(nq, 256), reps); // the identity-to-sparse edgestd::printf("FAILURES: %d\n", fails);diff --git a/tests/hip/router_fast.cpp b/tests/hip/router_fast.cppnew file mode 100644index 000000000..d0db85e59--- /dev/null+++ b/tests/hip/router_fast.cpp@@ -0,0 +1,101 @@+// S6: the AMD fast router (router_top10's default on HIP for 64 < n_expert <= 512, k <= 32) against the portable+// kernel, BITWISE: ids and weights of 65,536 rows of 512 logits - normal rows, rows with many exact ties, near-ties,+// a wide spread (tiny probabilities), all-equal rows and rows with a NaN - plus the fast kernel forced onto its+// serial-sum path, and a 256-expert / k=8 geometry. Then the time per single-token call of each.+#include <hip/hip_runtime.h>+#include "strata/kernels/router_top10.hpp"++#include <cmath>+#include <cstdio>+#include <cstring>+#include <random>+#include <vector>++#define CHECK(call) \+ do { \+ const hipError_t error = (call); \+ if (error != hipSuccess) { \+ std::fprintf(stderr, "%s: %s\n", #call, hipGetErrorString(error)); \+ return 2; \+ } \+ } while (0)++namespace k = strata::kernels;++static int compare(int n_expert, int topk, int rows, unsigned seed) {+ std::mt19937 rng(seed);+ std::normal_distribution<float> nd(0.f, 2.f);+ std::vector<float> lg((size_t) rows * n_expert);+ for (size_t i = 0; i < lg.size(); ++i) {+ const size_t r = i / n_expert;+ float x = nd(rng) * (r % 7 == 5 ? 40.0f : 1.0f);+ if (r % 3 == 1) x = std::round(x * 4.0f) / 4.0f;+ if (r % 3 == 2) x = std::round(x * 64.0f) / 64.0f;+ if (r % 1000 == 999 && (i % n_expert) == 77) x = NAN;+ if (r % 1000 == 998) x = 1.0f;+ lg[i] = x;+ }+ const size_t out = (size_t) rows * topk;+ float *d_l = nullptr, *d_w[3] = {};+ int* d_i[3] = {};+ CHECK(hipMalloc(&d_l, lg.size() * 4));+ CHECK(hipMemcpy(d_l, lg.data(), lg.size() * 4, hipMemcpyHostToDevice));+ std::vector<int> ids[3];+ std::vector<float> w[3];+ for (int v = 0; v < 3; ++v) {+ CHECK(hipMalloc(&d_w[v], out * 4));+ CHECK(hipMalloc(&d_i[v], out * 4));+ CHECK(hipMemset(d_w[v], 0x3c, out * 4)); // what an unwritten rank keeps (NaN rows)+ CHECK(hipMemset(d_i[v], 0x11, out * 4));+ if (!k::router_top10_variant(d_l, rows, n_expert, topk, d_i[v], d_w[v], nullptr, v)) {+ std::fprintf(stderr, "router_top10_variant %d refused\n", v);+ return 2;+ }+ CHECK(hipDeviceSynchronize());+ ids[v].resize(out);+ w[v].resize(out);+ CHECK(hipMemcpy(ids[v].data(), d_i[v], out * 4, hipMemcpyDeviceToHost));+ CHECK(hipMemcpy(w[v].data(), d_w[v], out * 4, hipMemcpyDeviceToHost));+ }+ int fails = 0;+ for (int v = 1; v < 3; ++v) {+ int bad = 0;+ for (int r = 0; r < rows; ++r)+ if (std::memcmp(&ids[0][(size_t) r * topk], &ids[v][(size_t) r * topk], topk * 4) ||+ std::memcmp(&w[0][(size_t) r * topk], &w[v][(size_t) r * topk], topk * 4)) {+ if (bad < 3)+ std::printf(" row %d differs: id0 %d/%d w0 %.9g/%.9g\n", r, ids[0][(size_t) r * topk],+ ids[v][(size_t) r * topk], w[0][(size_t) r * topk], w[v][(size_t) r * topk]);+ ++bad;+ }+ std::printf("%s %d experts, k %d, %d rows: %s vs the portable kernel: %d rows differ\n", bad ? "FAIL" : "PASS",+ n_expert, topk, rows, v == 1 ? "fast kernel" : "fast kernel, serial path", bad);+ fails += bad != 0;+ }+ // time: single-token calls back to back+ hipEvent_t e0, e1;+ CHECK(hipEventCreate(&e0));+ CHECK(hipEventCreate(&e1));+ for (int v = 0; v < 2; ++v) {+ const int reps = 2000;+ CHECK(hipEventRecord(e0));+ for (int i = 0; i < reps; ++i)+ k::router_top10_variant(d_l + (size_t) (i % 64) * n_expert, 1, n_expert, topk, d_i[v], d_w[v], nullptr, v);+ CHECK(hipEventRecord(e1));+ CHECK(hipEventSynchronize(e1));+ float ms = 0;+ CHECK(hipEventElapsedTime(&ms, e0, e1));+ std::printf(" %s: %.2f us per single-token call\n", v ? "fast" : "portable", 1000.0f * ms / reps);+ }+ for (int v = 0; v < 3; ++v) { (void) hipFree(d_w[v]); (void) hipFree(d_i[v]); }+ (void) hipFree(d_l);+ return fails;+}++int main() {+ int fails = 0;+ fails += compare(512, 10, 65536, 17);+ fails += compare(256, 8, 8192, 5);+ std::printf("FAILURES: %d\n", fails);+ return fails ? 1 : 0;+}