From 719b733e01f6729779cdc86362decfb99225b979 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 07:08:23 +0200 Subject: [PATCH 01/17] dq_q2_0: keep the Q2_0 signed-zero fix on every HIP arch/version (#1540, #1474) The negative-scale-times-zero workaround was gated to an arch list (gfx1012 on HIP < 7, gfx1151, gfx1200/gfx1201 since 0ff45cffb); the list only ever chased the newest report. The workaround writes the scale's sign bit for code 1, which is value-identical on targets whose compiler never folds: keep it on every HIP build. Ported from PR #1540 onto the tree that already carries the gfx1200/1201 entries; the comment text is adjusted. Co-authored-by: nekomario28 <206304251+nekomario28@users.noreply.github.com> --- src/kernels/cuda/iq_kernels.cu | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 947952a0..549e4e3e 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -1852,10 +1852,10 @@ __device__ void dq_q2_0(const void* vx, int64_t ibs, dst_t* yy, int tid) { for (int j = 0; j < 8; ++j) { const int i = part * 8 + j; const int code = (x[b].qs[i / 4] >> ((i % 4) * 2)) & 3; -#if defined(__HIPCC__) && ((defined(__gfx1012__) && HIP_VERSION_MAJOR < 7) || defined(__gfx1151__) || \ - defined(__gfx1200__) || defined(__gfx1201__)) - // HIP 5.7 on RDNA1, the HIP compiler on gfx1151 (PR #895, ROCm 7.13) and on RDNA4 gfx1200/gfx1201 (ROCm - // 7.10, #1474) fold the half path's negative scale times +0 to +0. Preserve the scale's sign, as the FP32/CPU paths do. +#if defined(__HIPCC__) + // HIP compilers fold the half path's negative scale times +0 to +0 (HIP 5.7 on gfx1012, gfx1151 on ROCm + // 7.13 - PR #895, gfx1200/gfx1201 on ROCm 7.10 - #1474); the gating arch list only ever chased the newest + // report (#1540). Preserve the scale's sign, as the FP32/CPU paths do: value-identical where the fold never happens. if constexpr (std::is_same_v) { if (code == 1) { yy[b * 64 + i] = __ushort_as_half(__half_as_ushort(x[b].d) & 0x8000u); From 557b79e78f8fe61c27fe7401d1938af9b786855e Mon Sep 17 00:00:00 2001 From: 0FL01 <117385366+0FL01@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:05:06 +0200 Subject: [PATCH 02/17] test: cover exact multi-row and fused HIP paths on gfx906 --- CMakeLists.txt | 15 ++++++ src/kernels/mmvf_rows_parity.cpp | 76 +++++++++++++++++++++++++++ src/kernels/native_grouped_parity.cpp | 17 +++++- 3 files changed, 106 insertions(+), 2 deletions(-) create mode 100644 src/kernels/mmvf_rows_parity.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index e28abd9b..6a7baf78 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -878,6 +878,21 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(native_grouped_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(native_grouped_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME native_grouped_parity COMMAND native_grouped_parity) + add_executable(mmvf_rows_parity src/kernels/mmvf_rows_parity.cpp) + target_include_directories(mmvf_rows_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(mmvf_rows_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME mmvf_rows_parity COMMAND mmvf_rows_parity) + set_tests_properties(mmvf_rows_parity PROPERTIES ENVIRONMENT "STRATA_MMVF_ROWS=1" TIMEOUT 120) + if(STRATA_HIP_GFX906) + add_test(NAME native_grouped_fused_parity COMMAND native_grouped_parity) + set_tests_properties(native_grouped_fused_parity PROPERTIES + ENVIRONMENT "STRATA_HIP_SWIGLU_FUSED=1;STRATA_EXP_MODE=7" TIMEOUT 120) + add_executable(gfx906_gdn_rec_head tests/hip/gdn_rec_head.cpp) + target_include_directories(gfx906_gdn_rec_head PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(gfx906_gdn_rec_head PRIVATE strata_prefill ${_strata_gpu_runtime_target}) + add_test(NAME gfx906_gdn_rec_head COMMAND gfx906_gdn_rec_head) + set_tests_properties(gfx906_gdn_rec_head PROPERTIES TIMEOUT 120) + endif() add_executable(shared_expert_parity src/kernels/shared_expert_parity.cpp) target_include_directories(shared_expert_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(shared_expert_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) diff --git a/src/kernels/mmvf_rows_parity.cpp b/src/kernels/mmvf_rows_parity.cpp new file mode 100644 index 00000000..189f5610 --- /dev/null +++ b/src/kernels/mmvf_rows_parity.cpp @@ -0,0 +1,76 @@ +// Exact multi-row BF16/F32 GEMV checks against independent single-row calls. +// Run with STRATA_MMVF_ROWS=1; synthetic data, no model or private prompts. +#include "strata/kernels/bf16_gemv.hpp" +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; +static void ck(cudaError_t e) { + if (e != cudaSuccess) { std::fprintf(stderr, "%s\n", cudaGetErrorString(e)); std::exit(2); } +} +template static T* alloc(size_t n) { + T* p = nullptr; ck(cudaMalloc(&p, n * sizeof(T))); return p; +} +int main() { + const char* flag = std::getenv("STRATA_MMVF_ROWS"); + if (!flag || flag[0] != '1') { std::fprintf(stderr, "set STRATA_MMVF_ROWS=1\n"); return 2; } + cudaStream_t s; ck(cudaStreamCreate(&s)); + const int shapes[][2] = {{64,64},{192,67},{512,65},{640,128},{2560,48}, + {2560,128},{2560,512},{2560,2560},{10240,320}}; + size_t cases = 0, values = 0, mismatches = 0; + for (const auto& shape : shapes) for (int nt = 1; nt <= 8; ++nt) + for (int pad : {0,2}) for (int range : {0,1,2}) { + const int ni = shape[0], no = shape[1], ldx = ni + pad, ldy = no + pad + 1; + std::mt19937 rng(1234 + nt * 17 + pad * 31 + range * 53 + ni + no); + std::uniform_real_distribution d(-1.f, 1.f); + const float xs = range == 0 ? 1.f : range == 1 ? 1.e-12f : 1.e12f; + const float ws = range == 0 ? 1.f : range == 1 ? 1.e-8f : 1.e8f; + std::vector x((size_t) nt * ldx); + std::vector w((size_t) (no + 1) * ni); + for (auto& v : x) v = d(rng) * xs; + for (auto& v : w) { const float f = d(rng) * ws; uint32_t b; std::memcpy(&b,&f,4); v = uint16_t(b >> 16); } + float* dx = alloc(x.size()); uint16_t* dw = alloc(w.size()); + const size_t count = (size_t) nt * ldy; + float* ref = alloc(count); float* got = alloc(count); + float* aux = alloc((size_t)nt * 3); float* aref = alloc((size_t)nt * 3); + ck(cudaMemcpy(dx,x.data(),x.size()*4,cudaMemcpyHostToDevice)); + ck(cudaMemcpy(dw,w.data(),w.size()*2,cudaMemcpyHostToDevice)); + ck(cudaMemset(ref,0xff,count*4)); ck(cudaMemset(got,0xff,count*4)); + ck(cudaMemset(aux,0xff,(size_t)nt*12)); ck(cudaMemset(aref,0xff,(size_t)nt*12)); + for (int t = 0; t < nt; ++t) { + k::bf16_gemv_fp32_mmvf(dx+(size_t)t*ldx,dw,ref+(size_t)t*ldy,ni,no,s); + k::bf16_gemv_fp32_mmvf(dx+(size_t)t*ldx,dw+(size_t)no*ni,aref+t*3,ni,1,s); + } + ck(cudaStreamSynchronize(s)); + cudaGraph_t graph; cudaGraphExec_t exec; + ck(cudaStreamBeginCapture(s,cudaStreamCaptureModeThreadLocal)); + k::bf16_gemv_fp32_mmvf_multi(dx,ldx,dw,got,ldy,ni,no,nt,s); + ck(cudaStreamEndCapture(s,&graph)); ck(cudaGraphInstantiate(&exec,graph,0)); + ck(cudaGraphLaunch(exec,s)); ck(cudaStreamSynchronize(s)); + auto compare = [&](float* a, float* b, size_t n) { + std::vector aa(n),bb(n); + ck(cudaMemcpy(aa.data(),a,n*4,cudaMemcpyDeviceToHost)); + ck(cudaMemcpy(bb.data(),b,n*4,cudaMemcpyDeviceToHost)); + size_t bad = 0; for (size_t i=0;i= 2 && no >= 64)) { std::printf("FAIL eligibility\n"); ++mismatches; } + ck(cudaGraphExecDestroy(exec)); ck(cudaGraphDestroy(graph)); + ck(cudaFree(dx)); ck(cudaFree(dw)); ck(cudaFree(ref)); ck(cudaFree(got)); ck(cudaFree(aux)); ck(cudaFree(aref)); + ++cases; + } + ck(cudaStreamDestroy(s)); + std::printf("mmvf_rows_parity: %zu cases, %zu values, %zu mismatches\n",cases,values,mismatches); + return mismatches ? 1 : 0; +} diff --git a/src/kernels/native_grouped_parity.cpp b/src/kernels/native_grouped_parity.cpp index 270de2cb..67b6e67a 100644 --- a/src/kernels/native_grouped_parity.cpp +++ b/src/kernels/native_grouped_parity.cpp @@ -99,6 +99,7 @@ std::vector random_rows(int t, int64_t rows, int64_t n, std::mt19937& r struct Setup { k::NativeExpertLayout L; int T = 0, K = 0, cap = 0, n_blobs = 0; + int active_lo = 0, active_hi = 0; size_t slot = 0; uint8_t* blobs = nullptr; uint8_t* xq = nullptr; @@ -174,6 +175,8 @@ struct Setup { } if (st.back() > cap) { std::fprintf(stderr, "plan: %d entries > cap %d\n", st.back(), cap); std::exit(2); } const int ng = (int) p.size(); + active_lo = base; + active_hi = st.back(); std::iota(ds.begin(), ds.end(), 0); std::shuffle(ds.begin(), ds.end(), rng); // scattered rows of `out` for (int e = 0; e < cap; ++e) tk_v.push_back(tk(rng)); @@ -197,6 +200,15 @@ struct Setup { ck(cudaStreamSynchronize(s), "sync"); std::vector o(out_floats); ck(cudaMemcpy(o.data(), out, o.size() * 4, cudaMemcpyDeviceToHost), "out"); + // Fused SwiGLU does not write h or inactive Q8 rows. Compare only the + // active Q8_1 bytes, appended after the full output (including padding). + const size_t fa = ((size_t) cap * L.n_ff * sizeof(float) + 255) & ~(size_t) 255; + const size_t qrow = (size_t) (L.n_ff / 32) * 36; + const size_t qb = (size_t) (active_hi - active_lo) * qrow; + const size_t old = o.size(); + o.resize(old + qb / sizeof(uint32_t)); + if (qb) + ck(cudaMemcpy(o.data() + old, scr + 3 * fa + active_lo * qrow, qb, cudaMemcpyDeviceToHost), "active hq"); return o; } }; @@ -210,7 +222,7 @@ void check(int gu, int dt, int64_t H, int64_t FF, cudaStream_t s, std::mt19937& const int ng = S.plan(groups, base, rng); const auto ref = S.result(true, 0, 0x00, s); size_t w = 0; - for (const uint32_t v : ref) w += v != 0xFFFFFFFFu; + for (size_t i = 0; i < S.out_floats; ++i) w += ref[i] != 0xFFFFFFFFu; written += w; for (const int64_t gy : {(int64_t) 0, (int64_t) 1, (int64_t) 2, (int64_t) 3, (int64_t) 4, (int64_t) S.cap + 3}) { const auto got = S.result(false, gy, (calls & 1) ? 0x7F : 0x00, s); @@ -218,7 +230,7 @@ void check(int gu, int dt, int64_t H, int64_t FF, cudaStream_t s, std::mt19937& size_t diff = 0; for (size_t i = 0; i < ref.size(); ++i) diff += ref[i] != got[i]; if (diff) { - std::printf(" %-8s/%-7s base %d, %d groups, grid_groups %lld: %zu of %zu floats differ FAIL\n", + std::printf(" %-8s/%-7s base %d, %d groups, grid_groups %lld: %zu of %zu output/Q8 words differ FAIL\n", name_of(gu), name_of(dt), base, ng, (long long) gy, diff, ref.size()); ++bad; } @@ -347,6 +359,7 @@ int main(int argc, char** argv) { #endif 8}) // STRATA_GU_FMTS for (int dt : {20, 23, 42, 7, 8}) check(gu, dt, 512, 256, s, rng); // STRATA_D_FMTS; IQ4_XS: n_ff % 256 + check(42, 42, 2560, 640, s, rng); check(21, 20, 2560, 640, s, rng); // a model's shapes check(21, 23, 2560, 768, s, rng); if (do_bench) bench(s, rng); From d0838c6c3a9e41e98cb6773fbf6e32d2f32eaceb Mon Sep 17 00:00:00 2001 From: xjc10 <69450118+xjc10@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:04:00 +0000 Subject: [PATCH 03/17] tests: hip_prefill_gemm runs the FP16-io prompt GEMMs (set_f16_io) on any HIP card, and its BF16 inputs are no longer zero The test ran only the FP32-out GEMMs, so the gfx103x prompt path's FP16-out GEMM (f16_inplace, widen_rows_f16) and bf16()'s W conversion through the scratch were not under ctest. Every shape now runs a second time with set_f16_io(true), forced on whatever HIP card runs the test: X as the FP16 image for the BF16 products, a scratch of 64 rows so a 96-row weight converts in two slices (the second written at Y + 64), ldy > N, an odd N (257), T = 1, and a beta = 1 f16() call, which keeps the FP32-out GEMM. FP16-out results are checked against the double reference at FP16's rounding (6e-4 relative per element plus 1e-4, rel L2 < 1e-3); the row padding and the guards around Y must be untouched, as before. The FP32-out runs keep their tolerance. Found while adding them: the BF16 inputs were all zero. hip_bfloat16(float) produced data 0 in this test's build (ROCm 10.0, gfx1030; not traced further), so the two BF16 cases passed on nothing (rel L2 printed 0). The BF16 bits are now made by hand (round to nearest even on the float's bits); with real inputs the BF16 cases pass at rel L2 1.9e-07 (FP32 out) and 2.2e-04 (FP16 out). On an RX 6900 XT (gfx1030, ROCm 10.0): 11 of 11 pass. (cherry picked from commit 4c6c9fe374c41c90d41b4c28decfc34352ad4e21) --- .../2026-10-04-rdna2-fp16-prompt/README.md | 6 +++ tests/hip/prefill_gemm.cpp | 52 +++++++++++++++---- 2 files changed, 48 insertions(+), 10 deletions(-) diff --git a/bench/results/2026-10-04-rdna2-fp16-prompt/README.md b/bench/results/2026-10-04-rdna2-fp16-prompt/README.md index 29f8e937..90f670a6 100644 --- a/bench/results/2026-10-04-rdna2-fp16-prompt/README.md +++ b/bench/results/2026-10-04-rdna2-fp16-prompt/README.md @@ -130,6 +130,12 @@ would need `STRATA_HIP_PROMPT_F16=0`. row from its end; `Gemm::bf16` converts W row slices to FP16 through the existing dequantization scratch (as `native()` does) and takes X as the FP16 image. `bf16x2_mode()` is 0 there (the BF16 low part has no FP16 meaning). - No new device memory, no host sync, no fallback branch; CUDA builds are unchanged (`#if defined(__HIPCC__)`). +- `hip_prefill_gemm` (ctest) runs its shapes a second time with `set_f16_io(true)` on any HIP card: X as the FP16 image + for the BF16 products, a scratch of 64 rows so a 96-row weight converts in two slices, `ldy > N`, an odd N, T = 1 and + a `beta = 1` f16() call (which keeps the FP32-out GEMM). The FP16-out results are checked against the double reference + at FP16's rounding (6e-4 relative per element, rel L2 < 1e-3); row padding and the guards around Y must be untouched. + The test's BF16 inputs are now made by hand: `hip_bfloat16(float)` produced 0 in this build, so the two BF16 cases had + passed on all-zero inputs (rel L2 printed 0); with real inputs they pass at 1.9e-07 (FP32 out) and 2.2e-04 (FP16 out). ## Limits diff --git a/tests/hip/prefill_gemm.cpp b/tests/hip/prefill_gemm.cpp index 1536c89e..dca156e7 100644 --- a/tests/hip/prefill_gemm.cpp +++ b/tests/hip/prefill_gemm.cpp @@ -1,4 +1,8 @@ // BF16/F16 prefill through the actual engine GEMM path against a CPU reference. +// +// Each shape runs twice: on the engine's GEMM as every card runs it (FP32 out), and with Gemm::set_f16_io(true), the +// gfx103x prompt path's FP16-out GEMM widened in place in Y's own rows (bench/results/2026-10-04-rdna2-fp16-prompt). +// The second mode is forced here on any HIP card, so the path is covered wherever the test runs. #include #include #include @@ -20,18 +24,27 @@ struct Buffer { ~Buffer() { if (p) (void) hipFree(p); } }; +// `f16_io`: the Gemm was set_f16_io(true). bf16() then takes X as the prompt path's FP16 image (W stays BF16), and +// every GEMM with beta = 0 writes its result as FP16 before widening it: those are checked at FP16's rounding +// (2^-11 relative per element, plus the FP32 accumulation) instead of the FP32-out tolerance. beta = 1 keeps the +// FP32-out GEMM on the f16() path, and bf16() refuses it there (the prompt path never accumulates a BF16 product). bool run(strata::prefill::Gemm& gemm, hipStream_t stream, bool bf16, - int t, int n, int k, int ldy, float beta) { + int t, int n, int k, int ldy, float beta, bool f16_io = false) { std::mt19937 rng(51012 + t + n); std::uniform_real_distribution dist(-0.25f, 0.25f); std::vector x((size_t)t*k), w((size_t)n*k); std::vector xf(x.size()), wf(w.size()); - auto fill = [&](auto& bits, auto& values) { + auto fill = [&](auto& bits, auto& values, bool as_bf16) { for (size_t i = 0; i < bits.size(); ++i) { - if (bf16) { - const hip_bfloat16 v(dist(rng)); - bits[i] = v.data; - const uint32_t wide = static_cast(v.data) << 16; + if (as_bf16) { + // the BF16 bits by hand (round to nearest even on the float's bits): hip_bfloat16(float) produced + // data 0 in this test's build (ROCm 10.0, not traced further), so both BF16 cases passed on all-zero + // inputs + const float f = dist(rng); + uint32_t u; std::memcpy(&u, &f, 4); + u += 0x7fffu + ((u >> 16) & 1u); + bits[i] = static_cast(u >> 16); + const uint32_t wide = static_cast(bits[i]) << 16; std::memcpy(&values[i], &wide, 4); } else { const __half v = __float2half_rn(dist(rng)); @@ -40,7 +53,8 @@ bool run(strata::prefill::Gemm& gemm, hipStream_t stream, bool bf16, } } }; - fill(x, xf); fill(w, wf); + fill(x, xf, bf16 && !f16_io); fill(w, wf, bf16); + const bool f16_out = f16_io && (bf16 || beta == 0.0f); constexpr int offset = 5; std::vector initial(offset + (size_t)t*ldy + 8, -777.25f); for (int r = 0; r < t; ++r) for (int c = 0; c < n; ++c) @@ -64,13 +78,15 @@ bool run(strata::prefill::Gemm& gemm, hipStream_t stream, bool bf16, for (int i=0;i n) and the guards before and after Y: untouched by the GEMM and the widening for (size_t j=0;j N and the odd N check widen_rows_f16's in-place + // walk (FP16 halves at the start of each FP32 row); T = 1 is a single block. + strata::prefill::Gemm gemm; + std::string error; + if (!gemm.init(stream,64*2560,error)) { std::fprintf(stderr,"%s\n",error.c_str()); return 2; } + gemm.set_f16_io(true); + ok=run(gemm,stream,true,16,96,2560,96,0,true) && ok; + ok=run(gemm,stream,true,17,48,2560,64,0,true) && ok; + ok=run(gemm,stream,false,32,640,2560,648,0,true) && ok; + ok=run(gemm,stream,false,64,2560,640,2560,0,true) && ok; + ok=run(gemm,stream,false,33,257,640,264,0,true) && ok; + ok=run(gemm,stream,false,1,96,2560,96,0,true) && ok; + ok=run(gemm,stream,false,17,48,2560,64,1,true) && ok; + } CHECK(hipStreamDestroy(stream)); return ok?0:1; } From c211cb3ebebdded3658ec71e4a72dd2a405839c7 Mon Sep 17 00:00:00 2001 From: xjc10 <69450118+xjc10@users.noreply.github.com> Date: Tue, 6 Oct 2026 00:14:13 -0400 Subject: [PATCH 04/17] hip gfx103x FP16 prompt: STRATA_F16_RANGE counts what enters and leaves FP16; the range measured (outputs peak at 410 of 65504) and the FP32 route compared The README's range check said "none beyond 65504" over 110K tokens without the numbers. The engine now has the counter: STRATA_F16_RANGE=1 records, per device, the largest |value| and the count beyond 65504 (or not finite) where a value enters or leaves FP16 - the activation images (hf_sat, the image writers' one funnel), the BF16 weights converted to FP16 (bf16_to_f16_rows) and the FP16 GEMM outputs as they are widened (widen_rows_f16: an output rocBLAS wrote beyond the range is Inf there) - and prints one line per prompt. Off, the cost is one flag read per value; on, a 34.4K-token prompt read at 889.8 tok/s against 888.5. to_f16 (the hc image for the FP16-weight GEMMs, the PLE key image) saturates like the other image writers now, so every FP16 image is under the same rule. The HIP shim gains cudaMemcpyFromSymbol. Measured on one RX 6900 XT over 466K tokens in nine prompts (corpus slices, two prompts built to push activations - delimiter floods, a token repeated 4,000 times, 6,000-character runs, base64, five scripts - and four batches of real requests): outputs peak at 409.5 (160x below 65504), activations at 112.2, the BF16 weights at 11.56; nothing beyond the range, nothing non-finite. The prompts built to push activations stayed below the ordinary corpus. One model (GSQ-RCO IQ3_S); the table is in the README's range section. The README also gains the same-card comparison with #1006, which takes these GEMMs as FP32 SGEMMs: 8.4K / 32.8K / 104K-token prompts 412 / 455 / 456 tok/s on the old path, 622 / 742 / 750 with #1006, 730 / 900 / 904 with this change (the card's FP32 rate against its FP16 rate), with the phase times and what the SGEMM route covers that this change does not. (cherry picked from commit e780c8581e2b0ad95e97191c343d583bcad2f50e) --- .../2026-10-04-rdna2-fp16-prompt/README.md | 53 +++++++++++++++++-- docs/AMD_HIP.md | 5 +- include/strata/hip_compat/cuda_runtime.h | 1 + include/strata/prefill/gemm.hpp | 7 +++ include/strata/prefill/kernels.hpp | 5 ++ src/prefill/gemm.cu | 45 ++++++++++++++++ src/prefill/kernels.cu | 38 ++++++++++++- src/prefill/prefill.cpp | 10 ++++ 8 files changed, 156 insertions(+), 8 deletions(-) diff --git a/bench/results/2026-10-04-rdna2-fp16-prompt/README.md b/bench/results/2026-10-04-rdna2-fp16-prompt/README.md index 90f670a6..be2ca3be 100644 --- a/bench/results/2026-10-04-rdna2-fp16-prompt/README.md +++ b/bench/results/2026-10-04-rdna2-fp16-prompt/README.md @@ -53,14 +53,57 @@ Both cards, cold server per run, one 8,275- and one 33,586-token prompt of repos Decode is the same within the noise in both setups (these short answers: 51-58 tok/s split, 36-42 helper). +## Against the FP32 route (#1006), same card (2026-10-06) + +#1006 takes the same gfx103x GEMMs the other way: both inputs widened to FP32 and the product as SGEMM (exact widening, +FP32 accumulate, `STRATA_RDNA2_SGEMM=0` for the old path). Built at its `63a92c2` and run next to this change's build +(`6add1a7`, `main` + this) on one RX 6900 XT: the same model and arguments as above, three prompts from one corpus, cold +server per arm, temperature 0, 8 tokens answered, `STRATA_PREFILL_TIMING=1`. The old path here is #1006's branch with +its switch off. One run per cell; a second cold run of this change's arm repeated it within 1.3%. + +| prompt tokens | old path | #1006 (SGEMM) | this change (FP16 HGEMM) | +| ---: | ---: | ---: | ---: | +| 8,368 | 412 tok/s | 622 tok/s (+51%) | 730 tok/s (+77%) | +| 32,813 | 455 tok/s | 742 tok/s (+63%) | 900 tok/s (+98%) | +| 104,412 | 456 tok/s | 750 tok/s (+65%) | 904 tok/s (+98%) | + +The 32,813-token prompt's GPU timeline, the phases these GEMMs sit in (old / SGEMM / FP16): gdn 22.0 -> 6.2 -> 4.0 s, +qsa proj 8.6 -> 3.2 -> 2.1 s, hc read 8.1 -> 6.1 -> 4.4 s, router+shared 4.0 -> 2.5 -> 0.7 s; `wait copy` is 1.0 s in +all three (PCIe 4.0 x8), so the GEMMs are not hidden behind the expert stream here. Per call this is the card's FP32 +rate against its FP16 rate: the N 10240 x K 2560 projection at ~15 TFLOPS as SGEMM (#1006's 27.7 ms at T 8192) and +37.7 as HGEMM, about 2x on the GEMM itself, 17-21% on the prompt. What the SGEMM route has that this change does not: +no FP16 output rounding, `beta != 0` and N < 64 covered. The three arms gave the same answer on each prompt. + ## Range check FP16 ends at 65504 where BF16 reaches 3.4e38, so the precondition is that nothing the prompt path feeds these GEMMs or gets -out of them leaves FP16's range. Measured on 0.1.38 with a diagnostic counter (not part of this change) over 33.7K tokens of -English docs, 43.3K of Chinese logs and 32.4K of C++ on one card: every BF16 GEMM's X and W and every FP16 output - **0** -values beyond 65504, **0** infinities. Non-zero |x| < 6.1e-5 (FP16's subnormal band): 0.008-1.8% of X, 0.1-0.9% of W. -Out-of-range values would still be finite: the activation writers saturate to +-65504 (`hf_sat`, as the FP16 images -already did), a NaN stays a NaN. +out of them leaves FP16's range. The engine now counts it: `STRATA_F16_RANGE=1` records, per device, the largest |value| +and the count beyond 65504 (or not finite) at the three places a value enters or leaves FP16 - the activation images +(`hf_sat`, every image writer's one funnel), the BF16 weights converted to FP16 (`bf16_to_f16_rows`) and the FP16 GEMM +outputs as they are widened (`widen_rows_f16`; an output rocBLAS wrote beyond the range is Inf there, not saturated) - +and prints one line per prompt (`strata f16 range: ...`). Off, the cost is one flag read per value; on, a 34.4K-token +prompt read at 889.8 tok/s against 888.5 without it. + +Measured on one card over 466K tokens in nine prompts: three 32-34K slices of the earlier corpus (English docs, Chinese +logs, C++), two prompts (118K and 64K tokens) built to push activations - delimiter floods (`<|im_start|>`, 200 newlines, +500 spaces), one token repeated 4,000 times, 6,000-character runs, 18-digit numbers, 20K characters of base64, emoji and +Japanese / Russian / Arabic / Hindi text, 2,000 SQL lines - and four batches (40-49K tokens) of real requests recorded +from this machine's API: + +| | activation images, max abs | BF16 weights, max abs | FP16 GEMM outputs, max abs | beyond 65504 / not finite | +| --- | ---: | ---: | ---: | ---: | +| corpus slices (3) | 84.0 / 103.4 / 112.2 | 11.56 | 387.0 / 392.0 / 391.5 | 0 | +| built to push (2) | 76.6 / 99.0 | 11.56 | 409.5 / 399.2 | 0 | +| real requests (4) | 73.9 - 92.7 | 11.56 | 374.2 - 382.5 | 0 | + +The largest output is 409.5, 160x below 65504; the largest activation 112, 580x below. The prompts built to push +activations did not: their maxima are below the ordinary corpus's. Offline, the pack's dense BF16 tensors (484 in the +first GGUF shard) peak at 8.56 (`hc_ffn_up`); 11.56 is in the second shard (the PLE). This is one model (GSQ-RCO IQ3_S); +the other models setup installs are fine-tunes of the same architecture, so the headroom is the same kind of number +there but has not been measured. Out-of-range activations would still be finite: the image writers saturate to ++-65504 (`hf_sat`), a NaN stays a NaN; an out-of-range GEMM output would be Inf, which is what the counter is for. +`to_f16` (the hc image for the FP16-weight GEMMs and the PLE key image) saturates and counts too now, so every FP16 +image writer is under the same rule; three of the prompts rerun with it in gave the same maxima. ## Distribution check (teacher-forced) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index a8fe8834..19b5c0fd 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -440,7 +440,10 @@ run it; the report below is from a community machine: an RX 6900 XT 16 GB (gfx10 N = 10240, T = 7313, K = 2560). `STRATA_HIP_PROMPT_F16=1` (opt-in, off by default; the engine prints a tip on gfx103x) runs the 16-bit prompt GEMMs FP16 in and out; unset is the old path. `STRATA_DBG_NAN=1` also counts the non-finite FP16 outputs (a sum past 65504). The output is not bit-identical to it (an FP16 rounding of each GEMM's output replaces the BF16 rounding of the BF16 GEMMs' activations); what the distribution check showed and did not show is in - [bench/results/2026-10-04-rdna2-fp16-prompt](../bench/results/2026-10-04-rdna2-fp16-prompt/README.md). Measured on a + [bench/results/2026-10-04-rdna2-fp16-prompt](../bench/results/2026-10-04-rdna2-fp16-prompt/README.md). FP16 ends at + 65504: `STRATA_F16_RANGE=1` prints, per prompt, the largest value that entered or left FP16 and how many were beyond + the range (466K tokens there: outputs peak at 410, activations at 112, none beyond; the image writers saturate, a GEMM + output beyond the range would be Inf and is what the counter is for). Measured on a second community machine - 2x RX 6900 XT 16 GB (one card for these numbers), Ryzen 5 5600X (6 cores, AVX2), 128 GB, Ubuntu 26.04, ROCm 10.0.0, engine 0.1.39 built by hand with `-DSTRATA_PREFILL_MMQ=ON` as setup does, GSQ-RCO IQ3_S: a 9.4K / 34.7K / 105.8K-token prompt reads at 744 / 915 / 926 tok/s instead of 439 / 466 / 461; decode is unchanged. diff --git a/include/strata/hip_compat/cuda_runtime.h b/include/strata/hip_compat/cuda_runtime.h index d669f0fe..4eec0684 100644 --- a/include/strata/hip_compat/cuda_runtime.h +++ b/include/strata/hip_compat/cuda_runtime.h @@ -142,5 +142,6 @@ inline hipError_t cudaGraphInstantiate(hipGraphExec_t* exec, hipGraph_t graph, } #define __trap() __builtin_trap() // the compiled-out sm_80 paths (never selected on AMD) #define cudaMemcpyToSymbol(symbol, ...) hipMemcpyToSymbol(HIP_SYMBOL(symbol), __VA_ARGS__) +#define cudaMemcpyFromSymbol(dst, symbol, ...) hipMemcpyFromSymbol(dst, HIP_SYMBOL(symbol), __VA_ARGS__) #include "intrinsics.hpp" diff --git a/include/strata/prefill/gemm.hpp b/include/strata/prefill/gemm.hpp index 0740fd0d..e8b4e9a9 100644 --- a/include/strata/prefill/gemm.hpp +++ b/include/strata/prefill/gemm.hpp @@ -12,6 +12,13 @@ namespace strata::prefill { +/// STRATA_F16_RANGE: count what the gfx103x FP16 route converts on this device - the BF16 weights to FP16 (slot 0) +/// and the FP16 GEMM outputs widened to FP32 (slot 1): the largest |value| and how many were beyond 65504 or not +/// finite. gemm_f16_range_read returns them (and resets when asked); false where the route does not exist (CUDA). +void gemm_set_f16_range(bool on); +bool gemm_f16_range_read(float max_abs[2], unsigned long long over[2], bool reset); + + class Gemm { public: Gemm() = default; diff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hpp index f12f34b9..7ea690b5 100644 --- a/include/strata/prefill/kernels.hpp +++ b/include/strata/prefill/kernels.hpp @@ -42,6 +42,11 @@ void gr_write_cvec_norm_rs(float* R, const float* bo, const float* inj, int64_t void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo = nullptr); /// The BF16-weight GEMMs' activation image (gr_* kernels, to_bf16) in FP16 instead of BF16, on the current device. void set_act_f16(bool on); +/// STRATA_F16_RANGE: count what the activation images convert to FP16 on this device (hf_sat): the largest |value| and +/// how many were beyond 65504 or NaN. f16_range_read returns them (and resets when asked); false if the device +/// refused the copy. +void set_f16_range(bool on); +bool f16_range_read(float& max_abs, unsigned long long& over, bool reset); /// mixed[t, d] = mean_c xn[t, c, d] * sigmoid(gated[t, c, d]); FP32, BF16 and FP16 (either image may be null). void gr_mix(const float* xn, const float* gated, float* mixed, uint16_t* mixed16, int64_t T, void* stream, uint16_t* mixed_h = nullptr, uint16_t* mixed16_lo = nullptr); diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu index 300da53b..2a0bfc9a 100644 --- a/src/prefill/gemm.cu +++ b/src/prefill/gemm.cu @@ -51,6 +51,18 @@ namespace strata::prefill { namespace { #if defined(__HIPCC__) +// STRATA_F16_RANGE (gemm_set_f16_range): the largest |value| and the count beyond 65504 / non-finite, for the BF16 +// weights converted to FP16 (slot 0, bf16_to_f16_rows) and the FP16 GEMM outputs widened (slot 1, widen_rows_f16 - +// an output rocBLAS wrote as FP16 is Inf there, not saturated). As the activation counter in kernels.cu. +__device__ int g_f16_range_on_g = 0; +__device__ unsigned g_f16_range_max_g[2] = {0, 0}; +__device__ unsigned long long g_f16_range_over_g[2] = {0, 0}; +__device__ __forceinline__ void f16_range_note_g(int k, float f) { + const float a = fabsf(f); + const unsigned bits = __float_as_uint(a); + if (bits > g_f16_range_max_g[k]) atomicMax(&g_f16_range_max_g[k], bits); + if (a > 65504.0f || isnan(f)) atomicAdd(&g_f16_range_over_g[k], 1ull); +} // Y's rows, written by an FP16-out GEMM as FP16 at the start of each FP32 row (ldc = 2 ldy halves), widened in place. // Float c overwrites halves 2c and 2c+1, so a row is walked from its end in blocks: a block's halves are read into // registers, the block syncs, then writes its floats - which only cover halves of blocks already read. @@ -64,6 +76,7 @@ __global__ void widen_rows_f16(float* __restrict__ Y, int64_t n, int64_t ldy, in const int64_t c = b * blockDim.x + threadIdx.x; const float v = c < n ? __half2float(h[c]) : 0.0f; if (count_nonfinite && c < n && !isfinite(v)) atomicAdd(&g_f16_nonfinite, 1ull); + if (c < n && g_f16_range_on_g) f16_range_note_g(1, v); __syncthreads(); if (c < n) y[c] = v; __syncthreads(); @@ -73,10 +86,42 @@ __global__ void widen_rows_f16(float* __restrict__ Y, int64_t n, int64_t ldy, in __global__ void bf16_to_f16_rows(const uint16_t* __restrict__ s, __half* __restrict__ d, int64_t n) { for (int64_t i = blockIdx.x * (int64_t) blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) { const float f = __uint_as_float((uint32_t) s[i] << 16); + if (g_f16_range_on_g) f16_range_note_g(0, f); d[i] = __float2half(isnan(f) ? f : fminf(fmaxf(f, -65504.0f), 65504.0f)); // as hf_sat: a NaN stays NaN } } #endif +} // namespace + +void gemm_set_f16_range(bool on) { +#if defined(__HIPCC__) + const int v = on ? 1 : 0; + if (cudaMemcpyToSymbol(g_f16_range_on_g, &v, sizeof v) != cudaSuccess) { + std::fprintf(stderr, "prefill gemm: setting the FP16 range check failed: %s\n", cudaGetErrorString(cudaGetLastError())); + std::exit(1); + } +#else + (void) on; +#endif +} +bool gemm_f16_range_read(float max_abs[2], unsigned long long over[2], bool reset) { +#if defined(__HIPCC__) + unsigned bits[2] = {0, 0}; unsigned long long o[2] = {0, 0}; + if (cudaMemcpyFromSymbol(bits, g_f16_range_max_g, sizeof bits) != cudaSuccess || + cudaMemcpyFromSymbol(o, g_f16_range_over_g, sizeof o) != cudaSuccess) { cudaGetLastError(); return false; } + for (int k = 0; k < 2; ++k) { union { unsigned u; float f; } c; c.u = bits[k]; max_abs[k] = c.f; over[k] = o[k]; } + if (reset) { + const unsigned z[2] = {0, 0}; const unsigned long long zz[2] = {0, 0}; + cudaMemcpyToSymbol(g_f16_range_max_g, z, sizeof z); cudaMemcpyToSymbol(g_f16_range_over_g, zz, sizeof zz); + } + return true; +#else + (void) max_abs; (void) over; (void) reset; + return false; +#endif +} + +namespace { void ck(cublasStatus_t s, const char* what) { if (s != CUBLAS_STATUS_SUCCESS) { diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index f58a189c..a0b622dc 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -45,7 +45,23 @@ __device__ __forceinline__ uint16_t hf(float f) { return __half_as_ushort(__floa // A SwiGLU product for an FP16 GEMM: saturated, so a token with a massive activation cannot turn into inf and then // NaN in the down projection (decode's q8_1 has room to ~8e6; FP16 ends at 65504). A NaN stays NaN (fminf/fmaxf // would make it -65504 and hide where it came from); finite values below 65504 round exactly as before. -__device__ __forceinline__ uint16_t hf_sat(float f) { return hf(isnan(f) ? f : fminf(fmaxf(f, -65504.0f), 65504.0f)); } +// STRATA_F16_RANGE=1 (set_f16_range): what reaches FP16's range on this device - the largest |value| the activation +// images converted (hf_sat is their one funnel) and how many were beyond 65504 or NaN; W and Y are counted in gemm.cu. +// Off, the cost is one flag read per value. The max is kept as float bits (positive floats order as unsigned ints), +// and a thread takes the atomic only when it beats the value it read, so the atomics stop once the max has settled. +__device__ int g_f16_range_on = 0; +__device__ unsigned g_f16_range_max = 0; +__device__ unsigned long long g_f16_range_over = 0; +__device__ __forceinline__ void f16_range_note(float f) { + const float a = fabsf(f); + const unsigned bits = __float_as_uint(a); + if (bits > g_f16_range_max) atomicMax(&g_f16_range_max, bits); + if (a > 65504.0f || isnan(f)) atomicAdd(&g_f16_range_over, 1ull); +} +__device__ __forceinline__ uint16_t hf_sat(float f) { + if (g_f16_range_on) f16_range_note(f); + return hf(isnan(f) ? f : fminf(fmaxf(f, -65504.0f), 65504.0f)); +} // The prompt path's 16-bit activation image for the BF16-weight GEMMs: BF16, or FP16 where the GEMM library is fast // only in FP16 (prompt_f16() in gemm.cu: rocBLAS on gfx103x). Set once per device before the first prompt. #if defined(__HIPCC__) // HIP only (#835): the CUDA kernels stay exactly as they were, they never read the flag @@ -1718,7 +1734,7 @@ __global__ void kv_append_kernel(const float* __restrict__ K, const float* __res } __global__ void to_f16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, int64_t n) { for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) - y[i] = hf(x[i]); + y[i] = hf_sat(x[i]); // saturated and counted like every other FP16 image (the hc / embedding image on gfx103x) } __global__ void round_f16_kernel(const float* __restrict__ x, float* __restrict__ y, int64_t n) { for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) @@ -1827,6 +1843,24 @@ void set_act_f16(bool on) { } #endif } +void set_f16_range(bool on) { + const int v = on ? 1 : 0; + if (cudaMemcpyToSymbol(g_f16_range_on, &v, sizeof v) != cudaSuccess) { + std::fprintf(stderr, "prefill: setting the FP16 range check failed: %s\n", cudaGetErrorString(cudaGetLastError())); + std::exit(1); + } +} +bool f16_range_read(float& max_abs, unsigned long long& over, bool reset) { + unsigned bits = 0; unsigned long long o = 0; + if (cudaMemcpyFromSymbol(&bits, g_f16_range_max, sizeof bits) != cudaSuccess || + cudaMemcpyFromSymbol(&o, g_f16_range_over, sizeof o) != cudaSuccess) { cudaGetLastError(); return false; } + union { unsigned u; float f; } c; c.u = bits; max_abs = c.f; over = o; + if (reset) { + const unsigned z = 0; const unsigned long long zz = 0; + cudaMemcpyToSymbol(g_f16_range_max, &z, sizeof z); cudaMemcpyToSymbol(g_f16_range_over, &zz, sizeof zz); + } + return true; +} void to_f16(const float* x, uint16_t* y, int64_t n, void* stream) { if (n <= 0) return; to_f16_kernel<<<(unsigned) ((n + 255) / 256 < 4096 ? (n + 255) / 256 : 4096), 256, 0, (cudaStream_t) stream>>>(x, y, n); diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 2fa71c7c..5724f04d 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1223,6 +1223,8 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co m.f16_io = prompt_f16(); m.gemm.set_f16_io(m.f16_io); set_act_f16(m.f16_io); + static const bool f16_range = std::getenv("STRATA_F16_RANGE") != nullptr; // what reaches FP16's range + if (f16_range) { set_f16_range(true); gemm_set_f16_range(true); } } if (!carve(T, &o)) { size_t fb = 0, tb = 0; @@ -4265,6 +4267,14 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri (long long) kv_prefetches); } stats_.ms_total += ms_since(t_start); + { + static const bool f16_range = std::getenv("STRATA_F16_RANGE") != nullptr; + float xm = 0.0f, wy[2] = {0.0f, 0.0f}; unsigned long long xo = 0, wyo[2] = {0, 0}; + if (f16_range && f16_range_read(xm, xo, true) && gemm_f16_range_read(wy, wyo, true)) + std::fprintf(stderr, "strata f16 range: %lld tokens: activation images max |x| %.1f (%llu beyond 65504 or NaN), " + "BF16 weights max |w| %.3f (%llu), FP16 GEMM outputs max |y| %.1f (%llu not finite)\n", + (long long) n, xm, xo, wy[0], wyo[0], wy[1], wyo[1]); + } if (pt.on) { pt.fold(); double total = 0.0; From f288cbfea95768ed00ef18b389d898cc84a396d6 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 07:09:41 +0200 Subject: [PATCH 05/17] F16_RANGE counters (#1149): HIP only, and the gfx906 compat layer maps cudaMemcpyFromSymbol Fix-up to the ported #1149 commits. The range counters and the saturating to_f16 are compiled for HIP only, so the CUDA kernels (hf_sat in the SwiGLU product, the embedding image) stay exactly as they were, with no flag read; set_f16_range / f16_range_read are no-ops there. strata_hip.h (the STRATA_HIP_GFX906 compat layer, which goes first on that backend's include path) gets the cudaMemcpyFromSymbol mapping the HIP shim already has, so the counters also compile for gfx906. --- include/strata/platform/hip_compat/strata_hip.h | 1 + src/prefill/kernels.cu | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/include/strata/platform/hip_compat/strata_hip.h b/include/strata/platform/hip_compat/strata_hip.h index 6d997fe0..8428b358 100644 --- a/include/strata/platform/hip_compat/strata_hip.h +++ b/include/strata/platform/hip_compat/strata_hip.h @@ -164,6 +164,7 @@ inline hipError_t cudaFuncSetAttribute(Kernel kernel, hipFuncAttribute attribute return hipFuncSetAttribute(reinterpret_cast(kernel), attribute, value); } #define cudaMemcpyToSymbol(sym, src, ...) hipMemcpyToSymbol(HIP_SYMBOL(sym), src, __VA_ARGS__) +#define cudaMemcpyFromSymbol(dst, sym, ...) hipMemcpyFromSymbol(dst, HIP_SYMBOL(sym), __VA_ARGS__) // CUDA 12 has a 3-argument cudaGraphInstantiate(exec, graph, flags) and the older 5-argument one; HIP spells // the first hipGraphInstantiateWithFlags. Both are used in the tree. diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index a0b622dc..4091e519 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -49,6 +49,7 @@ __device__ __forceinline__ uint16_t hf(float f) { return __half_as_ushort(__floa // images converted (hf_sat is their one funnel) and how many were beyond 65504 or NaN; W and Y are counted in gemm.cu. // Off, the cost is one flag read per value. The max is kept as float bits (positive floats order as unsigned ints), // and a thread takes the atomic only when it beats the value it read, so the atomics stop once the max has settled. +#if defined(__HIPCC__) // HIP only: the CUDA kernels stay exactly as they were (no flag read in hf_sat) __device__ int g_f16_range_on = 0; __device__ unsigned g_f16_range_max = 0; __device__ unsigned long long g_f16_range_over = 0; @@ -58,8 +59,11 @@ __device__ __forceinline__ void f16_range_note(float f) { if (bits > g_f16_range_max) atomicMax(&g_f16_range_max, bits); if (a > 65504.0f || isnan(f)) atomicAdd(&g_f16_range_over, 1ull); } +#endif __device__ __forceinline__ uint16_t hf_sat(float f) { +#if defined(__HIPCC__) if (g_f16_range_on) f16_range_note(f); +#endif return hf(isnan(f) ? f : fminf(fmaxf(f, -65504.0f), 65504.0f)); } // The prompt path's 16-bit activation image for the BF16-weight GEMMs: BF16, or FP16 where the GEMM library is fast @@ -1734,7 +1738,11 @@ __global__ void kv_append_kernel(const float* __restrict__ K, const float* __res } __global__ void to_f16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, int64_t n) { for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) +#if defined(__HIPCC__) y[i] = hf_sat(x[i]); // saturated and counted like every other FP16 image (the hc / embedding image on gfx103x) +#else + y[i] = hf(x[i]); // CUDA: as it was +#endif } __global__ void round_f16_kernel(const float* __restrict__ x, float* __restrict__ y, int64_t n) { for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) @@ -1844,13 +1852,21 @@ void set_act_f16(bool on) { #endif } void set_f16_range(bool on) { +#if defined(__HIPCC__) const int v = on ? 1 : 0; if (cudaMemcpyToSymbol(g_f16_range_on, &v, sizeof v) != cudaSuccess) { std::fprintf(stderr, "prefill: setting the FP16 range check failed: %s\n", cudaGetErrorString(cudaGetLastError())); std::exit(1); } +#else + (void) on; +#endif } bool f16_range_read(float& max_abs, unsigned long long& over, bool reset) { +#if !defined(__HIPCC__) + (void) max_abs; (void) over; (void) reset; + return false; +#else unsigned bits = 0; unsigned long long o = 0; if (cudaMemcpyFromSymbol(&bits, g_f16_range_max, sizeof bits) != cudaSuccess || cudaMemcpyFromSymbol(&o, g_f16_range_over, sizeof o) != cudaSuccess) { cudaGetLastError(); return false; } @@ -1860,6 +1876,7 @@ bool f16_range_read(float& max_abs, unsigned long long& over, bool reset) { cudaMemcpyToSymbol(g_f16_range_max, &z, sizeof z); cudaMemcpyToSymbol(g_f16_range_over, &zz, sizeof zz); } return true; +#endif } void to_f16(const float* x, uint16_t* y, int64_t n, void* stream) { if (n <= 0) return; From 8f949956b2f90a595d7c72f1a735b14ad9fe04fa Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 07:10:39 +0200 Subject: [PATCH 06/17] HIP RDNA2 (gfx103x): run the prompt path's 16-bit GEMMs as FP32 SGEMMs The rocBLAS the engine ships has tuned gfx1030 kernels for FP16->FP16, int8 and FP32->FP32 only; every FP16/BF16-input, FP32-output GEMM (rocBLAS HS/BS) runs a fallback kernel at ~5 TFLOPS. Widening the inputs to FP32 is exact and SGEMM accumulates in FP32 like the native call. Nothing passes through FP16, so unlike STRATA_HIP_PROMPT_F16=1 (#835) the route cannot overflow: an FP16 GEMM output above 65504 becomes inf and can spread as NaN, while here it stays a finite FP32 value. It is slower than the FP16 route, and not bit-identical to the native call (at most 4.3e-6 of the largest output apart on random inputs). RX 6800, Coder IQ1_M, fresh 12K-token prompts (4 each, A/B in one binary via STRATA_RDNA2_SGEMM=0): prompt 312 -> 452 tok/s, GPU timeline 37.2 -> 25.5 s (gdn 9.4 -> 2.8 s, qsa proj 3.6 -> 1.4 s, hc read 3.85 -> 2.84 s). Decode unchanged. A 9-task code-repair benchmark: 9/9 first try on both, model time 458 -> 374 s. Default on for gfx103x only; N < 64 keeps the native call; if the FP32 buffers cannot be allocated the native call runs. Rebased onto 296b59d2: the conflict in Gemm::f16 and gemm.hpp (the CUDA FP16 algorithm fallback and the sm_60 STRATA_DENSE_F32 block that main gained) is resolved by keeping both; the RDNA2 call sits before the CUDA/HIP GemmEx call. Co-authored-by: vallicgrr <2245906+vallicgrr@users.noreply.github.com> --- include/strata/prefill/gemm.hpp | 6 ++- src/prefill/gemm.cu | 92 +++++++++++++++++++++++++++++++++ 2 files changed, 97 insertions(+), 1 deletion(-) diff --git a/include/strata/prefill/gemm.hpp b/include/strata/prefill/gemm.hpp index e8b4e9a9..6a87ef93 100644 --- a/include/strata/prefill/gemm.hpp +++ b/include/strata/prefill/gemm.hpp @@ -82,7 +82,11 @@ private: static constexpr int kF16AlgoSlots = 32; int64_t f16_algo_shape_[kF16AlgoSlots] = {}; int f16_algo_n_ = 0; - // below sm_80: FP16 (Pascal: fp32) copies of a BF16 product's weight and activation slice (Gemm::bf16) + // RDNA2 (gfx103x, HIP): the product as an SGEMM on FP32 copies (tc_w_, tc_x_); false: the native call runs (gemm.cu) + bool rdna2_sgemm(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, + float beta, bool bf16); + // below sm_80: FP16 (Pascal: fp32) copies of a BF16 product's weight and activation slice (Gemm::bf16); + // RDNA2: FP32 copies of the weight and an activation slice (Gemm::rdna2_sgemm) uint16_t* tc_w_ = nullptr; int64_t tc_w_elems_ = 0; uint16_t* tc_x_ = nullptr; diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu index 2a0bfc9a..f07e84fd 100644 --- a/src/prefill/gemm.cu +++ b/src/prefill/gemm.cu @@ -666,6 +666,92 @@ bool Gemm::bf16_hcd_exact(const uint16_t* X, int64_t ldx, const uint16_t* W, flo #endif } +#if defined(__HIPCC__) +// ---- RDNA2 (gfx103x): the prompt path's GEMMs as FP32 SGEMMs ------------------------------------------------------ +// The GEMMs here take 16-bit inputs (FP16 or BF16) and write FP32 (rocBLAS's "HS" / "BS" types). The rocBLAS the engine +// ships has tuned gfx1030 kernels for FP16 -> FP16 ("HH"), int8 and FP32 -> FP32 ("SS") only: every 16-bit-input, +// FP32-output GEMM runs a "fallback" kernel at ~5 TFLOPS. Measured on an RX 6800 (ROCm 10.2.0a20260930) with the +// engine's exact calls (opA = T, opB = N, fp32 compute): at the Coder's prompt shapes the FP16 GEMMs of one fresh +// 12K-token prompt take 14.1 s, the same GEMMs as SGEMM on widened copies 4.7 s including the widening (e.g. +// N 10240 x T 8192 x K 2560: 86.7 -> 27.7 ms); the BF16 hyper-connection GEMMs 10.9 -> 7.5 ms (N 320, K 10240). +// Widening FP16 / BF16 to FP32 is exact and SGEMM accumulates in FP32 like the native call, so the products are the +// same up to summation order. The weight is widened once per call, the activations in slices of up to 128 MiB of +// FP32 (an 8,192-token chunk at K = 2560 is one slice). Small N (< 64: routers, gates) keeps the native call: +// there the widening costs more than the GEMM gains. If the FP32 buffers cannot be allocated, the native call runs. +// Default: on for gfx103x, off for every other AMD architecture. STRATA_RDNA2_SGEMM=0 / =1 turns it off / on for +// any AMD card (the A/B arms). +namespace { +__global__ void rdna2_bf16_to_f32_kernel(const uint16_t* __restrict__ in, float* __restrict__ out, int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) out[i] = __uint_as_float((uint32_t) in[i] << 16); +} +__global__ void rdna2_f16_to_f32_kernel(const __half* __restrict__ in, float* __restrict__ out, int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) out[i] = __half2float(in[i]); +} +void rdna2_widen(const uint16_t* in, float* out, int64_t n, bool bf16, cudaStream_t st) { + if (n <= 0) return; + const unsigned blocks = (unsigned) ((n + 255) / 256); + if (bf16) rdna2_bf16_to_f32_kernel<<>>(in, out, n); + else rdna2_f16_to_f32_kernel<<>>(reinterpret_cast(in), out, n); +} +// whether this GEMM runs as an SGEMM (see above) +bool rdna2_sgemm_on(int64_t N) { + static const int forced = [] { + const char* v = std::getenv("STRATA_RDNA2_SGEMM"); + return v != nullptr && v[0] != '\0' ? std::atoi(v) : -1; + }(); + if (forced == 0 || N < 64) return false; + if (forced > 0) return true; + static std::atomic arch[64] = {}; // per device: 0 not known, 1 gfx103x, 2 another architecture + int dev = 0; + if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= 64) { (void) hipGetLastError(); return false; } + int v = arch[dev].load(std::memory_order_relaxed); + if (v == 0) { + hipDeviceProp_t prop{}; + if (hipGetDeviceProperties(&prop, dev) != hipSuccess) { (void) hipGetLastError(); return false; } + v = std::strncmp(prop.gcnArchName, "gfx103", 6) == 0 ? 1 : 2; + arch[dev].store(v, std::memory_order_relaxed); + } + return v == 1; +} +// `have`, `want`: FP32 elements (the buffers are the instance's 2-byte tc_ buffers, sized in 2-byte elements) +bool rdna2_grow(uint16_t*& p, int64_t& have_u16, int64_t want_f32) { + const int64_t want = 2 * want_f32; + if (have_u16 >= want) return true; + if (p) cudaFree(p); + p = nullptr; + have_u16 = 0; + if (cudaMalloc((void**) &p, (size_t) want * 2) != cudaSuccess) { (void) cudaGetLastError(); p = nullptr; return false; } + have_u16 = want; + return true; +} +constexpr int64_t kRdna2SliceF32 = 32ll << 20; // 128 MiB of FP32 activations per slice +} // namespace + +// Y^T[N, T] (+)= W[N, K] . X^T[K, T] as SGEMMs on FP32 copies; false: not this card / shape, or no buffers (the caller +// runs its native GEMM, nothing was written) +bool Gemm::rdna2_sgemm(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, + float beta, bool bf16) { + if (K <= 0 || !rdna2_sgemm_on(N)) return false; + const int64_t rows = std::max(1, std::min(T, kRdna2SliceF32 / K)); + if (!rdna2_grow(tc_w_, tc_w_elems_, N * K) || !rdna2_grow(tc_x_, tc_x_elems_, rows * K)) return false; + float* const wf = reinterpret_cast(tc_w_); + float* const xf = reinterpret_cast(tc_x_); + const float alpha = 1.0f; + rdna2_widen(W, wf, N * K, bf16, (cudaStream_t) stream_); + for (int64_t t0 = 0; t0 < T; t0 += rows) { + const int64_t n = std::min(rows, T - t0); + rdna2_widen(X + t0 * K, xf, n * K, bf16, (cudaStream_t) stream_); + // every slice is a disjoint block of Y, so each gets the caller's beta + ck(hipblasSgemm((hipblasHandle_t) handle_, HIPBLAS_OP_T, HIPBLAS_OP_N, (int) N, (int) n, (int) K, &alpha, wf, + (int) K, xf, (int) K, &beta, Y + t0 * ldy, (int) ldy), + "hipblasSgemm (RDNA2)"); + } + return true; +} +#endif + void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, int64_t ldx) { if (T <= 0 || N <= 0) return; @@ -703,6 +789,9 @@ void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64 return; } #endif +#if defined(__HIPCC__) + if (rdna2_sgemm(X, W, Y, T, N, K, ldy, beta, true)) return; +#endif #if !defined(__HIPCC__) #if defined(STRATA_EXPERIMENTAL_SM60) constexpr bool kPascalPath = true; @@ -825,6 +914,9 @@ void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_ cudaGetLastError(); // no room for the copies: the FP16 call below } #endif +#if defined(__HIPCC__) + if (rdna2_sgemm(X, W, Y, T, N, K, ldy, beta, false)) return; +#endif #if !defined(__HIPCC__) const auto f16_gemm = [&](cublasGemmAlgo_t algo) { return cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &alpha, From 62a98cd3534cedeb1df01e1d3c358998da5f3a14 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 07:10:58 +0200 Subject: [PATCH 07/17] docs: RDNA2 prompt GEMMs as SGEMMs (measured on an RX 6800), and a Windows gfx1030 report Rebased onto 296b59d2: the docs/AMD_HIP.md conflict (the gfx1031/gfx1150/gfx1152 bullets main gained) is resolved by keeping main's text. Co-authored-by: vallicgrr <2245906+vallicgrr@users.noreply.github.com> --- docs/AMD_HIP.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 19b5c0fd..fcbd4f01 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -451,6 +451,36 @@ run it; the report below is from a community machine: an RX 6900 XT 16 GB (gfx10 matrix cores; `hip_prefill_hipblaslt_gemm`, no hipBLASLt table) and 3 that fail for reasons outside the engine (`ple_parity` needs a Q2_0 PLE file that is not on that machine, `expert_multi_test` refuses the CPU without AVX-512, `platform_memory_test` cannot `mlock` at the shell's default `ulimit -l`). +- **Prompt GEMMs as SGEMMs (engine 0.1.39 + `Gemm::rdna2_sgemm`):** the rocBLAS in setup's ROCm (10.2.0a20260930) + has tuned gfx1030 kernels for FP16 -> FP16, int8 and FP32 -> FP32 only. The prompt path's dense GEMMs take FP16 or + BF16 inputs and write FP32 (rocBLAS's HS / BS types), which run its fallback kernels at about 5 TFLOPS. On gfx103x + the engine widens both inputs to FP32 (exact) and runs SGEMM, which accumulates in FP32 like the native call + (`src/prefill/gemm.cu`; N < 64 keeps the native call; `STRATA_RDNA2_SGEMM=0` / `=1` turns it off / on for any AMD + card). Measured on an RX 6800 16 GB over OCuLink (PCIe 4.0 x4, 7.1 GB/s), Ryzen 7 8845HS, 28.8 GB RAM, Windows 11, + Coder IQ1_M with setup's arguments (64K context, MTP), fresh 12K-token prompts, 4 per arm, A/B in one binary: + + | | native GEMMs | SGEMM route | + |---|---|---| + | prompt | 312 tok/s | 452 tok/s | + | prompt GPU timeline (`STRATA_PREFILL_TIMING`) | 37.2 s | 25.5 s | + | of which gdn / qsa proj / hc read | 9.4 / 3.6 / 3.85 s | 2.8 / 1.4 / 2.84 s | + | decode | 29-34 tok/s | 29-35 tok/s | + + The exact calls on the card (opA = T, opB = N, FP32 out): N 10240 x T 8192 x K 2560 86.7 -> 27.7 ms including + the widening; N 320 x T 8192 x K 10240 (BF16) 10.9 -> 7.5 ms. Against a float64 reference on random inputs in + [-1, 1], the SGEMM route is as close as or closer than the native call on all 10 FP16 / BF16 shapes checked; the + two differ by at most 4.3e-6 of the largest output. A 9-task code-repair benchmark (the model patches seeded bugs + in a browser game until 38 browser checks pass) solved 9/9 on the first try with both, model time 458 -> 374 s. + The SGEMM route is the default on gfx103x when `STRATA_HIP_PROMPT_F16` is unset; with `STRATA_HIP_PROMPT_F16=1` + the FP16 route above runs first and the SGEMM route takes the products it leaves (`beta != 0`). Same RX 6800, one + session, fresh 12K-token prompts: native 310, SGEMM 439, FP16 (#835) 494 tok/s; `STRATA_F16_RANGE=1` on the Coder + IQ1_M peaked at 105.3 (activations) and 424.8 (FP16 outputs) with nothing beyond 65504, and the repair benchmark + solved 9/9 on the first try with both (model time 374 s SGEMM, 307 s FP16). The SGEMM route is the slower of the + two; no value passes through FP16, so it has no 65504 limit to stay under. It is not bit-identical to the native + call (at most 4.3e-6 of the largest output apart), which can flip a near-tied greedy token like any such change. +- **Windows** (the report above): setup's ready-made Windows engine 0.1.39 runs the RX 6800 beside a 780M iGPU + (HIP numbers the RX 6800 1; setup points the engine at it), and `tools/hip/build_windows.bat` with + `STRATA_HIP_ARCHS=gfx1030` builds a working engine from the `gfx103X-all` 10.2.0a20260930 wheels. - **gfx1031** (RX 6700 XT, #524): setup knows it (the `gfx103X-all` wheels, unvalidated); its reporter runs it daily on one card. More reports: an RX 6700 XT 12 GB run as gfx1030 on ROCm 7.2.4 (#1027: IQ2_XS, decode 30-32 tok/s, prompt about 300 tok/s, 6 of 6 needles), and an RX 6800M 12 GB on Windows with a self-built engine (#915, #1078: Q2_0, decode 9-27 tok/s, prompt 50-114 tok/s; the From 6dffb74a1fb9f2a2b880cbb41da2d42227e67059 Mon Sep 17 00:00:00 2001 From: vallicgrr <2245906+vallicgrr@users.noreply.github.com> Date: Tue, 6 Oct 2026 09:05:03 +0900 Subject: [PATCH 08/17] tests: hip_prefill_gemm crosses an RDNA2 SGEMM slice boundary (T 3300, K 10240; FP16 beta 1 with a padded ldy, and BF16) --- tests/hip/prefill_gemm.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/hip/prefill_gemm.cpp b/tests/hip/prefill_gemm.cpp index dca156e7..6c2cad29 100644 --- a/tests/hip/prefill_gemm.cpp +++ b/tests/hip/prefill_gemm.cpp @@ -103,6 +103,11 @@ int main() { ok=run(gemm,stream,true,17,48,2560,64,1) && ok; ok=run(gemm,stream,false,32,640,2560,648,0) && ok; ok=run(gemm,stream,false,64,2560,640,2560,1) && ok; + // RDNA2 (gfx103x) runs N >= 64 as an SGEMM on FP32 copies, the activations in slices of 32M floats + // (Gemm::rdna2_sgemm): at K = 10240 a slice is 3,276 rows, so these cross a slice boundary (padded ldy, beta 1). + // Other cards run them on the native path. + ok=run(gemm,stream,false,3300,64,10240,72,1) && ok; + ok=run(gemm,stream,true,3300,64,10240,64,0) && ok; } { // The FP16-io mode. The scratch holds 64 rows at K = 2560, so bf16()'s W conversion slices N = 96 in two From 6ccdb14167295a589f5309547137ce1e033eead3 Mon Sep 17 00:00:00 2001 From: vallicgrr <2245906+vallicgrr@users.noreply.github.com> Date: Tue, 6 Oct 2026 19:21:24 +0900 Subject: [PATCH 09/17] prefill gemm: a padded BF16 X (ldx, STRATA_PF_PAD) keeps the native call on the RDNA2 SGEMM route --- src/prefill/gemm.cu | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu index f07e84fd..183950f6 100644 --- a/src/prefill/gemm.cu +++ b/src/prefill/gemm.cu @@ -790,7 +790,8 @@ void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64 } #endif #if defined(__HIPCC__) - if (rdna2_sgemm(X, W, Y, T, N, K, ldy, beta, true)) return; + // a padded X (STRATA_PF_PAD, ldx > K) keeps the native call: the widening copies contiguous rows + if (ldx == 0 && rdna2_sgemm(X, W, Y, T, N, K, ldy, beta, true)) return; #endif #if !defined(__HIPCC__) #if defined(STRATA_EXPERIMENTAL_SM60) From 0c808eed00facbc3556a0915cb22c46689060ee0 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 07:11:51 +0200 Subject: [PATCH 10/17] RDNA2 SGEMM prompt GEMMs (#1123) are opt-in: STRATA_RDNA2_SGEMM=1 (gfx103x) / =all (any AMD card) Fix-up to the ported #1123 commits. The route is not bit-identical to the native call (the author measured at most 4.3e-6 of the largest output apart), so unset keeps the native path on every card, gfx103x included; =1 enables it on gfx103x devices only (a mixed layer split keeps the native call on the other cards), =all on every AMD device for A/B arms and tests. The buffers are no longer freed under an in-flight GEMM: the stream is synchronised before the FP32 copies grow, as the sm_60 FP32 route does. docs/AMD_HIP.md says so. --- docs/AMD_HIP.md | 10 +++++----- src/prefill/gemm.cu | 17 +++++++++++------ 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index fcbd4f01..b817e495 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -453,10 +453,10 @@ run it; the report below is from a community machine: an RX 6900 XT 16 GB (gfx10 `platform_memory_test` cannot `mlock` at the shell's default `ulimit -l`). - **Prompt GEMMs as SGEMMs (engine 0.1.39 + `Gemm::rdna2_sgemm`):** the rocBLAS in setup's ROCm (10.2.0a20260930) has tuned gfx1030 kernels for FP16 -> FP16, int8 and FP32 -> FP32 only. The prompt path's dense GEMMs take FP16 or - BF16 inputs and write FP32 (rocBLAS's HS / BS types), which run its fallback kernels at about 5 TFLOPS. On gfx103x - the engine widens both inputs to FP32 (exact) and runs SGEMM, which accumulates in FP32 like the native call - (`src/prefill/gemm.cu`; N < 64 keeps the native call; `STRATA_RDNA2_SGEMM=0` / `=1` turns it off / on for any AMD - card). Measured on an RX 6800 16 GB over OCuLink (PCIe 4.0 x4, 7.1 GB/s), Ryzen 7 8845HS, 28.8 GB RAM, Windows 11, + BF16 inputs and write FP32 (rocBLAS's HS / BS types), which run its fallback kernels at about 5 TFLOPS. With + `STRATA_RDNA2_SGEMM=1` (opt-in; `=all` forces it on any AMD card) the engine widens both inputs to FP32 (exact) and runs SGEMM, + which accumulates in FP32 like the native call (`src/prefill/gemm.cu`; N < 64 keeps the native call). The author ran it + as the gfx103x default; here it is a switch because it is not bit-identical to the native call (below). Measured on an RX 6800 16 GB over OCuLink (PCIe 4.0 x4, 7.1 GB/s), Ryzen 7 8845HS, 28.8 GB RAM, Windows 11, Coder IQ1_M with setup's arguments (64K context, MTP), fresh 12K-token prompts, 4 per arm, A/B in one binary: | | native GEMMs | SGEMM route | @@ -471,7 +471,7 @@ run it; the report below is from a community machine: an RX 6900 XT 16 GB (gfx10 [-1, 1], the SGEMM route is as close as or closer than the native call on all 10 FP16 / BF16 shapes checked; the two differ by at most 4.3e-6 of the largest output. A 9-task code-repair benchmark (the model patches seeded bugs in a browser game until 38 browser checks pass) solved 9/9 on the first try with both, model time 458 -> 374 s. - The SGEMM route is the default on gfx103x when `STRATA_HIP_PROMPT_F16` is unset; with `STRATA_HIP_PROMPT_F16=1` + With the switch on and `STRATA_HIP_PROMPT_F16` unset the SGEMM route runs; with `STRATA_HIP_PROMPT_F16=1` the FP16 route above runs first and the SGEMM route takes the products it leaves (`beta != 0`). Same RX 6800, one session, fresh 12K-token prompts: native 310, SGEMM 439, FP16 (#835) 494 tok/s; `STRATA_F16_RANGE=1` on the Coder IQ1_M peaked at 105.3 (activations) and 424.8 (FP16 outputs) with nothing beyond 65504, and the repair benchmark diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu index 183950f6..315c3017 100644 --- a/src/prefill/gemm.cu +++ b/src/prefill/gemm.cu @@ -678,8 +678,9 @@ bool Gemm::bf16_hcd_exact(const uint16_t* X, int64_t ldx, const uint16_t* W, flo // same up to summation order. The weight is widened once per call, the activations in slices of up to 128 MiB of // FP32 (an 8,192-token chunk at K = 2560 is one slice). Small N (< 64: routers, gates) keeps the native call: // there the widening costs more than the GEMM gains. If the FP32 buffers cannot be allocated, the native call runs. -// Default: on for gfx103x, off for every other AMD architecture. STRATA_RDNA2_SGEMM=0 / =1 turns it off / on for -// any AMD card (the A/B arms). +// OPT-IN here: STRATA_RDNA2_SGEMM=1 turns it on for gfx103x devices (other cards keep the native call, also in a +// mixed layer split); =all turns it on for every AMD card (A/B arms, tests); unset or 0 is the native path. The +// author ran it as the gfx103x default (RX 6800 343 -> 534 tok/s); it is not bit-identical to the native call. namespace { __global__ void rdna2_bf16_to_f32_kernel(const uint16_t* __restrict__ in, float* __restrict__ out, int64_t n) { const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; @@ -697,12 +698,14 @@ void rdna2_widen(const uint16_t* in, float* out, int64_t n, bool bf16, cudaStrea } // whether this GEMM runs as an SGEMM (see above) bool rdna2_sgemm_on(int64_t N) { - static const int forced = [] { + static const int mode = [] { // 0 off (unset), 1 gfx103x devices, 2 every AMD device const char* v = std::getenv("STRATA_RDNA2_SGEMM"); - return v != nullptr && v[0] != '\0' ? std::atoi(v) : -1; + if (v == nullptr || v[0] == '\0') return 0; + if (std::strcmp(v, "all") == 0) return 2; + return std::atoi(v) > 0 ? 1 : 0; }(); - if (forced == 0 || N < 64) return false; - if (forced > 0) return true; + if (mode == 0 || N < 64) return false; + if (mode == 2) return true; static std::atomic arch[64] = {}; // per device: 0 not known, 1 gfx103x, 2 another architecture int dev = 0; if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= 64) { (void) hipGetLastError(); return false; } @@ -735,6 +738,8 @@ bool Gemm::rdna2_sgemm(const uint16_t* X, const uint16_t* W, float* Y, int64_t T float beta, bool bf16) { if (K <= 0 || !rdna2_sgemm_on(N)) return false; const int64_t rows = std::max(1, std::min(T, kRdna2SliceF32 / K)); + // growing frees a buffer an earlier GEMM on this stream may still read (as the sm_60 FP32 route does) + if (tc_w_elems_ < 2 * N * K || tc_x_elems_ < 2 * rows * K) (void) hipStreamSynchronize((hipStream_t) stream_); if (!rdna2_grow(tc_w_, tc_w_elems_, N * K) || !rdna2_grow(tc_x_, tc_x_elems_, rows * K)) return false; float* const wf = reinterpret_cast(tc_w_); float* const xf = reinterpret_cast(tc_x_); From 57c95d5faf55032946de5bcb691294e9a791dc24 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 07:12:35 +0200 Subject: [PATCH 11/17] hip: a rocBLAS solution table for the FP16 prompt GEMMs on gfx103x (the GDN projection 7x below 1,152 tokens; short prompts -10 to -14%) rocBLAS picks the kernel for each FP16 product from its own table by shape, and on gfx1030 that pick is far from the best kernel the same library holds for some shapes: N = 10240 K = 2560 (the GDN input projection) below T = 1152 runs at 5.2 TFLOPS where the best of rocBLAS's 237 solutions for n = 799 is 6x faster (not an alignment effect: n = 800 is as slow as 799). tools/hip/tune_rocblas enumerates the library's solutions per shape and token bucket, checks each against the default kernel's output and that it also runs at smaller odd token counts, and writes the winners (and `default` rows bounding their reach) as tools/hip/-rocblas-.txt; Gemm::f16_inplace runs the table's solution for a shape (STRATA_ROCBLAS_TUNING: a file, or the directory from which the engine takes the file of its own rocBLAS build; the version string, tweak hash included, is checked). One tiny default product at startup opens rocBLAS's kernel library (a solution-index call before that fails although the index is valid); a refused solution falls back to the default kernel for that call, after three refusals for good. setup points the engine at tools/hip when a table for the card's architecture exists. Shipped: the gfx1030 table for ROCm 10.0.0's rocBLAS 5.6.0.8d1ae90e (112 rows, 76 with a solution). Measured (RX 6900 XT, 6f32ec0 + #835 + this, temperature 0, the same answers with and without): a 799-token prompt's GPU time 3,329 -> 2,985 ms (-10.3%), 495 tokens 2,477 -> 2,139 (-13.6%), 8,874 tokens 11,978 -> 11,459 (-4.3%); a PCIe-bound 1,108-token prompt unchanged (its saving reappeared as `wait copy`). ctest 66 of 70 (the 4 failures are outside this change); hip_prefill_rocblas_gemm, the new smoke test, passes with 0 fallbacks. Builds on #835. bench/results/2026-10-05-rdna2-rocblas-table has the per-run lines and the tuner's summary. (cherry picked from commit e35e103604eab6569c68ef2f82331710c9b5bdae) Rebased onto 296b59d2: conflicts in setup.py (SETUP_ENV gained STRATA_ROCBLAS_TUNING beside the 0.1.44 entries) and docs/AMD_HIP.md (kept both sections) resolved. Co-authored-by: xjc10 <69450118+xjc10@users.noreply.github.com> --- CMakeLists.txt | 20 ++ .../2026-10-05-rdna2-rocblas-table/README.md | 80 +++++ .../timing-off.txt | 9 + .../timing-on.txt | 9 + .../tune-summary.txt | 226 ++++++++++++++ cmake/hip_backend.cmake | 9 + docs/AMD_HIP.md | 51 +++- include/strata/prefill/gemm.hpp | 1 + setup.py | 10 +- src/prefill/gemm.cu | 164 +++++++++- src/prefill/rocblas_tuning.hpp | 129 ++++++++ tests/hip/prefill_rocblas_gemm.cpp | 206 +++++++++++++ tools/hip/gfx1030-rocblas-5.6.0.8d1ae90e.txt | 116 ++++++++ tools/hip/tune_rocblas.cpp | 281 ++++++++++++++++++ 14 files changed, 1305 insertions(+), 6 deletions(-) create mode 100644 bench/results/2026-10-05-rdna2-rocblas-table/README.md create mode 100644 bench/results/2026-10-05-rdna2-rocblas-table/timing-off.txt create mode 100644 bench/results/2026-10-05-rdna2-rocblas-table/timing-on.txt create mode 100644 bench/results/2026-10-05-rdna2-rocblas-table/tune-summary.txt create mode 100644 src/prefill/rocblas_tuning.hpp create mode 100644 tests/hip/prefill_rocblas_gemm.cpp create mode 100644 tools/hip/gfx1030-rocblas-5.6.0.8d1ae90e.txt create mode 100644 tools/hip/tune_rocblas.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 6a7baf78..f0d43616 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -618,6 +618,14 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_executable(tune_hipblaslt tools/hip/tune_hipblaslt.cpp) target_link_libraries(tune_hipblaslt PRIVATE hip::host roc::hipblas roc::hipblaslt) endif() + if(STRATA_ENABLE_HIP AND STRATA_ROCBLAS_AVAILABLE) + # the prompt path's rocBLAS solution table (STRATA_ROCBLAS_TUNING; tools/hip/tune_rocblas makes one) + target_compile_definitions(strata_prefill PRIVATE STRATA_ROCBLAS_AVAILABLE=1) + target_link_libraries(strata_prefill PRIVATE roc::rocblas) + + add_executable(tune_rocblas tools/hip/tune_rocblas.cpp) + target_link_libraries(tune_rocblas PRIVATE hip::host roc::rocblas) + endif() add_executable(strata src/program/generate.cpp) target_include_directories(strata PRIVATE ${_strata_gpu_include_directories}) @@ -733,6 +741,15 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) set_tests_properties(hip_prefill_hipblaslt_gemm PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) list(APPEND _strata_hip_tests hip_prefill_hipblaslt_gemm) endif() + if(STRATA_ROCBLAS_AVAILABLE) + # the rocBLAS solution table of the FP16-out prompt GEMMs (gfx103x): opt-in, skips without STRATA_ROCBLAS_TUNING + add_executable(hip_prefill_rocblas_gemm tests/hip/prefill_rocblas_gemm.cpp) + target_include_directories(hip_prefill_rocblas_gemm PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src/prefill") + target_link_libraries(hip_prefill_rocblas_gemm PRIVATE strata_prefill strata_hip_runtime roc::rocblas roc::hipblas) + add_test(NAME hip_prefill_rocblas_gemm COMMAND hip_prefill_rocblas_gemm) + set_tests_properties(hip_prefill_rocblas_gemm PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + list(APPEND _strata_hip_tests hip_prefill_rocblas_gemm) + endif() if(_strata_hip_tests) set_tests_properties(${_strata_hip_tests} PROPERTIES TIMEOUT 60) endif() @@ -742,6 +759,9 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) if(TARGET hip_prefill_hipblaslt_gemm) set_tests_properties(hip_prefill_hipblaslt_gemm PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endif() + if(TARGET hip_prefill_rocblas_gemm) + set_tests_properties(hip_prefill_rocblas_gemm PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endif() endif() add_executable(dequant_s2_parity src/kernels/dequant_s2_parity.cpp) diff --git a/bench/results/2026-10-05-rdna2-rocblas-table/README.md b/bench/results/2026-10-05-rdna2-rocblas-table/README.md new file mode 100644 index 00000000..fb9e5e36 --- /dev/null +++ b/bench/results/2026-10-05-rdna2-rocblas-table/README.md @@ -0,0 +1,80 @@ +# RX 6900 XT (gfx1030): rocBLAS's kernel choice for the FP16 prompt GEMMs, and a solution table (2026-10-05) + +On gfx103x the prompt path's dense GEMMs run through rocBLAS as FP16 in -> FP16 out (#835). rocBLAS picks the kernel +for each product from its own table by shape, and for some shapes that pick is far from the best kernel the same library +holds. The clearest case is the GDN input projection, N = 10240, K = 2560: below T = 1152 tokens rocBLAS's choice runs at +5.2-5.3 TFLOPS (n = 682 ... 1120, measured with `rocblas_gemm_ex` on this card, 8.1 ms at n = 799), at T = 1152 it jumps +to 38 TFLOPS (1.6 ms), and the best of the 237 solutions `rocblas_gemm_ex_get_solutions` lists for n = 799 runs it in +1.36 ms. It is not an alignment effect (n = 800 is as slow as 799). In the engine's own phase timing this is why the +"gdn" phase of a 799-token prompt (445 ms) was nearly as long as that of an 8,874-token one (1,345 ms). + +`tools/hip/tune_rocblas.cpp` enumerates rocBLAS's solutions per shape and token bucket, times them, checks the fastest +against the default kernel's output and writes the winners as a table; `Gemm::f16_inplace` runs the table's solution for +a shape in place of rocBLAS's choice (`STRATA_ROCBLAS_TUNING`; docs/AMD_HIP.md, "rocBLAS table"). The table shipped, +`tools/hip/gfx1030-rocblas-5.6.0.8d1ae90e.txt`, is calibrated against rocBLAS 5.6.0.8d1ae90e (ROCm 10.0.0, +`/opt/rocm/lib`); its indices are valid for that build only, and the engine refuses any other. + +## Rig + +- AMD Radeon RX 6900 XT 16 GB (gfx1030), PCIe 4.0 x8, one card of two (`HIP_VISIBLE_DEVICES` as setup sets it); AMD + Ryzen 5 5600X (6 cores, AVX2), 128 GB DDR4-3200; Ubuntu 26.04, kernel 7.0.0-38-generic, ROCm 10.0.0 (HIP 7.15.26333). + Note that a HIP build on this Ubuntu links Ubuntu's own `librocblas5` (a 5.1 build, package 7.1.0-1ubuntu4) unless + `lib_dirs` (`/opt/rocm/lib`) puts ROCm's first: the engine runs below had `lib_dirs` set, as setup's configuration does. + rocBLAS 5.1's default kernel for the shape above is as slow (8.1 ms at n = 799, measured too); its solution indices + differ, so it would need its own table. +- Model: Qwen3.8-Flash-Next GSQ-RCO IQ3_S (2 shards, `--native`), MTP draft, `--kv int8 --kv-resident 32768 + --max-context 131072 --expert-cache auto --prefill auto --spec 4 --spec-min-p 0.5 --adapt-every 100000` (the last the + #884 workaround; it does not touch the prompt path). +- Engine: `6f32ec0` (0.1.39) + #835 + this change, `-DSTRATA_ENABLE_HIP=ON -DCMAKE_HIP_ARCHITECTURES=gfx1030 + -DSTRATA_PREFILL_MMQ=ON`. #849 is not in this build, so the `qsa attn` phase is the slow pre-#849 kernel here (the same + in both arms). + +## Table + +`tune_rocblas --tuning-out ...` with the defaults: the engine's 14 FP16 dense shapes (ldy = N) at T = 256, 512, 768, +1024, 1536, 2048, 4096, 8192; 112 rows, 76 with a solution that beat the default by at least 5% and also ran at T-1, +T-37, T-63 and T/2+1 (a kernel can refuse a token count it was not measured at), `default` for the other 36. +[tune-summary.txt](tune-summary.txt) is the tool's per-case output (default ms, best solution, gain). The large gains +are at small T: N = 10240 K = 2560 at T = 256 ... 1024, 7.0-7.8x; N = 12288 K = 2560 at T = 256, 5.8x; N = 6144 K = +2560 at T = 256 / 512, 3.6-3.8x; N = 2560 K = 6144 at T = 256, 4.5x; N = 320 K = 10240 (`hc read`), 2.5-8.7x across the +buckets. At T >= 2048 most shapes keep the default (1.0-1.2x where a solution still wins). + +## Method + +One server per arm, the same binary; `STRATA_PREFILL_TIMING=1` (the engine's prompt-phase timing), +`STRATA_ROCBLAS_VERBOSE=1`; the on arm with `STRATA_ROCBLAS_TUNING` pointing at the directory holding the table. Four +prompts from four different offsets of one text (no prefix reuse between them), "Reply with one word", `max_tokens` 8, +temperature 0; the answer text compared between arms. The GPU timeline is the engine's `strata prefill timing` line; the +per-phase numbers are its phases ([timing-off.txt](timing-off.txt), [timing-on.txt](timing-on.txt)). One run per arm; the off +arm repeated an earlier run of the same prompts the same day (with the table's first version) to within 10 ms on every +prompt, and the on arm's gains repeated within 100 ms. + +## Results + +| prompt tokens (read) | arm | GPU timeline ms | gdn | hc read | wait copy | answer | +| ---: | --- | ---: | ---: | ---: | ---: | --- | +| 806 (799) | default | 3,329 | 443 | 270 | 1,376 | Estimated | +| 806 (799) | **table** | **2,985** | 177 | 77 | 1,384 | Estimated | +| 502 (495) | default | 2,477 | 365 | 81 | 1,077 | Incomplete | +| 502 (495) | **table** | **2,139** | 146 | 52 | 1,075 | Incomplete | +| 1,115 (1,108) | default | 3,391 | 598 | 158 | 1,144 | Incomplete | +| 1,115 (1,108) | table | 3,395 | 201 | 99 | 1,637 | Incomplete | +| 8,881 (8,874) | default | 11,978 | 1,346 | 1,200 | 1,683 | Strata | +| 8,881 (8,874) | **table** | **11,459** | 1,128 | 898 | 1,670 | Strata | + +- 799 tokens: -10.3%; 495 tokens: -13.6%; 8,874 tokens: -4.3% (the 682-token tail chunk's projections, and `hc read` + at both chunks). +- 1,108 tokens: no change. Its GDN time fell by 397 ms and `wait copy` rose by 493 ms: that prompt is bound by the + experts' PCIe transfer, and a faster GEMM only brings the GPU to the wait sooner. Which prompts are copy-bound depends + on how many distinct experts they touch, not on their length alone. +- The answers are the same in all four pairs. The tuner checked each solution it kept against the default kernel's FP16 + output (relative L2 within 2e-3, no element beyond 4 FP16 ulps of the largest output, nothing written outside the + N x T result); in the engine's run no solution was refused (0 fallbacks over 52 shape-and-T combinations served). +- Decode does not use these GEMMs; not measured here. + +## Limits + +One machine, one card, one model; one run per arm, four prompts. The table is for one rocBLAS build; another build (or +ROCm's 5.1 packaged by Ubuntu) needs `tune_rocblas` run against it. Prompts above ~1,150 tokens gain only through their +tail chunk and `hc read`, and copy-bound prompts gain nothing. Whether other gfx103x cards (gfx1031 / gfx1032) share +rocBLAS's gfx1030 kernel table was not checked; the engine's architecture check would refuse this table on them. diff --git a/bench/results/2026-10-05-rdna2-rocblas-table/timing-off.txt b/bench/results/2026-10-05-rdna2-rocblas-table/timing-off.txt new file mode 100644 index 00000000..8d3a86c0 --- /dev/null +++ b/bench/results/2026-10-05-rdna2-rocblas-table/timing-off.txt @@ -0,0 +1,9 @@ +strata serve: prompt chunk auto: 8192 tokens, a 384-slot ring +strata prefill timing: 799 tokens, GPU timeline 3329 ms, wall 3339 ms, host staging 55 ms: embed+steps 5 (0.2%) hc read 270 (8.1%) gdn 443 (13.3%) qsa proj 91 (2.7%) qsa indexer 0 (0.0%) qsa select 1 (0.0%) qsa attn 50 (1.5%) router+shared 44 (1.3%) host grouping 12 (0.3%) gather 11 (0.3%) wait copy 1376 (41.3%) dequant 415 (12.5%) gemm gate/up 311 (9.3%) gemm down 155 (4.6%) combine 18 (0.5%) ple 10 (0.3%) kv stage 0 (0.0%) gdn conv+gates 5 (0.1%) gdn recurrence 35 (1.0%) gdn out proj 78 (2.3%) +strata serve: prompt 806 tokens = 0 reused + 806 read in 3635 ms (221.7 tok/s), 2 generated in 140 ms (14.3 tok/s), drafts accepted 3 of 3, 1 checkpoints +strata prefill timing: 495 tokens, GPU timeline 2477 ms, wall 2479 ms, host staging 107 ms: embed+steps 0 (0.0%) hc read 81 (3.3%) gdn 365 (14.7%) qsa proj 83 (3.4%) qsa indexer 0 (0.0%) qsa select 0 (0.0%) qsa attn 24 (1.0%) router+shared 77 (3.1%) host grouping 15 (0.6%) gather 3 (0.1%) wait copy 1077 (43.5%) dequant 319 (12.9%) gemm gate/up 223 (9.0%) gemm down 109 (4.4%) combine 10 (0.4%) ple 6 (0.2%) kv stage 0 (0.0%) gdn conv+gates 3 (0.1%) gdn recurrence 20 (0.8%) gdn out proj 61 (2.5%) +strata serve: prompt 502 tokens = 0 reused + 502 read in 2667 ms (188.2 tok/s), 2 generated in 114 ms (17.5 tok/s), drafts accepted 3 of 3, 1 checkpoints +strata prefill timing: 1108 tokens, GPU timeline 3391 ms, wall 3396 ms, host staging 184 ms: embed+steps 3 (0.1%) hc read 158 (4.7%) gdn 598 (17.6%) qsa proj 117 (3.5%) qsa indexer 0 (0.0%) qsa select 2 (0.0%) qsa attn 88 (2.6%) router+shared 53 (1.6%) host grouping 14 (0.4%) gather 7 (0.2%) wait copy 1144 (33.7%) dequant 454 (13.4%) gemm gate/up 358 (10.6%) gemm down 179 (5.3%) combine 26 (0.8%) ple 14 (0.4%) kv stage 0 (0.0%) gdn conv+gates 12 (0.3%) gdn recurrence 55 (1.6%) gdn out proj 109 (3.2%) +strata serve: prompt 1115 tokens = 0 reused + 1115 read in 3676 ms (303.3 tok/s), 2 generated in 115 ms (17.4 tok/s), drafts accepted 3 of 3, 1 checkpoints +strata prefill timing: 8874 tokens, GPU timeline 11978 ms, wall 11981 ms, host staging 336 ms: embed+steps 38 (0.3%) hc read 1200 (10.0%) gdn 1346 (11.2%) qsa proj 597 (5.0%) qsa indexer 1 (0.0%) qsa select 62 (0.5%) qsa attn 1897 (15.8%) router+shared 228 (1.9%) host grouping 42 (0.3%) gather 56 (0.5%) wait copy 1683 (14.1%) dequant 854 (7.1%) gemm gate/up 1428 (11.9%) gemm down 706 (5.9%) combine 768 (6.4%) ple 34 (0.3%) kv stage 8 (0.1%) gdn conv+gates 92 (0.8%) gdn recurrence 491 (4.1%) gdn out proj 447 (3.7%) +strata serve: prompt 8881 tokens = 0 reused + 8881 read in 12470 ms (712.2 tok/s), 3 generated in 117 ms (25.7 tok/s), drafts accepted 3 of 3, 1 checkpoints diff --git a/bench/results/2026-10-05-rdna2-rocblas-table/timing-on.txt b/bench/results/2026-10-05-rdna2-rocblas-table/timing-on.txt new file mode 100644 index 00000000..4580cfbc --- /dev/null +++ b/bench/results/2026-10-05-rdna2-rocblas-table/timing-on.txt @@ -0,0 +1,9 @@ +strata serve: prompt chunk auto: 8192 tokens, a 384-slot ring +strata prefill timing: 799 tokens, GPU timeline 2985 ms, wall 2994 ms, host staging 58 ms: embed+steps 5 (0.2%) hc read 77 (2.6%) gdn 177 (5.9%) qsa proj 89 (3.0%) qsa indexer 0 (0.0%) qsa select 1 (0.0%) qsa attn 51 (1.7%) router+shared 156 (5.2%) host grouping 12 (0.4%) gather 14 (0.5%) wait copy 1384 (46.4%) dequant 414 (13.9%) gemm gate/up 313 (10.5%) gemm down 154 (5.2%) combine 18 (0.6%) ple 3 (0.1%) kv stage 0 (0.0%) gdn conv+gates 5 (0.2%) gdn recurrence 35 (1.2%) gdn out proj 78 (2.6%) +strata serve: prompt 806 tokens = 0 reused + 806 read in 3296 ms (244.5 tok/s), 2 generated in 140 ms (14.3 tok/s), drafts accepted 3 of 3, 1 checkpoints +strata prefill timing: 495 tokens, GPU timeline 2139 ms, wall 2142 ms, host staging 98 ms: embed+steps 0 (0.0%) hc read 52 (2.5%) gdn 146 (6.8%) qsa proj 66 (3.1%) qsa indexer 0 (0.0%) qsa select 0 (0.0%) qsa attn 24 (1.1%) router+shared 29 (1.3%) host grouping 10 (0.5%) gather 3 (0.2%) wait copy 1075 (50.3%) dequant 318 (14.9%) gemm gate/up 222 (10.4%) gemm down 109 (5.1%) combine 10 (0.5%) ple 2 (0.1%) kv stage 0 (0.0%) gdn conv+gates 3 (0.1%) gdn recurrence 20 (0.9%) gdn out proj 50 (2.3%) +strata serve: prompt 502 tokens = 0 reused + 502 read in 2336 ms (214.9 tok/s), 2 generated in 124 ms (16.1 tok/s), drafts accepted 3 of 3, 1 checkpoints +strata prefill timing: 1108 tokens, GPU timeline 3395 ms, wall 3399 ms, host staging 176 ms: embed+steps 3 (0.1%) hc read 99 (2.9%) gdn 201 (5.9%) qsa proj 109 (3.2%) qsa indexer 0 (0.0%) qsa select 2 (0.0%) qsa attn 88 (2.6%) router+shared 51 (1.5%) host grouping 12 (0.4%) gather 7 (0.2%) wait copy 1637 (48.2%) dequant 448 (13.2%) gemm gate/up 360 (10.6%) gemm down 179 (5.3%) combine 26 (0.8%) ple 3 (0.1%) kv stage 0 (0.0%) gdn conv+gates 11 (0.3%) gdn recurrence 54 (1.6%) gdn out proj 102 (3.0%) +strata serve: prompt 1115 tokens = 0 reused + 1115 read in 3685 ms (302.6 tok/s), 2 generated in 115 ms (17.4 tok/s), drafts accepted 3 of 3, 1 checkpoints +strata prefill timing: 8874 tokens, GPU timeline 11459 ms, wall 11461 ms, host staging 329 ms: embed+steps 39 (0.3%) hc read 898 (7.8%) gdn 1128 (9.8%) qsa proj 595 (5.2%) qsa indexer 1 (0.0%) qsa select 62 (0.5%) qsa attn 1901 (16.6%) router+shared 214 (1.9%) host grouping 41 (0.4%) gather 56 (0.5%) wait copy 1670 (14.6%) dequant 860 (7.5%) gemm gate/up 1434 (12.5%) gemm down 710 (6.2%) combine 783 (6.8%) ple 28 (0.2%) kv stage 8 (0.1%) gdn conv+gates 92 (0.8%) gdn recurrence 492 (4.3%) gdn out proj 447 (3.9%) +strata serve: prompt 8881 tokens = 0 reused + 8881 read in 11952 ms (743.0 tok/s), 3 generated in 155 ms (19.3 tok/s), drafts accepted 3 of 3, 1 checkpoints diff --git a/bench/results/2026-10-05-rdna2-rocblas-table/tune-summary.txt b/bench/results/2026-10-05-rdna2-rocblas-table/tune-summary.txt new file mode 100644 index 00000000..e82205bb --- /dev/null +++ b/bench/results/2026-10-05-rdna2-rocblas-table/tune-summary.txt @@ -0,0 +1,226 @@ +meta device_arch=gfx1030 rocblas_version=5.6.0.8d1ae90e shapes=112 min_gain=1.050 +case T=256 N=10240 K=2560 ldy=10240 default_ms=2.3582 default_padding_writes=0 +best T=256 N=10240 K=2560 ldy=10240 solution=-1086327703 ms=0.3478 default_ms=2.3582 gain=6.78 +case T=512 N=10240 K=2560 ldy=10240 default_ms=4.9305 default_padding_writes=0 +best T=512 N=10240 K=2560 ldy=10240 solution=-1086327703 ms=0.6744 default_ms=4.9305 gain=7.31 +case T=768 N=10240 K=2560 ldy=10240 default_ms=7.5687 default_padding_writes=0 +best T=768 N=10240 K=2560 ldy=10240 solution=-1086327719 ms=1.0134 default_ms=7.5687 gain=7.47 +case T=1024 N=10240 K=2560 ldy=10240 default_ms=10.1879 default_padding_writes=0 +best T=1024 N=10240 K=2560 ldy=10240 solution=-1086327687 ms=1.4093 default_ms=10.1879 gain=7.23 +case T=1536 N=10240 K=2560 ldy=10240 default_ms=1.9304 default_padding_writes=0 +keep_default T=1536 N=10240 K=2560 ldy=10240 (237 solutions; best 1.9404 ms vs default 1.9304) +case T=2048 N=10240 K=2560 ldy=10240 default_ms=2.5629 default_padding_writes=0 +keep_default T=2048 N=10240 K=2560 ldy=10240 (237 solutions; best 2.5848 ms vs default 2.5629) +case T=4096 N=10240 K=2560 ldy=10240 default_ms=5.2270 default_padding_writes=0 +keep_default T=4096 N=10240 K=2560 ldy=10240 (237 solutions; best 5.5127 ms vs default 5.2270) +case T=8192 N=10240 K=2560 ldy=10240 default_ms=12.2560 default_padding_writes=0 +keep_default T=8192 N=10240 K=2560 ldy=10240 (237 solutions; best 12.1342 ms vs default 12.2560) +case T=256 N=12288 K=2560 ldy=12288 default_ms=3.0070 default_padding_writes=0 +best T=256 N=12288 K=2560 ldy=12288 solution=-1086327718 ms=0.5044 default_ms=3.0070 gain=5.96 +case T=512 N=12288 K=2560 ldy=12288 default_ms=1.0101 default_padding_writes=0 +best T=512 N=12288 K=2560 ldy=12288 solution=-1086327703 ms=0.8314 default_ms=1.0101 gain=1.21 +case T=768 N=12288 K=2560 ldy=12288 default_ms=1.5441 default_padding_writes=0 +best T=768 N=12288 K=2560 ldy=12288 solution=-1086327703 ms=1.3048 default_ms=1.5441 gain=1.18 +case T=1024 N=12288 K=2560 ldy=12288 default_ms=1.8461 default_padding_writes=0 +best T=1024 N=12288 K=2560 ldy=12288 solution=-1086327687 ms=1.6263 default_ms=1.8461 gain=1.14 +case T=1536 N=12288 K=2560 ldy=12288 default_ms=2.6097 default_padding_writes=0 +best T=1536 N=12288 K=2560 ldy=12288 solution=-1086327687 ms=2.4141 default_ms=2.6097 gain=1.08 +case T=2048 N=12288 K=2560 ldy=12288 default_ms=3.3976 default_padding_writes=0 +best T=2048 N=12288 K=2560 ldy=12288 solution=-1086327687 ms=3.2127 default_ms=3.3976 gain=1.06 +case T=4096 N=12288 K=2560 ldy=12288 default_ms=6.8017 default_padding_writes=0 +keep_default T=4096 N=12288 K=2560 ldy=12288 (237 solutions; best 6.8216 ms vs default 6.8017) +case T=8192 N=12288 K=2560 ldy=12288 default_ms=14.3542 default_padding_writes=0 +keep_default T=8192 N=12288 K=2560 ldy=12288 (237 solutions; best 14.9711 ms vs default 14.3542) +case T=256 N=6144 K=2560 ldy=6144 default_ms=0.9801 default_padding_writes=0 +best T=256 N=6144 K=2560 ldy=6144 solution=-1086327717 ms=0.2813 default_ms=0.9801 gain=3.48 +case T=512 N=6144 K=2560 ldy=6144 default_ms=1.8331 default_padding_writes=0 +best T=512 N=6144 K=2560 ldy=6144 solution=-1086327703 ms=0.5097 default_ms=1.8331 gain=3.60 +case T=768 N=6144 K=2560 ldy=6144 default_ms=0.6667 default_padding_writes=0 +keep_default T=768 N=6144 K=2560 ldy=6144 (237 solutions; best 0.6687 ms vs default 0.6667) +case T=1024 N=6144 K=2560 ldy=6144 default_ms=0.8296 default_padding_writes=0 +keep_default T=1024 N=6144 K=2560 ldy=6144 (237 solutions; best 0.8873 ms vs default 0.8296) +case T=1536 N=6144 K=2560 ldy=6144 default_ms=1.2994 default_padding_writes=0 +keep_default T=1536 N=6144 K=2560 ldy=6144 (237 solutions; best 1.3967 ms vs default 1.2994) +case T=2048 N=6144 K=2560 ldy=6144 default_ms=2.4454 default_padding_writes=0 +best T=2048 N=6144 K=2560 ldy=6144 solution=-1086327687 ms=1.6310 default_ms=2.4454 gain=1.50 +case T=4096 N=6144 K=2560 ldy=6144 default_ms=3.2071 default_padding_writes=0 +keep_default T=4096 N=6144 K=2560 ldy=6144 (237 solutions; best 3.2142 ms vs default 3.2071) +case T=8192 N=6144 K=2560 ldy=6144 default_ms=6.3302 default_padding_writes=0 +keep_default T=8192 N=6144 K=2560 ldy=6144 (237 solutions; best 6.7397 ms vs default 6.3302) +case T=256 N=2560 K=6144 ldy=2560 default_ms=1.3017 default_padding_writes=0 +best T=256 N=2560 K=6144 ldy=2560 solution=-1086327764 ms=0.2927 default_ms=1.3017 gain=4.45 +case T=512 N=2560 K=6144 ldy=2560 default_ms=1.2293 default_padding_writes=0 +best T=512 N=2560 K=6144 ldy=2560 solution=-1086327719 ms=0.4751 default_ms=1.2293 gain=2.59 +case T=768 N=2560 K=6144 ldy=2560 default_ms=0.7950 default_padding_writes=0 +keep_default T=768 N=2560 K=6144 ldy=2560 (275 solutions; best 0.7770 ms vs default 0.7950) +case T=1024 N=2560 K=6144 ldy=2560 default_ms=1.0164 default_padding_writes=0 +best T=1024 N=2560 K=6144 ldy=2560 solution=-1086327719 ms=0.8868 default_ms=1.0164 gain=1.15 +case T=1536 N=2560 K=6144 ldy=2560 default_ms=1.5987 default_padding_writes=0 +best T=1536 N=2560 K=6144 ldy=2560 solution=-1086327703 ms=1.4385 default_ms=1.5987 gain=1.11 +case T=2048 N=2560 K=6144 ldy=2560 default_ms=1.8388 default_padding_writes=0 +keep_default T=2048 N=2560 K=6144 ldy=2560 (237 solutions; best 1.8535 ms vs default 1.8388) +case T=4096 N=2560 K=6144 ldy=2560 default_ms=3.4526 default_padding_writes=0 +keep_default T=4096 N=2560 K=6144 ldy=2560 (237 solutions; best 3.7885 ms vs default 3.4526) +case T=8192 N=2560 K=6144 ldy=2560 default_ms=7.1451 default_padding_writes=0 +keep_default T=8192 N=2560 K=6144 ldy=2560 (237 solutions; best 8.2445 ms vs default 7.1451) +case T=256 N=2560 K=640 ldy=2560 default_ms=0.0435 default_padding_writes=0 +best T=256 N=2560 K=640 ldy=2560 solution=-1086327695 ms=0.0385 default_ms=0.0435 gain=1.13 +case T=512 N=2560 K=640 ldy=2560 default_ms=0.0729 default_padding_writes=0 +best T=512 N=2560 K=640 ldy=2560 solution=-1086327711 ms=0.0594 default_ms=0.0729 gain=1.23 +case T=768 N=2560 K=640 ldy=2560 default_ms=0.0965 default_padding_writes=0 +best T=768 N=2560 K=640 ldy=2560 solution=-1086327694 ms=0.0798 default_ms=0.0965 gain=1.21 +case T=1024 N=2560 K=640 ldy=2560 default_ms=0.1084 default_padding_writes=0 +best T=1024 N=2560 K=640 ldy=2560 solution=-1086327709 ms=0.0945 default_ms=0.1084 gain=1.15 +case T=1536 N=2560 K=640 ldy=2560 default_ms=0.1569 default_padding_writes=0 +best T=1536 N=2560 K=640 ldy=2560 solution=-1086327713 ms=0.1383 default_ms=0.1569 gain=1.13 +case T=2048 N=2560 K=640 ldy=2560 default_ms=0.1833 default_padding_writes=0 +keep_default T=2048 N=2560 K=640 ldy=2560 (237 solutions; best 0.1776 ms vs default 0.1833) +case T=4096 N=2560 K=640 ldy=2560 default_ms=0.3481 default_padding_writes=0 +keep_default T=4096 N=2560 K=640 ldy=2560 (237 solutions; best 0.3392 ms vs default 0.3481) +case T=8192 N=2560 K=640 ldy=2560 default_ms=0.6858 default_padding_writes=0 +keep_default T=8192 N=2560 K=640 ldy=2560 (237 solutions; best 0.6570 ms vs default 0.6858) +case T=256 N=2560 K=2560 ldy=2560 default_ms=0.1292 default_padding_writes=0 +keep_default T=256 N=2560 K=2560 ldy=2560 (275 solutions; best 0.1254 ms vs default 0.1292) +case T=512 N=2560 K=2560 ldy=2560 default_ms=0.2150 default_padding_writes=0 +best T=512 N=2560 K=2560 ldy=2560 solution=-1086327719 ms=0.2046 default_ms=0.2150 gain=1.05 +case T=768 N=2560 K=2560 ldy=2560 default_ms=0.3035 default_padding_writes=0 +keep_default T=768 N=2560 K=2560 ldy=2560 (275 solutions; best 0.3088 ms vs default 0.3035) +case T=1024 N=2560 K=2560 ldy=2560 default_ms=0.4164 default_padding_writes=0 +best T=1024 N=2560 K=2560 ldy=2560 solution=-1086327719 ms=0.3567 default_ms=0.4164 gain=1.17 +case T=1536 N=2560 K=2560 ldy=2560 default_ms=0.5242 default_padding_writes=0 +keep_default T=1536 N=2560 K=2560 ldy=2560 (237 solutions; best 0.5240 ms vs default 0.5242) +case T=2048 N=2560 K=2560 ldy=2560 default_ms=0.6880 default_padding_writes=0 +keep_default T=2048 N=2560 K=2560 ldy=2560 (237 solutions; best 0.6871 ms vs default 0.6880) +case T=4096 N=2560 K=2560 ldy=2560 default_ms=1.5527 default_padding_writes=0 +best T=4096 N=2560 K=2560 ldy=2560 solution=-1086327703 ms=1.3273 default_ms=1.5527 gain=1.17 +case T=8192 N=2560 K=2560 ldy=2560 default_ms=2.8199 default_padding_writes=0 +best T=8192 N=2560 K=2560 ldy=2560 solution=-1086327703 ms=2.6153 default_ms=2.8199 gain=1.08 +case T=256 N=640 K=2560 ldy=640 default_ms=0.1526 default_padding_writes=0 +best T=256 N=640 K=2560 ldy=640 solution=-1086327725 ms=0.0563 default_ms=0.1526 gain=2.71 +case T=512 N=640 K=2560 ldy=640 default_ms=0.2008 default_padding_writes=0 +best T=512 N=640 K=2560 ldy=640 solution=-1086327724 ms=0.0830 default_ms=0.2008 gain=2.42 +case T=768 N=640 K=2560 ldy=640 default_ms=0.1659 default_padding_writes=0 +best T=768 N=640 K=2560 ldy=640 solution=-1086327723 ms=0.1138 default_ms=0.1659 gain=1.46 +case T=1024 N=640 K=2560 ldy=640 default_ms=0.2067 default_padding_writes=0 +best T=1024 N=640 K=2560 ldy=640 solution=-1086327764 ms=0.1255 default_ms=0.2067 gain=1.65 +case T=1536 N=640 K=2560 ldy=640 default_ms=0.2841 default_padding_writes=0 +best T=1536 N=640 K=2560 ldy=640 solution=-1086327719 ms=0.2013 default_ms=0.2841 gain=1.41 +case T=2048 N=640 K=2560 ldy=640 default_ms=0.2173 default_padding_writes=0 +best T=2048 N=640 K=2560 ldy=640 solution=-1086327703 ms=0.2062 default_ms=0.2173 gain=1.05 +case T=4096 N=640 K=2560 ldy=640 default_ms=0.3467 default_padding_writes=0 +keep_default T=4096 N=640 K=2560 ldy=640 (237 solutions; best 0.3515 ms vs default 0.3467) +case T=8192 N=640 K=2560 ldy=640 default_ms=0.6892 default_padding_writes=0 +keep_default T=8192 N=640 K=2560 ldy=640 (237 solutions; best 0.6712 ms vs default 0.6892) +case T=256 N=512 K=2560 ldy=512 default_ms=0.1569 default_padding_writes=0 +best T=256 N=512 K=2560 ldy=512 solution=-1086327769 ms=0.0474 default_ms=0.1569 gain=3.31 +case T=512 N=512 K=2560 ldy=512 default_ms=0.2025 default_padding_writes=0 +best T=512 N=512 K=2560 ldy=512 solution=-1086327722 ms=0.0734 default_ms=0.2025 gain=2.76 +case T=768 N=512 K=2560 ldy=512 default_ms=0.1474 default_padding_writes=0 +best T=768 N=512 K=2560 ldy=512 solution=-1086327774 ms=0.0978 default_ms=0.1474 gain=1.51 +case T=1024 N=512 K=2560 ldy=512 default_ms=0.1552 default_padding_writes=0 +best T=1024 N=512 K=2560 ldy=512 solution=-1086327722 ms=0.1194 default_ms=0.1552 gain=1.30 +case T=1536 N=512 K=2560 ldy=512 default_ms=0.2222 default_padding_writes=0 +best T=1536 N=512 K=2560 ldy=512 solution=-1086327768 ms=0.1703 default_ms=0.2222 gain=1.30 +case T=2048 N=512 K=2560 ldy=512 default_ms=0.2122 default_padding_writes=0 +keep_default T=2048 N=512 K=2560 ldy=512 (275 solutions; best 0.2031 ms vs default 0.2122) +case T=4096 N=512 K=2560 ldy=512 default_ms=0.3443 default_padding_writes=0 +keep_default T=4096 N=512 K=2560 ldy=512 (275 solutions; best 0.3530 ms vs default 0.3443) +case T=8192 N=512 K=2560 ldy=512 default_ms=0.6643 default_padding_writes=0 +keep_default T=8192 N=512 K=2560 ldy=512 (237 solutions; best 0.6684 ms vs default 0.6643) +case T=256 N=128 K=2560 ldy=128 default_ms=0.0608 default_padding_writes=0 +best T=256 N=128 K=2560 ldy=128 solution=-1086327780 ms=0.0371 default_ms=0.0608 gain=1.64 +case T=512 N=128 K=2560 ldy=128 default_ms=0.1992 default_padding_writes=0 +best T=512 N=128 K=2560 ldy=128 solution=-1086327780 ms=0.0377 default_ms=0.1992 gain=5.28 +case T=768 N=128 K=2560 ldy=128 default_ms=0.1137 default_padding_writes=0 +best T=768 N=128 K=2560 ldy=128 solution=-1086327780 ms=0.0452 default_ms=0.1137 gain=2.52 +case T=1024 N=128 K=2560 ldy=128 default_ms=0.1180 default_padding_writes=0 +best T=1024 N=128 K=2560 ldy=128 solution=-1086327774 ms=0.0493 default_ms=0.1180 gain=2.40 +case T=1536 N=128 K=2560 ldy=128 default_ms=0.1520 default_padding_writes=0 +best T=1536 N=128 K=2560 ldy=128 solution=-1086327772 ms=0.0664 default_ms=0.1520 gain=2.29 +case T=2048 N=128 K=2560 ldy=128 default_ms=0.1242 default_padding_writes=0 +best T=2048 N=128 K=2560 ldy=128 solution=-1086327768 ms=0.0753 default_ms=0.1242 gain=1.65 +case T=4096 N=128 K=2560 ldy=128 default_ms=0.1512 default_padding_writes=0 +best T=4096 N=128 K=2560 ldy=128 solution=-1086327764 ms=0.1248 default_ms=0.1512 gain=1.21 +case T=8192 N=128 K=2560 ldy=128 default_ms=0.2066 default_padding_writes=0 +keep_default T=8192 N=128 K=2560 ldy=128 (275 solutions; best 0.2036 ms vs default 0.2066) +case T=256 N=48 K=2560 ldy=48 default_ms=0.0456 default_padding_writes=0 +best T=256 N=48 K=2560 ldy=48 solution=-1086327840 ms=0.0208 default_ms=0.0456 gain=2.19 +case T=512 N=48 K=2560 ldy=48 default_ms=0.2023 default_padding_writes=0 +best T=512 N=48 K=2560 ldy=48 solution=-1086327781 ms=0.0387 default_ms=0.2023 gain=5.23 +case T=768 N=48 K=2560 ldy=48 default_ms=0.1029 default_padding_writes=0 +best T=768 N=48 K=2560 ldy=48 solution=-1086327779 ms=0.0418 default_ms=0.1029 gain=2.47 +case T=1024 N=48 K=2560 ldy=48 default_ms=0.1078 default_padding_writes=0 +best T=1024 N=48 K=2560 ldy=48 solution=-1086327779 ms=0.0439 default_ms=0.1078 gain=2.46 +case T=1536 N=48 K=2560 ldy=48 default_ms=0.1125 default_padding_writes=0 +best T=1536 N=48 K=2560 ldy=48 solution=-1086327776 ms=0.0512 default_ms=0.1125 gain=2.20 +case T=2048 N=48 K=2560 ldy=48 default_ms=0.1210 default_padding_writes=0 +best T=2048 N=48 K=2560 ldy=48 solution=-1086327779 ms=0.0565 default_ms=0.1210 gain=2.14 +case T=4096 N=48 K=2560 ldy=48 default_ms=0.1865 default_padding_writes=0 +best T=4096 N=48 K=2560 ldy=48 solution=-1086327736 ms=0.0972 default_ms=0.1865 gain=1.92 +case T=8192 N=48 K=2560 ldy=48 default_ms=0.2047 default_padding_writes=0 +best T=8192 N=48 K=2560 ldy=48 solution=-1086327762 ms=0.1489 default_ms=0.2047 gain=1.37 +case T=256 N=320 K=10240 ldy=320 default_ms=0.4283 default_padding_writes=0 +best T=256 N=320 K=10240 ldy=320 solution=-1086327781 ms=0.1325 default_ms=0.4283 gain=3.23 +case T=512 N=320 K=10240 ldy=320 default_ms=0.4971 default_padding_writes=0 +best T=512 N=320 K=10240 ldy=320 solution=-1086327769 ms=0.2001 default_ms=0.4971 gain=2.48 +case T=768 N=320 K=10240 ldy=320 default_ms=0.8265 default_padding_writes=0 +best T=768 N=320 K=10240 ldy=320 solution=-1086327722 ms=0.2416 default_ms=0.8265 gain=3.42 +case T=1024 N=320 K=10240 ldy=320 default_ms=1.1697 default_padding_writes=0 +best T=1024 N=320 K=10240 ldy=320 solution=-1086327773 ms=0.3623 default_ms=1.1697 gain=3.23 +case T=1536 N=320 K=10240 ldy=320 default_ms=1.6087 default_padding_writes=0 +best T=1536 N=320 K=10240 ldy=320 solution=-1086327738 ms=0.4669 default_ms=1.6087 gain=3.45 +case T=2048 N=320 K=10240 ldy=320 default_ms=2.1792 default_padding_writes=0 +best T=2048 N=320 K=10240 ldy=320 solution=-1086327724 ms=0.6335 default_ms=2.1792 gain=3.44 +case T=4096 N=320 K=10240 ldy=320 default_ms=9.6169 default_padding_writes=0 +best T=4096 N=320 K=10240 ldy=320 solution=-1086327717 ms=1.1841 default_ms=9.6169 gain=8.12 +case T=8192 N=320 K=10240 ldy=320 default_ms=2.2651 default_padding_writes=0 +keep_default T=8192 N=320 K=10240 ldy=320 (237 solutions; best 2.3719 ms vs default 2.2651) +case T=256 N=10240 K=320 ldy=10240 default_ms=0.0584 default_padding_writes=0 +best T=256 N=10240 K=320 ldy=10240 solution=-1086327694 ms=0.0556 default_ms=0.0584 gain=1.05 +case T=512 N=10240 K=320 ldy=10240 default_ms=0.0980 default_padding_writes=0 +keep_default T=512 N=10240 K=320 ldy=10240 (237 solutions; best 0.0964 ms vs default 0.0980) +case T=768 N=10240 K=320 ldy=10240 default_ms=0.1398 default_padding_writes=0 +keep_default T=768 N=10240 K=320 ldy=10240 (237 solutions; best 0.1377 ms vs default 0.1398) +case T=1024 N=10240 K=320 ldy=10240 default_ms=0.1815 default_padding_writes=0 +keep_default T=1024 N=10240 K=320 ldy=10240 (237 solutions; best 0.1806 ms vs default 0.1815) +case T=1536 N=10240 K=320 ldy=10240 default_ms=0.2626 default_padding_writes=0 +keep_default T=1536 N=10240 K=320 ldy=10240 (237 solutions; best 0.2625 ms vs default 0.2626) +case T=2048 N=10240 K=320 ldy=10240 default_ms=0.3437 default_padding_writes=0 +keep_default T=2048 N=10240 K=320 ldy=10240 (237 solutions; best 0.3432 ms vs default 0.3437) +case T=4096 N=10240 K=320 ldy=10240 default_ms=0.6693 default_padding_writes=0 +keep_default T=4096 N=10240 K=320 ldy=10240 (237 solutions; best 0.6686 ms vs default 0.6693) +case T=8192 N=10240 K=320 ldy=10240 default_ms=1.3531 default_padding_writes=0 +keep_default T=8192 N=10240 K=320 ldy=10240 (237 solutions; best 1.3274 ms vs default 1.3531) +case T=256 N=4 K=10240 ldy=4 default_ms=0.1050 default_padding_writes=0 +best T=256 N=4 K=10240 ldy=4 solution=-1086327846 ms=0.0503 default_ms=0.1050 gain=2.09 +case T=512 N=4 K=10240 ldy=4 default_ms=0.2470 default_padding_writes=0 +best T=512 N=4 K=10240 ldy=4 solution=-1086327840 ms=0.0544 default_ms=0.2470 gain=4.54 +case T=768 N=4 K=10240 ldy=4 default_ms=0.2539 default_padding_writes=0 +best T=768 N=4 K=10240 ldy=4 solution=-1086327840 ms=0.0610 default_ms=0.2539 gain=4.16 +case T=1024 N=4 K=10240 ldy=4 default_ms=0.2553 default_padding_writes=0 +best T=1024 N=4 K=10240 ldy=4 solution=-1086327850 ms=0.0801 default_ms=0.2553 gain=3.19 +case T=1536 N=4 K=10240 ldy=4 default_ms=0.2556 default_padding_writes=0 +best T=1536 N=4 K=10240 ldy=4 solution=-1086327840 ms=0.1116 default_ms=0.2556 gain=2.29 +case T=2048 N=4 K=10240 ldy=4 default_ms=0.3051 default_padding_writes=0 +best T=2048 N=4 K=10240 ldy=4 solution=-1086327815 ms=0.1429 default_ms=0.3051 gain=2.14 +case T=4096 N=4 K=10240 ldy=4 default_ms=0.4891 default_padding_writes=0 +best T=4096 N=4 K=10240 ldy=4 solution=-1086327922 ms=0.2538 default_ms=0.4891 gain=1.93 +case T=8192 N=4 K=10240 ldy=4 default_ms=1.1681 default_padding_writes=0 +best T=8192 N=4 K=10240 ldy=4 solution=-1086327922 ms=0.4845 default_ms=1.1681 gain=2.41 +case T=256 N=1 K=2560 ldy=1 default_ms=0.0433 default_padding_writes=0 +best T=256 N=1 K=2560 ldy=1 solution=-9 ms=0.0081 default_ms=0.0433 gain=5.33 +case T=512 N=1 K=2560 ldy=1 default_ms=0.2000 default_padding_writes=0 +best T=512 N=1 K=2560 ldy=1 solution=-9 ms=0.0107 default_ms=0.2000 gain=18.63 +case T=768 N=1 K=2560 ldy=1 default_ms=0.0865 default_padding_writes=0 +best T=768 N=1 K=2560 ldy=1 solution=-9 ms=0.0125 default_ms=0.0865 gain=6.90 +case T=1024 N=1 K=2560 ldy=1 default_ms=0.0914 default_padding_writes=0 +best T=1024 N=1 K=2560 ldy=1 solution=-9 ms=0.0167 default_ms=0.0914 gain=5.49 +case T=1536 N=1 K=2560 ldy=1 default_ms=0.0931 default_padding_writes=0 +best T=1536 N=1 K=2560 ldy=1 solution=-9 ms=0.0197 default_ms=0.0931 gain=4.72 +case T=2048 N=1 K=2560 ldy=1 default_ms=0.1200 default_padding_writes=0 +best T=2048 N=1 K=2560 ldy=1 solution=-9 ms=0.0307 default_ms=0.1200 gain=3.92 +case T=4096 N=1 K=2560 ldy=1 default_ms=0.0734 default_padding_writes=0 +best T=4096 N=1 K=2560 ldy=1 solution=-9 ms=0.0415 default_ms=0.0734 gain=1.77 +case T=8192 N=1 K=2560 ldy=1 default_ms=0.2007 default_padding_writes=0 +best T=8192 N=1 K=2560 ldy=1 solution=-9 ms=0.0728 default_ms=0.2007 gain=2.76 +wrote 112 rows (76 with a solution) to table-5.6-v2.txt diff --git a/cmake/hip_backend.cmake b/cmake/hip_backend.cmake index fcd9ba14..fda922a4 100644 --- a/cmake/hip_backend.cmake +++ b/cmake/hip_backend.cmake @@ -63,6 +63,9 @@ set(STRATA_HIP_BLAS_TARGETS roc::hipblas) if(hipblas_VERSION VERSION_LESS "1.0") find_package(rocblas CONFIG REQUIRED) list(APPEND STRATA_HIP_BLAS_TARGETS roc::rocblas) +else() + # the prompt path's rocBLAS solution table (STRATA_ROCBLAS_TUNING, gfx103x) calls rocBLAS by name + find_package(rocblas CONFIG QUIET) endif() find_package(hipblaslt CONFIG QUIET) @@ -78,6 +81,12 @@ else() set(STRATA_HIPBLASLT_AVAILABLE OFF) message(STATUS "Strata: hipBLASLt not found; solution-table dispatch is unavailable") endif() +if(TARGET roc::rocblas) + set(STRATA_ROCBLAS_AVAILABLE ON) +else() + set(STRATA_ROCBLAS_AVAILABLE OFF) + message(STATUS "Strata: rocBLAS CMake package not found; the rocBLAS solution table (gfx103x) is unavailable") +endif() # HIP's link step produces a PIE; make Strata and ggml objects PIC for the ROCm linker. set(CMAKE_POSITION_INDEPENDENT_CODE ON) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index b817e495..d8e5573c 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -42,7 +42,9 @@ the kernel's amdgpu driver (no ROCm install needed): - **hipBLASLt tuning table:** setup uses `tools/hip/-hipblaslt-.txt` only when it matches both the card's architecture and the installed hipBLASLt version (read from `hipblaslt-version.h`; 1.2.0 is `100200`). Otherwise it says so and the prompt's dense matrix products use plain hipBLAS (slower prompts, same answers). - A table's solution ids are valid only for that pair, and the engine refuses any other table. + A table's solution ids are valid only for that pair, and the engine refuses any other table. On gfx103x (RDNA2, + no hipBLASLt kernels) the same role falls to a rocBLAS table, `tools/hip/-rocblas-.txt`, which the + engine picks for its own rocBLAS build when setup points it at the directory ([RDNA2](#rdna2-gfx1030)). - **Several cards:** setup takes one card (the one with the most VRAM, or `--gpu N`) unless you name more: `./setup.sh --backend hip --gpus 1,0` splits the model's layers across them, the first one the main card (numbers as setup lists them; `--gpus all` = every supported card, the most VRAM first). Every chosen card must be one of the @@ -478,6 +480,26 @@ run it; the report below is from a community machine: an RX 6900 XT 16 GB (gfx10 solved 9/9 on the first try with both (model time 374 s SGEMM, 307 s FP16). The SGEMM route is the slower of the two; no value passes through FP16, so it has no 65504 limit to stay under. It is not bit-identical to the native call (at most 4.3e-6 of the largest output apart), which can flip a near-tied greedy token like any such change. +- **rocBLAS solution table** (for the `STRATA_HIP_PROMPT_F16=1` route above; with it off, nothing runs through the + table): rocBLAS picks the kernel for each of those FP16 GEMMs from its own table by shape, and + on gfx1030 that pick is far from the best kernel the library holds for some shapes: the GDN input projection + (N = 10240, K = 2560) below about 1,150 tokens runs at 5 TFLOPS where the best of rocBLAS's own 237 solutions for the + same shape runs at 32-38 (7x; the kernel choice flips at T = 1152). `tools/hip/tune_rocblas` enumerates the library's + solutions per shape and token bucket, checks each against the default kernel's output and writes the winners as + `tools/hip/-rocblas-.txt`; the engine reads the table through `STRATA_ROCBLAS_TUNING` (a file, or + the directory, from which it takes the file of its own rocBLAS build) and runs those solutions in place of rocBLAS's + choice, the default kernel for every shape without a row. Solution indices are valid for one architecture and one + rocBLAS build (the full version string, `5.6.0.8d1ae90e` for ROCm 10.0.0's), and the engine refuses any other + table. Shipped: `gfx1030-rocblas-5.6.0.8d1ae90e.txt` (ROCm 10.0.0, the `/opt/rocm` setup installs on Ubuntu); setup + points the engine at the directory when a table for the card's architecture exists, and the engine's log says + `rocBLAS tuning enabled (... rows ...)` or why not. Measured on the 2x RX 6900 XT machine above (one card, #835 + + this, `STRATA_PREFILL_TIMING=1`, temperature 0, the same answers with and without): a 799-token prompt's GPU time + 3,329 -> 2,985 ms (the GDN projections 443 -> 177 ms, `hc read` 270 -> 77), 495 tokens 2,477 -> 2,139 ms (365 -> + 146), 8,874 tokens 11,978 -> 11,459 ms (the 682-token tail chunk's projections, `hc read` 1,200 -> 898); a + 1,108-token prompt did not change (3,391 -> 3,395 ms): its GDN time fell 598 -> 201 ms and the whole saving + reappeared as `wait copy`, the experts' PCIe transfer, which bounds that prompt. Per-run lines and the tuner's + summary: [bench/results/2026-10-05-rdna2-rocblas-table](../bench/results/2026-10-05-rdna2-rocblas-table/README.md). Decode does not use these GEMMs and is unchanged. See [Tuning + table](#tuning-table) for making a table for another rocBLAS build. - **Windows** (the report above): setup's ready-made Windows engine 0.1.39 runs the RX 6800 beside a 780M iGPU (HIP numbers the RX 6800 1; setup points the engine at it), and `tools/hip/build_windows.bat` with `STRATA_HIP_ARCHS=gfx1030` builds a working engine from the `gfx103X-all` 10.2.0a20260930 wheels. @@ -662,6 +684,33 @@ timed right after it held 0.606-0.619 ms every time, so time a heavy case first first fresh prompt after the model loads is not a measurement: it gave 949 and 1,423 tok/s in the two arms of that A/B, while the three trials after it differed by 0.4-1.5%. +### rocBLAS table (gfx103x) + +On RDNA2 the prompt GEMMs run through rocBLAS in FP16 (#835), and hipBLASLt has no gfx1030 kernels; the rocBLAS table +does for rocBLAS what the one above does for hipBLASLt (the [RDNA2 section](#rdna2-gfx1030) has the measurements). A +table is valid for one architecture and one rocBLAS build - the full version string, tweak hash included - so it is +calibrated on the card with the rocBLAS the engine loads (`lib_dirs` in the run configuration; `/opt/rocm/lib` is +rocBLAS 5.6.0.8d1ae90e on ROCm 10.0.0, while Ubuntu's own `librocblas5` package is a 5.1 build): + +```sh +cmake --build build-hip --target tune_rocblas +LD_LIBRARY_PATH=/opt/rocm/lib ./build-hip/tune_rocblas --tuning-out table.txt # 14 shapes x 8 token buckets, ~5 min +``` + +The tool times rocBLAS's default kernel and every solution the library lists for each shape at T = 256 ... 8192 (the +engine's dense GEMM shapes; `--case T,N,K,ldy` adds one, `--tokens` changes the buckets), checks the fastest ones +against the default kernel's output (within FP16 rounding, no write outside the N x T result) and that they also run at +smaller, odd token counts, and writes one row per shape and bucket: the winning solution index where it beats the +default by `--min-gain` (1.05), `default` otherwise - a `default` row is what keeps a neighbouring bucket's solution from +reaching token counts where rocBLAS's own choice measured best. The file's header names the architecture and version +(`STRATA_ROCBLAS_TUNING_V1 gfx1030 5.6.0.8d1ae90e`); save it as `tools/hip/-rocblas-.txt` (the version +with trailing dots dropped) for setup, or point `STRATA_ROCBLAS_TUNING` at the file. `STRATA_ROCBLAS_VERBOSE=1` prints +the solution picked for each shape and a `tuned_launches=... fallbacks=...` summary at exit; a solution rocBLAS refuses +at run time (status 11 once while it sets up its workspace is normal) falls back to the default kernel for that call, and +after three refusals for good. `hip_prefill_rocblas_gemm` (with `STRATA_ROCBLAS_TUNING` set; skips otherwise) is the +smoke test: it refuses a table for another architecture or build and checks Gemm's FP16 route against hipBLASEx on the +table's first two shapes. + ## Original backend validation (PR #94) The following is historical validation of the original backend, not a fresh diff --git a/include/strata/prefill/gemm.hpp b/include/strata/prefill/gemm.hpp index 6a87ef93..0ec8c691 100644 --- a/include/strata/prefill/gemm.hpp +++ b/include/strata/prefill/gemm.hpp @@ -74,6 +74,7 @@ private: void* workspace_ = nullptr; bool external_ = false; void* hipblaslt_state_ = nullptr; + void* rocblas_state_ = nullptr; // HIP: the rocBLAS solution table of f16_inplace (STRATA_ROCBLAS_TUNING) bool f16_io_ = false; /// cuBLAS 12 answers the default FP16 algorithm of a few (N, K) shapes with CUBLAS_STATUS_INTERNAL_ERROR once /// another CUDA device in the process has initialized its context (issue #1650, Turing + Pascal). A fixed diff --git a/setup.py b/setup.py index 8bb6ef9b..79d0a819 100644 --- a/setup.py +++ b/setup.py @@ -4414,7 +4414,7 @@ def write_config(path: Path, cfg: dict): # "sampling" or "mcp_servers" block, "allowed_hosts", "cors_origins", "open_browser" - and is kept when setup runs again SETUP_KEYS = frozenset({"exe", "args", "cwd", "tokenizer", "model_name", "log", "lib_dirs", "port", "backend", "env", "gpu", "gpus_asked", "layer_split", "host", "api_key", "draft_vocab", "vision"}) -SETUP_ENV = frozenset({"STRATA_HIPBLASLT_TUNING", "STRATA_RESIDENT_PIN", "STRATA_NO_ARENA_THP", "STRATA_MMQ_KQ", "STRATA_HC_Q8", +SETUP_ENV = frozenset({"STRATA_HIPBLASLT_TUNING", "STRATA_ROCBLAS_TUNING", "STRATA_RESIDENT_PIN", "STRATA_NO_ARENA_THP", "STRATA_MMQ_KQ", "STRATA_HC_Q8", "STRATA_ROUTE_TAIL_SKIP"}) # the "env" entries setup writes # 0.1.44 added these three, written for Unsloth's files only (unsloth_default_env). In any other model's config they are the # user's own (STRATA_ROUTE_TAIL_SKIP=0 to turn the tail skip off, STRATA_MMQ_KQ=1 ...): a setup run again keeps them there @@ -6743,6 +6743,14 @@ def main() -> int: if GFX1103_OPT_IN and gfx_arch_is(gpu["arch"], "gfx1103") and not WIN: # the 780M's KFD queues are evicted (a GPU reset) while transparent huge pages move the pinned expert arena cfg.setdefault("env", {})["STRATA_NO_ARENA_THP"] = "1" + # RDNA2 (gfx103x): the prompt's FP16 GEMMs through rocBLAS's best kernel per shape (tools/hip/tune_rocblas; + # the GDN input projection 6x faster below 1,152 tokens on a 6900 XT). The ids are valid for one rocBLAS + # build, which only the engine can read, so setup points it at the directory and the engine picks the file + # -rocblas-.txt for its own library, or runs the default kernels and says so in its log. + rocblas_tables = sorted(p.name for p in (ROOT / "tools" / "hip").glob(f"{gpu['arch']}-rocblas-*.txt")) + if rocblas_tables: + cfg.setdefault("env", {})["STRATA_ROCBLAS_TUNING"] = str(ROOT / "tools" / "hip") + ok(f"rocBLAS tuning tables for {gpu['arch']}: {', '.join(rocblas_tables)} (the engine takes the one of its rocBLAS build)") if resident: # ROCm: large page-locked host allocations can fail or be slow for the CPU; keep the copy pageable cfg.setdefault("env", {})["STRATA_RESIDENT_PIN"] = "0" if gpu["count"] > 1 or a.gpu is not None: diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu index 315c3017..50ca2b14 100644 --- a/src/prefill/gemm.cu +++ b/src/prefill/gemm.cu @@ -43,6 +43,16 @@ #include #include #endif +#if defined(__HIPCC__) && defined(STRATA_ROCBLAS_AVAILABLE) +#include "rocblas_tuning.hpp" +#include +#include +#include +#include +#include +#include +#include +#endif #if defined(__HIPCC__) #include @@ -390,6 +400,137 @@ bool try_hipblaslt(void* opaque_state, strata::prefill::hipblaslt::InputType typ } #endif +#if defined(__HIPCC__) && defined(STRATA_ROCBLAS_AVAILABLE) +// The rocBLAS solution table of f16_inplace (STRATA_ROCBLAS_TUNING: a table file, or a directory holding +// -rocblas-.txt for this card and rocBLAS build; src/prefill/rocblas_tuning.hpp). rocBLAS's own +// pick for some shapes is up to 6x slower than the best kernel it holds for them (gfx1030: tools/hip/tune_rocblas.cpp). +struct RocBlasState { + rocblas_handle handle = nullptr; + strata::prefill::rocblas_tuning::Table table; + struct Pick { bool tuned = false; int solution = 0; int refusals = 0; }; + std::map, Pick> cache; // (T, N, K, ldy) -> the solution to run, or the default + uint64_t tuned_launches = 0; + uint64_t fallbacks = 0; + + ~RocBlasState() { + if (std::getenv("STRATA_ROCBLAS_VERBOSE")) { + std::fprintf(stderr, "prefill gemm: rocBLAS tuning summary tuned_launches=%llu fallbacks=%llu\n", + (unsigned long long) tuned_launches, (unsigned long long) fallbacks); + } + if (handle) rocblas_destroy_handle(handle); + } +}; + +std::unique_ptr create_rocblas_state(void* stream) { + const char* path = std::getenv("STRATA_ROCBLAS_TUNING"); + if (!path || !*path) return nullptr; + auto state = std::make_unique(); + if (rocblas_create_handle(&state->handle) != rocblas_status_success) { + std::fprintf(stderr, "prefill gemm: rocBLAS handle creation failed; its default kernels run\n"); + return nullptr; + } + rocblas_set_stream(state->handle, (hipStream_t) stream); + char version[128] = {0}; + if (rocblas_get_version_string(version, sizeof version) != rocblas_status_success) { + std::fprintf(stderr, "prefill gemm: rocBLAS version query failed; its default kernels run\n"); + return nullptr; + } + int device = 0; + hipDeviceProp_t properties{}; + if (hipGetDevice(&device) != hipSuccess || hipGetDeviceProperties(&properties, device) != hipSuccess) { + std::fprintf(stderr, "prefill gemm: HIP device query failed; rocBLAS's default kernels run\n"); + return nullptr; + } + std::string arch(properties.gcnArchName); + if (const auto suffix = arch.find(':'); suffix != std::string::npos) arch.resize(suffix); + std::filesystem::path file(path); + std::error_code ec; + if (std::filesystem::is_directory(file, ec)) { + // the table of this card and this rocBLAS build (its version string, trailing dots dropped) + std::string tag(version); + while (!tag.empty() && tag.back() == '.') tag.pop_back(); + file /= arch + "-rocblas-" + tag + ".txt"; + } + std::string error; + if (!state->table.load(file.string(), arch, version, error)) { + std::fprintf(stderr, "prefill gemm: %s (%s); rocBLAS's default kernels run\n", error.c_str(), + file.string().c_str()); + return nullptr; + } + // rocBLAS loads its kernel library on the first product through a handle; a solution-index call before that + // fails (rocblas_status_internal_error) although the index is valid. One tiny default product opens it. + { + uint16_t* tiny = nullptr; + if (hipMalloc(&tiny, 4 * 64 * 64 * 2) == hipSuccess) { + const float one = 1.0f, zero = 0.0f; + (void) rocblas_gemm_ex(state->handle, rocblas_operation_transpose, rocblas_operation_none, 64, 64, 64, &one, + tiny, rocblas_datatype_f16_r, 64, tiny + 64 * 64, rocblas_datatype_f16_r, 64, &zero, + tiny + 2 * 64 * 64, rocblas_datatype_f16_r, 128, tiny + 2 * 64 * 64, + rocblas_datatype_f16_r, 128, rocblas_datatype_f32_r, rocblas_gemm_algo_standard, 0, 0); + (void) hipStreamSynchronize((hipStream_t) stream); + (void) hipFree(tiny); + } + } + size_t tuned_rows = 0; + for (const auto& row : state->table.rows()) tuned_rows += row.tuned ? 1 : 0; + std::fprintf(stderr, "prefill gemm: rocBLAS tuning enabled (%zu rows, %zu with a solution, %s, rocBLAS %s)\n", + state->table.rows().size(), tuned_rows, arch.c_str(), version); + return state; +} + +// Gemm::f16_inplace's product through the table's solution for its shape. False when the shape has no row, or the +// launch was refused (then the default kernel runs, and for that shape from now on). +bool try_rocblas_f16o(void* opaque_state, const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, + int64_t K, int64_t ldy) { + auto* state = static_cast(opaque_state); + if (!state || T <= 0 || N <= 0 || K <= 0 || T > INT_MAX || N > INT_MAX || K > INT_MAX || ldy > INT_MAX / 2) return false; + const auto key = std::make_tuple((int) T, (int) N, (int) K, (int) ldy); + auto it = state->cache.find(key); + if (it == state->cache.end()) { + RocBlasState::Pick pick; + if (const auto* row = state->table.closest((int) N, (int) K, (int) ldy, (int) T); row && row->tuned) { + pick.tuned = true; + pick.solution = row->solution; + } + if (std::getenv("STRATA_ROCBLAS_VERBOSE")) { + if (pick.tuned) + std::fprintf(stderr, "prefill gemm: rocBLAS solution %d for T=%lld N=%lld K=%lld ldy=%lld\n", + pick.solution, (long long) T, (long long) N, (long long) K, (long long) ldy); + else + std::fprintf(stderr, "prefill gemm: rocBLAS default kernel; no row for T=%lld N=%lld K=%lld ldy=%lld\n", + (long long) T, (long long) N, (long long) K, (long long) ldy); + } + it = state->cache.emplace(key, pick).first; + } + if (!it->second.tuned) return false; + const float one = 1.0f, zero = 0.0f; + const rocblas_status status = rocblas_gemm_ex( + state->handle, rocblas_operation_transpose, rocblas_operation_none, (int) N, (int) T, (int) K, &one, W, + rocblas_datatype_f16_r, (int) K, X, rocblas_datatype_f16_r, (int) K, &zero, Y, rocblas_datatype_f16_r, + (int) (2 * ldy), Y, rocblas_datatype_f16_r, (int) (2 * ldy), rocblas_datatype_f32_r, + rocblas_gemm_algo_solution_index, it->second.solution, 0); + if (status == rocblas_status_success) { + ++state->tuned_launches; + return true; + } + // A refusal writes nothing (the default kernel runs now). The first one can be rocBLAS still setting up for the + // kernel (its device workspace: seen as invalid_value once, success after); a solution refused three times is + // dropped for this shape. + ++state->fallbacks; + if (++it->second.refusals >= 3) { + std::fprintf(stderr, "prefill gemm: rocBLAS solution %d refused (status %d) for T=%lld N=%lld K=%lld ldy=%lld " + "three times; the default kernel runs for this shape\n", it->second.solution, (int) status, + (long long) T, (long long) N, (long long) K, (long long) ldy); + it->second.tuned = false; + } else if (std::getenv("STRATA_ROCBLAS_VERBOSE")) { + std::fprintf(stderr, "prefill gemm: rocBLAS solution %d refused (status %d) for T=%lld N=%lld K=%lld ldy=%lld; " + "the default kernel this time\n", it->second.solution, (int) status, (long long) T, + (long long) N, (long long) K, (long long) ldy); + } + return false; +} +#endif + } // namespace bool prompt_f16() { @@ -426,6 +567,9 @@ Gemm::~Gemm() { #endif #if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) delete static_cast(hipblaslt_state_); +#endif +#if defined(__HIPCC__) && defined(STRATA_ROCBLAS_AVAILABLE) + delete static_cast(rocblas_state_); #endif if (handle_) cublasDestroy((cublasHandle_t) handle_); if (tc_w_) cudaFree(tc_w_); @@ -454,6 +598,9 @@ bool Gemm::init_external(void* stream, uint16_t* scratch, int64_t scratch_elems, scratch_elems_ = scratch_elems; #if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) hipblaslt_state_ = create_hipblaslt_state(workspace_, ws_bytes).release(); +#endif +#if defined(__HIPCC__) && defined(STRATA_ROCBLAS_AVAILABLE) + rocblas_state_ = create_rocblas_state(stream).release(); #endif return true; } @@ -492,6 +639,9 @@ bool Gemm::init(void* stream, int64_t scratch_elems, std::string& err) { note(cublasSetMathMode(h, CUBLAS_DEFAULT_MATH), "cublasSetMathMode"); #if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) hipblaslt_state_ = create_hipblaslt_state(workspace_, ws).release(); +#endif +#if defined(__HIPCC__) && defined(STRATA_ROCBLAS_AVAILABLE) + rocblas_state_ = create_rocblas_state(stream).release(); #endif if (scratch_elems > 0) { if (const cudaError_t e = cudaMalloc((void**) &scratch_, (size_t) scratch_elems * 2); e != cudaSuccess) { @@ -1021,10 +1171,16 @@ bool Gemm::native_mmq(const uint16_t* X, int type, const void* W, float* Y, int6 void Gemm::f16_inplace(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy) { #if defined(__HIPCC__) const float one = 1.0f, zero = 0.0f; - ck(cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &one, W, CUDA_R_16F, - (int) K, X, CUDA_R_16F, (int) K, &zero, Y, CUDA_R_16F, (int) (2 * ldy), CUBLAS_COMPUTE_32F, - CUBLAS_GEMM_DEFAULT), - "cublasGemmEx f16 out"); + bool done = false; +#if defined(STRATA_ROCBLAS_AVAILABLE) + done = try_rocblas_f16o(rocblas_state_, X, W, Y, T, N, K, ldy); // the table's kernel for this shape, if any +#endif + if (!done) { + ck(cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &one, W, + CUDA_R_16F, (int) K, X, CUDA_R_16F, (int) K, &zero, Y, CUDA_R_16F, (int) (2 * ldy), + CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT), + "cublasGemmEx f16 out"); + } static const bool dbg_nan = std::getenv("STRATA_DBG_NAN") != nullptr; widen_rows_f16<<<(unsigned) T, 256, 0, (cudaStream_t) stream_>>>(Y, N, ldy, dbg_nan ? 1 : 0); if (dbg_nan) { // debug only: a sync per GEMM diff --git a/src/prefill/rocblas_tuning.hpp b/src/prefill/rocblas_tuning.hpp new file mode 100644 index 00000000..99bf5414 --- /dev/null +++ b/src/prefill/rocblas_tuning.hpp @@ -0,0 +1,129 @@ +// src/prefill/rocblas_tuning.hpp - the rocBLAS solution table of the prompt path's FP16-out GEMMs (HIP, gfx103x). +// +// rocBLAS picks a kernel per GEMM shape from its own table, and on gfx1030 that pick is up to 6x slower than the best +// kernel the library holds for the same shape (N=10240 K=2560 below T=1152: tools/hip/tune_rocblas.cpp). A table +// made by that tool names, per shape and token bucket, the solution index to run instead; Gemm::f16_inplace reads it +// through STRATA_ROCBLAS_TUNING. Indices are valid for one architecture and one rocBLAS build (its full version +// string), and the table carries both; any other pair is refused and the default kernels run. +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::prefill::rocblas_tuning { + +struct Row { + int n = 0; + int k = 0; + int ldy = 0; + int t_bucket = 0; + bool tuned = false; // false: the default kernel measured best at this bucket (the row bounds its neighbours' reach) + int solution = 0; // rocBLAS solution indices can be negative +}; + +class Table { +public: + /// `expected_version`: rocblas_get_version_string() of the library the engine runs with. + bool load(const std::string& path, const std::string& expected_arch, const std::string& expected_version, + std::string& err) { + std::ifstream input(path); + if (!input) { + err = "cannot open rocBLAS tuning file"; + return false; + } + bool saw_header = false; + std::string line; + size_t line_number = 0; + while (std::getline(input, line)) { + ++line_number; + if (const auto hash = line.find('#'); hash != std::string::npos) line.resize(hash); + const auto first = line.find_first_not_of(" \t\r\n"); + if (first == std::string::npos) continue; + std::istringstream row(line.substr(first)); + if (!saw_header) { + std::string magic, arch, version, extra; + if (!(row >> magic >> arch >> version) || (row >> extra) || magic != "STRATA_ROCBLAS_TUNING_V1") { + err = "invalid rocBLAS tuning header at line " + std::to_string(line_number); + return false; + } + if (arch != expected_arch) { + err = "rocBLAS tuning architecture mismatch: file=" + arch + " runtime=" + expected_arch; + return false; + } + if (version != expected_version) { + err = "rocBLAS version mismatch: file=" + version + " runtime=" + expected_version; + return false; + } + arch_ = std::move(arch); + version_ = std::move(version); + saw_header = true; + continue; + } + std::string type, solution, extra; + Row parsed; + if (!(row >> type >> parsed.n >> parsed.k >> parsed.ldy >> parsed.t_bucket >> solution) || (row >> extra) || + type != "f16o" || parsed.n <= 0 || parsed.k <= 0 || parsed.ldy < parsed.n || parsed.t_bucket <= 0) { + err = "invalid rocBLAS tuning row at line " + std::to_string(line_number); + return false; + } + if (solution != "default") { + char* end = nullptr; + const long value = std::strtol(solution.c_str(), &end, 10); + if (!end || *end || value < INT_MIN || value > INT_MAX) { + err = "invalid rocBLAS solution index at line " + std::to_string(line_number); + return false; + } + parsed.tuned = true; + parsed.solution = (int) value; + } + for (const auto& existing : rows_) { + if (existing.n == parsed.n && existing.k == parsed.k && existing.ldy == parsed.ldy && + existing.t_bucket == parsed.t_bucket) { + err = "duplicate rocBLAS tuning key at line " + std::to_string(line_number); + return false; + } + } + rows_.push_back(parsed); + } + if (!saw_header) { + err = "rocBLAS tuning file has no header"; + return false; + } + return true; + } + + /// The row of this shape whose token bucket is nearest to t (the smaller bucket on a tie); null when the shape + /// has no row at all (never measured). A `default` row says the default kernel measured best there, so a tuned + /// neighbour's solution reaches no further than halfway to it. + const Row* closest(int n, int k, int ldy, int t) const { + const Row* best = nullptr; + int64_t best_distance = std::numeric_limits::max(); + for (const auto& row : rows_) { + if (row.n != n || row.k != k || row.ldy != ldy) continue; + const int64_t distance = row.t_bucket >= t ? int64_t(row.t_bucket) - t : int64_t(t) - row.t_bucket; + if (distance < best_distance || (distance == best_distance && row.t_bucket < best->t_bucket)) { + best = &row; + best_distance = distance; + } + } + return best; + } + + const std::vector& rows() const { return rows_; } + const std::string& arch() const { return arch_; } + const std::string& version() const { return version_; } + +private: + std::string arch_; + std::string version_; + std::vector rows_; +}; + +} // namespace strata::prefill::rocblas_tuning diff --git a/tests/hip/prefill_rocblas_gemm.cpp b/tests/hip/prefill_rocblas_gemm.cpp new file mode 100644 index 00000000..6433db5b --- /dev/null +++ b/tests/hip/prefill_rocblas_gemm.cpp @@ -0,0 +1,206 @@ +// Opt-in HIP smoke test for the rocBLAS solution table of the prompt path's FP16-out GEMMs (gfx103x); it needs +// STRATA_ROCBLAS_TUNING (SKIP otherwise). It checks that the table loads for this device and rocBLAS build, and that +// Gemm's FP16 path (set_f16_io, the route the table serves) matches an FP32-out hipBLASEx reference on the table's +// first two shapes, at their token bucket and at a smaller odd T that resolves to the same row. Like the hipBLASLt +// test it does not check that rocBLAS ran the table's solution: an id the library refuses falls back to the default +// kernel and the test still passes; STRATA_ROCBLAS_VERBOSE=1 prints the "tuned_launches=... fallbacks=..." summary. +#include +#include +#include +#include + +#include "strata/prefill/gemm.hpp" +#include "rocblas_tuning.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define HIP_CHECK(call) do { \ + const hipError_t status_ = (call); \ + if (status_ != hipSuccess) { \ + std::fprintf(stderr, "HIP failure at %s:%d: %s: %s\n", __FILE__, __LINE__, #call, hipGetErrorString(status_)); \ + std::exit(2); \ + } \ +} while (0) + +#define HIPBLAS_CHECK(call) do { \ + const hipblasStatus_t status_ = (call); \ + if (status_ != HIPBLAS_STATUS_SUCCESS) { \ + std::fprintf(stderr, "hipBLAS failure at %s:%d: %s: %d\n", __FILE__, __LINE__, #call, (int) status_); \ + std::exit(2); \ + } \ +} while (0) + +namespace { + +struct DeviceBuffer { + void* p = nullptr; + explicit DeviceBuffer(size_t bytes) { if (bytes) HIP_CHECK(hipMalloc(&p, bytes)); } + ~DeviceBuffer() { if (p) (void) hipFree(p); } + DeviceBuffer(const DeviceBuffer&) = delete; + DeviceBuffer& operator=(const DeviceBuffer&) = delete; +}; + +uint16_t f16_bits(float value) { + const __half half = __float2half_rn(value); + uint16_t bits = 0; + std::memcpy(&bits, &half, sizeof(bits)); + return bits; +} + +// Y[T, N] (fp32, row stride ldy, at output_offset floats into the buffer) = X[T, K] . W[N, K]^T, Gemm's FP16 route +// against hipBLASEx with FP32 out. The FP16 route rounds its outputs to FP16 (that is the measured, accepted cost of +// prompt_f16(), docs/AMD_HIP.md): the tolerance is a few FP16 ulps of the largest output. +bool run_case(strata::prefill::Gemm& gemm, hipblasHandle_t blas, hipStream_t stream, int t, int n, int k, int ldy, + int output_offset, uint32_t seed) { + std::mt19937 rng(seed); + std::uniform_real_distribution dist(-0.25f, 0.25f); + const size_t x_count = (size_t) t * k, w_count = (size_t) n * k; + std::vector x(x_count), w(w_count); + for (auto& value : x) value = f16_bits(dist(rng)); + for (auto& value : w) value = f16_bits(dist(rng)); + const size_t output_count = (size_t) output_offset + (size_t) t * ldy + 8; + std::vector initial(output_count, -777.25f); + + DeviceBuffer dx(x_count * 2), dw(w_count * 2), dy(output_count * 4), dref(output_count * 4); + HIP_CHECK(hipMemcpyAsync(dx.p, x.data(), x_count * 2, hipMemcpyHostToDevice, stream)); + HIP_CHECK(hipMemcpyAsync(dw.p, w.data(), w_count * 2, hipMemcpyHostToDevice, stream)); + HIP_CHECK(hipMemcpyAsync(dy.p, initial.data(), output_count * 4, hipMemcpyHostToDevice, stream)); + HIP_CHECK(hipMemcpyAsync(dref.p, initial.data(), output_count * 4, hipMemcpyHostToDevice, stream)); + HIP_CHECK(hipStreamSynchronize(stream)); + + const float alpha = 1.0f, beta = 0.0f; + HIPBLAS_CHECK(hipblasGemmEx(blas, HIPBLAS_OP_T, HIPBLAS_OP_N, n, t, k, &alpha, dw.p, HIP_R_16F, k, dx.p, HIP_R_16F, + k, &beta, (float*) dref.p + output_offset, HIP_R_32F, ldy, HIPBLAS_COMPUTE_32F, + HIPBLAS_GEMM_DEFAULT)); + gemm.f16((const uint16_t*) dx.p, (const uint16_t*) dw.p, (float*) dy.p + output_offset, t, n, k, ldy, beta); + HIP_CHECK(hipStreamSynchronize(stream)); + + std::vector got(output_count), ref(output_count); + HIP_CHECK(hipMemcpy(got.data(), dy.p, output_count * 4, hipMemcpyDeviceToHost)); + HIP_CHECK(hipMemcpy(ref.data(), dref.p, output_count * 4, hipMemcpyDeviceToHost)); + + std::vector active(output_count, 0); + double diff2 = 0.0, ref2 = 0.0, max_abs = 0.0, max_ref = 0.0; + for (int row = 0; row < t; ++row) { + for (int col = 0; col < n; ++col) { + const size_t index = (size_t) output_offset + (size_t) row * ldy + col; + active[index] = 1; + if (!std::isfinite(got[index]) || !std::isfinite(ref[index])) { + std::fprintf(stderr, "non-finite output T=%d N=%d K=%d index=%zu\n", t, n, k, index); + return false; + } + const double delta = (double) got[index] - ref[index]; + diff2 += delta * delta; + ref2 += (double) ref[index] * ref[index]; + max_abs = std::max(max_abs, std::abs(delta)); + max_ref = std::max(max_ref, (double) std::abs(ref[index])); + } + } + for (size_t i = 0; i < output_count; ++i) { + if (!active[i] && (got[i] != initial[i] || ref[i] != initial[i])) { + std::fprintf(stderr, "output touched padding/guard T=%d N=%d K=%d ldy=%d index=%zu got=%.9g\n", t, n, k, ldy, + i, got[i]); + return false; + } + } + const double relative_l2 = std::sqrt(diff2 / std::max(ref2, 1e-300)); + const double ulp = std::ldexp(1.0, (int) std::floor(std::log2(std::max(max_ref, 1e-30))) - 10); + const bool passed = relative_l2 <= 2e-3 && max_abs <= 4.0 * ulp; + std::printf("case T=%d N=%d K=%d ldy=%d output_offset=%d relative_l2=%.3g max_abs=%.3g (4 ulp = %.3g) %s\n", t, n, k, + ldy, output_offset, relative_l2, max_abs, 4.0 * ulp, passed ? "PASS" : "FAIL"); + return passed; +} + +} // namespace + +int main() { + const char* tuning_path = std::getenv("STRATA_ROCBLAS_TUNING"); + if (!tuning_path || !*tuning_path) { + std::fprintf(stderr, "SKIP: set STRATA_ROCBLAS_TUNING to a tuning table (or the tools/hip directory) for this GPU and rocBLAS build\n"); + return 77; + } + if (!strata::prefill::prompt_f16()) { + std::fprintf(stderr, "SKIP: the FP16 prompt GEMMs (prompt_f16) are off on this device; the table serves that route only\n"); + return 77; + } + + int device = 0; + HIP_CHECK(hipGetDevice(&device)); + hipDeviceProp_t properties{}; + HIP_CHECK(hipGetDeviceProperties(&properties, device)); + std::string arch(properties.gcnArchName); + if (const auto suffix = arch.find(':'); suffix != std::string::npos) arch.resize(suffix); + char version[128] = {0}; + if (rocblas_get_version_string(version, sizeof version) != rocblas_status_success) { + std::fprintf(stderr, "rocblas_get_version_string failed\n"); + return 2; + } + std::filesystem::path file(tuning_path); + std::error_code ec; + if (std::filesystem::is_directory(file, ec)) { // the engine's rule: -rocblas-.txt, trailing dots dropped + std::string tag(version); + while (!tag.empty() && tag.back() == '.') tag.pop_back(); + file /= arch + "-rocblas-" + tag + ".txt"; + } + strata::prefill::rocblas_tuning::Table table; + std::string error; + if (!table.load(file.string(), arch, version, error)) { + std::fprintf(stderr, "tuning table rejected: %s (%s)\n", error.c_str(), file.string().c_str()); + return 1; + } + if (table.rows().empty()) { + std::fprintf(stderr, "tuning table has no rows\n"); + return 1; + } + + hipStream_t stream = nullptr; + HIP_CHECK(hipStreamCreateWithFlags(&stream, hipStreamNonBlocking)); + bool ok = true; + int cases = 0; + { + std::string init_error; + strata::prefill::Gemm gemm; + if (!gemm.init((void*) stream, 0, init_error)) { + std::fprintf(stderr, "Gemm init failed: %s\n", init_error.c_str()); + HIP_CHECK(hipStreamDestroy(stream)); + return 2; + } + gemm.set_f16_io(true); + hipblasHandle_t blas = nullptr; + HIPBLAS_CHECK(hipblasCreate(&blas)); + HIPBLAS_CHECK(hipblasSetStream(blas, stream)); + + // the table's first two distinct shapes: at their bucket (an exact row) and at a smaller odd T (the closest + // row, a non-tile-multiple tail), the second with the output inside a larger buffer + std::vector picked; + for (const auto& row : table.rows()) { + if (!row.tuned) continue; + bool seen = false; + for (const auto* p : picked) seen = seen || (p->n == row.n && p->k == row.k && p->ldy == row.ldy); + if (!seen) picked.push_back(&row); + if (picked.size() == 2) break; + } + uint32_t seed = 201; + for (const auto* row : picked) { + ok &= run_case(gemm, blas, stream, row->t_bucket, row->n, row->k, row->ldy, 0, seed++); + ok &= run_case(gemm, blas, stream, std::max(1, row->t_bucket - 37), row->n, row->k, row->ldy, 7, seed++); + cases += 2; + } + HIPBLAS_CHECK(hipblasDestroy(blas)); + } + HIP_CHECK(hipStreamDestroy(stream)); + std::printf("smoke test: %d cases on the first %zu shapes of the table's %zu rows; %s\n", cases, + std::min(2, table.rows().size()), table.rows().size(), + ok ? "outputs match hipBLASEx within FP16 rounding (solution ids are not verified; see STRATA_ROCBLAS_VERBOSE)" + : "FAILED"); + return ok ? 0 : 1; +} diff --git a/tools/hip/gfx1030-rocblas-5.6.0.8d1ae90e.txt b/tools/hip/gfx1030-rocblas-5.6.0.8d1ae90e.txt new file mode 100644 index 00000000..717c3b52 --- /dev/null +++ b/tools/hip/gfx1030-rocblas-5.6.0.8d1ae90e.txt @@ -0,0 +1,116 @@ +# rocBLAS solution indices for the prompt path's FP16-out GEMMs; valid for this architecture and rocBLAS build only +# rows: type N K ldy T solution (type f16o: FP16 in, FP16 out, FP32 compute; Gemm::f16_inplace) +# solution: rocBLAS's solution index, or `default` where its own choice measured best at that bucket +STRATA_ROCBLAS_TUNING_V1 gfx1030 5.6.0.8d1ae90e +f16o 10240 2560 10240 256 -1086327703 # 2.35815 ms -> 0.347774 ms +f16o 10240 2560 10240 512 -1086327703 # 4.93049 ms -> 0.674375 ms +f16o 10240 2560 10240 768 -1086327719 # 7.56866 ms -> 1.01344 ms +f16o 10240 2560 10240 1024 -1086327687 # 10.1879 ms -> 1.40927 ms +f16o 10240 2560 10240 1536 default # 1.93035 ms +f16o 10240 2560 10240 2048 default # 2.56287 ms +f16o 10240 2560 10240 4096 default # 5.22701 ms +f16o 10240 2560 10240 8192 default # 12.256 ms +f16o 12288 2560 12288 256 -1086327718 # 3.00699 ms -> 0.504361 ms +f16o 12288 2560 12288 512 -1086327703 # 1.01009 ms -> 0.831414 ms +f16o 12288 2560 12288 768 -1086327703 # 1.54412 ms -> 1.30476 ms +f16o 12288 2560 12288 1024 -1086327687 # 1.84607 ms -> 1.62627 ms +f16o 12288 2560 12288 1536 -1086327687 # 2.60974 ms -> 2.41411 ms +f16o 12288 2560 12288 2048 -1086327687 # 3.39763 ms -> 3.2127 ms +f16o 12288 2560 12288 4096 default # 6.8017 ms +f16o 12288 2560 12288 8192 default # 14.3542 ms +f16o 6144 2560 6144 256 -1086327717 # 0.980093 ms -> 0.281347 ms +f16o 6144 2560 6144 512 -1086327703 # 1.83313 ms -> 0.509667 ms +f16o 6144 2560 6144 768 default # 0.666733 ms +f16o 6144 2560 6144 1024 default # 0.829613 ms +f16o 6144 2560 6144 1536 default # 1.29944 ms +f16o 6144 2560 6144 2048 -1086327687 # 2.4454 ms -> 1.63103 ms +f16o 6144 2560 6144 4096 default # 3.20715 ms +f16o 6144 2560 6144 8192 default # 6.33023 ms +f16o 2560 6144 2560 256 -1086327764 # 1.30173 ms -> 0.292693 ms +f16o 2560 6144 2560 512 -1086327719 # 1.22932 ms -> 0.475053 ms +f16o 2560 6144 2560 768 default # 0.795013 ms +f16o 2560 6144 2560 1024 -1086327719 # 1.01636 ms -> 0.886773 ms +f16o 2560 6144 2560 1536 -1086327703 # 1.59868 ms -> 1.43847 ms +f16o 2560 6144 2560 2048 default # 1.83883 ms +f16o 2560 6144 2560 4096 default # 3.45259 ms +f16o 2560 6144 2560 8192 default # 7.14512 ms +f16o 2560 640 2560 256 -1086327695 # 0.04352 ms -> 0.0384667 ms +f16o 2560 640 2560 512 -1086327711 # 0.0728533 ms -> 0.0594 ms +f16o 2560 640 2560 768 -1086327694 # 0.0964533 ms -> 0.07984 ms +f16o 2560 640 2560 1024 -1086327709 # 0.108387 ms -> 0.0945467 ms +f16o 2560 640 2560 1536 -1086327713 # 0.156893 ms -> 0.13828 ms +f16o 2560 640 2560 2048 default # 0.183253 ms +f16o 2560 640 2560 4096 default # 0.348147 ms +f16o 2560 640 2560 8192 default # 0.685773 ms +f16o 2560 2560 2560 256 default # 0.1292 ms +f16o 2560 2560 2560 512 -1086327719 # 0.215 ms -> 0.204587 ms +f16o 2560 2560 2560 768 default # 0.303533 ms +f16o 2560 2560 2560 1024 -1086327719 # 0.416427 ms -> 0.356733 ms +f16o 2560 2560 2560 1536 default # 0.52424 ms +f16o 2560 2560 2560 2048 default # 0.687973 ms +f16o 2560 2560 2560 4096 -1086327703 # 1.55271 ms -> 1.32725 ms +f16o 2560 2560 2560 8192 -1086327703 # 2.81991 ms -> 2.61531 ms +f16o 640 2560 640 256 -1086327725 # 0.152587 ms -> 0.0562933 ms +f16o 640 2560 640 512 -1086327724 # 0.200773 ms -> 0.0829867 ms +f16o 640 2560 640 768 -1086327723 # 0.165947 ms -> 0.11384 ms +f16o 640 2560 640 1024 -1086327764 # 0.206733 ms -> 0.125493 ms +f16o 640 2560 640 1536 -1086327719 # 0.284106 ms -> 0.201267 ms +f16o 640 2560 640 2048 -1086327703 # 0.217293 ms -> 0.206173 ms +f16o 640 2560 640 4096 default # 0.346747 ms +f16o 640 2560 640 8192 default # 0.689187 ms +f16o 512 2560 512 256 -1086327769 # 0.156933 ms -> 0.0474 ms +f16o 512 2560 512 512 -1086327722 # 0.202507 ms -> 0.0734 ms +f16o 512 2560 512 768 -1086327774 # 0.147413 ms -> 0.0978133 ms +f16o 512 2560 512 1024 -1086327722 # 0.15524 ms -> 0.11936 ms +f16o 512 2560 512 1536 -1086327768 # 0.2222 ms -> 0.17032 ms +f16o 512 2560 512 2048 default # 0.2122 ms +f16o 512 2560 512 4096 default # 0.344253 ms +f16o 512 2560 512 8192 default # 0.664307 ms +f16o 128 2560 128 256 -1086327780 # 0.0608 ms -> 0.03712 ms +f16o 128 2560 128 512 -1086327780 # 0.1992 ms -> 0.0377333 ms +f16o 128 2560 128 768 -1086327780 # 0.113667 ms -> 0.0451733 ms +f16o 128 2560 128 1024 -1086327774 # 0.118013 ms -> 0.0492533 ms +f16o 128 2560 128 1536 -1086327772 # 0.151973 ms -> 0.0664 ms +f16o 128 2560 128 2048 -1086327768 # 0.12424 ms -> 0.07528 ms +f16o 128 2560 128 4096 -1086327764 # 0.151187 ms -> 0.124813 ms +f16o 128 2560 128 8192 default # 0.206573 ms +f16o 48 2560 48 256 -1086327840 # 0.0455867 ms -> 0.0207733 ms +f16o 48 2560 48 512 -1086327781 # 0.202253 ms -> 0.0386667 ms +f16o 48 2560 48 768 -1086327779 # 0.102947 ms -> 0.04176 ms +f16o 48 2560 48 1024 -1086327779 # 0.10784 ms -> 0.04392 ms +f16o 48 2560 48 1536 -1086327776 # 0.11252 ms -> 0.0512133 ms +f16o 48 2560 48 2048 -1086327779 # 0.121 ms -> 0.0565467 ms +f16o 48 2560 48 4096 -1086327736 # 0.186493 ms -> 0.0971733 ms +f16o 48 2560 48 8192 -1086327762 # 0.204667 ms -> 0.148867 ms +f16o 320 10240 320 256 -1086327781 # 0.42828 ms -> 0.13252 ms +f16o 320 10240 320 512 -1086327769 # 0.497053 ms -> 0.20012 ms +f16o 320 10240 320 768 -1086327722 # 0.826453 ms -> 0.241627 ms +f16o 320 10240 320 1024 -1086327773 # 1.16967 ms -> 0.36232 ms +f16o 320 10240 320 1536 -1086327738 # 1.60872 ms -> 0.466893 ms +f16o 320 10240 320 2048 -1086327724 # 2.17916 ms -> 0.633547 ms +f16o 320 10240 320 4096 -1086327717 # 9.61694 ms -> 1.18415 ms +f16o 320 10240 320 8192 default # 2.26508 ms +f16o 10240 320 10240 256 -1086327694 # 0.0583733 ms -> 0.05556 ms +f16o 10240 320 10240 512 default # 0.0980133 ms +f16o 10240 320 10240 768 default # 0.1398 ms +f16o 10240 320 10240 1024 default # 0.181493 ms +f16o 10240 320 10240 1536 default # 0.262587 ms +f16o 10240 320 10240 2048 default # 0.343693 ms +f16o 10240 320 10240 4096 default # 0.669293 ms +f16o 10240 320 10240 8192 default # 1.35307 ms +f16o 4 10240 4 256 -1086327846 # 0.105 ms -> 0.05028 ms +f16o 4 10240 4 512 -1086327840 # 0.247013 ms -> 0.0543863 ms +f16o 4 10240 4 768 -1086327840 # 0.253867 ms -> 0.061 ms +f16o 4 10240 4 1024 -1086327850 # 0.255293 ms -> 0.0801467 ms +f16o 4 10240 4 1536 -1086327840 # 0.2556 ms -> 0.1116 ms +f16o 4 10240 4 2048 -1086327815 # 0.305107 ms -> 0.142907 ms +f16o 4 10240 4 4096 -1086327922 # 0.489133 ms -> 0.253813 ms +f16o 4 10240 4 8192 -1086327922 # 1.16808 ms -> 0.48448 ms +f16o 1 2560 1 256 -9 # 0.0432533 ms -> 0.00812 ms +f16o 1 2560 1 512 -9 # 0.2 ms -> 0.0107333 ms +f16o 1 2560 1 768 -9 # 0.0864667 ms -> 0.0125333 ms +f16o 1 2560 1 1024 -9 # 0.0914133 ms -> 0.0166533 ms +f16o 1 2560 1 1536 -9 # 0.09308 ms -> 0.0197333 ms +f16o 1 2560 1 2048 -9 # 0.120027 ms -> 0.030653 ms +f16o 1 2560 1 4096 -9 # 0.0734267 ms -> 0.04152 ms +f16o 1 2560 1 8192 -9 # 0.200733 ms -> 0.07284 ms diff --git a/tools/hip/tune_rocblas.cpp b/tools/hip/tune_rocblas.cpp new file mode 100644 index 00000000..dfd466b5 --- /dev/null +++ b/tools/hip/tune_rocblas.cpp @@ -0,0 +1,281 @@ +// tools/hip/tune_rocblas.cpp - a rocBLAS tuning table for the prompt path's FP16-out GEMMs (gfx103x, prompt_f16()). +// +// On RDNA2 the prompt path's dense products run as rocBLAS FP16 in -> FP16 out (docs/AMD_HIP.md, "RDNA2"). rocBLAS +// picks its kernel from a table by shape, and for some shapes that pick is far from the best kernel the library has: +// on an RX 6900 XT, N=10240 K=2560 (the GDN input projection) below T=1152 tokens runs at 5 TFLOPS where the best of +// rocBLAS's own 237 solutions for the same shape runs at 32 (E270, 2026-10-05). This tool enumerates the library's +// solutions for each shape (rocblas_gemm_ex_get_solutions), times them, checks each against the default kernel's +// output, and writes the rows where a solution beats the default by at least --min-gain (1.05 = 5%) as a table the +// engine reads through STRATA_ROCBLAS_TUNING (src/prefill/rocblas_tuning.hpp; Gemm::f16_inplace). +// +// Solution indices are valid only for one GPU architecture and one rocBLAS build (its version string, tweak hash +// included), so a table is calibrated on the card with the ROCm the engine runs with: +// +// cmake --build build-hip --target tune_rocblas +// ./build-hip/tune_rocblas --tuning-out tools/hip/-rocblas-.txt +// +// Defaults: the engine's 14 FP16 dense shapes at T = 256 ... 8192 (--tokens); --case T,N,K,ldy adds one shape. +#define ROCBLAS_BETA_FEATURES_API +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +#define HIP_CHECK(call) do { const hipError_t e = (call); if (e != hipSuccess) { \ + std::fprintf(stderr, "HIP %s:%d: %s: %s\n", __FILE__, __LINE__, #call, hipGetErrorString(e)); std::exit(2); } } while (0) +#define RB_CHECK(call) do { const rocblas_status e = (call); if (e != rocblas_status_success) { \ + std::fprintf(stderr, "rocBLAS %s:%d: %s: status=%d\n", __FILE__, __LINE__, #call, (int) e); std::exit(2); } } while (0) + +struct Buffer { + void* p = nullptr; + explicit Buffer(size_t bytes) { if (bytes) HIP_CHECK(hipMalloc(&p, bytes)); } + ~Buffer() { if (p) (void) hipFree(p); } + Buffer(const Buffer&) = delete; + Buffer& operator=(const Buffer&) = delete; +}; + +struct Shape { int t, n, k, ldy; }; +struct Options { + std::vector shapes; + std::vector tokens{256, 512, 768, 1024, 1536, 2048, 4096, 8192}; + std::string tuning_out; + double min_gain = 1.05; + bool explicit_shapes = false; +}; +struct Err { double rel_l2 = 0, max_abs = 0; bool finite = true, ok = true; size_t padding_writes = 0; }; +struct Row { Shape s; bool tuned; int solution; float default_ms, best_ms; }; + +constexpr int WARMUPS = 2, REPS = 3, TOP = 8; +constexpr uint16_t CANARY = 0x7BFF; // the largest finite FP16 (65504): never a product of (-1, 1) inputs + +uint16_t f16_bits(float x) { const __half h = __float2half_rn(x); uint16_t b; std::memcpy(&b, &h, 2); return b; } +float f16_value(uint16_t b) { __half h; std::memcpy(&h, &b, 2); return __half2float(h); } + +std::vector csv(const std::string& s) { + std::vector out; size_t b = 0; + for (;;) { + const size_t p = s.find(',', b); + out.push_back(s.substr(b, p == std::string::npos ? p : p - b)); + if (p == std::string::npos) return out; + b = p + 1; + } +} +int positive(const std::string& s, const char* label) { + char* e = nullptr; const long v = std::strtol(s.c_str(), &e, 10); + if (s.empty() || !e || *e || v < 1 || v > std::numeric_limits::max()) { + std::fprintf(stderr, "invalid %s: %s\n", label, s.c_str()); std::exit(2); + } + return (int) v; +} +void usage(const char* p) { + std::printf("Usage: %s [--case T,N,K,ldy]... [--tokens T1,T2,...] [--min-gain 1.05] [--tuning-out PATH]\n", p); + std::printf("Defaults: the engine's 14 FP16 dense shapes (ldy = N) at T = 256,512,768,1024,1536,2048,4096,8192.\n"); +} +Options options(int argc, char** argv) { + Options o; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + auto next = [&]() -> std::string { + if (i + 1 >= argc) { std::fprintf(stderr, "missing option value\n"); std::exit(2); } + return argv[++i]; + }; + if (a == "-h" || a == "--help") { usage(argv[0]); std::exit(0); } + else if (a == "--case") { + const auto f = csv(next()); + if (f.size() != 4) { std::fprintf(stderr, "--case expects T,N,K,ldy\n"); std::exit(2); } + const Shape s{positive(f[0], "T"), positive(f[1], "N"), positive(f[2], "K"), positive(f[3], "ldy")}; + if (s.ldy < s.n) { std::fprintf(stderr, "ldy must be >= N\n"); std::exit(2); } + o.shapes.push_back(s); o.explicit_shapes = true; + } else if (a == "--tokens") { + o.tokens.clear(); + for (const auto& x : csv(next())) o.tokens.push_back(positive(x, "token bucket")); + } else if (a == "--min-gain") { o.min_gain = std::atof(next().c_str()); if (o.min_gain < 1.0) o.min_gain = 1.0; } + else if (a == "--tuning-out") o.tuning_out = next(); + else { std::fprintf(stderr, "unknown option: %s\n", a.c_str()); usage(argv[0]); std::exit(2); } + } + if (!o.explicit_shapes) { + // Qwen3.8-Flash-Next's dense FP16 products, prompt_f16() on (the hc read, GDN and QSA projections, the router + // and the shared expert), ldy = N for every one of them. N K as the engine calls Gemm (ROCBLAS_LAYER=2). + const int nk[][2] = {{10240, 2560}, {12288, 2560}, {6144, 2560}, {2560, 6144}, {2560, 640}, {2560, 2560}, + {640, 2560}, {512, 2560}, {128, 2560}, {48, 2560}, {320, 10240}, {10240, 320}, + {4, 10240}, {1, 2560}}; + for (const auto& p : nk) for (int t : o.tokens) o.shapes.push_back({t, p[0], p[1], p[0]}); + } + return o; +} + +float time_ms(hipStream_t stream, hipEvent_t a, hipEvent_t b, const std::function& f, int reps, + bool& ok) { + HIP_CHECK(hipEventRecord(a, stream)); + for (int i = 0; i < reps; ++i) if (f() != rocblas_status_success) { ok = false; return 0; } + HIP_CHECK(hipEventRecord(b, stream)); + HIP_CHECK(hipEventSynchronize(b)); + float ms = 0; HIP_CHECK(hipEventElapsedTime(&ms, a, b)); + ok = true; + return ms / reps; +} + +// The candidate's FP16 output against the default kernel's, over the N x T results; the rest of each 2*ldy-half column +// (what the engine's widen_rows_f16 does not cover) must still hold the canary. +Err compare(const std::vector& ref, const std::vector& got, const Shape& s) { + Err e; long double d2 = 0, r2 = 0; float max_ref = 0; + const size_t ldc = (size_t) s.ldy * 2; + for (int col = 0; col < s.t; ++col) { + for (int row = 0; row < s.n; ++row) { + const float r = f16_value(ref[col * ldc + row]), g = f16_value(got[col * ldc + row]); + if (!std::isfinite(r) || !std::isfinite(g)) { e.finite = false; continue; } + const double d = (double) g - r; + d2 += (long double) d * d; r2 += (long double) r * r; + e.max_abs = std::max(e.max_abs, std::abs(d)); max_ref = std::max(max_ref, std::abs(r)); + } + for (size_t row = s.n; row < ldc; ++row) if (got[col * ldc + row] != CANARY) ++e.padding_writes; + } + e.rel_l2 = std::sqrt((double) (d2 / std::max(r2, 1e-300L))); + // the two kernels sum K products in different orders, then both round to FP16: a few last-bit differences + const float ulp = std::ldexp(1.0f, (int) std::floor(std::log2(std::max(max_ref, 1e-30f))) - 10); + e.ok = e.finite && e.padding_writes == 0 && e.rel_l2 <= 2e-3 && e.max_abs <= 4.0 * ulp; + return e; +} +} // namespace + +int main(int argc, char** argv) { + const Options o = options(argc, argv); + rocblas_handle h; RB_CHECK(rocblas_create_handle(&h)); + hipStream_t stream; HIP_CHECK(hipStreamCreateWithFlags(&stream, hipStreamNonBlocking)); + RB_CHECK(rocblas_set_stream(h, stream)); + char ver[128] = {0}; RB_CHECK(rocblas_get_version_string(ver, sizeof ver)); + int device = 0; hipDeviceProp_t prop{}; + HIP_CHECK(hipGetDevice(&device)); HIP_CHECK(hipGetDeviceProperties(&prop, device)); + std::string arch(prop.gcnArchName); if (const auto c = arch.find(':'); c != std::string::npos) arch.resize(c); + std::printf("meta device_arch=%s rocblas_version=%s shapes=%zu min_gain=%.3f\n", arch.c_str(), ver, o.shapes.size(), o.min_gain); + hipEvent_t ea, eb; HIP_CHECK(hipEventCreate(&ea)); HIP_CHECK(hipEventCreate(&eb)); + + std::vector rows; + for (size_t ci = 0; ci < o.shapes.size(); ++ci) { + const Shape& s = o.shapes[ci]; + const size_t na = (size_t) s.n * s.k, nb = (size_t) s.t * s.k, ldc = (size_t) s.ldy * 2, nc = ldc * s.t; + std::vector ha(na), hb(nb), canary(nc, CANARY); + std::mt19937 rng(0x5A17C3u + (uint32_t) ci * 0x10001u); + std::uniform_real_distribution dist(-1.0f, 1.0f); + for (auto& x : ha) x = f16_bits(dist(rng)); + for (auto& x : hb) x = f16_bits(dist(rng)); + Buffer da(na * 2), db(nb * 2), dc(nc * 2); + HIP_CHECK(hipMemcpy(da.p, ha.data(), na * 2, hipMemcpyHostToDevice)); + HIP_CHECK(hipMemcpy(db.p, hb.data(), nb * 2, hipMemcpyHostToDevice)); + const float alpha = 1.0f, beta = 0.0f; + // the engine's call (Gemm::f16_inplace): C[N x T] = W^T . X, FP16 out, ldc = 2 * ldy halves + auto gemm = [&](rocblas_gemm_algo algo, int32_t sol) { + return rocblas_gemm_ex(h, rocblas_operation_transpose, rocblas_operation_none, s.n, s.t, s.k, &alpha, + da.p, rocblas_datatype_f16_r, s.k, db.p, rocblas_datatype_f16_r, s.k, &beta, dc.p, + rocblas_datatype_f16_r, (int) ldc, dc.p, rocblas_datatype_f16_r, (int) ldc, + rocblas_datatype_f32_r, algo, sol, 0); + }; + bool ok = true; + HIP_CHECK(hipMemcpy(dc.p, canary.data(), nc * 2, hipMemcpyHostToDevice)); + for (int i = 0; i < WARMUPS; ++i) RB_CHECK(gemm(rocblas_gemm_algo_standard, 0)); + const float default_ms = time_ms(stream, ea, eb, [&] { return gemm(rocblas_gemm_algo_standard, 0); }, REPS, ok); + HIP_CHECK(hipDeviceSynchronize()); + std::vector ref(nc); + HIP_CHECK(hipMemcpy(ref.data(), dc.p, nc * 2, hipMemcpyDeviceToHost)); + const Err self = compare(ref, ref, s); + std::printf("case T=%d N=%d K=%d ldy=%d default_ms=%.4f default_padding_writes=%zu\n", s.t, s.n, s.k, s.ldy, + default_ms, self.padding_writes); + + rocblas_int count = 0; + auto solutions = [&](rocblas_int* list, rocblas_int* n) { + return rocblas_gemm_ex_get_solutions(h, rocblas_operation_transpose, rocblas_operation_none, s.n, s.t, s.k, + &alpha, da.p, rocblas_datatype_f16_r, s.k, db.p, rocblas_datatype_f16_r, + s.k, &beta, dc.p, rocblas_datatype_f16_r, (int) ldc, dc.p, + rocblas_datatype_f16_r, (int) ldc, rocblas_datatype_f32_r, + rocblas_gemm_algo_solution_index, 0, list, n); + }; + if (solutions(nullptr, &count) != rocblas_status_success || count <= 0) { + std::printf("no_solutions T=%d N=%d K=%d ldy=%d\n", s.t, s.n, s.k, s.ldy); + continue; + } + std::vector ids(count); + RB_CHECK(solutions(ids.data(), &count)); + // pass 1: one timed call each; pass 2: the TOP fastest get the full measurement and the output check + std::vector> quick; + for (rocblas_int id : ids) { + if (gemm(rocblas_gemm_algo_solution_index, id) != rocblas_status_success) continue; + const float ms = time_ms(stream, ea, eb, [&] { return gemm(rocblas_gemm_algo_solution_index, id); }, 1, ok); + if (ok) quick.push_back({ms, id}); + } + std::sort(quick.begin(), quick.end()); + rocblas_int best = 0; float best_ms = std::numeric_limits::infinity(); + for (size_t i = 0; i < quick.size() && i < (size_t) TOP; ++i) { + const rocblas_int id = quick[i].second; + HIP_CHECK(hipMemcpy(dc.p, canary.data(), nc * 2, hipMemcpyHostToDevice)); + for (int w = 0; w < WARMUPS; ++w) if (gemm(rocblas_gemm_algo_solution_index, id) != rocblas_status_success) { ok = false; break; } + if (!ok) continue; + const float ms = time_ms(stream, ea, eb, [&] { return gemm(rocblas_gemm_algo_solution_index, id); }, REPS, ok); + if (!ok) continue; + HIP_CHECK(hipDeviceSynchronize()); + std::vector got(nc); + HIP_CHECK(hipMemcpy(got.data(), dc.p, nc * 2, hipMemcpyDeviceToHost)); + Err e = compare(ref, got, s); + // the engine applies a row to every T nearest its bucket, and a kernel can refuse a T it was not + // measured at (a tile or grid predicate): the solution must also run at odd, smaller token counts + bool accepts_neighbors = true; + for (int tn : {s.t - 1, s.t - 37, s.t - 63, s.t / 2 + 1}) { + if (tn < 1) continue; + const rocblas_status st = rocblas_gemm_ex( + h, rocblas_operation_transpose, rocblas_operation_none, s.n, tn, s.k, &alpha, da.p, + rocblas_datatype_f16_r, s.k, db.p, rocblas_datatype_f16_r, s.k, &beta, dc.p, rocblas_datatype_f16_r, + (int) ldc, dc.p, rocblas_datatype_f16_r, (int) ldc, rocblas_datatype_f32_r, + rocblas_gemm_algo_solution_index, id, 0); + if (st != rocblas_status_success) { accepts_neighbors = false; break; } + } + HIP_CHECK(hipDeviceSynchronize()); + e.ok = e.ok && accepts_neighbors; + std::printf(" solution=%d ms=%.4f gain=%.2f relative_l2=%.3g max_abs=%.3g padding_writes=%zu %s%s\n", (int) id, + ms, default_ms / ms, e.rel_l2, e.max_abs, e.padding_writes, e.ok ? "ok" : "REJECT", + accepts_neighbors ? "" : " (refuses a smaller T)"); + if (e.ok && ms < best_ms) { best = id; best_ms = ms; } + } + if (std::isfinite(best_ms) && default_ms / best_ms >= o.min_gain) { + std::printf("best T=%d N=%d K=%d ldy=%d solution=%d ms=%.4f default_ms=%.4f gain=%.2f\n", s.t, s.n, s.k, s.ldy, + (int) best, best_ms, default_ms, default_ms / best_ms); + rows.push_back({s, true, (int) best, default_ms, best_ms}); + } else { + // written too: the engine applies a row to the token counts nearest its bucket, and a `default` row keeps + // a neighbouring bucket's solution from reaching token counts where the default kernel measured best + std::printf("keep_default T=%d N=%d K=%d ldy=%d (%zu solutions; best %.4f ms vs default %.4f)\n", s.t, s.n, s.k, + s.ldy, quick.size(), best_ms, default_ms); + rows.push_back({s, false, 0, default_ms, best_ms}); + } + } + + if (!o.tuning_out.empty()) { + std::ofstream f(o.tuning_out); + if (!f) { std::fprintf(stderr, "cannot write tuning output: %s\n", o.tuning_out.c_str()); return 2; } + f << "# rocBLAS solution indices for the prompt path's FP16-out GEMMs; valid for this architecture and rocBLAS build only\n"; + f << "# rows: type N K ldy T solution (type f16o: FP16 in, FP16 out, FP32 compute; Gemm::f16_inplace)\n"; + f << "# solution: rocBLAS's solution index, or `default` where its own choice measured best at that bucket\n"; + f << "STRATA_ROCBLAS_TUNING_V1 " << arch << " " << ver << "\n"; + size_t tuned = 0; + for (const auto& r : rows) { + f << "f16o " << r.s.n << " " << r.s.k << " " << r.s.ldy << " " << r.s.t << " "; + if (r.tuned) { f << r.solution << " # " << r.default_ms << " ms -> " << r.best_ms << " ms\n"; ++tuned; } + else f << "default # " << r.default_ms << " ms\n"; + } + std::printf("wrote %zu rows (%zu with a solution) to %s\n", rows.size(), tuned, o.tuning_out.c_str()); + } + HIP_CHECK(hipEventDestroy(ea)); HIP_CHECK(hipEventDestroy(eb)); + HIP_CHECK(hipStreamDestroy(stream)); RB_CHECK(rocblas_destroy_handle(h)); + return 0; +} From 4b3e4d096f60bdbb50769d9e4975fdeca36f20fd Mon Sep 17 00:00:00 2001 From: xjc10 <69450118+xjc10@users.noreply.github.com> Date: Wed, 7 Oct 2026 20:45:27 -0400 Subject: [PATCH 12/17] rocBLAS table docs: the shipped gfx1030 table was measured on an RX 6900 XT; other gfx1030 cards can make their own with tune_rocblas (reports welcome) --- docs/AMD_HIP.md | 5 ++++- tools/hip/gfx1030-rocblas-5.6.0.8d1ae90e.txt | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index d8e5573c..63991377 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -490,7 +490,10 @@ run it; the report below is from a community machine: an RX 6900 XT 16 GB (gfx10 the directory, from which it takes the file of its own rocBLAS build) and runs those solutions in place of rocBLAS's choice, the default kernel for every shape without a row. Solution indices are valid for one architecture and one rocBLAS build (the full version string, `5.6.0.8d1ae90e` for ROCm 10.0.0's), and the engine refuses any other - table. Shipped: `gfx1030-rocblas-5.6.0.8d1ae90e.txt` (ROCm 10.0.0, the `/opt/rocm` setup installs on Ubuntu); setup + table. Shipped: `gfx1030-rocblas-5.6.0.8d1ae90e.txt` (ROCm 10.0.0, the `/opt/rocm` setup installs on Ubuntu), measured + on an RX 6900 XT. Other gfx1030 cards (RX 6800 / 6800 XT / 6950 XT, Radeon PRO W6800 / V620) run it as well - the + indices are valid on every gfx1030 - but have fewer CUs or other clocks, so their own table may pick differently; + `tune_rocblas` makes one in about 5 minutes ([Tuning table](#tuning-table)), and a report of what it changed is welcome. Setup points the engine at the directory when a table for the card's architecture exists, and the engine's log says `rocBLAS tuning enabled (... rows ...)` or why not. Measured on the 2x RX 6900 XT machine above (one card, #835 + this, `STRATA_PREFILL_TIMING=1`, temperature 0, the same answers with and without): a 799-token prompt's GPU time diff --git a/tools/hip/gfx1030-rocblas-5.6.0.8d1ae90e.txt b/tools/hip/gfx1030-rocblas-5.6.0.8d1ae90e.txt index 717c3b52..b1badd74 100644 --- a/tools/hip/gfx1030-rocblas-5.6.0.8d1ae90e.txt +++ b/tools/hip/gfx1030-rocblas-5.6.0.8d1ae90e.txt @@ -1,6 +1,7 @@ # rocBLAS solution indices for the prompt path's FP16-out GEMMs; valid for this architecture and rocBLAS build only # rows: type N K ldy T solution (type f16o: FP16 in, FP16 out, FP32 compute; Gemm::f16_inplace) # solution: rocBLAS's solution index, or `default` where its own choice measured best at that bucket +# measured on an RX 6900 XT (80 CUs); another gfx1030 card can make its own with tools/hip/tune_rocblas STRATA_ROCBLAS_TUNING_V1 gfx1030 5.6.0.8d1ae90e f16o 10240 2560 10240 256 -1086327703 # 2.35815 ms -> 0.347774 ms f16o 10240 2560 10240 512 -1086327703 # 4.93049 ms -> 0.674375 ms From 4f21be8723172cd8c1fa44093a83a8644bfa73e1 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 07:12:53 +0200 Subject: [PATCH 13/17] hip: the FP32 tiled QSA block scorer on HIP cards (opt-in STRATA_SELECT_SIMT=1, as on CUDA), tiled 32/128/16/8 on gfx103x The scorer of 65ce329 is plain FP32 arithmetic, so it runs on any HIP card as it is; without matrix cores the prompt path otherwise scores on the warp kernel. Its tiling becomes template parameters: every tiling keeps each score's fmaf chain over k = 0..127 in order and the same relu sum over the heads, so every tiling gives the same bytes (RX 6900 XT, qsa_select_bench at 32K and 128K: 14 tilings, also on 60 and 72 of its 80 CUs through HSA_CU_MASK, all byte-identical to the original kernel; the fastest tiling the same at every width). CUDA keeps the tiling it was written with; gfx103x runs 32/128/16/8: 256 queries at 128K 2.69 ms (warp kernel) -> 0.695 ms (the original tiling) -> 0.587 ms. FP64 gate passed, selections identical 256/256. On the 2x RX 6900 XT layer split a 128K-token prompt reads 7.4% faster, 32K 0.8%. A HIP ctest runs it at 131K. Rebased onto 296b59d2: the docs/AMD_HIP.md conflict (main's SGEMM/rocBLAS-table bullets from the ports before it) is resolved by keeping all bullets. Co-authored-by: xjc10 <69450118+xjc10@users.noreply.github.com> --- CMakeLists.txt | 3 + .../README.md | 79 ++++++++++++ docs/AMD_HIP.md | 11 ++ src/kernels/cuda/qsa_select.cu | 121 ++++++++++++------ 4 files changed, 178 insertions(+), 36 deletions(-) create mode 100644 bench/results/2026-10-07-rdna2-qsa-select-simt/README.md diff --git a/CMakeLists.txt b/CMakeLists.txt index f0d43616..8c15ec2a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -417,6 +417,9 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) set_source_files_properties(src/kernels/qsa_select_bench.cpp PROPERTIES LANGUAGE HIP) target_link_libraries(qsa_select_bench PRIVATE strata_kernels strata_hip_runtime) add_test(NAME qsa_select_bench COMMAND qsa_select_bench 32768 256 3 262144) + # the FP32 tiled scorer (STRATA_SELECT_SIMT=1) on HIP: FP64 gate and selections against the warp kernel at 131K + add_test(NAME qsa_select_bench_fp32_tiled COMMAND qsa_select_bench 131072 256 3 262144) + set_tests_properties(qsa_select_bench_fp32_tiled PROPERTIES ENVIRONMENT "STRATA_SELECT_SIMT=1") endif() # the same on CUDA: the tensor-core scorer (sm_80+) or the FP32 tiled one (below sm_80, and forced on any card by # STRATA_QSA_WARP=1 in the second test) against the warp kernel and FP64, at 32K and 131K diff --git a/bench/results/2026-10-07-rdna2-qsa-select-simt/README.md b/bench/results/2026-10-07-rdna2-qsa-select-simt/README.md new file mode 100644 index 00000000..f3581857 --- /dev/null +++ b/bench/results/2026-10-07-rdna2-qsa-select-simt/README.md @@ -0,0 +1,79 @@ +# RX 6900 XT (gfx1030): the FP32 tiled QSA block scorer on HIP (2026-10-07) + +`STRATA_SELECT_SIMT=1` runs the FP32 tiled scorer of 65ce329 (konijiwa110's #742) on HIP cards too, tiled +32/128/16/8 on gfx103x. Without it the prompt path scores the QSA blocks on the warp kernel, as before. + +## Rig + +- 2x RX 6900 XT 16 GB (gfx1030, PCIe 4.0 x8 each), Ryzen 5 5600X, 128 GB DDR4-3200, Ubuntu 26.04, Linux 7.0, ROCm 10.0.0. +- Engine: `origin/main` at `d5ea713` (0.1.40.3) with this change, built with `-DSTRATA_ENABLE_HIP=ON + -DCMAKE_HIP_ARCHITECTURES=gfx1030 -DSTRATA_PREFILL_MMQ=ON -DSTRATA_NATIVE_EXPERTS=ON`. +- Model: Qwen3.8-Flash-Next GSQ-RCO IQ3_S, MTP head, layer split over both cards, `--kv int8 --kv-resident 32768 + --max-context 131072 --ple-io ram --spec 4`, `STRATA_HIP_PROMPT_F16=1 STRATA_SH_STREAM=1 + STRATA_HIP_ADAPT_KERNEL_COPY=1 STRATA_PREFILL_CPU_SHARE=auto STRATA_IO_THREADS=128`. + +## `qsa_select_bench`, one card, 256 queries (two runs each, min / max) + +Every tiling below gave scores byte-identical to the original kernel (the valid cells of every query, 33.5 MB at 128K +and 8.4 MB at 32K, compared with `cmp`), passed the FP64 gate and selected the same blocks as the warp kernel for +256/256 queries. Warp kernel: 2.69-2.74 ms at 128K, 0.67 ms at 32K. + +| tiling QT/NB/KC/TN | 128K ms | 32K ms | +|---|---:|---:| +| 32/64/32/4 (the original) | 0.695 / 0.695 | 0.186 / 0.186 | +| 32/128/16/8 (this PR, gfx103x) | 0.587 / 0.591 | 0.169 / 0.171 | +| 16/128/16/4 | 0.592 / 0.593 | 0.165 / 0.166 | +| 16/256/16/8 | 0.609 / 0.610 | 0.173 / 0.174 | +| 32/128/8/8 | 0.612 / 0.614 | 0.190 / 0.195 | +| 64/64/16/8 | 0.621 / 0.623 | 0.180 / 0.183 | +| 16/128/32/4 | 0.666 / 0.669 | 0.180 / 0.180 | +| 8/256/16/4 | 0.706 / 0.712 | 0.193 / 0.194 | +| 16/128/8/4 | 0.765 / 0.783 | 0.306 / 0.308 | +| 32/256/16/16 | 0.955 / 0.962 | 0.286 / 0.288 | +| 64/128/16/16 | 0.969 / 0.980 | 0.287 / 0.294 | + +The width does not move the ranking: 128K, the card restricted to 72 and 60 of its 80 CUs with `HSA_CU_MASK` +(the original tiling slows 1.40x at 60 CUs, so the mask takes effect). Scores byte-identical at every width too. + +| tiling | 80 CUs | 72 CUs | 60 CUs | +|---|---:|---:|---:| +| 32/64/32/4 | 0.694 | 0.764 | 0.970 | +| 32/128/16/8 | 0.587 | 0.645 | 0.795 | +| 16/128/32/4 | 0.666 | 0.734 | 0.929 | +| 32/128/32/8 | 0.717 | 0.784 | 0.993 | +| 64/64/32/8 | 0.751 | 0.817 | 1.030 | +| 32/64/64/4 | 0.837 | 0.926 | 1.178 | + +## End to end + +`benchmark.py` (synthetic prompts with a fresh nonce each, temperature 0, 256 generated tokens), one cold server per +arm, ABBA. Prompt medians, SIMT against the warp kernel: 128K +7.3% and +7.5%, 32K +0.8% and +0.8%. The scores' +summation order changes the generated text, so decode speed is not comparable between the arms (each arm's own two +starts gave the same text, except one 128K request between the two warp-kernel starts). No stalls. + +| arm | request | prompt tokens | prompt tok/s | decode tok/s | +|---|---|---:|---:|---:| +| warp-1 | 32768-run-1 | 32,768 | 1,561 | 60.1 | +| warp-1 | 32768-run-2 | 32,768 | 1,571 | 66.7 | +| warp-1 | 32768-run-3 | 32,768 | 1,573 | 67.8 | +| warp-1 | 128000-run-1 | 128,000 | 1,745 | 60.3 | +| warp-1 | 128000-run-2 | 128,000 | 1,735 | 65.5 | +| warp-1 | 128000-run-3 | 128,000 | 1,701 | 68.5 | +| simt-1 | 32768-run-1 | 32,768 | 1,562 | 64.0 | +| simt-1 | 32768-run-2 | 32,768 | 1,586 | 65.3 | +| simt-1 | 32768-run-3 | 32,768 | 1,584 | 72.2 | +| simt-1 | 128000-run-1 | 128,000 | 1,862 | 62.8 | +| simt-1 | 128000-run-2 | 128,000 | 1,861 | 66.8 | +| simt-1 | 128000-run-3 | 128,000 | 1,854 | 68.3 | +| simt-2 | 32768-run-1 | 32,768 | 1,547 | 63.7 | +| simt-2 | 32768-run-2 | 32,768 | 1,582 | 65.2 | +| simt-2 | 32768-run-3 | 32,768 | 1,574 | 71.9 | +| simt-2 | 128000-run-1 | 128,000 | 1,867 | 62.8 | +| simt-2 | 128000-run-2 | 128,000 | 1,858 | 66.7 | +| simt-2 | 128000-run-3 | 128,000 | 1,849 | 68.4 | +| warp-2 | 32768-run-1 | 32,768 | 1,540 | 60.0 | +| warp-2 | 32768-run-2 | 32,768 | 1,564 | 66.7 | +| warp-2 | 32768-run-3 | 32,768 | 1,561 | 67.7 | +| warp-2 | 128000-run-1 | 128,000 | 1,729 | 60.3 | +| warp-2 | 128000-run-2 | 128,000 | 1,727 | 63.2 | +| warp-2 | 128000-run-3 | 128,000 | 1,724 | 69.0 | diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 63991377..2b443dd3 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -503,6 +503,17 @@ run it; the report below is from a community machine: an RX 6900 XT 16 GB (gfx10 reappeared as `wait copy`, the experts' PCIe transfer, which bounds that prompt. Per-run lines and the tuner's summary: [bench/results/2026-10-05-rdna2-rocblas-table](../bench/results/2026-10-05-rdna2-rocblas-table/README.md). Decode does not use these GEMMs and is unchanged. See [Tuning table](#tuning-table) for making a table for another rocBLAS build. +- **QSA block scores on the FP32 tiled scorer (`STRATA_SELECT_SIMT=1`, opt-in, as on CUDA below sm_80):** without + matrix cores the prompt path's QSA selection scores every (query, KV block) pair on the warp kernel, the one prompt + term that grows with the context. The switch runs the FP32 tiled scorer instead (FP32 in another summation order: + not bitwise the warp kernel, so off by default), tiled 32/128/16/8 on gfx103x. `qsa_select_bench`, 256 queries: + 2.69 -> 0.587 ms at 128K (the original 32/64/32/4 tiling: 0.695), 0.67 -> 0.169 ms at 32K; FP64 gate passed, + selections identical 256/256. Every tiling gives the same bytes (each score is one fmaf chain over k in order), and + the fastest tiling was the same with 60 and 72 of the card's 80 CUs (`HSA_CU_MASK`). On the 2x RX 6900 XT split + (0.1.40.3, IQ3_S, `--kv int8 --kv-resident 32768`, two cold starts per arm, ABBA) a 128K-token prompt reads 1,735 -> + 1,861 and 1,727 -> 1,858 tok/s (+7.4%), 32K +0.8%; decode is not affected (the text changes with the scores' order, + so its speed is not compared). Measurements: + [bench/results/2026-10-07-rdna2-qsa-select-simt](../bench/results/2026-10-07-rdna2-qsa-select-simt/README.md). - **Windows** (the report above): setup's ready-made Windows engine 0.1.39 runs the RX 6800 beside a 780M iGPU (HIP numbers the RX 6800 1; setup points the engine at it), and `tools/hip/build_windows.bat` with `STRATA_HIP_ARCHS=gfx1030` builds a working engine from the `gfx103X-all` 10.2.0a20260930 wheels. diff --git a/src/kernels/cuda/qsa_select.cu b/src/kernels/cuda/qsa_select.cu index cb06396a..6a2ae9be 100644 --- a/src/kernels/cuda/qsa_select.cu +++ b/src/kernels/cuda/qsa_select.cu @@ -8,6 +8,7 @@ #include +#include #include #include #include @@ -458,6 +459,19 @@ bool sel_gfx12_device() { } return ok[dev] == 1; } + +// RDNA2 (gfx1030-gfx1036): the FP32 tiled scorer's tiling measured there +bool sel_gfx103_device() { + static int ok[64] = {}; // per device: 0 unknown, 1 yes, 2 no + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } + if (ok[dev] == 0) { + cudaDeviceProp prop; + ok[dev] = (cudaGetDeviceProperties(&prop, dev) == cudaSuccess && std::strncmp(prop.gcnArchName, "gfx103", 6) == 0) ? 1 : 2; + cudaGetLastError(); + } + return ok[dev] == 1; +} #endif // __HIPCC__ // the tail block n_bid of each query: exactly block_scores_kernel's arithmetic for that block @@ -487,51 +501,61 @@ __global__ void __launch_bounds__(32) block_scores_tail_kernel(const float* __re } } -// ---- the block scores as an FP32 tiled GEMM for CUDA cards without TF32 tensor cores (below sm_80): rows (query, -// indexer head) x columns (blocks), K = 128 through shared memory, 2 queries x 4 heads x 4 blocks per thread, relu per -// head summed in registers. The warp kernel spends 5 shuffles per 4 products and reached ~1 TFLOPS on an RTX 2080 -// Ti; this one ~6.9 (256 queries: 4.5x at 4K, 6.8x at 120K-250K). FP32 like the warp kernel in another summation -// order, so not bitwise (as the tensor-core scorer). Blocks < n_bid only; the tail block is block_scores_tail_kernel's. -constexpr int SM_QT = 32, SM_NB = 64, SM_KC = 32, SM_QS = SM_QT * IDX_HEADS + 4, SM_KS = SM_NB + 4; +// ---- the block scores as an FP32 tiled GEMM for cards without a matrix-core scorer (CUDA below sm_80; HIP, opt-in): +// rows (query, indexer head) x columns (blocks), K = 128 through shared memory, 2 queries x 4 heads x TN blocks per +// thread, relu per head summed in registers. The warp kernel spends 5 shuffles per 4 products and reached ~1 TFLOPS +// on an RTX 2080 Ti; this one ~6.9 (256 queries: 4.5x at 4K, 6.8x at 120K-250K). FP32 like the warp kernel in another +// summation order, so not bitwise (as the tensor-core scorer). Blocks < n_bid only; the tail block is +// block_scores_tail_kernel's. +// +// The tiling (QT queries and NB blocks per CTA, KC of K per shared-memory pass, TN blocks per thread) only decides +// which thread computes which score: every score is still the fmaf chain over k = 0..127 in order and the same relu sum +// over the heads, so every tiling gives the same bytes (an RX 6900 XT, qsa_select_bench at 32K and 128K, 14 tilings, +// also with 60 and 72 of its 80 CUs: all byte-identical). CUDA keeps the tiling it was written with (32/64/32/4); +// gfx103x runs 32/128/16/8, 15% faster there at 128K (0.695 -> 0.587 ms per 256 queries). +template __global__ void __launch_bounds__(256) block_scores_simt_kernel(const float* __restrict__ pooled, const float* __restrict__ q_idx, const int32_t* __restrict__ steps, int64_t nq, int64_t max_blocks, int64_t reach, float* __restrict__ out) { - __shared__ __align__(16) float Qs[SM_KC][SM_QS]; - __shared__ __align__(16) float Ks[SM_KC][SM_KS]; - const int64_t q0 = (int64_t) blockIdx.y * SM_QT, b0 = (int64_t) blockIdx.x * SM_NB; - const int64_t qlast = (q0 + SM_QT < nq ? q0 + SM_QT : nq) - 1; + constexpr int ROWS = QT * IDX_HEADS, QS = ROWS + 4, KS = NB + 4, CX = NB / TN; + static_assert((ROWS / 8) * CX == 256, "256 threads, 8 rows (2 queries x 4 heads) each"); + static_assert(TN % 4 == 0 && KC % 4 == 0 && IDX_DIM % KC == 0, "float4 loads"); + __shared__ __align__(16) float Qs[KC][QS]; + __shared__ __align__(16) float Ks[KC][KS]; + const int64_t q0 = (int64_t) blockIdx.y * QT, b0 = (int64_t) blockIdx.x * NB; + const int64_t qlast = (q0 + QT < nq ? q0 + QT : nq) - 1; if (b0 >= steps[qlast * kStepCount + kStepNBid]) return; // n_bid rises with the position - const int tid = threadIdx.x, tx = tid & 15, ty = tid >> 4; - float acc[8][4] = {}; - for (int kc = 0; kc < IDX_DIM; kc += SM_KC) { -#pragma unroll - for (int i = 0; i < 4; ++i) { // the query rows: 128 x 8 float4 - const int idx = tid + i * 256, r = idx >> 3, k4 = idx & 7; + const int tid = threadIdx.x, tx = tid % CX, ty = tid / CX; + float acc[8][TN] = {}; + for (int kc = 0; kc < IDX_DIM; kc += KC) { + for (int idx = tid; idx < ROWS * (KC / 4); idx += 256) { // the query rows: ROWS x KC/4 float4 + const int r = idx / (KC / 4), k4 = idx % (KC / 4); float4 v = make_float4(0.f, 0.f, 0.f, 0.f); if (q0 + (r >> 2) < nq) v = *reinterpret_cast(q_idx + (q0 * IDX_HEADS + r) * IDX_DIM + kc + k4 * 4); Qs[k4 * 4 + 0][r] = v.x; Qs[k4 * 4 + 1][r] = v.y; Qs[k4 * 4 + 2][r] = v.z; Qs[k4 * 4 + 3][r] = v.w; } -#pragma unroll - for (int i = 0; i < 2; ++i) { // the pooled keys: 64 x 8 float4 - const int idx = tid + i * 256, c = idx >> 3, k4 = idx & 7; + for (int idx = tid; idx < NB * (KC / 4); idx += 256) { // the pooled keys: NB x KC/4 float4 + const int c = idx / (KC / 4), k4 = idx % (KC / 4); float4 v = make_float4(0.f, 0.f, 0.f, 0.f); if (b0 + c < reach) v = *reinterpret_cast(pooled + (b0 + c) * IDX_DIM + kc + k4 * 4); Ks[k4 * 4 + 0][c] = v.x; Ks[k4 * 4 + 1][c] = v.y; Ks[k4 * 4 + 2][c] = v.z; Ks[k4 * 4 + 3][c] = v.w; } __syncthreads(); #pragma unroll 8 - for (int k = 0; k < SM_KC; ++k) { - const float4 qa = *reinterpret_cast(&Qs[k][ty * 8]); - const float4 qb = *reinterpret_cast(&Qs[k][ty * 8 + 4]); - const float4 kv = *reinterpret_cast(&Ks[k][tx * 4]); - const float qr[8] = {qa.x, qa.y, qa.z, qa.w, qb.x, qb.y, qb.z, qb.w}, kr[4] = {kv.x, kv.y, kv.z, kv.w}; + for (int k = 0; k < KC; ++k) { + float qr[8], kr[TN]; + *reinterpret_cast(&qr[0]) = *reinterpret_cast(&Qs[k][ty * 8]); + *reinterpret_cast(&qr[4]) = *reinterpret_cast(&Qs[k][ty * 8 + 4]); +#pragma unroll + for (int t = 0; t < TN; t += 4) + *reinterpret_cast(&kr[t]) = *reinterpret_cast(&Ks[k][tx * TN + t]); #pragma unroll for (int i = 0; i < 8; ++i) #pragma unroll - for (int j = 0; j < 4; ++j) acc[i][j] = fmaf(qr[i], kr[j], acc[i][j]); + for (int j = 0; j < TN; ++j) acc[i][j] = fmaf(qr[i], kr[j], acc[i][j]); } __syncthreads(); } @@ -541,8 +565,8 @@ __global__ void __launch_bounds__(256) block_scores_simt_kernel(const float* __r if (q >= nq) continue; const int64_t n_bid = steps[q * kStepCount + kStepNBid]; #pragma unroll - for (int j = 0; j < 4; ++j) { - const int64_t b = b0 + tx * 4 + j; + for (int j = 0; j < TN; ++j) { + const int64_t b = b0 + tx * TN + j; if (b >= n_bid || b >= max_blocks) continue; float sc = 0.0f; #pragma unroll @@ -555,6 +579,23 @@ __global__ void __launch_bounds__(256) block_scores_simt_kernel(const float* __r } } +// The FP32 tiled scores and the tail block; false when the grid does not fit. `rdna2_tiles`: gfx103x's tiling. +static bool block_scores_simt(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, + int64_t nq, int64_t max_blocks, int64_t reach, float* scores, cudaStream_t stream, + bool rdna2_tiles) { + const int64_t qt = 32, nb = rdna2_tiles ? 128 : 64; + const dim3 grid((unsigned) ((reach + nb - 1) / nb), (unsigned) ((nq + qt - 1) / qt)); + if (grid.y > 65535) return false; + if (rdna2_tiles) + block_scores_simt_kernel<32, 128, 16, 8><<>>(pooled, q_idx, steps, nq, max_blocks, reach, scores); + else + block_scores_simt_kernel<32, 64, 32, 4><<>>(pooled, q_idx, steps, nq, max_blocks, reach, scores); + block_scores_tail_kernel<<<(unsigned) nq, 32, 0, stream>>>(dead, q_idx, steps, max_blocks, scores); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores (simt): %s\n", cudaGetErrorString(e)); std::exit(1); } + return true; +} + // ---- the same top-k with each query's keys read once: 1,024 threads hold up to TK_PER consecutive blocks' keys in // registers (contexts up to 4 * 1024 * TK_PER cells), per-warp histograms, block-wide scans. The selection rule is // block_topk_kernel's (radix threshold, ties to the lowest index, cells ascending): identical ids. @@ -1129,6 +1170,21 @@ bool qsa_block_scores_tc(const float* pooled, const float* dead, const float* q_ const char* v = std::getenv("STRATA_SELECT_WMMA"); return v != nullptr && v[0] != '\0' && v[0] != '0'; }(); + // any HIP card: the FP32 tiled scorer, opt-in as on CUDA (STRATA_SELECT_SIMT=1; another summation order than the + // warp kernel, so the default keeps the warp kernel). RX 6900 XT, 256 queries at 128K: 2.71 -> 0.587 ms + static const bool simt_on = [] { + const char* v = std::getenv("STRATA_SELECT_SIMT"); + return v != nullptr && v[0] == '1'; + }(); + if (simt_on && !(wmma_on && sel_gfx12_device())) { + const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks; + const bool rdna2 = sel_gfx103_device(); + static std::atomic said{false}; + if (!said.exchange(true)) + std::fprintf(stderr, "qsa select: FP32 tiled scorer (STRATA_SELECT_SIMT=1), tiles %s\n", + rdna2 ? "32/128/16/8 (gfx103x)" : "32/64/32/4"); + return block_scores_simt(pooled, dead, q_idx, steps, nq, max_blocks, reach, scores, (cudaStream_t) stream, rdna2); + } if (!wmma_on || !sel_gfx12_device()) return false; { const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks; @@ -1164,15 +1220,8 @@ bool qsa_block_scores_tc(const float* pooled, const float* dead, const float* q_ }(); if (!simt) return false; const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks; - const dim3 grid((unsigned) ((reach + SM_NB - 1) / SM_NB), (unsigned) ((nq + SM_QT - 1) / SM_QT)); - if (grid.y > 65535) return false; - block_scores_simt_kernel<<>>(pooled, q_idx, steps, nq, max_blocks, - reach, scores); - block_scores_tail_kernel<<<(unsigned) nq, 32, 0, (cudaStream_t) stream>>>(dead, q_idx, steps, max_blocks, - scores); - const cudaError_t e = cudaGetLastError(); - if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores (simt): %s\n", cudaGetErrorString(e)); std::exit(1); } - return true; + return block_scores_simt(pooled, dead, q_idx, steps, nq, max_blocks, reach, scores, (cudaStream_t) stream, + false); } } static bool attr[64] = {}; // the shared-memory opt-in is per device (a layer split runs it on several) From eb6e0f1e4d7b699b751cbea788ac1e288a46917a Mon Sep 17 00:00:00 2001 From: Vop3p <69450118+Vop3p@users.noreply.github.com> Date: Sun, 11 Oct 2026 15:18:38 -0400 Subject: [PATCH 14/17] calibrate: measure the shared-expert stream fork on AMD (STRATA_SH_STREAM, off against on) and keep it per PC The fork stays off by default on HIP (#816, #826): an RX 6800 on Windows and 4x R9700 decode 12-45% faster without it. The same card family on another PC goes the other way (#1272: 2x RX 6900 XT on Linux), and the output is identical either way, so it is a per-PC choice - the open item of #1272. - tools/calibrate.py: step 6, HIP only. With everything chosen before, the engine is started twice, with STRATA_SH_STREAM=0 and =1 set explicitly, two rates each; "1" is kept only when it beats "0" by more than MIN_GAIN (the rule of the other steps). measure() returns the choice as "env"; a failed start drops that candidate (#1337). start_engine takes an optional env; apply_env() sets the chosen variables and removes the others of ENV_KEYS, so an older calibration's choice does not linger. - setup.py: --calibrate writes "env" into the config and the settings file; a reinstall applies a saved calibration's "env" the same way (a calibration saved before this step leaves "env" as it is). - docs/AMD_HIP.md: the SH_STREAM note says calibrate measures it. - tools/test_calibrate.py: the step runs on HIP only, keeps the fork only on a win, falls back on a failed start; apply_env; setup writes and later removes the variable. Measured with the real engine (0.1.42 tag, 2x RX 6900 XT gfx1030, Linux, IQ3_S layer split, setup-style config): the whole calibration took 982 s, the new step chose STRATA_SH_STREAM=1 (off 62.2 / 61.3, on 67.2 / 66.6 tok/s, +8.3%). Separately, with a fixed protocol, the fork's output is byte-identical to off (4 of 4 requests, one card and the split). --- docs/AMD_HIP.md | 5 +++- setup.py | 12 ++++++-- tools/calibrate.py | 55 ++++++++++++++++++++++++++++++++---- tools/test_calibrate.py | 62 +++++++++++++++++++++++++++++++++++++++-- 4 files changed, 123 insertions(+), 11 deletions(-) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 2b443dd3..3f978208 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -216,7 +216,10 @@ machine). Windows HIP: the doorbell kernels fence their store (#697), and the sh that default stays. The measurements disagree by platform. 2x RX 6900 XT on Linux (#1272): turning it off costs 5-13% of decode (one card 47.5 / 46.9 / 48.3 -> 50.5 / 48.5 / 51.3 tok/s with it on). RX 6800 on Windows (#816, `bench/results/2026-10-04-community-rx-6800-windows`): on was 12-22% slower. 4x R9700: fork off was 13-45% faster. -Linux RX 6000 users can try `STRATA_SH_STREAM=1`; the output is identical either way. +Linux RX 6000 users can try `STRATA_SH_STREAM=1`; the output is identical either way. Since the same card goes +both ways on different PCs, `./setup.sh --calibrate` measures it on yours (off against on, a restart each) and writes +`STRATA_SH_STREAM=1` into the config's `"env"` only when it wins by more than 3%; a later calibration that finds it no +longer faster removes it again. **The draft's side stream (`STRATA_MTP_SIDE_STREAM`):** HIP does not use the MTP drafter's branch stream, and since 0.1.40.2 it does not create it (#1240: an R9700 lost prompt speed with it). gfx103x is the exception and creates it: on diff --git a/setup.py b/setup.py index 79d0a819..6e28ec90 100644 --- a/setup.py +++ b/setup.py @@ -4766,13 +4766,17 @@ def calibrate_config(cfg_path: Path) -> bool: say(f" the engine said: {why}") return False cfg["args"] = CAL.apply(cfg["args"], res["settings"]) + if "env" in res: # HIP: the engine variables it measured (STRATA_SH_STREAM) + cfg["env"] = CAL.apply_env(cfg.get("env"), res["env"]) write_config(cfg_path, cfg) st = load_settings() - st.setdefault("calibration", {})[hardware_key(cfg)] = {"settings": res["settings"], "tok_s": res["report"].get("tok_s"), + st.setdefault("calibration", {})[hardware_key(cfg)] = {"settings": res["settings"], "env": res.get("env") or {}, + "tok_s": res["report"].get("tok_s"), "date": time.strftime("%Y-%m-%d")} save_settings(st) - if res["settings"]: - ok("tuned for this PC: " + ", ".join(f"{k} {v}" for k, v in res["settings"].items()) + chosen = {**res["settings"], **(res.get("env") or {})} + if chosen: + ok("tuned for this PC: " + ", ".join(f"{k} {v}" if k.startswith("--") else f"{k}={v}" for k, v in chosen.items()) + (f" ({res['report']['tok_s']} tok/s)" if res["report"].get("tok_s") else "")) else: ok("tuned for this PC: the default settings are already the fastest here" @@ -6812,6 +6816,8 @@ def main() -> int: sys.path.insert(0, str(ROOT / "tools")) import calibrate as CAL cfg["args"] = CAL.apply(cfg["args"], cal.get("settings") or {}) + if "env" in cal: # a calibration from before the env step leaves "env" as it is + cfg["env"] = CAL.apply_env(cfg.get("env"), cal["env"]) ok("the settings tuned for this PC earlier are used" + (f" ({cal['date']})" if cal.get("date") else "")) else: # #642: measured counts (a calibration) win over the rule cfg["args"] = recommend_pool_workers(cfg["args"]) diff --git a/tools/calibrate.py b/tools/calibrate.py index 3ed6a4c8..52dda9db 100644 --- a/tools/calibrate.py +++ b/tools/calibrate.py @@ -13,6 +13,11 @@ measured on (a Ryzen 5 7600 + RTX 5070 on PCIe 5): its use counts fade. A PC whose CPU reads the missed experts slowly (DDR3, ~24 GB/s) gains from swapping more: 160 swaps every window measured +7.9% over the default tier on a Xeon E5-2673 v3 (DDR3) with an RTX 4060 Ti on PCIe 3.0 x8 (Q2_0; with the swaps taking effect a window later, #764). + STRATA_SH_STREAM (AMD only) + the shared expert on its own stream. Off by default on HIP (#816: an RX 6800 on Windows and 4x R9700 + decode 12-45% faster without it), but the same card family on another PC goes the other way (#1272: + 2x RX 6900 XT on Linux, 6-11% faster with it), so it is measured here, per PC, and written into the + config's "env" only when it wins. The output is identical either way (same token ids). The first two are measured through one engine (per-request `strata_tune` keys); the worker count and the adaptive tier need a restart per value. Decode speed only: the prompt path streams every expert whatever these settings say. @@ -40,6 +45,8 @@ SPEC_MIN_PS = (0.3, 0.5, 0.7) SWEEP_ROUNDS = 3 # how many times the sweep visits each value (see `sweep`) # the adaptive tier's candidates (every, swaps, decay) against the engine's own (None): swapping more and remembering # longer, the rest of the set as the engine has it +# HIP: the shared-expert stream fork, off (the HIP default) against on; an engine environment variable, not an argument +SH_STREAM = "STRATA_SH_STREAM" ADAPT_CANDIDATES = (None, ("1", "80", "0.97"), ("1", "160", "0.97")) ADAPT_FLAGS = ("--adapt-every", "--adapt-swaps", "--adapt-decay") MAX_NEW = 128 @@ -139,8 +146,10 @@ def run(cfg: dict, say=print, start_engine=None) -> dict: if start_engine is None: from serve.server import StrataEngine, child_env - def start_engine(args): - return StrataEngine(cfg["exe"], args, cwd=cfg.get("cwd"), log=cfg.get("log"), env=child_env(cfg)) + def start_engine(args, env=None): + e = child_env(cfg) + e.update(env or {}) + return StrataEngine(cfg["exe"], args, cwd=cfg.get("cwd"), log=cfg.get("log"), env=e) import strata_tokenizer as ST tpath = Path(cfg["tokenizer"]) vocab = json.loads((tpath / "vocab.json").read_text(encoding="utf-8")) @@ -150,7 +159,7 @@ def run(cfg: dict, say=print, start_engine=None) -> dict: tok = ST.Tokenizer(toks, (tpath / "merges.txt").read_text(encoding="utf-8").split("\n"), json.loads((tpath / "token_type.json").read_text())) ids_list = [chat_ids(tok, p) for p in PROMPTS] - return measure(engine_args(cfg), ids_list, start_engine, say, host_worker_extras()) + return measure(engine_args(cfg), ids_list, start_engine, say, host_worker_extras(), hip=cfg.get("backend") == "hip") def engine_args(cfg: dict) -> list[str]: @@ -199,7 +208,7 @@ def sweep(s, values: list, base_tune: dict, key: str, label: str, say) -> dict: return out -def measure(base_args: list[str], ids_list, start_engine, say=print, extra_workers=()) -> dict: +def measure(base_args: list[str], ids_list, start_engine, say=print, extra_workers=(), hip: bool = False) -> dict: t0 = time.time() report: dict = {} say(" Loading the model for the measurements ...") @@ -290,9 +299,34 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke base_rate = statistics.median(by_adapt[a_best]) elif by_adapt.get("default"): base_rate = statistics.median(by_adapt["default"]) + # 6. HIP: the shared-expert stream fork (a restart each), with everything chosen so far. Both values are set + # explicitly, so a value the config carried before does not decide the baseline. + env = {} + if hip: + tuned = apply(base_args, settings) + by_fork = {} + for v in ("0", "1"): + say(f" Measuring the shared expert {'on its own stream' if v == '1' else 'on the main stream (the AMD default)'}" + " (restarts the engine) ...") + e = restart(lambda a: start_engine(a, {SH_STREAM: v}), tuned, f"{SH_STREAM}={v}", say, report) + if e is None: + continue + try: + sf = Session(e, ids_list) + sf.warm_up(1) + by_fork[v] = [sf.rate(), sf.rate()] + say(f" {statistics.median(by_fork[v]):.1f} tok/s") + finally: + close(e) + report["sh_stream"] = by_fork + if pick(by_fork, "0") == "1": + env[SH_STREAM] = "1" + base_rate = statistics.median(by_fork["1"]) + elif by_fork.get("0"): + base_rate = statistics.median(by_fork["0"]) report["seconds"] = round(time.time() - t0) report["tok_s"] = round(base_rate, 1) if base_rate else None - return {"settings": settings, "report": report} + return {"settings": settings, "env": env, "report": report} def restart(start_engine, args, what, say, report): @@ -336,6 +370,17 @@ def apply(args: list[str], settings: dict) -> list[str]: return out +ENV_KEYS = (SH_STREAM,) + + +def apply_env(env: dict | None, calibrated: dict | None) -> dict: + """The config's "env" with a calibration's engine variables: the ones it chose are set, the others in ENV_KEYS are + removed (back to the engine's default), so an older calibration's choice never lingers.""" + out = {k: v for k, v in (env or {}).items() if k not in ENV_KEYS} + out.update(calibrated or {}) + return out + + if __name__ == "__main__": if len(sys.argv) != 2: sys.exit("usage: calibrate.py ") diff --git a/tools/test_calibrate.py b/tools/test_calibrate.py index 7ce1bdd0..3fb4804a 100644 --- a/tools/test_calibrate.py +++ b/tools/test_calibrate.py @@ -126,6 +126,48 @@ class Calibrate(unittest.TestCase): self.assertIsNone(CAL.arg_value(starts[0], "--pool-workers")) self.assertEqual(CAL.arg_value(starts[0], "--spec-min-p"), "0.5") + def test_sh_stream_is_measured_on_hip_only(self): + # #1272 / #816: the shared-expert fork is measured off (the HIP default) against on, each with a restart and + # the engine variable set explicitly; it is kept only when it wins by more than MIN_GAIN + def run(bonus, hip=True): + starts, envs = [], [] + + def start(args, env=None): + envs.append(dict(env or {})) + fork = (env or {}).get(CAL.SH_STREAM) == "1" + return FakeEngine(args, lambda f, p, w: 50.0 * (bonus if fork else 1.0), 6, starts) + res = CAL.measure(BASE, [[1, 2, 3]] * 3, start, say=lambda *_: None, hip=hip) + return res, starts, envs + res, starts, envs = run(1.08) + self.assertEqual(res["env"], {CAL.SH_STREAM: "1"}) + self.assertEqual(envs[-2:], [{CAL.SH_STREAM: "0"}, {CAL.SH_STREAM: "1"}]) + self.assertEqual(starts[-1], starts[-2]) # the same args for both: only the variable differs + self.assertGreater(res["report"]["tok_s"], 52.0) # the reported speed is the fork's + flat, _, _ = run(1.02) # within noise: the default stays + self.assertEqual(flat["env"], {}) + self.assertEqual(set(flat["report"]["sh_stream"]), {"0", "1"}) + slower, _, _ = run(0.80) + self.assertEqual(slower["env"], {}) + cuda, _, envs = run(1.50, hip=False) # not AMD: no step, no engine variable + self.assertEqual(cuda["env"], {}) + self.assertNotIn("sh_stream", cuda["report"]) + self.assertTrue(all(e == {} for e in envs)) + + def test_a_failed_fork_start_keeps_the_default(self): + def start(args, env=None): + if (env or {}).get(CAL.SH_STREAM) == "1": + raise RuntimeError("out of memory") + return FakeEngine(args, lambda f, p, w: 50.0, 6) + res = CAL.measure(BASE, [[1, 2, 3]] * 3, start, say=lambda *_: None, hip=True) + self.assertEqual(res["env"], {}) + self.assertIn(f"{CAL.SH_STREAM}=1", res["report"]["failed_starts"]) + + def test_apply_env(self): + old = {"STRATA_ROCBLAS_TUNING": "tools/hip", CAL.SH_STREAM: "1"} + self.assertEqual(CAL.apply_env(old, {}), {"STRATA_ROCBLAS_TUNING": "tools/hip"}) # an older choice goes + self.assertEqual(CAL.apply_env({"X": "1"}, {CAL.SH_STREAM: "1"}), {"X": "1", CAL.SH_STREAM: "1"}) + self.assertEqual(CAL.apply_env(None, None), {}) + def test_apply(self): a = CAL.apply(BASE, {"--pcie-frac": "0.35", "--pool-workers": "4"}) self.assertEqual(CAL.arg_value(a, "--pcie-frac"), "0.35") @@ -157,14 +199,15 @@ class Calibrate(unittest.TestCase): (tok / "token_type.json").write_text(json.dumps([1, 1])) seen = [] saved = CAL.measure - CAL.measure = lambda args, ids_list, start_engine, say=print, extra=(): seen.append(args) or {} + CAL.measure = lambda args, ids_list, start_engine, say=print, extra=(), hip=False: seen.append((args, hip)) or {} fake = type("ST", (), {"Tokenizer": lambda *a: type("T", (), {"encode": lambda s, t, **k: [0]})()}) try: with mock.patch.dict(sys.modules, {"strata_tokenizer": fake}): CAL.run({"tokenizer": d, "args": list(BASE), "gpu": [0]}, start_engine=lambda a: None) + CAL.run({"tokenizer": d, "args": list(BASE), "gpu": [0], "backend": "hip"}, start_engine=lambda a: None) finally: CAL.measure = saved - self.assertEqual(seen, [BASE]) + self.assertEqual(seen, [(BASE, False), (BASE, True)]) # the shared-expert step runs on AMD only def test_engine_error(self): with tempfile.TemporaryDirectory() as d: @@ -236,6 +279,21 @@ class SetupIntegration(unittest.TestCase): other = dict(written, args=CAL.with_arg(written["args"], "--max-context", "131072")) self.assertIsNone(self.S.saved_calibration(other)) + def test_calibrate_config_writes_the_env_choice(self): + # HIP: the measured engine variable goes into the config's "env" and the settings file; a re-run that finds it + # no longer faster removes it again, and leaves the config's other variables alone + cfg_path = Path(self.tmp.name) / "strata-iq3_s.json" + cfg = {"exe": "x", "args": list(BASE), "model_name": "m", "backend": "hip", "env": {"STRATA_ROCBLAS_TUNING": "t"}} + cfg_path.write_text(json.dumps(cfg)) + CAL.run = lambda c, say=print, start_engine=None: {"settings": {}, "env": {CAL.SH_STREAM: "1"}, "report": {"tok_s": 70.1}} + self.assertTrue(self.S.calibrate_config(cfg_path)) + written = json.loads(cfg_path.read_text()) + self.assertEqual(written["env"], {"STRATA_ROCBLAS_TUNING": "t", CAL.SH_STREAM: "1"}) + self.assertEqual(self.S.saved_calibration(written)["env"], {CAL.SH_STREAM: "1"}) + CAL.run = lambda c, say=print, start_engine=None: {"settings": {}, "env": {}, "report": {"tok_s": 65.0}} + self.assertTrue(self.S.calibrate_config(cfg_path)) + self.assertEqual(json.loads(cfg_path.read_text())["env"], {"STRATA_ROCBLAS_TUNING": "t"}) + def test_failed_calibration_keeps_defaults(self): cfg_path = Path(self.tmp.name) / "strata-q2_0.json" cfg_path.write_text(json.dumps({"exe": "x", "args": list(BASE), "model_name": "m"})) From 10552345e97f6b3a81a263a300f7624b2af1f072 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 07:14:17 +0200 Subject: [PATCH 15/17] AMD HIP: the primary ordinal, and the helper caches beside the resident RAM mode Three changes for two-card AMD PCs whose faster card does not come first in the runtime's enumeration (Windows HIP orders the cards itself; HIP_VISIBLE_DEVICES only filters): - gfx1032 (RX 6600) joins the unvalidated build list - it shares the gfx1030 / gfx1031 / gfx1034 dp4a path. - STRATA_PRIMARY_DEVICE=N picks the visible ordinal the engine's own session runs on; it is set before any context or allocation exists. The helper caches take the other visible devices, the HIP arch check and the peer tier's device queries follow it, and the primary's session is created on the chosen device. A layer split still assumes device 0 and is refused with this set. Unset or 0 is upstream's behavior unchanged. - The helper-GPU caches are allowed beside the resident RAM mode: the experts a helper holds are left out of the RAM copy as a split stage's are, and the two adaptive tiers already keep each other's experts out. RemoteExperts::finish spins on its stream like PeerExperts::finish - on HIP the CUDA branch's cudaInitDevice(ScheduleSpin) does not exist. Measured on an RX 6800 (16 GB, gfx1030) + RX 6600 (8 GB, gfx1032), Windows 11, 32 GB of RAM, Swift 1.5 IQ3_XXS at 160K context, the resident RAM mode with the helper's cache left out of the copy: decode 37.5 -> 44.2 tok/s on 8K-token requests with a 3800-slot helper; the CPU pool's share of the routed experts falls from ~2.9 to ~0.4 entries per layer-window. Rebased onto 296b59d2 (conflicts in generate.cpp, peer_experts.cpp, hip_backend.cmake, docs/AMD_HIP.md resolved by keeping main's code and adding the PR's). Changes: remote_caches is kept (still used by the --batch-mtp check); the spin in RemoteExperts::finish is HIP only (CUDA keeps its cudaInitDevice(ScheduleSpin) + blocking sync). NOT COMPILED YET, not run. Co-authored-by: tuandat3019 --- cmake/hip_backend.cmake | 2 +- docs/AMD_HIP.md | 6 ++- docs/SECOND_GPU.md | 47 ++++++++++++++++++++++++ include/strata/core/device.hpp | 8 ++++ src/core/device.cu | 7 ++++ src/core/peer_experts.cpp | 9 +++-- src/core/remote_experts.cpp | 33 +++++++++++++++-- src/program/generate.cpp | 67 +++++++++++++++++++++++++++++++--- 8 files changed, 164 insertions(+), 15 deletions(-) diff --git a/cmake/hip_backend.cmake b/cmake/hip_backend.cmake index fda922a4..966fa21d 100644 --- a/cmake/hip_backend.cmake +++ b/cmake/hip_backend.cmake @@ -12,7 +12,7 @@ endif() # same wave32 / 64 KiB LDS / sudot4 family as gfx1100, on a unified-memory APU; experimental. set(_strata_hip_validated gfx1100 gfx1201) set(_strata_hip_community gfx1101 gfx1200) -set(_strata_hip_unvalidated gfx1010 gfx1011 gfx1012 gfx1102 gfx1103 gfx1030 gfx1031 gfx1034 gfx1150 gfx1151 gfx1152) # gfx1103: Radeon 780M iGPU, opt-in, WMMA kernels like gfx1100; gfx1152: Krackan, Radeon 860M / 840M (#1625), builds with the portable kernels, no card report yet +set(_strata_hip_unvalidated gfx1010 gfx1011 gfx1012 gfx1102 gfx1103 gfx1030 gfx1031 gfx1032 gfx1034 gfx1150 gfx1151 gfx1152) # gfx1103: Radeon 780M iGPU, opt-in, WMMA kernels like gfx1100; gfx1152: Krackan, Radeon 860M / 840M (#1625), builds with the portable kernels, no card report yet # CMake hands HIP a ';' list, but a -DCMAKE_HIP_ARCHITECTURES typed by hand (or ROCm's own Windows tooling) may use # spaces, which foreach(IN LISTS) would otherwise treat as one element. string(REPLACE " " ";" _strata_hip_norm "${CMAKE_HIP_ARCHITECTURES}") diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 3f978208..8c54a3c9 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -538,7 +538,11 @@ run it; the report below is from a community machine: an RX 6900 XT 16 GB (gfx10 `-DCMAKE_HIP_ARCHITECTURES=gfx1152` builds with a warning. It runs the portable kernels (the matrix-core guards name gfx1150 and gfx1151 only), no card has reported on it, and setup does not install for it (an integrated Radeon other than Strix Halo is named and not supported). A report from a real 860M is welcome. -- **Not validated:** gfx1032 (the same `dp4a` path, no hardware report), setup's own build path and the +- **gfx1032** (RX 6600/6600 XT): unvalidated; built with `STRATA_HIP_ARCHS=gfx1030;gfx1032` and ran under Windows as + the *helper* expert GPU of an RX 6800 ([SECOND_GPU.md](SECOND_GPU.md)), 3.4-3.8k expert slots in its 8 GB and + +8-18% decode over the 6800 alone. Its 14 WGP make a helper row about 2-3x the 6800's cost, so it pays as a + cache tier for the CPU pool, not as a compute peer. No report of it as a primary card. +- **Not validated:** setup's own build path and the `gfx103X-all` wheels on gfx1030, images, answer-quality benchmarks. RDNA1 (gfx1012, RX 5500 XT) builds by hand: [OLDER_GPUS.md](OLDER_GPUS.md#amd-building-gfx906-and-gfx1012). diff --git a/docs/SECOND_GPU.md b/docs/SECOND_GPU.md index 9201f26d..2a48b9c9 100644 --- a/docs/SECOND_GPU.md +++ b/docs/SECOND_GPU.md @@ -171,3 +171,50 @@ not yet combined with the peer's rows. Mapped host buffers gain context write them. The tier size is manual for now (`--peer-reserve-mib`, `--peer-slots`); automatic sizing on small cards wants the buffer lending of #216 and is a follow-up. + +## The resident RAM mode with the helper caches + +`--resident-experts` (the low-RAM mode) works with the helper caches: the +experts a helper holds are left out of the RAM copy as a split stage's are, and +the helpers' refills read through the source - the RAM copy when it holds the +bytes, the files otherwise. Measured here on an RX 6800 (gfx1030, 16 GB) + RX +6600 (gfx1032, 8 GB), Windows 11, an i5-11400F and 32 GB of RAM (the 6800 alone: +~37.5 decode tok/s, the same worker configuration): the 6600's 3.4-3.8k-expert +cache lifted decode to ~40.6 / 44.2 tok/s on 8K-token requests at 3800 slots, +with the CPU pool's share of the experts down from ~2.9 to ~0.4 entries per +layer-window. The helper's rows cost about 0.3-0.6 ms per layer on the pool's +critical path - usually less than the CPU rows and page faults they replace, +which is why the 6600 (about 2-3x the 6800's cost per row) still pays off as a +cache tier. + +**Size a helper against the card's *real* free VRAM.** `--expert-cache-device1 +auto` reads `cudaMemGetInfo`, which on Windows reports the *process's* WDDM +budget: it cannot see the desktop, the vision encoder (a separate process), a +streaming host or other apps on that card. A helper auto-sized on a card that +also drives the display or the encoder over-commits, WDDM backs the excess with +system RAM ("shared GPU memory"), and that memory leaves the machine's RAM - on +a 32 GB PC it pushed the resident complement into the pagefile and made the +helper read its own cache over PCIe. An explicit count +(`--expert-cache-device1 3800` here, of ~4100 that fit an empty card) kept the +cache in real VRAM; freeing another app's sticky allocation on the same card +was worth about the same again. Prefer explicit counts on a card that shares +its VRAM with anything else. + +## Choosing the primary device on Windows (`STRATA_PRIMARY_DEVICE`) + +The engine runs the model on the device the runtime numbers 0. Windows' HIP +runtime enumerates the cards in a fixed order that `HIP_VISIBLE_DEVICES` only +filters - it cannot reorder - so on a PC whose faster card comes second (an RX +6800 after an RX 6600, say) a run with both visible could only put the model on +the slow one. `STRATA_PRIMARY_DEVICE=N` picks another visible ordinal as the +primary; unset or 0 is upstream's behavior. + +- the helper caches (`--expert-cache-device1..3`) take the visible devices + other than the primary, in order; +- the peer tier's cross-device checks use the same ordinal; +- a layer split is refused with this set (its later stages must be > 0, and + stage 0 is the primary); +- NVIDIA cards do not need it: `CUDA_VISIBLE_DEVICES` with + `CUDA_DEVICE_ORDER=PCI_BUS_ID` already reorders. + +Measured on RX 6800 + RX 6600, Windows 11; the report accompanies this change. diff --git a/include/strata/core/device.hpp b/include/strata/core/device.hpp index 091dff1c..1745f8f2 100644 --- a/include/strata/core/device.hpp +++ b/include/strata/core/device.hpp @@ -48,6 +48,14 @@ int device_count(); // the runtime cannot describe it. bool device_summary(int ordinal, std::string& name, std::string& detail); +// STRATA_PRIMARY_DEVICE (generate.cpp): the ordinal the engine's own session runs on; 0 = the runtime's first +// visible device (upstream's behavior). The Windows HIP runtime enumerates the cards in a fixed order no +// HIP_VISIBLE_DEVICES list can change (it only filters), so a PC whose faster card comes second could not run +// the model on it while the first card served as a helper. The helper expert caches and the peer tier must +// live on another device. Set once, before any context exists. +void set_primary_device(int ordinal); +int primary_device(); + // Throws when there is no CUDA device. The engine targets sm_120 specifically and must say so rather than // run slowly on something else: `CMakeLists.txt` already refuses to COMPILE for another architecture, and // this is the matching check at run time (a binary can be carried to a different machine). diff --git a/src/core/device.cu b/src/core/device.cu index 34bc679d..5c59554b 100644 --- a/src/core/device.cu +++ b/src/core/device.cu @@ -84,6 +84,13 @@ int device_count() { return count < 0 ? 0 : count; } +// STRATA_PRIMARY_DEVICE: see the declaration in device.hpp. 0 = upstream's behavior (the runtime's first +// visible device). Set once, before any context exists, by generate.cpp's STRATA_PRIMARY_DEVICE handling. +static int g_primary_device = 0; + +void set_primary_device(int ordinal) { g_primary_device = ordinal; } +int primary_device() { return g_primary_device; } + bool device_summary(int ordinal, std::string& name, std::string& detail) { cudaDeviceProp p{}; if (ordinal < 0 || ordinal >= device_count() || cudaGetDeviceProperties(&p, ordinal) != cudaSuccess) { diff --git a/src/core/peer_experts.cpp b/src/core/peer_experts.cpp index 6c8f567e..230f8169 100644 --- a/src/core/peer_experts.cpp +++ b/src/core/peer_experts.cpp @@ -1,6 +1,7 @@ // src/core/peer_experts.cpp - see include/strata/core/peer_experts.hpp. #include "strata/core/peer_experts.hpp" +#include "strata/core/device.hpp" // primary_device() (STRATA_PRIMARY_DEVICE) #include "strata/kernels/cpu/expert_layout.hpp" #include "strata/kernels/elementwise.hpp" #include "strata/kernels/iq_kernels.hpp" @@ -96,16 +97,16 @@ bool PeerExperts::open(int device, const std::vector res_.assign((size_t) (n_layers * n_expert), kNotResident); { // direct access both ways (NVLink or another P2P path): the prompt path copies activations and results over it int a = 0, b = 0; - cudaDeviceCanAccessPeer(&a, 0, device); - cudaDeviceCanAccessPeer(&b, device, 0); + cudaDeviceCanAccessPeer(&a, primary_device(), device); + cudaDeviceCanAccessPeer(&b, device, primary_device()); if (const char* np = std::getenv("STRATA_PEER_NO_P2P"); np != nullptr && std::atoi(np) != 0) a = 0; // test knob: pretend the pair has no P2P p2p_ = a && b; if (p2p_) { - On on0(0); + On on0(primary_device()); cudaError_t e0 = cudaDeviceEnablePeerAccess(device, 0); if (e0 == cudaErrorPeerAccessAlreadyEnabled) { cudaGetLastError(); e0 = cudaSuccess; } On on1(device); - cudaError_t e1 = cudaDeviceEnablePeerAccess(0, 0); + cudaError_t e1 = cudaDeviceEnablePeerAccess(primary_device(), 0); if (e1 == cudaErrorPeerAccessAlreadyEnabled) { cudaGetLastError(); e1 = cudaSuccess; } p2p_ = e0 == cudaSuccess && e1 == cudaSuccess; } diff --git a/src/core/remote_experts.cpp b/src/core/remote_experts.cpp index f01bf6fe..7148cf74 100644 --- a/src/core/remote_experts.cpp +++ b/src/core/remote_experts.cpp @@ -1,4 +1,5 @@ #include "strata/core/remote_experts.hpp" +#include "strata/core/device.hpp" // primary_device() (STRATA_PRIMARY_DEVICE) #include "strata/core/remote_expert_opt.hpp" #include "strata/kernels/cpu/expert_layout.hpp" @@ -68,10 +69,15 @@ RemoteExperts::~RemoteExperts() { close(); } bool RemoteExperts::preflight(int device, double& free_gib, std::string& err) { int count = 0; if (!check(cudaGetDeviceCount(&count), "cudaGetDeviceCount", err, device)) return false; - if (device < 1 || device >= count) { + if (device < 0 || device >= count) { err = "CUDA" + std::to_string(device) + " experts: CUDA device is not visible"; return false; } + if (device == primary_device()) { // the primary may be any visible ordinal; the helper cannot be it + err = "CUDA" + std::to_string(device) + " experts: the helper cannot be the primary device " + "(STRATA_PRIMARY_DEVICE)"; + return false; + } // The layer waits for this GPU on the CPU pool's critical path: spin instead of sleeping, whose wake-up // costs more than a small expert batch takes (measured: ~0.3 ms per round trip on Windows). Only possible // before the device's context exists, so first thing; STRATA_REMOTE_SPIN=0 keeps the driver's default. @@ -129,8 +135,9 @@ bool RemoteExperts::open(int device, int slots, int64_t layers, int64_t experts, close(); int count = 0; if (!check(cudaGetDeviceCount(&count), "cudaGetDeviceCount", err, device)) return false; - if (device < 1 || device >= count || slots <= 0 || ranked.empty() || - layers <= 0 || experts <= 0 || claimed.size() != (size_t) layers * (size_t) experts) { + if (device < 0 || device >= count || slots <= 0 || ranked.empty() || + layers <= 0 || experts <= 0 || claimed.size() != (size_t) layers * (size_t) experts || + device == primary_device()) { // the helper cannot be the primary device (any visible ordinal) err = "CUDA" + std::to_string(device) + " experts: need the device, ranked experts and positive slot count"; return false; } @@ -338,7 +345,27 @@ bool RemoteExperts::finish(float* out, std::string& err) { DeviceScope scope(device_); if (!scope.ok) { err = scope.error(device_); return false; } const auto w0 = std::chrono::steady_clock::now(); + // Spin on the stream like PeerExperts::finish instead of the blocking sync: the layer waits for this helper + // on the CPU pool's critical path, and a blocking sync's wake-up costs more than the helper's small batch + // takes - on HIP especially, where the CUDA branch's cudaInitDevice(ScheduleSpin) does not exist and the + // device keeps its default policy. STRATA_REMOTE_SPIN=0 keeps the blocking sync (the same switch the CUDA + // branch reads). +#if defined(STRATA_USE_HIP) // HIP only: the CUDA branch's cudaInitDevice(ScheduleSpin) already makes the sync spin + static const bool spin = [] { + const char* v = std::getenv("STRATA_REMOTE_SPIN"); + return !(v != nullptr && v[0] == '0'); + }(); + if (spin) { + cudaError_t e; + while ((e = cudaStreamQuery(stream_)) == cudaErrorNotReady) { + } + if (!check(e, "finish", err, device_)) return false; + } else if (!check(cudaStreamSynchronize(stream_), "finish", err, device_)) { + return false; + } +#else if (!check(cudaStreamSynchronize(stream_), "finish", err, device_)) return false; +#endif ms_wait_ += std::chrono::duration(std::chrono::steady_clock::now() - w0).count(); if (remote_opt_ && remote_opt_->active()) { remote_opt_->accumulate(*this); return true; } for (size_t i = 0; i < original_row_.size(); ++i) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index ba00f94d..a5fb822a 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -2343,6 +2343,16 @@ int main(int argc, char** argv) { if (o.serve && o.conversation_cache_mib > 0 && (o.prompt_cache == 0 || o.conversation_cache_slots == 0)) std::fprintf(stderr, "strata serve: warning: conversation caching is disabled by %s\n", o.prompt_cache == 0 ? "--prompt-cache 0" : "--conversation-cache-slots 0"); + // STRATA_PRIMARY_DEVICE: which VISIBLE device the engine's own session runs on. The Windows HIP runtime + // enumerates the cards in a fixed order no HIP_VISIBLE_DEVICES list can change (it only filters), so with a + // slower card first a run could only put the model on it (RX 6600 before RX 6800). 0 (unset) is upstream's + // behavior; the helper caches and the peer tier follow it, a layer split still assumes device 0 (see below). + const int primary_device = [] { + const char* v = std::getenv("STRATA_PRIMARY_DEVICE"); + const int n = v != nullptr ? std::atoi(v) : 0; + return n > 0 ? n : 0; + }(); + strata::core::set_primary_device(primary_device); // parking with --layer-split saves every stage (SavedConversation::stage_images) // Layer split (multi-GPU): the later stages run layers [K_i, K_i+1) on their own GPUs (--split-device, default // the next visible ones); "auto" places the K from each GPU's free VRAM once the weights are in (below). KV @@ -2405,6 +2415,14 @@ int main(int argc, char** argv) { } } bool multi_gpu = !split_devs.empty() && !split_same; // cleared by --split-skip-if-fits before any stage loads + // STRATA_PRIMARY_DEVICE: a later stage's list (`--split-device` values must be > 0) still assumes the + // primary is device 0 - refuse the combination rather than mis-place a stage. The peer tier takes the + // primary into account (peer_experts.cpp). + if (primary_device != 0 && !o.layer_split.empty()) { + std::fprintf(stderr, "strata generate: STRATA_PRIMARY_DEVICE %d is not supported with a layer split yet\n", + primary_device); + return 2; + } 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"); @@ -2418,13 +2436,23 @@ int main(int argc, char** argv) { o.expert_cache_remote[2] > 0; // A layer split keeps the resident RAM mode: every stage's GPU cache is left out of the RAM copy, and an adaptive // swap copies an evicted expert back from the card that owns its layer (resident_stage_swaps). - if (o.resident_cpu_experts && remote_caches) { - std::fprintf(stderr, "strata generate: --resident-cpu-experts does not support remote expert caches\n"); - return 2; - } + // The helper-GPU caches are allowed beside the resident RAM mode too: their experts are left out of the RAM copy + // like a stage's (below), the helpers' refills read through the source (the RAM copy when it holds the bytes), + // and the two adaptive tiers already keep each other's experts out (helper_holds in the primary's candidates, + // RemoteExpertOpt::adapt's resident table). Measured on RX 6800 + RX 6600, Windows (docs/SECOND_GPU.md). // the helper-GPU expert caches (--expert-cache-remote, docs/SECOND_GPU.md): CUDA1..3 on one GPU; with a layer // split, the visible GPUs no stage runs on, in order int remote_dev[3] = {1, 2, 3}; + if (primary_device != 0) { + // STRATA_PRIMARY_DEVICE: the helpers are the visible devices except the primary, in order + int n_vis = 1; + if (cudaGetDeviceCount(&n_vis) != cudaSuccess || n_vis < 1) n_vis = 1; + cudaGetLastError(); + int k = 0; + for (int d = 0; d < n_vis && k < 3; ++d) + if (d != primary_device) remote_dev[k++] = d; + for (; k < 3; ++k) remote_dev[k] = -1; + } if (multi_gpu) { if (o.expert_profile.empty()) { std::fprintf(stderr, "strata generate: a layer split across GPUs needs --expert-profile\n"); @@ -2508,7 +2536,7 @@ int main(int argc, char** argv) { { // every GPU this run uses must be an architecture the binary has code for (a gfx1100 build on a gfx1201 // card would otherwise fail later with "invalid device function") - std::vector used{0}; + std::vector used{primary_device}; // STRATA_PRIMARY_DEVICE: the primary is not always 0 if (multi_gpu) used.insert(used.end(), split_devs.begin(), split_devs.end()); for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) used.push_back(remote_dev[r]); @@ -2831,6 +2859,25 @@ int main(int argc, char** argv) { } } const bool native_pack = strata::kernels::cpu::expert_layout().native; + // STRATA_PRIMARY_DEVICE: switch the engine's own thread to the chosen card BEFORE any GPU + // context or allocation exists below (the helper preflights, the PCIe probe, the weights and the + // arena all follow it). Every other device switch in the engine saves and restores the current + // device, so this single call is where the primary is picked. + if (primary_device != 0) { + int n_vis = 0; + if (cudaGetDeviceCount(&n_vis) != cudaSuccess || primary_device >= n_vis) { + cudaGetLastError(); + std::fprintf(stderr, "strata generate: STRATA_PRIMARY_DEVICE=%d: no such visible device (%d visible)\n", + primary_device, n_vis); + return 2; + } + if (cudaSetDevice(primary_device) != cudaSuccess) { + std::fprintf(stderr, "strata generate: STRATA_PRIMARY_DEVICE=%d: cudaSetDevice failed: %s\n", + primary_device, cudaGetErrorString(cudaGetLastError())); + return 1; + } + std::fprintf(stderr, "strata generate: primary device from STRATA_PRIMARY_DEVICE: CUDA%d\n", primary_device); + } // STRATA_EARLY_REMOTE_CONTEXTS=1: create EVERY secondary context here, like CUDA1's. Under WSL2 the driver's // pinned/mapped host budget (dxg gpadl, ~1 GiB) is spent by CUDA0's weights and MTP before the later loop runs, // and a new context then fails with cudaErrorMemoryAllocation (CUDA2: "cudaSetDevice(2) failed: out of memory"). @@ -4386,7 +4433,7 @@ int main(int argc, char** argv) { // held all 48 layers' state whatever layers it ran, which is the same disease the chunked-QSA-prefill PR // fixed in llama.cpp: allocation sized by the whole model instead of the device's own work. { - const strata::core::OnDevice on0(0); + const strata::core::OnDevice on0(primary_device); // STRATA_PRIMARY_DEVICE (upstream: a literal 0) const int64_t hi0 = multi_gpu ? split_at[0] : -1; // the elastic K/V (--kv-grow, see kvg_ensure): one GPU, the whole K/V in VRAM (no streaming), a profiled cache // that can give slots up, and every expert in RAM for the CPU to compute the ones it gives up @@ -7026,6 +7073,14 @@ int main(int argc, char** argv) { for (int64_t l = st->lb; l < st->le; ++l) for (int64_t e = 0; e < g.n_expert; ++e) if (st->cache.slot_of(l, e) >= 0) stage_pairs.emplace_back((int32_t) l, (int32_t) e); + // A helper GPU's experts are left out of the RAM copy as a stage's are - the RAM + // that duplication would take goes to colder experts instead. + for (int r = 0; r < 3; ++r) { + if (o.expert_cache_remote[(size_t) r] <= 0) continue; + for (int64_t l = 0; l < g.n_layers; ++l) + for (int64_t e = 0; e < g.n_expert; ++e) + if (remote_experts[(size_t) r].holds(l, (int32_t) e)) stage_pairs.emplace_back((int32_t) l, (int32_t) e); + } // The split's lend regions. The serve scan lends the tail slots of EVERY part's cache - CUDA0's own // part first, then every stage (the `pf_parts` loop below) - and `lend_from` above is switched off in // pin_cache_complement the moment `additional_gpu_pairs` is non-empty, so until now none of those experts From 1d6fd9f97ab09da231b35cbbd84a2879adb6d77f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 17:45:01 +0200 Subject: [PATCH 16/17] file tier: the old room rule on the gfx906 backend (#1752), STRATA_FILE_CACHE_OLD_RULE=1/0 on any Linux build On an MI50 ROCm queues are suspended while the kernel reclaims around the HMM-tracked arena; the cached reads of the new rule churn the page cache. The gfx906 backend keeps the old room >= read_bytes rule; other HIP cards keep the current rule (the PR applied it to every HIP build). Co-authored-by: KevinX8 --- src/core/expert_source.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index 4878c111..e55261a7 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -527,8 +527,18 @@ bool file_tier_unbuffered(const std::vector& paths, uint64_t arena_ // #1194: the experts read from the files are a skewed set: a cache holding a twentieth of them (at least 1.5 GiB) // serves most of the repeats, and beat the unbuffered reads at every room measured (it reads 2 to 7 times less from // the drive). `avail` already has what this process and the cgroup hold taken off, so 1 GiB is left for the rest. - const bool keepable = strata::platform::file_cache_keeps(avail, arena_bytes, read_bytes, 1ull << 30, 0.05, - 3ull << 29); + // #1752 (KevinX8): ROCm queues are suspended while the kernel reclaims around the process's HMM-tracked arena + // (#1691) on an MI50 (gfx906): the cached reads churn the page cache and reclaim unmaps the arena, so the gfx906 + // backend keeps the old room >= read_bytes rule. Other HIP cards (gfx1201 measured: not affected) keep the new + // rule; STRATA_FILE_CACHE_OLD_RULE=1 / 0 forces the old rule on / off on any Linux build. + bool old_rule = false; +#if defined(STRATA_HIP_GFX906) + old_rule = true; +#endif + if (const char* r = std::getenv("STRATA_FILE_CACHE_OLD_RULE"); r != nullptr && r[0] != '\0') old_rule = r[0] != '0'; + const bool keepable = old_rule + ? strata::platform::file_cache_keeps(avail, arena_bytes, read_bytes) + : strata::platform::file_cache_keeps(avail, arena_bytes, read_bytes, 1ull << 30, 0.05, 3ull << 29); char msg[256]; std::snprintf(msg, sizeof msg, "%.1f GiB available, %.1f GiB of it still to be taken by the RAM copy, %.1f GiB " "of experts read from the files: the file cache %s keep the ones that come back", From 31340f7279c7bceb7ca0a36e61c1a57db5487674 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 17:45:17 +0200 Subject: [PATCH 17/17] docs: STRATA_FILE_CACHE_OLD_RULE (#1752) --- docs/AMD_HIP.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 8c54a3c9..29c77d04 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -517,6 +517,7 @@ run it; the report below is from a community machine: an RX 6900 XT 16 GB (gfx10 1,861 and 1,727 -> 1,858 tok/s (+7.4%), 32K +0.8%; decode is not affected (the text changes with the scores' order, so its speed is not compared). Measurements: [bench/results/2026-10-07-rdna2-qsa-select-simt](../bench/results/2026-10-07-rdna2-qsa-select-simt/README.md). +- **File-tier cache rule on gfx906 (`STRATA_FILE_CACHE_OLD_RULE`):** on an MI50 ROCm queues are suspended while the kernel reclaims around the process's HMM-tracked arena (#1752, KevinX8: stalls, prompt 46 -> 360 tok/s once the file tier stops churning the page cache). The gfx906 backend therefore keeps the old rule (the file cache is used only when the room left is at least the bytes read from the files); other HIP cards keep the current rule. `STRATA_FILE_CACHE_OLD_RULE=1` forces the old rule on any Linux build, `=0` the current one. - **Windows** (the report above): setup's ready-made Windows engine 0.1.39 runs the RX 6800 beside a 780M iGPU (HIP numbers the RX 6800 1; setup points the engine at it), and `tools/hip/build_windows.bat` with `STRATA_HIP_ARCHS=gfx1030` builds a working engine from the `gfx103X-all` 10.2.0a20260930 wheels.