From 1d94e416a6b073c15360e7c84b52fc382d168e98 Mon Sep 17 00:00:00 2001 From: Constantin Date: Mon, 16 Nov 2026 00:15:47 -0500 Subject: [PATCH] libr4d: keep short IQR verification on the decode path A speculative verify issues several rows where a plain decode issues one. Two IQR kernels accumulated those rows differently, so the same weights and activations could round to different bf16 outputs. A greedy choice near a tie could therefore diverge even though every draft was accepted. gemm_iqr_nt_m64: a U5 row-scale trellis (computed trellis, 5-bit, one f32 scale a row) already folds one to four rows as a GEMV in the single-token order. Above that, through the GEMV's eight-row limit, the multi-row fold differs. Those rows now run as independent single-row GEMV blocks on grid.y, including a chained launch. Gated GEMMs and every other form keep their dispatch. moe_gemm_iqr: a short token-order gate/up batch (more than one token, at most eight times top_k, top_k below the one-wave threshold, K at least eight 128-blocks, and a one-token step inside the decode band) used the run grid. Several tokens on one expert then took the WMMA tile instead of the one-row dot. Those batches now give each sorted slot its own block and the same wide-K dot reduction as a one-token gate/up. Sorted down projections, longer batches and the prefill map are unchanged. r4d_selftest checks both against independent single-row launches, bit for bit, including an untouched output tail on the dense row. The existing grouped numerical suite still passes. Measured on an R9700, the dense U5 path at N=8192 K=2560 is 26.5 us at M=1, 51.2 at M=4 and 105.2 at M=7. A 512-expert Qwen3.8-Flash-Next gate/up (768:512 x 2560, 5-bit, ten slots a token) is 28.9 us at one token, 52.4 at four and 82.2 at seven. Prefill remains the old kernel. On the isolated build, Qwen3.8-Flash-Next U5-gate/W5-down matched its non-speculative token ids at MTP 3 and 6 on arithmetic, writing, code, explanation and JSON. StillDeadcode's IQR-V4 control matched on the arithmetic and writing prompts at MTP 3. A layer trace of the previously divergent writing token was bit-identical between the two schedules. --- libr4d/r4d_gemm_iqr.hip | 26 +++++++-- libr4d/r4d_moe_iqr.hip | 30 +++++++++-- libr4d/r4d_selftest.cpp | 114 ++++++++++++++++++++++++++++++++++++++-- 3 files changed, 159 insertions(+), 11 deletions(-) diff --git a/libr4d/r4d_gemm_iqr.hip b/libr4d/r4d_gemm_iqr.hip index 7d99034a..e367a432 100644 --- a/libr4d/r4d_gemm_iqr.hip +++ b/libr4d/r4d_gemm_iqr.hip @@ -3,7 +3,9 @@ // // gemm_iqr_nt_m64 M <= 64 (decode and speculative verify). At one token (a computed trellis; // M <= 8 for the other forms) a GEMV: a block a 16-row tile, its waves across -// K, each lane's decoded values one sudot4 against the activation. To 16 tokens +// K, each lane's decoded values one sudot4 against the activation. The U5 +// row-f32 trunk uses the GEMV through M=8, so its verify rows retain the +// single-token decode's accumulation order. To 16 tokens // a WMMA tile of the same shape, each 128-K unit decoded and transposed into // fragment order through the wave's LDS just before its WMMA steps. Above, the // i8a8 narrow tile with the same per-unit decode. @@ -155,6 +157,13 @@ void iqr_gemv_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restri uint16_t* __restrict__ Y, uint32_t N, uint32_t x_ld, uint32_t xs_ld, GatedOut go) { if (CH::on) r4d_chain_wait(); + /* A non-gated single-token GEMV may put independent token rows on grid.y. Every block then + * executes exactly the M=1 arithmetic over its own row, including the chained launch. */ + if constexpr (!GATED && MT == 1) { + X += (size_t)blockIdx.y * x_ld; + XS += (size_t)blockIdx.y * xs_ld; + Y += (size_t)blockIdx.y * N; + } using D = Dec; constexpr uint32_t NW = (GATED ? 2u : 1u) * KW; __shared__ __attribute__((aligned(16))) int8_t s_tab[D::kTab]; @@ -952,6 +961,11 @@ int gemv_launch(const Operands& g, RadStream stream, const GatedOut* go = nullpt * 4 bits: gate_up 146.6 / 147.1 us, down 76.0 / 78.4, the 5120 x 6144 outputs 31.4 / 31.9, * attn_k 9.5 / 8.8). */ const uint32_t kw = N >= 4096u ? 4u : 8u; + /* U5 row-f32's GEMV has the single-token fold order through MT=4. At MT>4 it uses a different + * fold, so put independent single-row blocks on grid.y instead. Gated GEMMs keep their + * existing dispatch and counter layout. */ + const bool row_grid = !go && F::KIND == kTrellisMad && F::B == 5u && F::LRB == 0u && + F::SC == kRowF32 && M > 4u && M <= kGemvMaxM; const GatedOut gz = go ? *go : GatedOut{}; uint16_t* const y = go ? nullptr : (uint16_t*)g.y->data; int rc = RAD_E_SHAPE; @@ -959,7 +973,8 @@ int gemv_launch(const Operands& g, RadStream stream, const GatedOut* go = nullpt rc = go ? R4D_EMIT(stream, (iqr_gemv_kernel), dim3(N / 32u), \ dim3(2u * kw_ * kWave), 0, c, (const int8_t*)g.a->data, \ (const float*)g.as->data, y, N, (uint32_t)g.a_ld, (uint32_t)g.sa_ld, gz) \ - : R4D_EMIT(stream, (iqr_gemv_kernel), dim3(N / 16u), \ + : R4D_EMIT(stream, (iqr_gemv_kernel), \ + dim3(N / 16u, row_grid ? M : 1u), \ dim3(kw_ * kWave), 0, c, (const int8_t*)g.a->data, \ (const float*)g.as->data, y, N, (uint32_t)g.a_ld, (uint32_t)g.sa_ld, gz) #define R4D_IQR_GV(mt_, kw_) \ @@ -970,7 +985,9 @@ int gemv_launch(const Operands& g, RadStream stream, const GatedOut* go = nullpt R4D_IQR_GV_E(mt_, kw_, R4dUnchained); \ } } while (0) #define R4D_IQR_GVK(mt_) do { if (kw == 4u) R4D_IQR_GV(mt_, 4u); else R4D_IQR_GV(mt_, 8u); } while (0) - switch (M) { + if (row_grid) { + R4D_IQR_GVK(1u); + } else switch (M) { case 1u: R4D_IQR_GVK(1u); break; case 2u: R4D_IQR_GVK(2u); break; case 3u: R4D_IQR_GVK(3u); break; @@ -1052,7 +1069,8 @@ template int m64_launch(const Operands& g, void* scratch, long long scratch_bytes, int split_n, RadStream stream) { const uint32_t N = (uint32_t)g.N, K = (uint32_t)g.K, M = (uint32_t)g.M; - if (M <= gemv_max()) return gemv_launch(g, stream); + const bool row_grid = F::KIND == kTrellisMad && F::B == 5u && F::LRB == 0u && F::SC == kRowF32; + if (M <= gemv_max() || (row_grid && M <= kGemvMaxM)) return gemv_launch(g, stream); if (M <= (tiles_form() ? 64u : 16u) && ((uintptr_t)g.y->data & 15u) == 0u) return m16_launch(g, stream); /* At most eight waves a block: each has its own transpose tile in LDS. The wave count changes diff --git a/libr4d/r4d_moe_iqr.hip b/libr4d/r4d_moe_iqr.hip index 66a2359d..a7ced689 100644 --- a/libr4d/r4d_moe_iqr.hip +++ b/libr4d/r4d_moe_iqr.hip @@ -223,7 +223,7 @@ __device__ __forceinline__ void moe_iqr_body(R4D_MOEIQR_PARAMS) { static_assert(TPW == 1u || KW == 1u, "several weight tiles a wave: a wave a tile's whole K"); constexpr uint32_t NW = KW * RTB, NTHR = NW * kWave, kCols = RTB * TPW * 16u; /* `mode`: bit 0 `a_sorted`, bits 1-2 the class shift, bit 3 the activation's scale per 256 of - * K, bits 8+ `parts` (r4d_moe.hip's). */ + * K, bit 4 the short token-order parity grid, bits 8+ `parts` (r4d_moe.hip's). */ const uint32_t a_sorted = mode & 1u, cshift = (mode >> 1) & 3u, ash = (mode >> 3) & 1u; const uint32_t parts = mode >> 8; /* the waves' transpose tiles, then their partials (8 x 32 floats a wave, in its own tile) */ @@ -253,6 +253,21 @@ __device__ __forceinline__ void moe_iqr_body(R4D_MOEIQR_PARAMS) { const uint32_t oe = (uint32_t)off[e + 1]; re = oe < T ? oe : T; if (re > rs + kRows * NT) re = rs + kRows * NT; + } else if (mode & 16u) { + /* A short verification batch must use the single-token dot and K reduction even when + * several tokens route to the same expert. One block owns one sorted slot; locate its + * expert from the monotonic offsets. Dropped slots are zeroed just as in the run grid. */ + rs = blockIdx.x; + if (rs >= T) return; + if (rs >= (uint32_t)off[n_expert]) { zero_rows(rs, rs + 1u); return; } + uint32_t lo = 0, hi = n_expert; + while (lo < hi) { + const uint32_t mid = (lo + hi) / 2u; + if ((uint32_t)off[mid + 1u] <= rs) lo = mid + 1u; + else hi = mid; + } + e = lo; + re = rs + 1u; } else { /* The (tile, run) grid. The block's first wave finds the run and the others take it from * LDS after one barrier: each of its lanes holds kMaxExpert / 32 consecutive experts' @@ -569,7 +584,8 @@ int launch_form(const Launch& g, RadStream stream) { * a wide K (eight 128-K blocks and up) under kOneWaveMinRows routed rows is shared between * four waves a tile, and a narrow one between kTwoTileMinRows and kTwoTileMaxRows rows gives a * wave two tiles in turn and a block eight. */ - const bool wide_k = g.nkb >= 8u && (g.T < kOneWaveMinRows || (g.N / 16u) % 4u); + const bool wide_k = g.nkb >= 8u && + ((g.mode & 16u) || g.T < kOneWaveMinRows || (g.N / 16u) % 4u); const bool two = !wide_k && g.nkb < 8u && g.N % (16u * 8u) == 0u && g.T >= kTwoTileMinRows && g.T <= kTwoTileMaxRows; if (g.map) R4D_MOEIQR_GO(1u, 4u, true, kMapTiles, 1u); @@ -672,7 +688,13 @@ int moe_iqr_launch(const RadArgs* a, RadStream stream, int ncls) { if (M < (a_sorted ? T : (T + top_k - 1) / top_k)) return R4D_NO(RAD_E_SHAPE); g.nkb = (uint32_t)(K / kBlock); - const bool band = r4d_moe_in_decode_band(T, n_expert); + /* The common short verification shape uses the same wide-K dot reduction as a one-token + * gate/up. Limit this to geometries whose one-token step takes that decode path; larger batches + * retain the throughput-oriented run/map kernels. */ + const bool parity_rows = !a_sorted && top_k < (long long)kOneWaveMinRows && + T > top_k && T <= 8 * top_k && g.nkb >= 8u && + r4d_moe_in_decode_band(top_k, n_expert); + const bool band = parity_rows || r4d_moe_in_decode_band(T, n_expert); /* a narrow-K projection and the run map's grid take four weight tiles a block */ if (((!band || g.nkb < 8u) && (N / 16) % 4) || (N / parts) % 16) return R4D_NO(RAD_E_SHAPE); g.x = (const int8_t*)Aq->data; @@ -694,7 +716,7 @@ int moe_iqr_launch(const RadArgs* a, RadStream stream, int ncls) { g.inv_ft = parts > 1 ? (uint32_t)(((uint64_t)1 << 32) / (uint64_t)(N / parts / 16) + 1u) : 0u; const uint32_t cshift = ncls == 4 ? 2u : 1u; g.mode = (a_sorted ? 1u : 0u) | cshift << 1 | (a_group == 2 * (long long)kBlock ? 8u : 0u) | - (uint32_t)parts << 8; + (parity_rows ? 16u : 0u) | (uint32_t)parts << 8; if (band) { g.map = nullptr; diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index a1a2fab2..478ffb34 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -6366,12 +6366,13 @@ static void i8a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N * scale on libquant's tcq_rb grid), `two` E4M3 scales under one f32, `rot` the fwht128 forms. */ struct IqrCase { int kind, B, V, L, rb; bool two, rot; bool rowf = false; }; -static void iqr_gemm_case(const Plugin& pl, const IqrCase& f, int64_t M, int64_t N, int64_t K) { +static void iqr_gemm_case(const Plugin& pl, const IqrCase& f, int64_t M, int64_t N, int64_t K, + bool row_invariance = false) { const char* row = M <= 64 ? "gemm_iqr_nt_m64" : "gemm_iqr_tiled"; const char* ref = M <= 64 ? "gemm_i8a8_nt_m16" : f.rb >= 32 ? "gemm_i8a8_rb32_tiled" : f.rb >= 8 ? "gemm_i8a8_rb8_tiled" : "gemm_i8a8_tiled"; - if (!sel(row) && !sel("gemm_iqr")) return; + if (!row_invariance && !sel(row) && !sel("gemm_iqr")) return; static const char* kKind[] = { "", "signed", "zero", "table", "grid", "trellis", "trellis-mad" }; const bool tr = f.kind == 5 || f.kind == 6; /* 6: the computed trellis (tcq_code=mad) */ char nm[200]; @@ -6649,6 +6650,52 @@ static void iqr_gemm_case(const Plugin& pl, const IqrCase& f, int64_t M, int64_t std::vector y((size_t)(M * N)), yr((size_t)(M * N)); st_memcpy(y.data(), d_y, y.size() * 2, hipMemcpyDeviceToHost); st_memcpy(yr.data(), d_yr, yr.size() * 2, hipMemcpyDeviceToHost); + + /* A verify issues several rows where a plain decode issues one. Same weight and activation + * must give the same bytes at every position, not merely agree with an oracle to tolerance. */ + if (row_invariance) { + std::vector batch((size_t)(M * N)), single((size_t)N); + for (int64_t width = 2; width <= M; ++width) { + auto q = tq; + q[0] = T(d_a, RAD_I8, { width, K }); + q[1] = T(d_as, RAD_F32, { width, nkb }); + q[4] = T(d_y, RAD_BF16, { width, N }); + std::vector p = { PI("M", width), PI("N", N), PI("K", K), + PI("group", 128), PS("dtype", dt) }; + st_memset(d_y, 0x7f, (size_t)(M * N) * 2); + int rc = launch(r, q, p); + if (rc == RAD_OK) + st_memcpy(batch.data(), d_y, (size_t)(M * N) * 2, hipMemcpyDeviceToHost); + int64_t different = 0, first = -1, tail_touched = 0; + if (rc == RAD_OK) + for (int64_t n = width * N; n < M * N; ++n) + if (batch[(size_t)n] != 0x7f7f) ++tail_touched; + for (int64_t j = 0; j < width && rc == RAD_OK; ++j) { + auto q1 = tq; + q1[0] = T((int8_t*)d_a + j * K, RAD_I8, { 1, K }); + q1[1] = T((float*)d_as + j * nkb, RAD_F32, { 1, nkb }); + q1[4] = T(d_yr, RAD_BF16, { 1, N }); + std::vector p1 = { PI("M", 1), PI("N", N), PI("K", K), + PI("group", 128), PS("dtype", dt) }; + rc = launch(r, q1, p1); + if (rc != RAD_OK) break; + st_memcpy(single.data(), d_yr, (size_t)N * 2, hipMemcpyDeviceToHost); + for (int64_t n = 0; n < N; ++n) + if (batch[(size_t)(j * N + n)] != single[(size_t)n]) { + if (first < 0) first = j * N + n; + ++different; + } + } + const std::string label = "U5 IQR verify M=" + std::to_string(width) + + " equals independent decodes N=" + std::to_string(N) + + " K=" + std::to_string(K); + ok(label.c_str(), rc == RAD_OK && different == 0 && tail_touched == 0, + "rc=" + std::to_string(rc) + ", differing BF16=" + std::to_string(different) + + ", first=" + std::to_string(first) + ", untouched-tail violations=" + + std::to_string(tail_touched)); + } + } + /* M <= 16 is the GEMV or the 16-token tile, which sum per wave before summing across waves: * the product within f32 rounding, so bf16 outputs a rounding apart. The computed trellis * under a bf16 scale a (row, 128) takes that tile to 64 tokens. Above, the int8 tiles' bytes. */ @@ -6695,7 +6742,7 @@ struct MoeIqrShape { }; static void moe_iqr_case(const Plugin& pl, const MoeIqrShape& sh) { - if (!sel("moe_gemm_iqr")) return; + if (!sel("moe_gemm_iqr") && !sel("moe_iqr_row_invariance")) return; char nm[240]; std::snprintf(nm, sizeof nm, "moe_gemm_iqr %s B=%d L=%d run=%lld E=%lld T=%lld N=%lld:%lld " "K=%lld:%lld", sh.what, sh.B, sh.L, (long long)sh.run, (long long)sh.E, @@ -6863,6 +6910,55 @@ static void moe_iqr_case(const Plugin& pl, const MoeIqrShape& sh) { std::vector y((size_t)(Tr * N)); st_memcpy(y.data(), d_y, y.size() * 2, hipMemcpyDeviceToHost); + /* Exact verify-vs-decode regression: each token's gate/up is routed to the same experts with + * the same activations and weights, once inside this batch and once as a single-token step. + * Preserve every expert/slot association while remapping the sorted rows for the latter. */ + if (g_case && sel("moe_iqr_row_invariance")) { + if (sh.sorted || sh.drop) { ok(nm, false, "regression expects token-order inputs"); dfree_all(); return; } + void* d_so1 = dalloc((size_t)top_k * 4); + void* d_of1 = dalloc((size_t)(E + 1) * 4); + void* d_y1 = dalloc((size_t)(top_k * N) * 2); + if (!d_so1 || !d_of1 || !d_y1) { ok(nm, false, "regression allocation failed"); dfree_all(); return; } + int64_t bad = 0, total = 0; + for (int64_t tok = 0; tok < sh.Mtok; ++tok) { + std::vector so1, of1((size_t)E + 1), original; + for (int64_t e = 0; e < E; ++e) { + of1[(size_t)e] = (int32_t)so1.size(); + for (int32_t i = off[(size_t)e]; i < off[(size_t)e + 1]; ++i) { + const int32_t slot = sorted[(size_t)i]; + if (slot / top_k == tok) { + so1.push_back((int32_t)(slot % top_k)); + original.push_back(i); + } + } + } + of1[(size_t)E] = (int32_t)so1.size(); + if ((int64_t)so1.size() != top_k) { ok(nm, false, "routing remap failed"); dfree_all(); return; } + st_memcpy(d_so1, so1.data(), so1.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_of1, of1.data(), of1.size() * 4, hipMemcpyHostToDevice); + auto t1 = ts; + t1[0] = T((int8_t*)d_a + tok * K, RAD_I8, { 1, K }); + t1[1] = T((float*)d_as + tok * nkb, RAD_F32, { 1, nkb }); + t1[4] = T(d_so1, RAD_I32, { top_k }); + t1[5] = T(d_of1, RAD_I32, { E + 1 }); + t1[8] = T(d_y1, RAD_BF16, { top_k, N }); + auto p1 = ps; p1[0] = PI("M", 1); + const int r1 = launch(r, t1, p1); + if (r1 != RAD_OK) { ok(nm, false, "decode reference rc " + std::to_string(r1)); dfree_all(); return; } + std::vector one((size_t)(top_k * N)); + st_memcpy(one.data(), d_y1, one.size() * 2, hipMemcpyDeviceToHost); + for (int64_t i = 0; i < top_k; ++i) + for (int64_t col = 0; col < N; ++col) { + ++total; + if (one[(size_t)(i * N + col)] != y[(size_t)(original[(size_t)i] * N + col)]) ++bad; + } + } + ok(nm, bad == 0, std::to_string(bad) + " of " + std::to_string(total) + + " BF16 outputs differ from independent decode"); + dfree_all(); + return; + } + /* The reference, a run's rows at a time through the dense row over the same buffers. */ std::vector want((size_t)(Tr * N), 0.0f); std::vector live((size_t)(Tr * N), 0); /* 0: a padding column or a dropped row */ @@ -31992,6 +32088,12 @@ static void device_phase(const Plugin& pl) { iqr_gated_case(pl, b, m, 1024, 1280); iqr_gated_case(pl, 4, 1, 17408, 5120); iqr_gated_case(pl, 4, 9, 17408, 5120); + if (sel("iqr_row_invariance")) { + const IqrCase f{ 6, 5, 0, 16, 1, false, true, true }; + iqr_gemm_case(pl, f, 8, 2048, 2560, true); + iqr_gemm_case(pl, f, 8, 6144, 2560, true); + iqr_gemm_case(pl, f, 8, 8192, 2560, true); + } for (const IqrCase& f : fs) { iqr_gemm_case(pl, f, 1, 512, 1024); iqr_gemm_case(pl, f, 2, 4096, 1024); @@ -32741,6 +32843,12 @@ static void device_phase(const Plugin& pl) { }; for (const MoeIqrShape& sh : kIqr) moe_iqr_case(pl, sh); } + if (g_case && sel("moe_iqr_row_invariance")) { + for (int B : { 4, 5 }) + for (int64_t m : { (int64_t)2, (int64_t)3, (int64_t)4, (int64_t)7 }) + moe_iqr_case(pl, { "row-invariance gate/up", B, 16, 128, 16, 10, m, + 768, 512, 2560, 2560, 2, false, 0 }); + } const bool w4 = sel("moe_gemm_w4a8i8"), w4m = sel("moe_gemm_w4a8i8_mod4"); const bool w8 = sel("moe_gemm_i8a8"), w8m = sel("moe_gemm_i8a8_mod4"); if ((w4 || w4m || w8 || w8m) && !g_case)