From 73ba449679a82d65982423649df7f6f10815bb8f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 06:44:23 +0200 Subject: [PATCH 01/11] HIP (S6): RDNA4 matrix-core prompt attention for int8 KV, opt-in (STRATA_HIP_WMMA=1, gfx12 only) The v2 tensor-core design with gfx12's v_wmma_f32_16x16x16_f16: one block per (query, KV head), wave w owns dims [64w, 64w+64) (int8 scale group w), q and p split into FP16 hi + lo parts, int8 codes exact as FP16, scales in FP32, the four groups' q.k partials added in a fixed order, online softmax over 32-cell chunks. Masked (non-resident) cells get no weight, as in the decode kernel. FP32-level accuracy, not bitwise equal to the default kernel, hence opt-in. hip_prompt_attn_wmma = qsa_prompt_attn_parity built for HIP (skips off gfx12). NVIDIA builds unchanged (all new code is under __HIPCC__ / the HIP test section). --- CMakeLists.txt | 6 + src/kernels/cuda/qsa_prompt_attn.cu | 291 ++++++++++++++++++++++++- src/kernels/qsa_prompt_attn_parity.cpp | 19 ++ 3 files changed, 315 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index a47c32e6..3bc403e5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -414,6 +414,12 @@ 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 RDNA4 matrix-core prompt attention (STRATA_HIP_WMMA) against the FP32 kernel and FP64; skips off gfx12 + add_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) + add_test(NAME hip_prompt_attn_wmma COMMAND hip_prompt_attn_wmma 32768 2048 3) + set_tests_properties(hip_prompt_attn_wmma PROPERTIES TIMEOUT 600 SKIP_RETURN_CODE 77) + list(APPEND _strata_hip_tests hip_prompt_attn_wmma) if(STRATA_HIPBLASLT_AVAILABLE AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/hip/prefill_hipblaslt_gemm.cpp") add_executable(hip_prefill_hipblaslt_gemm tests/hip/prefill_hipblaslt_gemm.cpp) target_include_directories(hip_prefill_hipblaslt_gemm PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src/prefill") diff --git a/src/kernels/cuda/qsa_prompt_attn.cu b/src/kernels/cuda/qsa_prompt_attn.cu index e87ec02c..7273eb2f 100644 --- a/src/kernels/cuda/qsa_prompt_attn.cu +++ b/src/kernels/cuda/qsa_prompt_attn.cu @@ -9,6 +9,7 @@ #include #include +#include #include namespace strata::kernels { @@ -685,6 +686,287 @@ bool launch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const return true; } +#if defined(__HIPCC__) +// ---- S6: the int8-KV prompt attention on RDNA4 matrix cores (opt-in: STRATA_HIP_WMMA=1, gfx12 only). The design of +// the v2 kernel above with gfx12's v_wmma_f32_16x16x16_f16 (wave32) in place of m16n8k16: wave w owns dims +// [64w, 64w+64) (int8 scale group w) for q.k and p.v; q and p are split into FP16 hi + lo parts, the int8 codes enter +// exactly as FP16, the scales are applied in FP32 and the four groups' q.k partials are added in a fixed order. +// FP32-level accuracy, deterministic, but not bitwise equal to qsa_decode_attn_batch (another summation order). +// Fragment layout (16x16x16, wave32, checked on gfx1201): A lane l holds A[l % 16][(l / 16) * 8 + i], B lane l holds +// B[(l / 16) * 8 + i][l % 16], C/D lane l holds D[(l / 16) * 8 + i][l % 16], i = 0..7. +#if defined(__gfx1200__) || defined(__gfx1201__) +#define STRATA_PA_WMMA 1 +#else +#define STRATA_PA_WMMA 0 +#endif +typedef _Float16 wh8 __attribute__((ext_vector_type(8))); +typedef float wf8 __attribute__((ext_vector_type(8))); +constexpr int WCH = 32; // cells per chunk (two 16-cell tiles) +constexpr int WVS = 80; // staged V row stride in bytes (64 codes, 16-byte aligned, banks spread) +struct alignas(16) SmemW { + float part[4][16][WCH + 1]; // q.k per dim group + float p[16][WCH + 1]; + float vs[4][WCH]; // V scale per (group, cell) + int valid[WCH]; // the cell has a resident pool row + uint8_t v[4][WCH][WVS]; // per wave: the chunk's V codes of its group, one row per cell + float qmax[4]; + float alpha[16]; + float lsum[16]; + float mrow[16]; +}; + +__device__ __forceinline__ wf8 wmma_f16(wh8 a, wh8 b, wf8 c) { +#if STRATA_PA_WMMA + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); +#else + __builtin_trap(); + return c; +#endif +} + +__device__ __forceinline__ wh8 i8x8_to_h8(uint2 x) { // exact: |code| <= 128 + wh8 h; +#pragma unroll + for (int i = 0; i < 4; ++i) { + h[i] = (_Float16) (int) (int8_t) (x.x >> (8 * i)); + h[4 + i] = (_Float16) (int) (int8_t) (x.y >> (8 * i)); + } + return h; +} + +__global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* __restrict__ q, QsaAttnPools p, + const int32_t* __restrict__ ids, + const int32_t* __restrict__ steps, int n_kv_heads, + int page_size, float scale_log2, + float* __restrict__ attn, int cap) { +#if STRATA_PA_WMMA + __shared__ SmemW S; + const int qi = blockIdx.x, kvh = blockIdx.y; + const int n_head = n_kv_heads * G; + q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; + attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; + ids += (size_t) qi * cap; + const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth); + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int col = lane & 15, half = lane >> 4; // fragment column / k half + const int dim0 = warp * 64; + + float qm = 0.0f; + for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i])); +#pragma unroll + for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o)); + if (lane == 0) S.qmax[warp] = qm; + if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; } + __syncthreads(); + qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3])); + int qe = 0; + if (qm > 0.0f) frexpf(qm, &qe); + const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14); + // q A fragments of this wave's 64 dims: row = col (heads 12..15 zero), k = dim0 + kk*16 + half*8 + i + wh8 qh[4], ql[4]; +#pragma unroll + for (int kk = 0; kk < 4; ++kk) { + float x[8]; + if (col < G) { + const float4* src = reinterpret_cast(q + (size_t) col * HD + dim0 + kk * 16 + half * 8); + const float4 a = src[0], b = src[1]; + x[0] = a.x; x[1] = a.y; x[2] = a.z; x[3] = a.w; x[4] = b.x; x[5] = b.y; x[6] = b.z; x[7] = b.w; + } else { +#pragma unroll + for (int i = 0; i < 8; ++i) x[i] = 0.0f; + } +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float v = x[i] * qup; + const _Float16 hi = (_Float16) v; + qh[kk][i] = hi; + ql[kk][i] = (_Float16) (v - (float) hi); + } + } + + wf8 acc[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) acc[j] = wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; + + const int n_chunks = (n + WCH - 1) / WCH; + for (int ci = 0; ci < n_chunks; ++ci) { + const int c0 = ci * WCH; + // this lane's cell of the chunk (lane = cell index): its pool row, or -1 (past the selection, or a block the + // KV streaming left non-resident: masked as in the decode kernel) + long long myrow = -1; + if (c0 + lane < n) { + const int cell = __ldg(ids + c0 + lane); + const long long page = (long long) __ldg(p.page_table + cell / page_size); + if (page >= 0) myrow = (page * n_kv_heads + kvh) * page_size + (cell % page_size); + } + // stage this wave's V slice of the chunk (64 bytes of each row) and the V scale; the K fragments come straight + // from global memory (8 consecutive codes per lane) + { + uint4 v0 = make_uint4(0, 0, 0, 0), v1 = v0, v2 = v0, v3 = v0; + float vsc = 0.0f; + if (myrow >= 0) { + const uint4* src = reinterpret_cast(p.v_q + myrow * HD + dim0); + v0 = __ldg(src); v1 = __ldg(src + 1); v2 = __ldg(src + 2); v3 = __ldg(src + 3); + vsc = __half2float(__ushort_as_half(__ldg(p.v_scale + myrow * (HD / KV_Q8_GROUP) + warp))); + } + uint4* dst = reinterpret_cast(&S.v[warp][lane][0]); + dst[0] = v0; dst[1] = v1; dst[2] = v2; dst[3] = v3; + S.vs[warp][lane] = vsc; + if (warp == 0) S.valid[lane] = myrow >= 0; + } + // q.k over this wave's 64 dims for two 16-cell tiles, times the cell's K scale for this group +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + const long long rr = __shfl(myrow, nt * 16 + col); + wf8 s = wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; + float ksc = 0.0f; + if (rr >= 0) ksc = __half2float(__ushort_as_half(__ldg(p.k_scale + rr * (HD / KV_Q8_GROUP) + warp))); +#pragma unroll + for (int kk = 0; kk < 4; ++kk) { + uint2 kx = make_uint2(0, 0); + if (rr >= 0) kx = __ldg(reinterpret_cast(p.k_q + rr * HD + dim0 + kk * 16 + half * 8)); + const wh8 b = i8x8_to_h8(kx); + s = wmma_f16(qh[kk], b, s); + s = wmma_f16(ql[kk], b, s); + } +#pragma unroll + for (int i = 0; i < 8; ++i) S.part[warp][half * 8 + i][nt * 16 + col] = s[i] * ksc; + } + __syncthreads(); + // online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread + { + const int r = t >> 3, sub = t & 7; + float x[4], mx = -INFINITY; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int c = sub * 4 + j; + // past the selection, or a masked cell (non-resident page, as in the decode kernel): no weight + x[j] = S.valid[c] ? (((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c]) * qdown + : -INFINITY; + mx = fmaxf(mx, x[j]); + } +#pragma unroll + for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o)); + const float m_old = S.mrow[r]; + const float m_new = fmaxf(m_old, mx); + float sum = 0.0f; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new); + S.p[r][sub * 4 + j] = e; + sum += e; + } +#pragma unroll + for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); + if (sub == 0) { + const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new); + S.alpha[r] = a; + S.lsum[r] = fmaf(S.lsum[r], a, sum); + S.mrow[r] = m_new; + } + } + __syncthreads(); + // p.v over this wave's 64 dims: 4 tiles of 16 dims, 2 k-steps of 16 cells + { + float vmax = S.vs[warp][lane]; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o)); + const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f); + wf8 tmp[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) tmp[j] = wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; +#pragma unroll + for (int ks = 0; ks < 2; ++ks) { + const int cb = ks * 16 + half * 8; // this lane's 8 cells + wh8 ah, al; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float pv = S.p[col][cb + i] * (S.vs[warp][cb + i] * vup); + const _Float16 hi = (_Float16) pv; + ah[i] = hi; + al[i] = (_Float16) (pv - (float) hi); + } +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int d = j * 16 + col; + wh8 b; +#pragma unroll + for (int i = 0; i < 8; ++i) b[i] = (_Float16) (int) (int8_t) S.v[warp][cb + i][d]; + tmp[j] = wmma_f16(ah, b, tmp[j]); + tmp[j] = wmma_f16(al, b, tmp[j]); + } + } + float a[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) a[i] = S.alpha[half * 8 + i]; +#pragma unroll + for (int j = 0; j < 4; ++j) +#pragma unroll + for (int i = 0; i < 8; ++i) acc[j][i] = fmaf(acc[j][i], a[i], tmp[j][i] * vdown); + } + // no barrier here: `v`/`vs` are this wave's own, and `p`/`alpha`/`valid` are rewritten only after the next + // chunk's first barrier (which every wave reaches after its p.v) + } + float inv[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float l = S.lsum[half * 8 + i]; + inv[i] = l > 0.0f ? 1.0f / l : 0.0f; + } +#pragma unroll + for (int j = 0; j < 4; ++j) +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int row = half * 8 + i; + if (row < G) attn[(size_t) row * HD + dim0 + j * 16 + col] = acc[j][i] * inv[i]; + } +#else + __builtin_trap(); +#endif +} + +// gfx12 (RDNA4) only, and only on request: the output differs from the default kernel's in its last bits +bool hip_wmma_usable() { + static const bool want = [] { + const char* e = std::getenv("STRATA_HIP_WMMA"); + return e != nullptr && e[0] == '1'; + }(); + if (!want) return false; + static int arch[64] = {}; // 0 unknown, 1 gfx12, 2 other + int dev = 0; + if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= 64) { (void) hipGetLastError(); return false; } + if (arch[dev] == 0) { + hipDeviceProp_t prop{}; + if (hipGetDeviceProperties(&prop, dev) != hipSuccess) { (void) hipGetLastError(); return false; } + arch[dev] = std::strncmp(prop.gcnArchName, "gfx12", 5) == 0 ? 1 : 2; + static bool told = false; + if (!told) { + told = true; + std::fprintf(stderr, "strata: STRATA_HIP_WMMA: the prompt attention on matrix cores %s (%s)\n", + arch[dev] == 1 ? "on" : "unavailable", prop.gcnArchName); + } + } + return arch[dev] == 1; +} + +bool launch_wmma(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, + const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) { + const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD); + for (int64_t q0 = 0; q0 < n_q; q0 += 65535) { + const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535; + prompt_attn_wmma_kernel<<>>( + q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv, + (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap); + } + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_prompt_attn_batch (wmma): %s\n", cudaGetErrorString(e)); + std::exit(1); + } + return true; +} +#endif + } // namespace bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, @@ -709,7 +991,14 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3 turing = cc_major[dev] < 8; } #if defined(__HIPCC__) - return false; // the tensor-core kernel is compiled out on AMD (its major version is not a CUDA sm) + // the tensor-core kernels are compiled out on AMD (its major version is not a CUDA sm); RDNA4 has its own int8-KV + // matrix-core kernel, opt-in (STRATA_HIP_WMMA=1); everything else keeps the old kernel + (void) turing; + if (pools.k_q != nullptr && pools.v_q != nullptr && pools.k_scale != nullptr && pools.v_scale != nullptr && + pools.k_q4 == nullptr && pools.v_q4 == nullptr && s.head_dim == HD && s.n_head == (int64_t) G * s.n_head_kv && + cap > 0 && ids && steps && pools.page_table && hip_wmma_usable()) + return launch_wmma(q, pools, ids, steps, cap, s, attn, n_q, (cudaStream_t) stream); + return false; #endif if (pools.k_q4 != nullptr || s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !ids || !steps || !pools.page_table) diff --git a/src/kernels/qsa_prompt_attn_parity.cpp b/src/kernels/qsa_prompt_attn_parity.cpp index 3b3fe194..9525d0cf 100644 --- a/src/kernels/qsa_prompt_attn_parity.cpp +++ b/src/kernels/qsa_prompt_attn_parity.cpp @@ -7,6 +7,7 @@ // 1. against FP64, the new kernel's error is no larger than a small multiple of the old kernel's (both FP32 math); // 2. the new and old outputs agree to a relative 1e-4 of the output scale; // then times both over a prompt chunk (the old one in batches of 32, as prefill.cpp calls it). +// HIP builds (S6): the same checks for the RDNA4 matrix-core kernel (STRATA_HIP_WMMA), skipped (77) off gfx12. // Usage: qsa_prompt_attn_parity [context=32768] [queries=2048] [reps=5] #include "strata/kernels/qsa.hpp" #include "strata/kernels/qsa_decode_attn.hpp" @@ -19,6 +20,7 @@ #include #include #include +#include #include #include @@ -196,6 +198,23 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16 } // namespace int main(int argc, char** argv) { +#if defined(__HIP_PLATFORM_AMD__) + // S6: on AMD the kernel under test is the RDNA4 matrix-core one (opt-in in the engine); other cards skip + { + int dev = 0; + hipDeviceProp_t prop{}; + if (hipGetDevice(&dev) != hipSuccess || hipGetDeviceProperties(&prop, dev) != hipSuccess) return 2; + if (std::strncmp(prop.gcnArchName, "gfx12", 5) != 0) { + std::printf("SKIP: %s is not gfx12 (the matrix-core prompt attention is RDNA4 only)\n", prop.gcnArchName); + return 77; + } +#if defined(_WIN32) + _putenv_s("STRATA_HIP_WMMA", "1"); +#else + setenv("STRATA_HIP_WMMA", "1", 1); +#endif + } +#endif const int64_t ctx = argc > 1 ? std::atoll(argv[1]) : 32768; const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 2048; const int reps = argc > 3 ? std::atoi(argv[3]) : 5; From a2be1670bbae1c0e5269e599fd37a18f98531125 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 07:24:19 +0200 Subject: [PATCH 02/11] HIP (S6): router_top10 without its serial parts on AMD, bitwise the same (default on HIP; STRATA_HIP_ROUTER_OLD=1: old) On RDNA4 the router took 39 us per call in decode (16% of the decode GPU time): 512 dependent FP64 adds, ten selection passes with 20 block barriers, a renormalisation re-reading its weights from global memory. The sum's only use is inv = (float)(1.0 / sum): all terms are positive with the largest exactly 1, so the serial sum and a tree sum are within 2^-43 of each other; when the bracket tree*(1 -+ 2^-40) maps to one float, that float is the serial sum's (1/x and the cast are monotone), otherwise thread 0 runs the serial sum as before. The selection runs on wave 0 from registers (the argmax with the lowest index on ties is unique), the renormalisation from registers in rank order. hip_router_fast checks ids and weights bitwise against the portable kernel (65,536 rows with ties, near-ties, NaN rows, the forced serial path; and 256 experts / k 8). CUDA builds unchanged (HIP-only code). --- CMakeLists.txt | 5 + include/strata/kernels/router_top10.hpp | 6 + src/kernels/cuda/router_top10.cu | 176 ++++++++++++++++++++++++ src/kernels/qsa_prompt_attn_parity.cpp | 4 +- tests/hip/router_fast.cpp | 101 ++++++++++++++ 5 files changed, 291 insertions(+), 1 deletion(-) create mode 100644 tests/hip/router_fast.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 3bc403e5..ef40fd74 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 gfx12 add_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.hpp index 2158c1fd..e10295e1 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::kernels diff --git a/src/kernels/cuda/router_top10.cu b/src/kernels/cuda/router_top10.cu index 1f137e59..88138d5a 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 +__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<<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>( + logits, n_tokens, n_expert, k, ids, weights); + return; + } + if (mode == 2) { + router_top10_fast_kernel<<<(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; + } + } +#endif if (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.cpp index 9525d0cf..c5dad7c9 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 +#endif fails += run(1, 1500, std::min(nq, 1500), reps); // short context: the selection is every cell fails += run(1, 2100, std::min(nq, 256), reps); // the identity-to-sparse edge std::printf("FAILURES: %d\n", fails); diff --git a/tests/hip/router_fast.cpp b/tests/hip/router_fast.cpp new file mode 100644 index 00000000..d0db85e5 --- /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 +#include "strata/kernels/router_top10.hpp" + +#include +#include +#include +#include +#include + +#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 nd(0.f, 2.f); + std::vector 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 ids[3]; + std::vector 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; +} From cfb1866ec5700c54266730ef0220c5fecb40b000 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:07:46 +0200 Subject: [PATCH 03/11] HIP (S6): router_top10.cu - drop a nested #if that left the HIP block unterminated --- src/kernels/cuda/router_top10.cu | 1 - 1 file changed, 1 deletion(-) diff --git a/src/kernels/cuda/router_top10.cu b/src/kernels/cuda/router_top10.cu index 88138d5a..f23a63d7 100644 --- a/src/kernels/cuda/router_top10.cu +++ b/src/kernels/cuda/router_top10.cu @@ -311,7 +311,6 @@ void launch_generic(const float* logits, int n_tokens, int n_expert, int k, int* 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<<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>( logits, n_tokens, n_expert, k, ids, weights); From 348d65da7bc18c547a98db67a28a1c7763f2b449 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:24:54 +0200 Subject: [PATCH 04/11] #340 prototype: a layer split refills every stage's prompt loan concurrently (queue all, then wait); STRATA_REFILL_SERIAL=1: stage after stage; STRATA_TRACE times the loan and the refill One stage: refill_one exactly as before (single-GPU unchanged). The same copies into the same slots either way. --- src/program/generate.cpp | 46 +++++++++++++++++++++++++++++++++++----- 1 file changed, 41 insertions(+), 5 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index caf47d6b..6ac2ce62 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -4780,8 +4780,8 @@ int main(int argc, char** argv) { // the arena, the residency table is restored, and one upload puts it on every device. A stage refills // through its own cache and its own device - a slot refilled into the wrong cache would leave that // stage's cache holding an expert it does not own, which is silent and produces plausible tokens. - auto refill_one = [&](PfPart& p, std::string& e) -> bool { - if (p.lent.empty()) return true; + // (split in two halves so a layer split can queue every stage's copies before it waits for any: #340) + auto refill_issue = [&](PfPart& p, std::string& e) -> bool { tr("refill start", (long long) p.lent.size()); const strata::core::OnDevice on(p.dev); for (const auto& [i, slot] : p.lent) { // D-4: queued, one wait (STRATA_REFILL_BLOCKING=1: each) @@ -4792,16 +4792,44 @@ int main(int argc, char** argv) { return false; host_res[(size_t) i] = slot; } + return true; + }; + auto refill_wait = [&](PfPart& p, std::string& e) -> bool { + const strata::core::OnDevice on(p.dev); if (!p.cache->sync_queued(e)) return false; p.lent.clear(); p.lent_chunk = 0; return true; }; + auto refill_one = [&](PfPart& p, std::string& e) -> bool { + if (p.lent.empty()) return true; + return refill_issue(p, e) && refill_wait(p, e); + }; + // #340: with several stages every stage's copies go out first (each card on its own link), then each is + // waited for - the same copies into the same slots, so the same cache; one stage: refill_one exactly. + // STRATA_REFILL_SERIAL=1: stage after stage, as 0.1.30/0.1.31. + static const bool refill_serial = std::getenv("STRATA_REFILL_SERIAL") != nullptr; auto refill = [&](std::string& e) -> bool { - bool any = false; + const auto t_rf = Clock::now(); + int64_t n_lent = 0, n_parts = 0; for (PfPart& p : pf_parts) - if (!p.lent.empty()) { any = true; if (!refill_one(p, e)) return false; } - if (any) res_upload(); + if (!p.lent.empty()) { n_lent += (int64_t) p.lent.size(); ++n_parts; } + if (n_parts > 1 && !refill_serial) { + for (PfPart& p : pf_parts) + if (!p.lent.empty() && !refill_issue(p, e)) return false; + for (PfPart& p : pf_parts) + if (!p.lent.empty() && !refill_wait(p, e)) return false; + } else { + for (PfPart& p : pf_parts) + if (!p.lent.empty() && !refill_one(p, e)) return false; + } + if (n_parts > 0) res_upload(); + if (trace && n_parts > 0) { + std::fprintf(stderr, "strata trace: refilled %lld slots on %lld stage(s) in %.1f ms\n", + (long long) n_lent, (long long) n_parts, + std::chrono::duration(Clock::now() - t_rf).count()); + std::fflush(stderr); + } return true; }; // lend the slots `tokens` batched prompt tokens need: the prompt path's buffers for min(chunk, tokens @@ -4809,6 +4837,7 @@ int main(int argc, char** argv) { // participant's own cache, and marking only that participant's own layers auto lend = [&](int64_t tokens, std::string& e) -> bool { if (pf_parts.empty()) return true; // its own buffers: nothing to lend + const auto t_ln = Clock::now(); // what this segment needs, capped by the configured chunk: a request lends only what its own // prompt needs, so a large chunk costs a short prompt nothing const int64_t want = request_chunk(tokens, o.prefill_chunk); @@ -4844,6 +4873,13 @@ int main(int argc, char** argv) { p.lent_chunk = want; } if (any) res_upload(); + if (trace) { + int64_t n_lent = 0; + for (const PfPart& p : pf_parts) n_lent += (int64_t) p.lent.size(); + std::fprintf(stderr, "strata trace: lent %lld slots for %lld tokens in %.1f ms\n", (long long) n_lent, + (long long) want, std::chrono::duration(Clock::now() - t_ln).count()); + std::fflush(stderr); + } return true; }; apply_pending(true); From 469bdaf891316316d6fa9b0f69db3cb99eb079fb Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 08:37:18 +0200 Subject: [PATCH 05/11] #340 prototype: a split stage with room for its prompt buffers keeps them as its own (no loan, nothing streamed or refilled for it); STRATA_SPLIT_OWN_BUFFERS=0: every stage borrows One GPU: unchanged (the rule is for layer splits only; the single-cache loan is computed exactly as before). --- src/program/generate.cpp | 46 ++++++++++++++++++++++++++++++++-------- 1 file changed, 37 insertions(+), 9 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 6ac2ce62..e55595ab 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -3697,9 +3697,34 @@ int main(int argc, char** argv) { p.first = (int32_t) (p.cache->slots() - part_slots(p, chunk)); p.first_now = p.first; } + // #340: a split stage whose card still has room for the chunk's buffers (its cache already holds + // every expert of its layers, so auto stopped short of its VRAM) keeps them as its own instead of + // borrowing cache slots: nothing of it is lent, streamed during the prompt or refilled after it. + // Room = the buffers + 1.5 GiB (the verify windows, the draft head, hipBLAS/cuBLAS workspaces made + // after this). Layer splits only - one GPU keeps its loan exactly as before. + // STRATA_SPLIT_OWN_BUFFERS=0: every stage borrows (0.1.30/0.1.31). + static const bool own_ok = [] { + const char* v = std::getenv("STRATA_SPLIT_OWN_BUFFERS"); + return v == nullptr || v[0] != '0'; + }(); + if (pf_parts.size() > 1 && own_ok) { + for (PfPart& p : pf_parts) { + const strata::core::OnDevice on(p.dev); + size_t fb = 0, tb = 0; + if (cudaMemGetInfo(&fb, &tb) != cudaSuccess) { (void) cudaGetLastError(); continue; } + const uint64_t need = strata::prefill::Prefill::bytes_needed(g, *p.ses, chunk); + if ((uint64_t) fb >= need + (3ull << 29)) { + std::fprintf(stderr, "strata serve: CUDA%d keeps its own prompt buffers (%.2f GiB of " + "%.2f GiB free): no loan\n", p.dev < 0 ? 0 : p.dev, + (double) need / 1073741824.0, (double) fb / 1073741824.0); + p.first = -1; + p.first_now = -1; + } + } + } lend_first = pf_parts[0].first; - borrow = xcache.device_slot(lend_first); - borrow_bytes = part_bytes(pf_parts[0], lend_first); + borrow = lend_first >= 0 ? xcache.device_slot(lend_first) : nullptr; + borrow_bytes = lend_first >= 0 ? part_bytes(pf_parts[0], lend_first) : 0; } else if (o.prefill_auto) { o.prefill_chunk = 1024; // nothing lendable: small buffers of its own } else if (pf_parts.size() > 1) { @@ -3718,11 +3743,14 @@ int main(int argc, char** argv) { } else if (o.prefill_auto && d_res == nullptr) { o.prefill_chunk = 1024; // #85: no expert cache at all (a full 8 GB card): small buffers of its own } - if (borrow != nullptr) { - std::fprintf(stderr, "strata serve: the prompt path borrows %lld CUDA0 cache slots (%.2f GiB)\n", - (long long) (xcache.slots() - lend_first), (double) borrow_bytes / 1073741824.0); + bool any_loan = borrow != nullptr; + for (size_t i = 1; i < pf_parts.size(); ++i) any_loan = any_loan || pf_parts[i].first >= 0; + if (any_loan) { + if (borrow != nullptr) + std::fprintf(stderr, "strata serve: the prompt path borrows %lld CUDA0 cache slots (%.2f GiB)\n", + (long long) (xcache.slots() - lend_first), (double) borrow_bytes / 1073741824.0); for (size_t i = 1; i < pf_parts.size(); ++i) // one loan per stage, from that stage's own cache - std::fprintf(stderr, "strata serve: CUDA%d prompt path borrows %lld of its %lld slots (%.2f GiB)\n", + if (pf_parts[i].first >= 0) std::fprintf(stderr, "strata serve: CUDA%d prompt path borrows %lld of its %lld slots (%.2f GiB)\n", pf_parts[i].dev, (long long) (pf_parts[i].cache->slots() - pf_parts[i].first), (long long) pf_parts[i].cache->slots(), (double) part_bytes(pf_parts[i], pf_parts[i].first) / 1073741824.0); @@ -3814,15 +3842,15 @@ int main(int argc, char** argv) { sp.reset(); (void) cudaGetLastError(); o.prefill_chunk = next; - if (borrow != nullptr) { // smaller loans for the smaller chunk + if (any_loan) { // smaller loans for the smaller chunk for (PfPart& p : pf_parts) if (p.first >= 0) { p.first = (int32_t) (p.cache->slots() - part_slots(p, next)); p.first_now = p.first; } lend_first = pf_parts[0].first; - borrow = xcache.device_slot(lend_first); - borrow_bytes = part_bytes(pf_parts[0], lend_first); + borrow = lend_first >= 0 ? xcache.device_slot(lend_first) : nullptr; + borrow_bytes = lend_first >= 0 ? part_bytes(pf_parts[0], lend_first) : 0; } err.clear(); continue; From 88f4146c53ed3cf56e42c29c59becdd33c6b8663 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 09:22:58 +0200 Subject: [PATCH 06/11] #340 prototype: a split's streamed ring is 96 slots when most experts are resident (STRATA_SPLIT_RING); STRATA_SPLIT_SMALL_OWN=S keeps an S-token chunk's buffers per lending stage for the session; --no-prefill-borrow on a split books the ring (it no longer starves the draft head) One GPU: unchanged (all three rules are for layer splits only). --- include/strata/prefill/prefill.hpp | 3 ++ src/prefill/prefill.cpp | 4 ++- src/program/generate.cpp | 58 +++++++++++++++++++++++++++++- 3 files changed, 63 insertions(+), 2 deletions(-) diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index 38f64a91..da225d3b 100644 --- a/include/strata/prefill/prefill.hpp +++ b/include/strata/prefill/prefill.hpp @@ -73,6 +73,9 @@ public: /// ring (a big one only pays when the copy engine, not the host copies, is the limit); set before bytes_needed. static void set_pinned_share(double share); static double pinned_share(); + /// #340: the streamed ring's slot count for chunks that stream every expert, instead of the pinned-share rule + /// (0 = that rule). Set before any `bytes_needed`/`init` (both count the ring); STRATA_PREFILL_RING still wins. + static void set_ring_override(int slots); /// Device bytes `init` needs for a chunk of `chunk` tokens (what a borrowed region must hold). static uint64_t bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk); diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 117cae95..278f92e6 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -86,9 +86,10 @@ double g_pinned_share = 1.0; // 8192-token chunks: 96 slots 1153 tok/s, 384 1294 (the next layer's experts arrive during its attention half) - // and 96 when a large share goes through host copies (IQ3_S on 64 GB, a third unpinned: 96 slots 1216, 256 1070 - // the host copies are the limit and the bigger ring only takes cache slots). STRATA_PREFILL_RING overrides. +int g_ring_override = 0; // #340: set by a layer split (Prefill::set_ring_override); 0 = the rule below inline int ring_slots(size_t T) { const char* v = std::getenv("STRATA_PREFILL_RING"); - const int r = v ? std::atoi(v) : (g_pinned_share >= 0.9 ? 384 : 96); + const int r = v ? std::atoi(v) : g_ring_override > 0 ? g_ring_override : (g_pinned_share >= 0.9 ? 384 : 96); if (v && r == STAGE) return STAGE; // Explicit opt-in to routed-only staging, including large chunks. const int big = r < 16 ? 16 : r > RING_MAX ? RING_MAX : r; return (int64_t) T >= stream_all_min() ? big : STAGE; @@ -843,6 +844,7 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t return true; } void Prefill::set_pinned_share(double share) { g_pinned_share = share; } +void Prefill::set_ring_override(int slots) { g_ring_override = slots > 0 ? slots : 0; } double Prefill::pinned_share() { return g_pinned_share; } uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk) { diff --git a/src/program/generate.cpp b/src/program/generate.cpp index e55595ab..8a513a1e 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -2144,7 +2144,16 @@ int main(int argc, char** argv) { // for buffers that cannot be priced exactly yet because the sessions do not exist. `plan_lend` uses the // exact `Prefill::bytes_needed` as soon as it can. const bool pf_borrow = !o.no_prefill_borrow && !o.expert_profile.empty(); - const int64_t split_pf_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0; + // (#340: the estimate predates the streamed ring: from 1024-token chunks the prompt path also holds a ring of + // whole expert blobs, which a split without borrowing sizes at 96 (Prefill::set_ring_override below) and books + // here - without it a `--no-prefill-borrow` split filled the cards and the draft head no longer fit) + const int64_t split_ring_mib = + (multi_gpu && !pf_borrow && o.prefill_chunk >= 1024) + ? (int64_t) ((96ull * (uint64_t) strata::kernels::cpu::expert_layout().max_blob + (1ull << 20) - 1) >> 20) + : 0; + if (split_ring_mib > 0) strata::prefill::Prefill::set_ring_override(96); + const int64_t split_pf_mib = + (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 + split_ring_mib : 0; // ---- WHAT A STAGE RESERVES, AND ON WHICH STAGE. The flat 1 GiB this used to withhold from EVERY stage // after the first was booked "for its windows and the drafter", but the windows measure 75 MiB ("window up // to 6 tokens, 74.1 MiB of device buffers", on every boot) and the drafter is loaded on ONE stage - the @@ -3657,6 +3666,22 @@ int main(int argc, char** argv) { : (uint64_t) (xc.slots() - first) * (uint64_t) strata::kernels::cpu::expert_layout().max_blob; }; + // #340: a layer split whose caches already hold most experts streams few of them through the prompt path, so + // the 384-slot ring (sized for a card that streams nearly every expert of a chunk) only makes every stage's + // loan bigger: 96 slots (0.1.30's ring here) when >= 75% of the (layer, expert) pairs are resident. One GPU + // keeps the pinned-share rule. STRATA_SPLIT_RING=N: N slots on a split; 0: the pinned-share rule. + if (multi_gpu && !host_res.empty()) { + int64_t res_n = 0; + for (const int32_t r : host_res) res_n += r >= 0; + const double res_share = (double) res_n / (double) host_res.size(); + const char* v = std::getenv("STRATA_SPLIT_RING"); + const int ring = v ? std::atoi(v) : (res_share >= 0.75 ? 96 : 0); + if (ring > 0) { + strata::prefill::Prefill::set_ring_override(ring); + std::fprintf(stderr, "strata serve: layer split: %.0f%% of the experts resident, the prompt path's " + "streamed ring %d slots\n", 100.0 * res_share, ring); + } + } std::vector pf_parts; // a cache too small to lend the prompt path its buffers would make it allocate them on top - on a card // whose cache already filled its reserve, that is the over-subscription the auto sizing avoids - so the @@ -3863,6 +3888,37 @@ int main(int argc, char** argv) { return 1; } mem_mark("the head and the prompt path"); + // #340: STRATA_SPLIT_SMALL_OWN=S (tokens): on a layer split, every stage that borrows keeps the slots for an + // S-token chunk's buffers for the whole session (0.1.29's own buffers, carved from the tail of its cache): + // a request of at most S prompt tokens then lends, streams and refills nothing, a longer one lends (and + // refills) only the slots above them. Their experts stay non-resident (the CPU / PCIe path computes them). + if (multi_gpu && !pf_parts.empty() && !host_res.empty()) { + const char* v = std::getenv("STRATA_SPLIT_SMALL_OWN"); + const int64_t S = v ? request_chunk(std::atoll(v), o.prefill_chunk) : 0; + int64_t evicted = 0; + for (PfPart& p : pf_parts) { + if (S <= 0 || p.first < 0) continue; + const int32_t first_s = std::max(p.first, (int32_t) (p.cache->slots() - part_slots(p, S))); + int64_t n = 0; + for (int64_t l = p.lb; l < p.le; ++l) + for (int64_t ex = 0; ex < g.n_expert; ++ex) { + int32_t& r = host_res[(size_t) (l * g.n_expert + ex)]; + if (r >= first_s) { r = strata::core::kNotResident; ++n; } + } + evicted += n; + std::fprintf(stderr, "strata serve: CUDA%d keeps %lld slots for %lld-token prompts (%lld experts " + "no longer resident)\n", p.dev < 0 ? 0 : p.dev, + (long long) (p.cache->slots() - first_s), (long long) S, (long long) n); + } + if (evicted > 0) { + if (d_res != nullptr) + cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + for (auto& st : stages) { + const strata::core::OnDevice on(st->dev); + cudaMemcpy(st->d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + } + } + } // the penalty-history buffer: one row per verify-window row (`penalty_rows`), each the last // `penalty_last_n` tokens that row's pick follows, -1 padded in front. Allocated once at the cap for // the widest window; a request without penalties gets a null buffer and takes the byte-for-byte From b7bb142060e98f4d59c934a809dfdd0e6c6d2332 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 10:04:08 +0200 Subject: [PATCH 07/11] #340 prototype: STRATA_SPLIT_SMALL_MAX=M - a split request of at most M prompt tokens reads in the stages' own S-token chunks (nothing lent) --- src/program/generate.cpp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 8a513a1e..d700f61d 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -3892,9 +3892,15 @@ int main(int argc, char** argv) { // S-token chunk's buffers for the whole session (0.1.29's own buffers, carved from the tail of its cache): // a request of at most S prompt tokens then lends, streams and refills nothing, a longer one lends (and // refills) only the slots above them. Their experts stay non-resident (the CPU / PCIe path computes them). + // STRATA_SPLIT_SMALL_MAX=M: a request of at most M prompt tokens reads in S-token chunks on those stages + // (several chunks, still nothing lent) instead of borrowing for a bigger one. + int64_t split_small = 0, split_small_max = 0; if (multi_gpu && !pf_parts.empty() && !host_res.empty()) { const char* v = std::getenv("STRATA_SPLIT_SMALL_OWN"); const int64_t S = v ? request_chunk(std::atoll(v), o.prefill_chunk) : 0; + const char* vm = std::getenv("STRATA_SPLIT_SMALL_MAX"); + split_small = S; + split_small_max = S > 0 ? std::max(S, vm ? std::atoll(vm) : S) : 0; int64_t evicted = 0; for (PfPart& p : pf_parts) { if (S <= 0 || p.first < 0) continue; @@ -4924,7 +4930,10 @@ int main(int argc, char** argv) { const auto t_ln = Clock::now(); // what this segment needs, capped by the configured chunk: a request lends only what its own // prompt needs, so a large chunk costs a short prompt nothing - const int64_t want = request_chunk(tokens, o.prefill_chunk); + const int64_t want_full = request_chunk(tokens, o.prefill_chunk); + // #340: a short enough request reads in the stages' own S-token chunks (nothing lent) + const int64_t want = split_small > 0 && tokens <= split_small_max ? std::min(want_full, split_small) + : want_full; if (want <= 0) { e = "prefill: cannot lend buffers for an empty request segment"; return false; From d70df548ad5db047e248cd95edb54a640f58f380 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 10:25:03 +0200 Subject: [PATCH 08/11] #340: a layer split keeps 0.1.29's own prompt buffers (2048-token chunks, priced into the split search) when they are at most 12% of every card's VRAM; smaller cards keep borrowing (STRATA_SPLIT_OWN=1/0 forces) Measured on 9070 XT + R9700 (Coder IQ1_M): 2K/4K/8K/16K prompts 1588/1771/1943/2006 tok/s (0.1.29 1568/1730/1870/1935, 0.1.31 993/1212/1350/1852). One GPU unchanged; --split-skip-if-fits keeps the loans. --- src/program/generate.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index d700f61d..95b98000 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1303,6 +1303,46 @@ int main(int argc, char** argv) { // more than either 8 GB card had - which is how adding two GPUs to the two 12 GB ones lost 260K. // The loan is the tail of the stage's own cache (see `PfPart` in the serve block); outside the prompt // that tail is expert cache, so a large chunk costs a stage nothing permanent. + // #340 - BUT A LOAN IS NOT FREE PER REQUEST: every stage streams the lent experts during the prompt and + // copies them back after it, so on cards that hold (nearly) every expert of their layers a 2K prompt read + // 37% slower than 0.1.29's own buffers (2x RX 9070 XT / R9700: 1570 -> 990 tok/s; 2x A5000 in #340: -35%). + // So a split keeps 0.1.29's own buffers (2048-token chunks, priced into the split search) when they are a + // small part of every card - at most 12% of its VRAM (16 GB and larger cards) - and borrows on smaller cards, + // where the reserve would cost the cache (and the context) the paragraph above is about. Measured with own + // buffers on the 9070 XT + R9700: 2K 1588 tok/s, 16K 2006 (0.1.29 1568 / 1935, 0.1.31 993 / 1852). + // STRATA_SPLIT_OWN=1: own buffers on any cards; 0: borrow (0.1.30 / 0.1.31). --split-skip-if-fits keeps the + // loans (it can fall back to one GPU, which must stay as it is). + if (!o.no_prefill_borrow && !o.split_skip_if_fits) { + const char* v = std::getenv("STRATA_SPLIT_OWN"); + bool own = v ? v[0] == '1' : true; + // the buffers of a 2048-token chunk (or the --prefill one) + a 96-blob ring (as split_pf_mib prices them) + const int64_t own_chunk = o.prefill_auto || o.prefill_chunk <= 0 ? 2048 : o.prefill_chunk; + const int64_t reserve_mib = 160 + (own_chunk * 680) / 1024 + 96 * 4; + std::string why; + if (!v) { + std::vector devs = {0}; + for (const int d : split_devs) devs.push_back(d); + for (const int d : devs) { + cudaDeviceProp prop{}; + if (cudaGetDeviceProperties(&prop, d) != cudaSuccess) { cudaGetLastError(); own = false; break; } + const int64_t total_mib = (int64_t) (prop.totalGlobalMem >> 20); + if (reserve_mib * 100 > 12 * total_mib) { + own = false; + why = "CUDA" + std::to_string(d) + " has " + std::to_string(total_mib) + " MiB"; + break; + } + } + } + if (own) { + o.no_prefill_borrow = true; + std::fprintf(stderr, "strata generate: layer split: every stage keeps its own prompt buffers (~%lld MiB " + "each, %lld-token chunks)%s\n", (long long) reserve_mib, (long long) own_chunk, + v ? " (STRATA_SPLIT_OWN=1)" : ""); + } else if (!why.empty()) { + std::fprintf(stderr, "strata generate: layer split: the prompt paths borrow from the caches (%s)\n", + why.c_str()); + } + } int n_vis = 1; if (cudaGetDeviceCount(&n_vis) != cudaSuccess || n_vis < 1) n_vis = 1; cudaGetLastError(); From c92c4540e3e5a97addf790f220da36af429c8078 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 11:34:19 +0200 Subject: [PATCH 09/11] #340: with the split's own prompt buffers (its rule, not --no-prefill-borrow) the boundary is searched as the borrowing configuration would; the reserve only shrinks the caches (STRATA_SPLIT_OWN_PLACE=reserve: the search sees it) 9070 XT + R9700: the reserve moved K 28 -> 32 and split decode 58.5 -> 54.8 tok/s; own buffers at K=28 decode 58.4. --- src/program/generate.cpp | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 95b98000..1f60944e 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1272,6 +1272,7 @@ int main(int argc, char** argv) { } } bool multi_gpu = !split_devs.empty() && !split_same; // cleared by --split-skip-if-fits before any stage loads + bool split_own_auto = false; // #340: the split keeps own prompt buffers by its rule (not --no-prefill-borrow) if (o.mmap_experts && !o.shared_expert_arena.empty()) { std::fprintf(stderr, "strata generate: --shared-expert-arena backs the resident arena and cannot be used with --mmap-experts\n"); return 2; @@ -1335,6 +1336,7 @@ int main(int argc, char** argv) { } if (own) { o.no_prefill_borrow = true; + split_own_auto = true; std::fprintf(stderr, "strata generate: layer split: every stage keeps its own prompt buffers (~%lld MiB " "each, %lld-token chunks)%s\n", (long long) reserve_mib, (long long) own_chunk, v ? " (STRATA_SPLIT_OWN=1)" : ""); @@ -2203,13 +2205,23 @@ int main(int argc, char** argv) { // the windows and - only on the stage that carries them - the drafter and the head. const int64_t kWindowMib = 96; // the verify windows; 75 MiB measured, rounded up const int64_t kDrafterMib = 1000; // the MTP drafter (839 MiB) + the head, on the last stage only - auto stage_room = [&](int dev, bool later, bool drafter) -> int64_t { + // #340: with the own prompt buffers chosen by the split's rule (not asked for with --no-prefill-borrow) the + // boundary is searched as the borrowing configuration would (no reserve): the reserve then only makes the caches + // smaller, which measured cost no decode (K=28 on 9070 XT + R9700: 58.4 tok/s own vs 58.5 borrowing), while a + // search with the reserve moved the boundary to K=32 and decode to 54.8. STRATA_SPLIT_OWN_PLACE=reserve: the + // search sees the reserve. + static const bool place_with_reserve = [] { + const char* v = std::getenv("STRATA_SPLIT_OWN_PLACE"); + return v != nullptr && std::string(v) == "reserve"; + }(); + auto stage_room = [&](int dev, bool later, bool drafter, bool search = false) -> int64_t { const strata::core::OnDevice on(dev); size_t fb = 0, tb = 0; if (const cudaError_t e = cudaMemGetInfo(&fb, &tb); e != cudaSuccess) std::fprintf(stderr, "strata generate: layer split: CUDA%d free memory: %s\n", dev < 0 ? 0 : dev, cudaGetErrorString(e)); - const int64_t reserve = ((int64_t) o.vram_reserve_mib + split_pf_mib + (later ? kWindowMib : 0) + + const int64_t pf = search && split_own_auto && !place_with_reserve ? 0 : split_pf_mib; + const int64_t reserve = ((int64_t) o.vram_reserve_mib + pf + (later ? kWindowMib : 0) + (drafter ? kDrafterMib : 0)) << 20; return std::max((int64_t) fb - reserve, 0); }; @@ -2220,7 +2232,7 @@ int main(int argc, char** argv) { std::vector layer_ms((size_t) ns); for (int i = 0; i < ns; ++i) { const int dev = i == 0 ? 0 : stages[(size_t) i - 1]->dev; - cap[(size_t) i] = stage_room(i == 0 ? -1 : dev, i > 0, i + 1 == ns); + cap[(size_t) i] = stage_room(i == 0 ? -1 : dev, i > 0, i + 1 == ns, true); int sms = 0, khz = 0; cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev); if (cudaDeviceGetAttribute(&khz, cudaDevAttrClockRate, dev) != cudaSuccess || khz <= 0) khz = 1800000; From e6a06be558b9789dae9967c4d910b6035627019e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 13:06:56 +0200 Subject: [PATCH 10/11] HIP (S6): STRATA_HIP_WMMA=1 also takes a 96-slot prompt expert ring (9070 XT 4K prompts 718 -> 1,211 tok/s with it); docs/AMD_HIP.md: the router and WMMA switches, with credit to PR #329's equal-speed kernel --- docs/AMD_HIP.md | 13 +++++++++++++ src/prefill/prefill.cpp | 9 +++++++++ 2 files changed, 22 insertions(+) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 39a47002..767b1bdd 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -176,6 +176,19 @@ an RX 9070 XT 16 GB and a Radeon AI PRO R9700 32 GB (both gfx1201), a Ryzen 9 39 starts. `"split_skip_if_fits": true` in the config (0.1.31, opt-in) runs such a pair on the first card alone when it holds every profiled expert: with the R9700 first, 4K prompts 1,776 tok/s (split: 1,244) and decode ~60 tok/s (split: ~51), the tokens of the R9700 alone (docs/MULTI_GPU.md). +- **Speed switches (engine 0.1.32, measured on the R9700 / 9070 XT with the Coder IQ1_M pack):** + - the MoE router (`router_top10`) runs a HIP kernel without its serial FP64 sum and block barriers by default: the + same ids and weights bit for bit (`hip_router_fast` checks 65,536 rows), 39 -> 9-12 us per call, decode + 62.4 -> 70.0 tok/s on the R9700 and +4% on the 9070 XT, the same greedy tokens (5 + 5 starts). + `STRATA_HIP_ROUTER_OLD=1` runs the portable kernel. + - `STRATA_HIP_WMMA=1` (opt-in, gfx12 only, int8 KV): the prompt path's QSA attention on RDNA4 matrix cores + (`v_wmma_f32_16x16x16_f16`, FP16 hi + lo halves like the CUDA tensor-core kernel; `hip_prompt_attn_wmma` bounds it + against the FP32 kernel and FP64). 7.2-7.5x the portable kernel; R9700 prompts 4K 1,784 -> 2,427 tok/s, 16K + 1,797 -> 2,700. Not bitwise: greedy text differs from token ~50 on, as with the CUDA tensor-core attention. With it + the prompt path's expert ring is 96 slots (as STRATA_PREFILL_RING=96): with the default 384 the 9070 XT's 4K + prompts fell to 718 tok/s; with 96 they gain (1,017 -> 1,211; 16K 1,518 -> 2,032). PR #329 + (bsorensen110) contributed an equivalent gfx12 WMMA kernel of the same speed (within 1%); this one also masks KV + pages that KV streaming has not made resident, as the decode kernel does. - **Known:** rarely (about 1 start in 10) a HIP run's greedy output differs from another start's at some token, on one card or two and on engine 0.1.29 as well; not yet explained. - **Not validated:** images, long contexts beyond 16K, answer-quality benchmarks. diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 278f92e6..72a1b88d 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -89,6 +89,15 @@ double g_pinned_share = 1.0; int g_ring_override = 0; // #340: set by a layer split (Prefill::set_ring_override); 0 = the rule below inline int ring_slots(size_t T) { const char* v = std::getenv("STRATA_PREFILL_RING"); +#if defined(STRATA_USE_HIP) + // S6: with the opt-in RDNA4 matrix-core attention (STRATA_HIP_WMMA=1) a 96-slot ring: measured with it, 9070 XT + // 4K prompts 718 -> 1,211 tok/s (16K 1,949 -> 2,032), R9700 4K 2,426 -> 2,483 (16K the same) + static const bool wmma = [] { + const char* e = std::getenv("STRATA_HIP_WMMA"); + return e != nullptr && e[0] == '1'; + }(); + if (!v && g_ring_override <= 0 && wmma) return (int64_t) T >= stream_all_min() ? 96 : STAGE; +#endif const int r = v ? std::atoi(v) : g_ring_override > 0 ? g_ring_override : (g_pinned_share >= 0.9 ? 384 : 96); if (v && r == STAGE) return STAGE; // Explicit opt-in to routed-only staging, including large chunks. const int big = r < 16 ? 16 : r > RING_MAX ? RING_MAX : r; From dadc9e781a96af5a11500653b811cdd2ea8bf500 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 14:30:39 +0200 Subject: [PATCH 11/11] #340: a split's own prompt buffers are opt-in (STRATA_SPLIT_OWN=1, or auto for the 12% rule) - the owner's choice: the default borrows as 0.1.31 did, with the concurrent refill, the 96-blob split ring and own buffers only on a card with free VRAM, so the split's output stays 0.1.31's (2K +27%, 16K +5%, decode unchanged on the R9700 + 9070 XT); docs --- docs/MULTI_GPU.md | 9 +++++++++ src/program/generate.cpp | 12 ++++++++---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 67fdfea1..97d4dac4 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -60,6 +60,15 @@ profiled expert plus the context's KV, the draft layer and the reserve, and says stays. On an R9700 32 GB + RX 9070 XT the R9700 holds all of the Coder's experts: with the flag 4K prompts read at 1,776 tok/s instead of 1,244 (split) and decode runs at ~60 tok/s instead of ~51 (16K prompts ~5% slower than split). +**Short prompts on a split (0.1.32, #340).** 0.1.30 gave each card's prompt path a loan from its own expert cache, +refilled after every request; on cards that hold nearly all their experts that cost short prompts up to a third of +their speed. 0.1.32 refills all cards at once, uses a smaller streaming ring on a split, and lets a card with free +VRAM keep its own prompt buffers - the same output as 0.1.31, measured on an R9700 + RX 9070 XT: 2K prompts 993 -> +1,265 tok/s, 16K 1,852 -> 1,950, decode unchanged. `STRATA_SPLIT_OWN=1` (opt-in) gives every card its own buffers: +2K 1,450 and 16K 2,227 tok/s there, but a full card then keeps a different set of experts resident, so the output +differs from the default's (stable and coherent); `STRATA_SPLIT_OWN=auto` does that only where the buffers are at +most 12% of each card's VRAM. + The engine flags behind it: `--layer-split K1[,K2..]|auto` and `--split-device D1[,D2..]` (the later stages' devices; default the next visible ones). `--layer-split K --split-device 0` runs both stages on one card sharing everything - the bit-exact check of the hand-off, not a speed mode. diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 1f60944e..73106038 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1311,10 +1311,14 @@ int main(int argc, char** argv) { // small part of every card - at most 12% of its VRAM (16 GB and larger cards) - and borrows on smaller cards, // where the reserve would cost the cache (and the context) the paragraph above is about. Measured with own // buffers on the 9070 XT + R9700: 2K 1588 tok/s, 16K 2006 (0.1.29 1568 / 1935, 0.1.31 993 / 1852). - // STRATA_SPLIT_OWN=1: own buffers on any cards; 0: borrow (0.1.30 / 0.1.31). --split-skip-if-fits keeps the - // loans (it can fall back to one GPU, which must stay as it is). - if (!o.no_prefill_borrow && !o.split_skip_if_fits) { - const char* v = std::getenv("STRATA_SPLIT_OWN"); + // OPT-IN (the owner's choice for 0.1.32): own buffers change which experts a full card keeps resident, so the + // split's output differs from 0.1.31's; the default borrows as 0.1.31 did - with the concurrent refill and the + // 96-blob split ring that alone gave 2K +27%, 16K +5% over 0.1.31, decode unchanged, output identical. + // STRATA_SPLIT_OWN=auto: the 12% rule above; 1: own buffers on any cards; unset/0: borrow. + // --split-skip-if-fits keeps the loans (it can fall back to one GPU, which must stay as it is). + const char* own_env = std::getenv("STRATA_SPLIT_OWN"); + if (!o.no_prefill_borrow && !o.split_skip_if_fits && own_env != nullptr && own_env[0] != '0') { + const char* v = std::string(own_env) == "auto" ? nullptr : own_env; bool own = v ? v[0] == '1' : true; // the buffers of a 2048-token chunk (or the --prefill one) + a 96-blob ring (as split_pf_mib prices them) const int64_t own_chunk = o.prefill_auto || o.prefill_chunk <= 0 ? 2048 : o.prefill_chunk;