Repository navigation
Refactoring: Use STL in input processing and fix off-by-one bug - #115
Closed
thomasantony wants to merge 1 commit into
Closed
thomasantony wants to merge 1 commit into
thomasantony wants to merge 1 commit into
Conversation
thomasantony
force-pushed
the
refactor_input_processing
branch
from
March 14, 2023 05:07
faacdb5 to
68897eb
Compare
ggerganov
added a commit
that referenced
this pull request
Mar 19, 2023
Member
|
Thanks for spotting this! |
jesusmb1995
added a commit
to jesusmb1995/llama.cpp
that referenced
this pull request
Apr 17, 2026
Apply the loop-shape suggested in PR review (ggml-org#115 r3099918856) to the remaining TBQ/PQ vec_dot kernels in ggml/src/ggml-cpu/quants.c, mirroring the pattern already used by ggml_vec_dot_tbq3_0_64_q8_0: - one fewer scratch buffer: drop tmp_y[QK8_0]; q8_0 dequantizes directly into the per-sub-block slice of tmp_y_full (TBQ), or into a single reused tmp_y (PQ, no QJL stage). - one fewer copy loop: no more "tmp_y_full[j*QK8_0+k] = tmp_y[k]" next to the dot accumulation. - one fewer induction variable: replace the running pos++ with the closed-form index &y[i*M + j], with M = QK_{TQ,TQ_64} / QK8_0. - shorter dependency chain on sumf: accumulate per q8_0 sub-block into a local 'acc', sum sub-blocks into a 'base', then update sumf once per outer block (TBQ adds the QJL correction at the same time). - two software prefetches per outer iteration for the next x and y blocks (__builtin_prefetch with rw=0, locality=0). - GGML_RESTRICT on inner xb/yb pointers to make non-aliasing explicit. Kernels touched: - ggml_vec_dot_tbq3_0_q8_0 - ggml_vec_dot_tbq4_0_q8_0 - ggml_vec_dot_pq3_0_q8_0 - ggml_vec_dot_pq3_0_64_q8_0 - ggml_vec_dot_pq4_0_q8_0 - ggml_vec_dot_pq4_0_64_q8_0 The *_64 TBQ kernels already followed this shape and are unchanged. The *_generic wrappers just forward to the main kernels and inherit the changes automatically. Numerics: the algorithm is unchanged; only the FP32 reduction order inside each block changes (associative-only reordering). The QJL correction term and all dequantization paths are bit-identical. Validation on a CPU-only build (Ryzen AI 7 PRO 360, GGML_VULKAN=OFF): - tests/test-turboquant.sh: all checks pass * test-quantize-fns: ok for all TBQ/PQ types * test-quantize-perf perf-sanity gates: ok * test-backend-ops -p "tbq|pq": ok - test-quantize-perf vec_dot_q (4 KB L1-resident microbench, n=10): neutral within ~5% noise, as expected for a fully cache-hot loop where dequantize_row_* dominates and prefetch cannot help. - llama-bench (Mistral-7B-Instruct-v0.3-Q4_K_S, pp128/tg32, fa=on, K=tbq3_0 V=pq3_0, 4 alternating BEFORE/AFTER trials with cooldown): pp: +3.0% mean, won 4/4 trials tg: +3.4% mean, won 4/4 trials - llama-perplexity spot-check on 4 K/V configs x 2 n_ctx (8 datapoints, Mistral-7B-Q4_K_S, wikitext-2, 2 chunks each, fa=on): 5/8 datapoints PPL <= baseline, 3/8 slightly above mean delta = -0.09%, range [-1.49%, +1.22%] all well inside per-chunk stdev (~+/-1.3 absolute, ~+/-11%) -> symmetric around zero, consistent with FP32 reduction-order rounding noise; no regression.
jesusmb1995
added a commit
to jesusmb1995/llama.cpp
that referenced
this pull request
Apr 17, 2026
The `GG_BUILD_LOW_PERF` → `-DGGML_NATIVE=OFF` append was placed inside `gg_run_ctest_release`, but the top-level driver runs `gg_run ctest_debug` first and `gg_run ctest_release` second. As a result the debug build on the low-perf CI runners (`ggml-ci-x64-cpu-low-perf` and `ggml-ci-arm64-cpu-low-perf`) was compiled with `-march=native` against the build host's CPU and then executed on a different, older-microarch runner in the pool, producing SIGILL during ctest_debug. Ref PR ggml-org#115 CI run 24463228694. Move the append into the top-level flag-handling block, right after `GG_BUILD_NO_SVE`, so `CMAKE_EXTRA` gets `-DGGML_NATIVE=OFF` once, before either ctest function is invoked, and both debug and release builds pick it up. Remove the duplicate inside `gg_run_ctest_release`. No workflow change required: `.github/workflows/build.yml` already exports `GG_BUILD_LOW_PERF=1` for the two low-perf jobs, which was correct; the bug was purely a scoping error in `ci/run.sh`. The other `GG_BUILD_LOW_PERF` checks in the script (ctest label filter, and the top-level branches that skip heavier test functions) are left untouched — they were already at the correct scope.
jesusmb1995
added a commit
to jesusmb1995/llama.cpp
that referenced
this pull request
Apr 20, 2026
The `GG_BUILD_LOW_PERF` → `-DGGML_NATIVE=OFF` append was placed inside
`gg_run_ctest_release`, but the top-level driver runs `gg_run
ctest_debug` first and `gg_run ctest_release` second. As a result the
debug build on the low-perf CI runners (`ggml-ci-x64-cpu-low-perf`
and `ggml-ci-arm64-cpu-low-perf`) was compiled with `-march=native`
against the build host's CPU and then executed on a different,
older-microarch runner in the pool, producing SIGILL during
ctest_debug. Ref PR ggml-org#115 CI run 24463228694.
Move the append into the top-level flag-handling block, right after
`GG_BUILD_NO_SVE`, so `CMAKE_EXTRA` gets `-DGGML_NATIVE=OFF` once,
before either ctest function is invoked, and both debug and release
builds pick it up. Remove the duplicate inside `gg_run_ctest_release`.
No workflow change required: `.github/workflows/build.yml` already
exports `GG_BUILD_LOW_PERF=1` for the two low-perf jobs, which was
correct; the bug was purely a scoping error in `ci/run.sh`. The other
`GG_BUILD_LOW_PERF` checks in the script (ctest label filter, and the
top-level branches that skip heavier test functions) are left
untouched — they were already at the correct scope.
diff --git a/ci/run.sh b/ci/run.sh
index 7fa469b..5c2f7e7 100755
--- a/ci/run.sh
+++ b/ci/run.sh
@@ -118,6 +118,15 @@ if [ ! -z ${GG_BUILD_NO_SVE} ]; then
CMAKE_EXTRA="${CMAKE_EXTRA} -DGGML_NATIVE=OFF -DGGML_CPU_ARM_ARCH=armv8.5-a+fp16+i8mm"
fi
+# Disable native CPU optimizations for low-perf builds to ensure binary
+# compatibility with the (often heterogeneous) CI runner pool. Must be applied
+# at the top level so BOTH gg_run_ctest_debug and gg_run_ctest_release pick it
+# up — otherwise the debug build (which runs first) compiles with -march=native
+# and can SIGILL on a runner whose microarch is older than the build host.
+if [ ! -z ${GG_BUILD_LOW_PERF} ]; then
+ CMAKE_EXTRA="${CMAKE_EXTRA} -DGGML_NATIVE=OFF"
+fi
+
if [ -n "${GG_BUILD_KLEIDIAI}" ]; then
echo ">>===== Enabling KleidiAI support"
@@ -236,11 +245,6 @@ function gg_run_ctest_release {
# Check cmake, make and ctest are installed
gg_check_build_requirements
- # Disable native CPU optimizations for low-perf builds to ensure compatibility
- if [ ! -z ${GG_BUILD_LOW_PERF} ]; then
- CMAKE_EXTRA="${CMAKE_EXTRA} -DGGML_NATIVE=OFF"
- fi
-
(time cmake -DCMAKE_BUILD_TYPE=Release ${CMAKE_EXTRA} .. ) 2>&1 | tee -a $OUT/${ci}-cmake.log
(time make -j$(nproc) ) 2>&1 | tee -a $OUT/${ci}-make.log
diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp
index 247775b..bcc1759 100644
--- a/src/llama-graph.cpp
+++ b/src/llama-graph.cpp
@@ -49,6 +49,25 @@ static ggml_tensor * ggml_rotate_hadamard(
return res;
}
+// Allocate the Hadamard rotation input used by ggml_rotate_hadamard() for a
+// TurboQuant/PolarQuant K or V stream. Size is the largest power-of-two that
+// divides n_embd_head (>= 64), so the rotation matches the head dim and the
+// PQ/TBQ codebooks see the full d-wide rotated distribution they were fitted
+// to. Returns nullptr when can_rot is false.
+static ggml_tensor * build_hadamard_rot(ggml_context * ctx, bool can_rot, int n_embd_head) {
+ if (!can_rot) {
+ return nullptr;
+ }
+
+ int nrot = 64;
+ do { nrot *= 2; } while (n_embd_head % nrot == 0);
+ nrot /= 2;
+
+ ggml_tensor * rot = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, nrot, nrot);
+ ggml_set_input(rot);
+ return rot;
+}
+
void llm_graph_input_embd::set_input(const llama_ubatch * ubatch) {
if (ubatch->token) {
const int64_t n_tokens = ubatch->n_tokens;
@@ -1626,30 +1645,13 @@ static std::unique_ptr<llm_graph_input_attn_kv> build_attn_inp_kv_impl(
hparams.n_embd_head_k % 64 == 0 &&
ggml_is_quantized(mctx_cur->type_k());
- if (can_rotk) {
- int nrot = 64;
- do { nrot *= 2; } while (hparams.n_embd_head_k % nrot == 0);
- nrot /= 2;
-
- inp->self_rotk = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, nrot, nrot);
- ggml_set_input(inp->self_rotk);
- } else {
- inp->self_rotk = nullptr;
- }
-
const bool can_rotv =
!hparams.is_n_embd_v_gqa_variable() &&
hparams.n_embd_head_v % 64 == 0 &&
ggml_is_quantized(mctx_cur->type_v());
- if (can_rotv) {
- int nrot = 64;
-
- inp->self_rotv = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, nrot, nrot);
- ggml_set_input(inp->self_rotv);
- } else {
- inp->self_rotv = nullptr;
- }
+ inp->self_rotk = build_hadamard_rot(ctx0, can_rotk, hparams.n_embd_head_k);
+ inp->self_rotv = build_hadamard_rot(ctx0, can_rotv, hparams.n_embd_head_v);
}
return inp;
@@ -1947,30 +1949,13 @@ llm_graph_input_attn_kv_iswa * llm_graph_context::build_attn_inp_kv_iswa() const
hparams.n_embd_head_k % 64 == 0 &&
ggml_is_quantized(mctx_cur->get_base()->type_k());
- if (can_rotk) {
- int nrot = 64;
- do { nrot *= 2; } while (hparams.n_embd_head_k % nrot == 0);
- nrot /= 2;
-
- inp->self_rotk = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, nrot, nrot);
- ggml_set_input(inp->self_rotk);
- } else {
- inp->self_rotk = nullptr;
- }
-
const bool can_rotv =
!hparams.is_n_embd_v_gqa_variable() &&
hparams.n_embd_head_v % 64 == 0 &&
ggml_is_quantized(mctx_cur->get_base()->type_v());
- if (can_rotv) {
- int nrot = 64;
-
- inp->self_rotv = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, nrot, nrot);
- ggml_set_input(inp->self_rotv);
- } else {
- inp->self_rotv = nullptr;
- }
+ inp->self_rotk = build_hadamard_rot(ctx0, can_rotk, hparams.n_embd_head_k);
+ inp->self_rotv = build_hadamard_rot(ctx0, can_rotv, hparams.n_embd_head_v);
}
return (llm_graph_input_attn_kv_iswa *) res->add_input(std::move(inp));
jesusmb1995
added a commit
to jesusmb1995/llama.cpp
that referenced
this pull request
Apr 20, 2026
Register explicit `MUL_MAT` test cases for the TurboQuant / PolarQuant
types (`tbq3_0`, `tbq4_0`, `pq3_0`, `pq4_0`) with `type_b ∈ {f32, f16}`
and sizes that span both dispatch paths:
- n=1, n=8 -> mul_mat_vec path (decode-like)
- n=16, n=32 -> dequant + f16 matmul path (prefill-like)
Motivation: the existing TBQ/PQ coverage in `test-backend-ops` only
registers `FLASH_ATTN_EXT` cases, so the `tests/test-turboquant.sh`
filter (`test-backend-ops test -p "tbq|pq"`) never exercises the
standalone `MUL_MAT` path. That path is the one reported as
`supports_op == yes` on NV `VK_NV_cooperative_matrix2` devices but has
no matching pipeline created in `pipeline_dequant_mul_mat_mat_f16[]`
(see `ggml-vulkan.cpp:3412` — "TBQ/PQ cm2 matmul shaders not yet
generated"). With these cases in place:
- On NV coopmat2 (RTX 5090): the n>=16 cases segfault, matching the
external reproduction from the PR ggml-org#115 review and making the bug
visible to CI.
- On KHR coopmat1 (AMD gfx1150): the n>=16 cases return numerical
garbage (err ~ 1.0), exposing the same missing-fallback issue in
a non-crashing form.
- The n=1/n=8 cases continue to pass via the existing
`mul_mat_vec_tbq*_0` / `mul_mat_vec_pq*_0` shaders, so the new
coverage cleanly isolates which dispatch path is broken.
No source changes to the Vulkan backend; this commit only adds the
test cases needed so the pre-existing bug is caught by
`tests/test-turboquant.sh`.
jesusmb1995
added a commit
to jesusmb1995/llama.cpp
that referenced
this pull request
Apr 20, 2026
…d=64 variants Before this patch, `supports_op` reported TBQ3_0/TBQ4_0/PQ3_0/PQ4_0 (and their `_64` / head_dim=64 variants) as supported for `GGML_OP_MUL_MAT` on the Vulkan backend, but there was no working pipeline behind it. This is the state the external review flags as Issue 3 on PR ggml-org#115: on cm2 (RTX 5090) the support probe claims support, the correctness run then segfaults. The previous `test-backend-ops` commit adds the exact repro for this. Root causes: - On cm2 (NV coopmat2) devices the slot in `pipeline_dequant_mul_mat_mat_f16[]` was empty - the shader was never generated - so dispatches crashed when flash attention was not used. - On cm1 and scalar devices the slot in `pipeline_dequant_mul_mat_mat[]` was wired up, but `mul_mm_funcs.glsl` had no `load_a_to_shmem` implementation for TBQ/PQ. The generic `mul_mm.comp` ran with uninitialized shared memory and produced near-random output. - Even once data loading was fixed, TBQ3_0/TBQ4_0 still produced a small bias for `n > mul_mat_vec_max_cols` because the QJL Stage 2 correction that `mul_mat_vec_tbq*_0.comp` applies in the vec path has no equivalent in the generic matmul shader. - For head_dim=64 models that use the `_64` block variants (TBQ*_0_64 / PQ*_0_64) the `_64` mul_mm pipelines, the `_64` QJL correction shaders, and the `_64`-sized Lloyd-Max codebook / sign arrays were missing, and the vec path is intentionally skipped for `_64` (so every `n` needs the full matmul + QJL correction pair). Scope of this patch is strictly the standalone `MUL_MAT` path with TBQ/PQ `src0` and f32 `src1` that the Issue 3 repro hits, i.e. the `-fa off` K matmul. Fused flash attention (scalar, cm1, cm2) already handles QJL correctly and is unchanged. MoE FFN weights are not affected either: TBQ/PQ are KV-cache quantizations (there is no `llama-quantize` target that produces TBQ/PQ model weights), so `MUL_MAT_ID` never sees them as `src0` - attention in MoE models is a plain `MUL_MAT` / `FLASH_ATTN_EXT` and reuses the same fix. The upstream "V cache quantization requires flash_attn" context-level guard in `src/llama-context.cpp` is intentionally left unchanged: the V matmul under `-fa off` uses a transposed quantized-V layout populated by `ggml_set_rows` with row_size=1, which corrupts any `blck_size > 1` type at write time (reproducible on CPU as well), and that is a separate KV-cache issue out of scope here. Changes: - Add `load_a_to_shmem` implementations for TBQ3_0, TBQ4_0, PQ3_0, PQ4_0 (and their `_64` variants) in `mul_mm_funcs.glsl`, reusing `tbq3_dequant_raw` / `tbq4_dequant_raw` from `tq_utils.comp`. This makes `mul_mm.comp` correct for the centroid part of dequantization (`tbq*_dequant_raw(qs) * d`) on all eight types. - `tq_utils.comp`: pick Stage-1 / QJL-Stage-2 sign bitmasks and the Lloyd-Max codebook (TBQ3_CB / TBQ4_CB) based on whether any `DATA_{A,K,V}_*_0_64` is defined. d=64 blocks use seeds 43/139 and a wider codebook (sigma = 1/sqrt(d) is larger at d=64 than at d=128); previously the shader hardcoded the d=128 constants, so the d=64 variants silently dequantized against the wrong codebook. - New shader `mul_mm_tbq_qjl_correction.comp`. It runs after the main matmul as an additive pass: one workgroup per `(row, col, batch)`, `QUANT_K` threads performing the same Walsh-Hadamard butterfly + `qjl[]` dot product as the vec shader, and accumulates `d_r * sqrt(pi/2) / QUANT_K * sum_qjl(H(B))` into D. Parameterized over `QUANT_K` so the same source emits both `_128` and `_64` SPIR-V. Only TBQ3_0 and TBQ4_0 (and `_64`) have `d_r`/`qjl`, so only those four get a correction pipeline. - `vulkan-shaders-gen.cpp`: * Register the eight correction variants (`mul_mm_qjl_{tbq3_0,tbq4_0}{,_64}_{f32,f16}`). * Emit `matmul_{tbq,pq}{3,4}_0_64_{f32,f16}[_aligned]` for `mul_mm.comp`, in a dedicated block outside the main `type_names` loop so we don't cascade through FA / MUL_MAT_ID / get_rows / ... which either already have dedicated `_64` handling (FA) or don't apply to TBQ/PQ at all. - `ggml-vulkan.cpp`: * Add `pipeline_mul_mm_tbq_qjl[GGML_TYPE_COUNT][2]` on the device and create pipelines at init time for all four TBQ types (128 and 64 block sizes). * In `ggml_vk_get_mul_mat_mat_pipeline`, let cm2 fall through to the cm1/scalar pipeline when no cm2 `_mat_f16` shader exists for a given TBQ/PQ type, so cm2 devices stop segfaulting on these types. * Register TBQ/PQ `_64` in `supports_op` `MUL_MAT` switch so d=64 models are actually routed to the new pipelines instead of falling back to CPU. * Force `split_k = 1` for TBQ `src0` - the QJL correction pass would otherwise be added once per split. * Dispatch the QJL correction pass after the main matmul for TBQ3_0 / TBQ4_0 (and `_64`). For `_128` it's gated on `n > mul_mat_vec_max_cols` (the vec path already corrects for smaller n); for `_64` it runs unconditionally because there is no vec path on this block size. Verified on AMD RDNA3.5 (RADV gfx1150, no cm1/cm2) with `test-backend-ops -o MUL_MAT -b Vulkan0`: all 32 TBQ/PQ x {128, 64} x n in {1,8,16,32} cases pass against f32 B. f16 B for standalone MUL_MAT on TBQ/PQ still reports `not supported` on this device (the scalar/cm1 pipeline consumes f32 src1), which is consistent with the matmul path shipping f32 src1 on the `-fa off` decode/prefill paths used by these tests. cm2 verification is expected to run on the reviewer's RTX 5090 via the Issue 3 repro branch. debug: sentinel in QJL correction vulkan: add dequantize-to-f16 cpy shaders so MUL_MAT with non-contiguous quantized src0 can run on GPU
jesusmb1995
added a commit
to jesusmb1995/llama.cpp
that referenced
this pull request
Apr 21, 2026
…d=64 variants Before this patch, `supports_op` reported TBQ3_0/TBQ4_0/PQ3_0/PQ4_0 (and their `_64` / head_dim=64 variants) as supported for `GGML_OP_MUL_MAT` on the Vulkan backend, but there was no working pipeline behind it. This is the state the external review flags as Issue 3 on PR ggml-org#115: on cm2 (RTX 5090) the support probe claims support, the correctness run then segfaults. The previous `test-backend-ops` commit adds the exact repro for this. Root causes: - On cm2 (NV coopmat2) devices the slot in `pipeline_dequant_mul_mat_mat_f16[]` was empty - the shader was never generated - so dispatches crashed when flash attention was not used. - On cm1 and scalar devices the slot in `pipeline_dequant_mul_mat_mat[]` was wired up, but `mul_mm_funcs.glsl` had no `load_a_to_shmem` implementation for TBQ/PQ. The generic `mul_mm.comp` ran with uninitialized shared memory and produced near-random output. - Even once data loading was fixed, TBQ3_0/TBQ4_0 still produced a small bias for `n > mul_mat_vec_max_cols` because the QJL Stage 2 correction that `mul_mat_vec_tbq*_0.comp` applies in the vec path has no equivalent in the generic matmul shader. - For head_dim=64 models that use the `_64` block variants (TBQ*_0_64 / PQ*_0_64) the `_64` mul_mm pipelines, the `_64` QJL correction shaders, and the `_64`-sized Lloyd-Max codebook / sign arrays were missing, and the vec path is intentionally skipped for `_64` (so every `n` needs the full matmul + QJL correction pair). Scope of this patch is strictly the standalone `MUL_MAT` path with TBQ/PQ `src0` and f32 `src1` that the Issue 3 repro hits, i.e. the `-fa off` K matmul. Fused flash attention (scalar, cm1, cm2) already handles QJL correctly and is unchanged. MoE FFN weights are not affected either: TBQ/PQ are KV-cache quantizations (there is no `llama-quantize` target that produces TBQ/PQ model weights), so `MUL_MAT_ID` never sees them as `src0` - attention in MoE models is a plain `MUL_MAT` / `FLASH_ATTN_EXT` and reuses the same fix. The upstream "V cache quantization requires flash_attn" context-level guard in `src/llama-context.cpp` is intentionally left unchanged: the V matmul under `-fa off` uses a transposed quantized-V layout populated by `ggml_set_rows` with row_size=1, which corrupts any `blck_size > 1` type at write time (reproducible on CPU as well), and that is a separate KV-cache issue out of scope here. Changes: - Add `load_a_to_shmem` implementations for TBQ3_0, TBQ4_0, PQ3_0, PQ4_0 (and their `_64` variants) in `mul_mm_funcs.glsl`, reusing `tbq3_dequant_raw` / `tbq4_dequant_raw` from `tq_utils.comp`. This makes `mul_mm.comp` correct for the centroid part of dequantization (`tbq*_dequant_raw(qs) * d`) on all eight types. - `tq_utils.comp`: pick Stage-1 / QJL-Stage-2 sign bitmasks and the Lloyd-Max codebook (TBQ3_CB / TBQ4_CB) based on whether any `DATA_{A,K,V}_*_0_64` is defined. d=64 blocks use seeds 43/139 and a wider codebook (sigma = 1/sqrt(d) is larger at d=64 than at d=128); previously the shader hardcoded the d=128 constants, so the d=64 variants silently dequantized against the wrong codebook. - New shader `mul_mm_tbq_qjl_correction.comp`. It runs after the main matmul as an additive pass: one workgroup per `(row, col, batch)`, `QUANT_K` threads performing the same Walsh-Hadamard butterfly + `qjl[]` dot product as the vec shader, and accumulates `d_r * sqrt(pi/2) / QUANT_K * sum_qjl(H(B))` into D. Parameterized over `QUANT_K` so the same source emits both `_128` and `_64` SPIR-V. Only TBQ3_0 and TBQ4_0 (and `_64`) have `d_r`/`qjl`, so only those four get a correction pipeline. - `vulkan-shaders-gen.cpp`: * Register the eight correction variants (`mul_mm_qjl_{tbq3_0,tbq4_0}{,_64}_{f32,f16}`). * Emit `matmul_{tbq,pq}{3,4}_0_64_{f32,f16}[_aligned]` for `mul_mm.comp`, in a dedicated block outside the main `type_names` loop so we don't cascade through FA / MUL_MAT_ID / get_rows / ... which either already have dedicated `_64` handling (FA) or don't apply to TBQ/PQ at all. - `ggml-vulkan.cpp`: * Add `pipeline_mul_mm_tbq_qjl[GGML_TYPE_COUNT][2]` on the device and create pipelines at init time for all four TBQ types (128 and 64 block sizes). * In `ggml_vk_get_mul_mat_mat_pipeline`, let cm2 fall through to the cm1/scalar pipeline when no cm2 `_mat_f16` shader exists for a given TBQ/PQ type, so cm2 devices stop segfaulting on these types. * Register TBQ/PQ `_64` in `supports_op` `MUL_MAT` switch so d=64 models are actually routed to the new pipelines instead of falling back to CPU. * Force `split_k = 1` for TBQ `src0` - the QJL correction pass would otherwise be added once per split. * Dispatch the QJL correction pass after the main matmul for TBQ3_0 / TBQ4_0 (and `_64`). For `_128` it's gated on `n > mul_mat_vec_max_cols` (the vec path already corrects for smaller n); for `_64` it runs unconditionally because there is no vec path on this block size. Verified on AMD RDNA3.5 (RADV gfx1150, no cm1/cm2) with `test-backend-ops -o MUL_MAT -b Vulkan0`: all 32 TBQ/PQ x {128, 64} x n in {1,8,16,32} cases pass against f32 B. f16 B for standalone MUL_MAT on TBQ/PQ still reports `not supported` on this device (the scalar/cm1 pipeline consumes f32 src1), which is consistent with the matmul path shipping f32 src1 on the `-fa off` decode/prefill paths used by these tests. cm2 verification is expected to run on the reviewer's RTX 5090 via the Issue 3 repro branch. debug: sentinel in QJL correction vulkan: add dequantize-to-f16 cpy shaders so MUL_MAT with non-contiguous quantized src0 can run on GPU vulkan: add d=64 decision boundaries for TBQ/PQ copy_to_quant Commit 6e26e8b ("vulkan: fix TBQ/PQ standalone MUL_MAT path, QJL correction pass, and d=64 variants") added TQ_D64-gated d=64 Lloyd-Max codebook centroids and random sign diagonals to tq_utils.comp, so that the Vulkan encoder, FA decoder, and non-FA QJL correction pass all match the CPU reference's d=64 constants (ggml-quants.c: TQ{3,4}_CODEBOOK_64, TQ/QJL_SIGN_SEED_64). It missed the corresponding d=64 *decision boundaries* in copy_to_quant.comp, however. The boundaries are the midpoints between adjacent codebook centroids and determine which centroid an input coordinate is quantized to. CPU derives them at runtime from the selected codebook via tq_compute_boundaries(), so it automatically used the d=64 midpoints for _64 blocks. The Vulkan encoder hard-codes them as const float TBQ3_B[7] / TBQ4_B[15], and those constants remained at the d=128 midpoints even inside the #if block that accepts both DATA_A_TBQ*_0 and DATA_A_TBQ*_0_64. Net effect on a head_dim=64 model (Qwen2.5-0.5B): - copy_to_quant bucketed each coordinate by the narrower d=128 boundaries (centroids spaced ~sigma=1/sqrt(128)). - The resulting index was then dequantized with the wider d=64 centroids (spaced ~sigma=1/sqrt(64)), a completely different alphabet. - Every value near a boundary landed on the wrong centroid. Before commit 6e26e8b this was silently consistent: the codebook was also d=128, so encoder and decoder were at least in agreement (just producing a rescaled quantization). When the codebook was fixed to d=64, the boundaries had to move with it. Add a #if defined(TQ_D64) branch for TBQ3_B and TBQ4_B that uses the d=64 midpoints computed from TQ{3,4}_CODEBOOK_64. Values regenerated with scripts/compute_tq_codebooks.py, which now also emits the GLSL boundaries array alongside the C codebook array so future codebook updates keep the two in sync from one source of truth. Measured impact on Qwen2.5-0.5B-Instruct-Q8_0, wiki.test offset_64 (--chunks 1), Vulkan AMD RADV gfx1150: tbq3_0 / f16 fa=off: 1659 -> 230 (7.2x better) tbq4_0 / f16 fa=off: ~ -> 300 pq3_0 / f16 fa=off: ~ -> 230 pq4_0 / f16 fa=off: ~ -> 300 pq3_0 / f16 fa=on: ~ -> 225 (now matches fa=off) pq4_0 / f16 fa=on: ~ -> 299 (now matches fa=off) tbq3_0/tbq4_0 fa=on still diverges from fa=off due to a separate issue in the FA QJL Stage-2 correction on d=64 blocks, addressed in a follow- up patch. vulkan: read raw Q from the input SSBO for the FA QJL projection The flash-attention shaders compute the QJL Stage-2 correction as correction = d_r * sqrt(pi/2) / QUANT_K * (2*pos_sum - proj_q_sum) where (pos_sum, proj_q_sum) are reductions over FHT(D_qjl * Q). The scalar (flash_attn.comp) and coopmat1 (flash_attn_cm1.comp) paths used to derive the FHT input by reading from Qf -- the shared-memory buffer that already has the attention scale (1/sqrt(head_dim)) multiplied in for the main Q*K dot -- and then dividing that value by p.scale to recover the raw Q before multiplying by the QJL sign diagonal. On cm1 Qf is f16, so the scale round-trip is lossy for the large- magnitude activations seen in e.g. Qwen2.5-0.5B's first-layer massive activations. On the scalar path Qf is f32 and p.scale is usually a power of two (1/sqrt(head_dim)), so x * p.scale / p.scale is bit-exact in principle -- but empirically the pre-scaled-then-un-scaled read still produced materially different FHT input than a raw-Q read. The standalone non-FA QJL shader (mul_mm_tbq_qjl_correction.comp) has always read Q directly from src1 and gets correct results. Match that pattern in the FA path: read Q straight from the data_qv4 SSBO into Qf_qjl_proj, bypassing Qf entirely. cm2 already reads raw Q from data_q directly, so it does not need the change. Measured impact on Qwen2.5-0.5B-Instruct-Q8_0, wikitext-2 test (Vulkan AMD RADV gfx1150): wiki.test --chunks 4 -n 128, K=tbq3_0/f16: fa=off : 531 fa=on, before : ~2000 (broken) fa=on, after : 154 wiki.test --chunks 4 -n 128, K=tbq4_0/f16: fa=off : 207 fa=on, after : 77 K=f16/f16 and K=pq*/V=f16 fa=on/off stay within 1% of each other, confirming the change is confined to the TBQ QJL path. vulkan: run non-FA TBQ QJL correction on permuted src0 too The standalone MUL_MAT QJL (Stage 2) correction pass was gated on `!x_non_contig`, which silently skipped the correction on the no-FA attention path because `kq = mul_mat(k, q)` feeds in K after `ggml_permute(k, 0, 2, 1, 3)` -- a non-dim01-contiguous view of the KV cache. With that gate the TBQ attention on the no-FA path was reduced to PQ Stage 1 (centroid-only), producing bit-identical output to `pq3_0` / `pq4_0` and regressing quality vs a CPU-reference TBQ run. It was masked on the MUL_MAT test-backend-ops coverage because those tests use contiguous src0. Two changes: * mul_mm_tbq_qjl_correction.comp: index the A matrix by a real in-memory block stride instead of the `num_blocks_per_row = K / QUANT_K` shortcut. `p.stride_a` and `p.batch_stride_a` are now interpreted as strides in BLOCK units (src0->nb[1] / sizeof(block) and src0->nb[2] / sizeof(block) respectively), matching the way `ggml_vk_flash_attn` already feeds `k_stride` / `k_offset` to the FA shader. For a contiguous src0 the new stride equals the old num_blocks_per_row, so existing tests are unaffected. * ggml_vk_mul_mat_q_f16: compute `qjl_stride_a` / `qjl_stride_batch_a` from src0->nb and drop the `!x_non_contig` exclusion from both the descriptor-set request and the dispatch site. The `qx_buf_offset` still points at the original (pre-permute) TBQ blocks in d_Qx, which is exactly what the correction pass wants -- it just needed the real strides to reach the right block for each (row_a, batch_id). Both paths have to be gated identically -- if only one of them is changed, the dispatched pipeline ends up without a descriptor set and `vkCmdPushConstants` crashes with VK_NULL_HANDLE layout. Measured impact on Qwen2.5-0.5B-Instruct-Q8_0, wiki.test --chunks 4 -n 128 (Vulkan AMD RADV gfx1150): K=tbq3_0 V=f16 fa=off (vs fa=off pq3_0): before fix: 561 == 561 (QJL silently skipped, TBQ==PQ) after fix : 634 != 561 (QJL running, TBQ distinct from PQ) CPU ref : 546 K=tbq4_0 V=f16 fa=off (vs fa=off pq4_0): before fix: 173 == 173 (QJL silently skipped) after fix : 133 != 173 (QJL running, 23% lower PPL) CPU ref : 154 f16/f16 and pq* paths are unchanged: the gate only opens for TBQ. FA is unaffected since it has its own inlined QJL epilogue.
Seunghhon
pushed a commit
to Seunghhon/llama.cpp
that referenced
this pull request
Apr 26, 2026
phuongncn
pushed a commit
to phuongncn/llama.cpp-gx10-dgx-sparks-deepseekv4
that referenced
this pull request
Apr 28, 2026
* MMQ for Q6_0 * Add Q6_0 MMQ to template generator --------- Co-authored-by: Iwan Kawrakow <[email protected]>
LifesLight
pushed a commit
to LifesLight/custom.llama.cpp
that referenced
this pull request
May 2, 2026
Cherry-pick signalnine PR ggml-org#53: auto-asymmetric GQA + turbo VEC FA opts
ljubomirj
pushed a commit
to ljubomirj/llama.cpp
that referenced
this pull request
May 6, 2026
jimbothigpen
added a commit
to jimbothigpen/af-engn
that referenced
this pull request
May 21, 2026
Port the layer-adaptive KV precision block from TheTom's TQ-KV state (5aeb2fd llama-kv-cache.cpp lines 267-326) plus mode 7 from da4a02e. Steps 1-4's cumulative ports landed everything else recon/08 §Step 5 intended; Step 5 is reduced to this single block (gap analysis in body). Modes: - 0 = uniform (default, no behavior change) - 1 = q8_0 K+V for first 4 + last 4 layers (turbo K+V outer-protection) - 2 = q8_0 K+V for last 8 layers - 5 = first2+last2 V=TURBOQ4_0, rest V=TURBOQ3_0 (K unchanged) - 6 = last8 V=TURBOQ4_0, rest V=TURBOQ3_0 (K unchanged) - 7 = Boundary V (recommended): first2+last2 V=q8_0, rest V=TURBOQ3_0 (K unchanged) Yggdrasil adjustments: - TURBO2_0 (TQ-KV slot 42) substituted with TURBOQ3_0 in the "middle" slot of modes 5/6/7. TURBOQ2_0 is deferred per phase-1 scope; when it lands, restore TURBO2_0 -> TURBOQ2_0 in those three branches to recover TQ-KV's original compression ratios. - TQ-KV's auto-enable on V=TURBO2_0 is intentionally dropped per recon/08 §Step 5 validation ("Boundary V default-off — no behavioral change without explicit flag"). Mode 0 stays the default. - Banner LLAMA_LOG_INFO uses a per-constructor-call local flag, not a static, because fit-probe + real construction each invoke the constructor; logger output is suppressed during the probe pass. Gap analysis (recon/08 §Step 5 commits, post-Step-3 cumulative-port state): - f2b3936 Metal asymmetric K/V: SKIP — Metal-only, no Metal backend. - 0fa61d7 PR ggml-org#115 auto-asymmetric merge: already absorbed via Step 3 (5aeb2fd). fattn-vec.cuh has K_is_turbo/V_is_turbo; is_kv_compat permits asymmetric pairs of {TURBOQ3_0, TURBOQ4_0, Q8_0, F16, BF16}. - b6f8e7f ggml-org#78 GQA reshape fix: N/A — targets padded_v_head / orig_v_head block in build_attn that doesn't exist in yggdrasil (mainline post-April refactor never had it). - e9f05a9 64-elem WHT + MLA Q rotation: partially absorbed (CUDA kernel supports group_size {128,64,32}); ggml_turbo_wht C-API stays 3-arg with hardcoded group_size=128 + assert ne[0]%128==0. The K-only build_attn Q rotation + %64 fallback are MLA-only; Phase 1 baseline (Qwen3.5-9B head_dim=128) doesn't exercise them. - 53ca939 MLA inverse WHT group_size from K: MLA-only. Deferred to a future phase that adds an MLA model (DeepSeek-V2 head_dim 192, GLM-4.7 head_dim 576): C-API extension of ggml_turbo_wht to take explicit group_size, Q rotation in inp_attn_k build_attn, %64 fallback, 53ca939's K-derived inverse-WHT guard. PPL parity gate (Qwen3.5-9B-BF16, 32-chunk c=512, eval-shared wikitext): | Backend | mode | PPL | |---------|---------|--------| | ROCm | default | 7.5939 | (= session 11, bit-identical: no regression) | Vulkan | default | 7.6065 | (= session 11, bit-identical: no regression) Cross-backend Δ = +0.17% (well within <0.5% threshold per design decision ggml-org#9). Mode 7 activation spot-check (4-chunk): | Backend | mode | PPL | |---------|------|--------| | ROCm | 0 | 8.2261 | | ROCm | 7 | 8.1180 | (-1.31%; boundary q8_0-V improves quality) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
jimbothigpen
added a commit
to jimbothigpen/af-engn
that referenced
this pull request
May 25, 2026
Port the layer-adaptive KV precision block from TheTom's TQ-KV state (5aeb2fd llama-kv-cache.cpp lines 267-326) plus mode 7 from da4a02e. Steps 1-4's cumulative ports landed everything else recon/08 §Step 5 intended; Step 5 is reduced to this single block (gap analysis in body). Modes: - 0 = uniform (default, no behavior change) - 1 = q8_0 K+V for first 4 + last 4 layers (turbo K+V outer-protection) - 2 = q8_0 K+V for last 8 layers - 5 = first2+last2 V=TURBOQ4_0, rest V=TURBOQ3_0 (K unchanged) - 6 = last8 V=TURBOQ4_0, rest V=TURBOQ3_0 (K unchanged) - 7 = Boundary V (recommended): first2+last2 V=q8_0, rest V=TURBOQ3_0 (K unchanged) Yggdrasil adjustments: - TURBO2_0 (TQ-KV slot 42) substituted with TURBOQ3_0 in the "middle" slot of modes 5/6/7. TURBOQ2_0 is deferred per phase-1 scope; when it lands, restore TURBO2_0 -> TURBOQ2_0 in those three branches to recover TQ-KV's original compression ratios. - TQ-KV's auto-enable on V=TURBO2_0 is intentionally dropped per recon/08 §Step 5 validation ("Boundary V default-off — no behavioral change without explicit flag"). Mode 0 stays the default. - Banner LLAMA_LOG_INFO uses a per-constructor-call local flag, not a static, because fit-probe + real construction each invoke the constructor; logger output is suppressed during the probe pass. Gap analysis (recon/08 §Step 5 commits, post-Step-3 cumulative-port state): - f2b3936 Metal asymmetric K/V: SKIP — Metal-only, no Metal backend. - 0fa61d7 PR ggml-org#115 auto-asymmetric merge: already absorbed via Step 3 (5aeb2fd). fattn-vec.cuh has K_is_turbo/V_is_turbo; is_kv_compat permits asymmetric pairs of {TURBOQ3_0, TURBOQ4_0, Q8_0, F16, BF16}. - b6f8e7f ggml-org#78 GQA reshape fix: N/A — targets padded_v_head / orig_v_head block in build_attn that doesn't exist in yggdrasil (mainline post-April refactor never had it). - e9f05a9 64-elem WHT + MLA Q rotation: partially absorbed (CUDA kernel supports group_size {128,64,32}); ggml_turbo_wht C-API stays 3-arg with hardcoded group_size=128 + assert ne[0]%128==0. The K-only build_attn Q rotation + %64 fallback are MLA-only; Phase 1 baseline (Qwen3.5-9B head_dim=128) doesn't exercise them. - 53ca939 MLA inverse WHT group_size from K: MLA-only. Deferred to a future phase that adds an MLA model (DeepSeek-V2 head_dim 192, GLM-4.7 head_dim 576): C-API extension of ggml_turbo_wht to take explicit group_size, Q rotation in inp_attn_k build_attn, %64 fallback, 53ca939's K-derived inverse-WHT guard. PPL parity gate (Qwen3.5-9B-BF16, 32-chunk c=512, eval-shared wikitext): | Backend | mode | PPL | |---------|---------|--------| | ROCm | default | 7.5939 | (= session 11, bit-identical: no regression) | Vulkan | default | 7.6065 | (= session 11, bit-identical: no regression) Cross-backend Δ = +0.17% (well within <0.5% threshold per design decision ggml-org#9). Mode 7 activation spot-check (4-chunk): | Backend | mode | PPL | |---------|------|--------| | ROCm | 0 | 8.2261 | | ROCm | 7 | 8.1180 | (-1.31%; boundary q8_0-V improves quality) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Soket1
pushed a commit
to Soket1/llama.cpp-xdna
that referenced
this pull request
Jul 26, 2026
…F3BEST_SKIPQ (it drifts) The f3best LOOP delegates [pre_norm .. kv_hi] to the CPU per layer, purely to get the K/V cache written. That span also recomputes Q-proj + Q-rope, which f3best computes on-chip from the same normed input — the layer's largest matmul (2048x2048 vs K/V 2048x512) done twice. The LIVE path already starts the delegate at q_rope_idx+1 for exactly this reason, so mirroring it in the LOOP looked free. Measured (XDNA_F3BEST_LOOPTIME, steady-state): default (full prefix) KVdeleg ~1500us/token token-match: exact PASS skip Q-proj KVdeleg ~700us/token token-match: DRIFT after 21 chars So it is NOT free: halving the delegate costs byte-exactness against the CPU baseline. The two Q paths are not equivalent — f3best's on-chip Q differs enough to change sampling downstream. Default therefore stays on the correct (slower) path; XDNA_F3BEST_SKIPQ=1 re-enables the fast form for measurement. Worth noting the LIVE path applies this same trick unconditionally, so its output is likely drifting too — untested here, and LIVE is not the production path. Context: ggml-org#115 token decomposition put ~3.3ms/token outside the f3best dispatches; this delegate is ~1.5ms of it (the rest is planners, standalone RMS_NORM, tail).
This was referenced Aug 15, 2026
ckti
pushed a commit
to ckti/llama.cpp-consolidated
that referenced
this pull request
Sep 13, 2026
Five unsupported-type switch lists in ops.cpp enumerate Q2_0 but not Q2_0_G128, which is fatal under -Werror=switch in CI (first hit: ggml_compute_forward_clamp; the remaining four would fail serially). Add the case alongside Q2_0 at each site, same abort behavior as the other quant types. Verified locally with GGML_FATAL_WARNINGS=ON: ggml-cpu builds with zero warnings. A repo sweep found no other CPU-side switches missing the type; the SYCL/Vulkan gaps are the known not-yet-ported backends and their dispatch switches carry defaults.
wangqi
pushed a commit
to wangqi/llama.cpp
that referenced
this pull request
Sep 18, 2026
Five unsupported-type switch lists in ops.cpp enumerate Q2_0 but not Q2_0_G128, which is fatal under -Werror=switch in CI (first hit: ggml_compute_forward_clamp; the remaining four would fail serially). Add the case alongside Q2_0 at each site, same abort behavior as the other quant types. Verified locally with GGML_FATAL_WARNINGS=ON: ggml-cpu builds with zero warnings. A repo sweep found no other CPU-side switches missing the type; the SYCL/Vulkan gaps are the known not-yet-ported backends and their dispatch switches carry defaults. (cherry picked from commit ed4119b)
tgrid0
pushed a commit
to tgrid0/llama.cpp
that referenced
this pull request
Oct 6, 2026
qwen4exp : use maskless block selection only where the selected-key kernels run
tgrid0
pushed a commit
to tgrid0/llama.cpp
that referenced
this pull request
Oct 6, 2026
Complete-block selection builds a maskless FLASH_ATTN_EXT whose visibility is only in the selection list (src[5]). Vulkan had no kernel that reads the list: ggml-org#115 makes it decline the op, and Vulkan then takes the masked per-cell top-k path, which is correct but slow at depth. flash_attn_sel.comp computes the op: one workgroup per query x K/V head, one 64-lane subgroup per query head of that K/V head (GQA 4/8/12, head 256). It sorts the query's list in shared memory and skips invalid and duplicate entries, as the CPU path does, then gathers K and V in blocks of 32 cells. Two lanes score one key, so the online softmax needs two subgroup reductions per block. With fewer than 64 workgroups the rows are split, and flash_attn_split_k_reduce combines the parts. supports_op takes a maskless selected-key op exactly when this kernel does. llama_memory_hybrid_idx asks each QSA layer's device with a probe op instead of checking for ROCm by name. HIP stays accepted; CUDA is not asked, because its supports_op ignores the list. Radeon 890M (gfx1150), Qwen3.8-Flash-Next UD-IQ4_XS: - test-backend-ops: QSA_PREFILL_MASKLESS 6/6 and QSA_DECODE_MASKLESS 25/25 (master: 0/6 and 0/25), NMSE <= 6.9e-13 against the FP64 reference - pp2048 at depth 12000 / 32000: 140.9 / 134.1 t/s (masked path, ggml-org#115: 139.0 / 88.7) Assisted-by: Claude Opus 5.5 Co-Authored-By: Claude Opus 5.5 <[email protected]>
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Oct 29, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005).
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Oct 29, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11).
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Oct 30, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11).
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Oct 30, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. Its third patch (a pass gathering small GDN projections into the row concat) is NOT taken: it needs a quantized <=256-row weight and skips Q8_0, and in every GGUF we have the GDN ssm_alpha / ssm_beta are F32 (the UD quants) or Q8_0, so it cannot fire -- measured neutral to -0.7 % on the 35B on both arches.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Oct 30, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Oct 30, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Oct 30, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Oct 31, 2026
Also adds mmf32, the F32 counterpart of MMB: the
shapes MMB cannot take -- non-quantized (F32) weights with more than 16 token columns -- currently fall
through ggml_cuda_mul_mat_cublas() to rocBLAS, which dispatches to hipBLASLt.
Two reasons to own that path:
* correctness: hipBLASLt picks its solution per process start from a heap-ordered container, so the prefill
arithmetic (and therefore the logits) changes between fresh runs -- GREEDY-PURITY.md §44, TODO ggml-org#75: 3
logit classes in 8 starts on 35B-A3B, 3 in 18 on gemma4;
* speed: the solution the heuristic lands on is the slowest in the pool for these shapes (0.13-0.19 ms vs
0.046 ms for a well-chosen one).
mmf32 is a plain SIMT tiled GEMM (RDNA has no F32 MMA form: amd_mfma_available is CDNA-only,
amd_wmma_available is f16/bf16). 32 output rows per block, a 4x8 thread sub-tile, BN=256 for m <= 64 (the
GDN ssm_alpha/ssm_beta projections) and 64 above it (the MoE routers), and the k range split into contiguous
chunks summed in increasing z -- a fixed reduction tree, no atomics, so a run is bit-stable by construction.
No approximation: an F32 FMA accumulation in a pinned order.
Scope: F32 weights only, m <= 256, 17 <= n <= 65536, 256 <= k <= 8192, ldc == m; every other mul_mat keeps the
rocBLAS call unchanged (BF16/f16 prefill -- Flash-Next -- is untouched, as is its hipBLASLt advantage; a
full-F32 model's FFN GEMMs, m >> 256, stay on rocBLAS: a recorded limitation).
Measured on gfx1201 (35B-A3B Q4_K_M, one GPU): deterministic -- one logits class in 12/12 fresh starts (6/6 at
2 GPU -sm tensor), --chunks 8 dumps byte-identical; +4.2 % pp512 / +4.1 % pp2048, decode flat (3 interleaved
llama-bench visits); kernel 0.032 ms vs 0.046 ms for the best hipBLASLt class on 32x512x2048. Correctness:
16-shape oracle NMSE ~1e-13, and 11x closer to the CPU reference than the rocBLAS path on the
test-backend-ops cases it intercepts. Purity: judged with the family-switch gate at a confident point
(in-domain corpus, base PPL 1.43) at 0.014646 / 98.045 % against a same-kernel control of 0.018100 / 97.808 %.
Default-on for RDNA4 (GGML_CUDA_MMF32=0 disables; opt-in on RDNA3/RDNA3_5 until those boxes run the same
determinism + bench pair). GGML_CUDA_MMF32_LOG prints the resolved plans (diagnostic only).
Amended (r132): the per-arch dispatch is keyed to the device the kernel runs on, not the primary. mmb_enabled,
mmb_cfg, mmb_cfg_dump_once, mmb_dense_flag, mmb_wtype_mask and mmb_dense_tmask read
ggml_cuda_info().devices[ggml_cuda_get_device()].cc, and mmb_cfg() takes one magic static per architecture class
(mmb_arch_defaults() only discriminates RDNA4 and RDNA3_0, so every cc that reaches the fallback shares the same
pre-S11 table). ggml_backend_cuda_graph_optimize() now selects its own context's device before it consults those
predicates, so the MMB marking half agrees with the launch path under the Meta backend, where the pass is
forwarded per child from meta graph_compute and the current device is still the previously computed one.
Reported in PR ggml-org#218 (@slavap): on a mixed-arch box (gfx1100 primary + gfx1030 secondary) the policy froze at the
primary's, so the RDNA2 card ran RDNA3-tuned MMB kernels -- byte-exact zero output-projection logits (PPL ==
vocab) or garbled tail layers, depending on where the output projection sat. On a single-arch box this is
bit-for-bit the previous behaviour (validated here on 3x gfx1201: 12/12 same-seed configs byte-identical,
prefill-logit KLD 0.000000 on both recorded points, no GPU faults).
Co-authored-by: Slava P. <[email protected]>
Fold (r134, issue ggml-org#224): the width probe's n_ctx is now the prefill length plus the decode
width instead of a fixed 4096, and a purity run must pass P >= 4096. The RDNA4 band's
64-column block (query widths 5..8) is only reachable above the launcher's KV-length gate
(K->ne[1] >= 4096), and K->ne[1] is the context's used length, so the P=256 default never
reached that block: the probe reported PASS on every arm while widths 5..8 ran a geometry
that was not bit-identical to widths 1..4. At P=4096 the r126 geometry fails it
(width_purity=FAIL, worst maxdiff 0.199764 on q8_0 K/V, row-0 hash split between W=4 and
W=5), and the shipped band geometry passes with maxdiff 0.
Amended (r171): the MMB stand-down predicates are gone (TODO ggml-org#115). The two type-only helpers this
block carried -- ggml_cuda_mmb_dense_will_take() / _routed_will_take() -- answered a weight-TYPE
question while the dispatch asks a SHAPE question, so a fusion that stood down for MMB stood down for
shapes MMB does not claim at all (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block
count, a non-contiguous dst, ...) and handed the pair to another fusion instead. Worse, it disagreed
with this block's BF16-activation marking, which can leave a preempted reader's F32 buffer unwritten.
The fusion sites now ask ggml_cuda_mmb_supported_mm() / _supported_mmid(), the predicates
ggml_cuda_mul_mat() / _mul_mat_id() themselves dispatch on, and both are null-safe now so a matcher can
probe an arbitrary node pair. This block's HC16 marking also keeps a ROUTED activation's F32 output
(marking the bf16 copy instead, so the MMB reader still finds it): the gate+up MUL_MAT_ID pair reading
it can be served by a mmq fusion rather than by two individual MMB muls. Inert on the measured arms:
gfx1201 byte-identical (27B Q8_0, 35B-A3B Q4_K_M at 1 and 3 GPU, LFM2 Q6_K; prefill-logit KLD
0.000000 / top-p 100.000 % on 27B and 35B-A3B), gfx1151 identical on every arm (LFM2 Q6_K and
35B-A3B Q4_K_M; the pair and the triple produce the same greedy text).
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Oct 31, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Oct 31, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Oct 31, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Oct 31, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Oct 31, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 1, 2026
Also adds mmf32, the F32 counterpart of MMB: the
shapes MMB cannot take -- non-quantized (F32) weights with more than 16 token columns -- currently fall
through ggml_cuda_mul_mat_cublas() to rocBLAS, which dispatches to hipBLASLt.
Two reasons to own that path:
* correctness: hipBLASLt picks its solution per process start from a heap-ordered container, so the prefill
arithmetic (and therefore the logits) changes between fresh runs -- GREEDY-PURITY.md §44, TODO ggml-org#75: 3
logit classes in 8 starts on 35B-A3B, 3 in 18 on gemma4;
* speed: the solution the heuristic lands on is the slowest in the pool for these shapes (0.13-0.19 ms vs
0.046 ms for a well-chosen one).
mmf32 is a plain SIMT tiled GEMM (RDNA has no F32 MMA form: amd_mfma_available is CDNA-only,
amd_wmma_available is f16/bf16). 32 output rows per block, a 4x8 thread sub-tile, BN=256 for m <= 64 (the
GDN ssm_alpha/ssm_beta projections) and 64 above it (the MoE routers), and the k range split into contiguous
chunks summed in increasing z -- a fixed reduction tree, no atomics, so a run is bit-stable by construction.
No approximation: an F32 FMA accumulation in a pinned order.
Scope: F32 weights only, m <= 256, 17 <= n <= 65536, 256 <= k <= 8192, ldc == m; every other mul_mat keeps the
rocBLAS call unchanged (BF16/f16 prefill -- Flash-Next -- is untouched, as is its hipBLASLt advantage; a
full-F32 model's FFN GEMMs, m >> 256, stay on rocBLAS: a recorded limitation).
Measured on gfx1201 (35B-A3B Q4_K_M, one GPU): deterministic -- one logits class in 12/12 fresh starts (6/6 at
2 GPU -sm tensor), --chunks 8 dumps byte-identical; +4.2 % pp512 / +4.1 % pp2048, decode flat (3 interleaved
llama-bench visits); kernel 0.032 ms vs 0.046 ms for the best hipBLASLt class on 32x512x2048. Correctness:
16-shape oracle NMSE ~1e-13, and 11x closer to the CPU reference than the rocBLAS path on the
test-backend-ops cases it intercepts. Purity: judged with the family-switch gate at a confident point
(in-domain corpus, base PPL 1.43) at 0.014646 / 98.045 % against a same-kernel control of 0.018100 / 97.808 %.
Default-on for RDNA4 (GGML_CUDA_MMF32=0 disables; opt-in on RDNA3/RDNA3_5 until those boxes run the same
determinism + bench pair). GGML_CUDA_MMF32_LOG prints the resolved plans (diagnostic only).
Amended (r132): the per-arch dispatch is keyed to the device the kernel runs on, not the primary. mmb_enabled,
mmb_cfg, mmb_cfg_dump_once, mmb_dense_flag, mmb_wtype_mask and mmb_dense_tmask read
ggml_cuda_info().devices[ggml_cuda_get_device()].cc, and mmb_cfg() takes one magic static per architecture class
(mmb_arch_defaults() only discriminates RDNA4 and RDNA3_0, so every cc that reaches the fallback shares the same
pre-S11 table). ggml_backend_cuda_graph_optimize() now selects its own context's device before it consults those
predicates, so the MMB marking half agrees with the launch path under the Meta backend, where the pass is
forwarded per child from meta graph_compute and the current device is still the previously computed one.
Reported in PR ggml-org#218 (@slavap): on a mixed-arch box (gfx1100 primary + gfx1030 secondary) the policy froze at the
primary's, so the RDNA2 card ran RDNA3-tuned MMB kernels -- byte-exact zero output-projection logits (PPL ==
vocab) or garbled tail layers, depending on where the output projection sat. On a single-arch box this is
bit-for-bit the previous behaviour (validated here on 3x gfx1201: 12/12 same-seed configs byte-identical,
prefill-logit KLD 0.000000 on both recorded points, no GPU faults).
Co-authored-by: Slava P. <[email protected]>
Fold (r134, issue ggml-org#224): the width probe's n_ctx is now the prefill length plus the decode
width instead of a fixed 4096, and a purity run must pass P >= 4096. The RDNA4 band's
64-column block (query widths 5..8) is only reachable above the launcher's KV-length gate
(K->ne[1] >= 4096), and K->ne[1] is the context's used length, so the P=256 default never
reached that block: the probe reported PASS on every arm while widths 5..8 ran a geometry
that was not bit-identical to widths 1..4. At P=4096 the r126 geometry fails it
(width_purity=FAIL, worst maxdiff 0.199764 on q8_0 K/V, row-0 hash split between W=4 and
W=5), and the shipped band geometry passes with maxdiff 0.
Amended (r171): the MMB stand-down predicates are gone (TODO ggml-org#115). The two type-only helpers this
block carried -- ggml_cuda_mmb_dense_will_take() / _routed_will_take() -- answered a weight-TYPE
question while the dispatch asks a SHAPE question, so a fusion that stood down for MMB stood down for
shapes MMB does not claim at all (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block
count, a non-contiguous dst, ...) and handed the pair to another fusion instead. Worse, it disagreed
with this block's BF16-activation marking, which can leave a preempted reader's F32 buffer unwritten.
The fusion sites now ask ggml_cuda_mmb_supported_mm() / _supported_mmid(), the predicates
ggml_cuda_mul_mat() / _mul_mat_id() themselves dispatch on, and both are null-safe now so a matcher can
probe an arbitrary node pair. This block's HC16 marking also keeps a ROUTED activation's F32 output
(marking the bf16 copy instead, so the MMB reader still finds it): the gate+up MUL_MAT_ID pair reading
it can be served by a mmq fusion rather than by two individual MMB muls. Inert on the measured arms:
gfx1201 byte-identical (27B Q8_0, 35B-A3B Q4_K_M at 1 and 3 GPU, LFM2 Q6_K; prefill-logit KLD
0.000000 / top-p 100.000 % on 27B and 35B-A3B), gfx1151 identical on every arm (LFM2 Q6_K and
35B-A3B Q4_K_M; the pair and the triple produce the same greedy text).
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 1, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 1, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 1, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - The dense 1-token row concat across a K-quant / Q6_K weight pair (PR ggml-org#260): mul_mat_vec_q_ksplit_cat2 runs the Q6_K body (with that segment's own row stride) for attn_v's row blocks and the launch type's body for the rest, for the K-quant "M" mixes. GGML_CUDA_MMVQ_ROW_CONCAT_MIXED=0 is the kill switch. The ksplit body lives in mmvq-ksplit-body.inc and is #included into both, so the pre-existing kernel's source is unchanged: as a __device__ body it changed the compiled code of the multi-column verify kernels and cost 6-7 % of MTP decode on gfx1201 (TODO ggml-org#128). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 1, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 and q4_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - The dense 1-token row concat across a K-quant / Q6_K weight pair (PR ggml-org#260): mul_mat_vec_q_ksplit_cat2 runs the Q6_K body (with that segment's own row stride) for attn_v's row blocks and the launch type's body for the rest, for the K-quant "M" mixes. GGML_CUDA_MMVQ_ROW_CONCAT_MIXED=0 is the kill switch. The ksplit body lives in mmvq-ksplit-body.inc and is #included into both, so the pre-existing kernel's source is unchanged: as a __device__ body it changed the compiled code of the multi-column verify kernels and cost 6-7 % of MTP decode on gfx1201 (TODO ggml-org#128). - The q4_0 KV cache write fold (PR ggml-org#262): with -ctk/-ctv q4_0 the rotated K and V rows are written by the same fused rope + FWHT kernel that already served a q8_0 cache, through ggml_cuda_quantize_q4_0_group (one block from the 32 lanes of a wave, bit-identical to quantize_f32_q4_0_block: the scan's FIRST element of largest |v|, never a NaN, vmax = +0 for an all-zero group). The quantizer is a compile-time choice (the kernels' kv template value 0/1/2 -- a runtime select cost the q8_0 kernel 12.8 -> 15.1 us), wave32 only, and GGML_CUDA_KV_FOLD_Q4_0=0 is the kill switch. Worth +10.7 % tg128 / +10.2 % @4096 on gfx1201, +12.0 % / +11.3 % on gfx1100 and +2.6 % on gfx1151 on a q4_0-KV 30B-A3B, with f16 and q8_0 KV unchanged; bit-identical (the --kv q4_0 --ub 1 prefill-logit A/B reads -0.000000 / 100.000 %, the width probe matches at P=3584 and P>=4096, and greedy text is byte-identical on all three arches). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 1, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 and q4_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - The dense 1-token row concat across a K-quant / Q6_K weight pair (PR ggml-org#260): mul_mat_vec_q_ksplit_cat2 runs the Q6_K body (with that segment's own row stride) for attn_v's row blocks and the launch type's body for the rest, for the K-quant "M" mixes. GGML_CUDA_MMVQ_ROW_CONCAT_MIXED=0 is the kill switch. The ksplit body lives in mmvq-ksplit-body.inc and is #included into both, so the pre-existing kernel's source is unchanged: as a __device__ body it changed the compiled code of the multi-column verify kernels and cost 6-7 % of MTP decode on gfx1201 (TODO ggml-org#128). - The q4_0 KV cache write fold (PR ggml-org#262): with -ctk/-ctv q4_0 the rotated K and V rows are written by the same fused rope + FWHT kernel that already served a q8_0 cache, through ggml_cuda_quantize_q4_0_group (one block from the 32 lanes of a wave, bit-identical to quantize_f32_q4_0_block: the scan's FIRST element of largest |v|, never a NaN, vmax = +0 for an all-zero group). The quantizer is a compile-time choice (the kernels' kv template value 0/1/2 -- a runtime select cost the q8_0 kernel 12.8 -> 15.1 us), wave32 only, and GGML_CUDA_KV_FOLD_Q4_0=0 is the kill switch. Worth +10.7 % tg128 / +10.2 % @4096 on gfx1201, +12.0 % / +11.3 % on gfx1100 and +2.6 % on gfx1151 on a q4_0-KV 30B-A3B, with f16 and q8_0 KV unchanged; bit-identical (the --kv q4_0 --ub 1 prefill-logit A/B reads -0.000000 / 100.000 %, the width probe matches at P=3584 and P>=4096, and greedy text is byte-identical on all three arches). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 1, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 and q4_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - The dense 1-token row concat across a K-quant / Q6_K weight pair (PR ggml-org#260): mul_mat_vec_q_ksplit_cat2 runs the Q6_K body (with that segment's own row stride) for attn_v's row blocks and the launch type's body for the rest, for the K-quant "M" mixes. GGML_CUDA_MMVQ_ROW_CONCAT_MIXED=0 is the kill switch. The ksplit body lives in mmvq-ksplit-body.inc and is #included into both, so the pre-existing kernel's source is unchanged: as a __device__ body it changed the compiled code of the multi-column verify kernels and cost 6-7 % of MTP decode on gfx1201 (TODO ggml-org#128). - The q4_0 KV cache write fold (PR ggml-org#262): with -ctk/-ctv q4_0 the rotated K and V rows are written by the same fused rope + FWHT kernel that already served a q8_0 cache, through ggml_cuda_quantize_q4_0_group (one block from the 32 lanes of a wave, bit-identical to quantize_f32_q4_0_block: the scan's FIRST element of largest |v|, never a NaN, vmax = +0 for an all-zero group). The quantizer is a compile-time choice (the kernels' kv template value 0/1/2 -- a runtime select cost the q8_0 kernel 12.8 -> 15.1 us), wave32 only, and GGML_CUDA_KV_FOLD_Q4_0=0 is the kill switch. Worth +10.7 % tg128 / +10.2 % @4096 on gfx1201, +12.0 % / +11.3 % on gfx1100 and +2.6 % on gfx1151 on a q4_0-KV 30B-A3B, with f16 and q8_0 KV unchanged; bit-identical (the --kv q4_0 --ub 1 prefill-logit A/B reads -0.000000 / 100.000 %, the width probe matches at P=3584 and P>=4096, and greedy text is byte-identical on all three arches). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm. The gate/beta fusions' unit oracle covers both weight types at the delivered models' contraction length (r202, issue ggml-org#265 follow-up): tests/test-fusion-gate-beta-multiseq.cpp runs {BF16, 1024}, {Q8_0, 1024} and {Q8_0, 5120} over the same 11 (T,S) shapes = 33 cases, because BF16-at-1024 alone is neither the type nor the shape any delivered GDN model runs (blk.N.ssm_alpha/beta.weight is Q8_0, K=5120) and that blindness is what let the softplus rounding difference ship for ten releases. 33/33 bit-identical and all fused on gfx1100 and gfx1201.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 1, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 and q4_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - The dense 1-token row concat across a K-quant / Q6_K weight pair (PR ggml-org#260): mul_mat_vec_q_ksplit_cat2 runs the Q6_K body (with that segment's own row stride) for attn_v's row blocks and the launch type's body for the rest, for the K-quant "M" mixes. GGML_CUDA_MMVQ_ROW_CONCAT_MIXED=0 is the kill switch. The ksplit body lives in mmvq-ksplit-body.inc and is #included into both, so the pre-existing kernel's source is unchanged: as a __device__ body it changed the compiled code of the multi-column verify kernels and cost 6-7 % of MTP decode on gfx1201 (TODO ggml-org#128). - The q4_0 KV cache write fold (PR ggml-org#262): with -ctk/-ctv q4_0 the rotated K and V rows are written by the same fused rope + FWHT kernel that already served a q8_0 cache, through ggml_cuda_quantize_q4_0_group (one block from the 32 lanes of a wave, bit-identical to quantize_f32_q4_0_block: the scan's FIRST element of largest |v|, never a NaN, vmax = +0 for an all-zero group). The quantizer is a compile-time choice (the kernels' kv template value 0/1/2 -- a runtime select cost the q8_0 kernel 12.8 -> 15.1 us), wave32 only, and GGML_CUDA_KV_FOLD_Q4_0=0 is the kill switch. Worth +10.7 % tg128 / +10.2 % @4096 on gfx1201, +12.0 % / +11.3 % on gfx1100 and +2.6 % on gfx1151 on a q4_0-KV 30B-A3B, with f16 and q8_0 KV unchanged; bit-identical (the --kv q4_0 --ub 1 prefill-logit A/B reads -0.000000 / 100.000 %, the width probe matches at P=3584 and P>=4096, and greedy text is byte-identical on all three arches). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 2, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 and q4_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - The dense 1-token row concat across a K-quant / Q6_K weight pair (PR ggml-org#260): mul_mat_vec_q_ksplit_cat2 runs the Q6_K body (with that segment's own row stride) for attn_v's row blocks and the launch type's body for the rest, for the K-quant "M" mixes. GGML_CUDA_MMVQ_ROW_CONCAT_MIXED=0 is the kill switch. The ksplit body lives in mmvq-ksplit-body.inc and is #included into both, so the pre-existing kernel's source is unchanged: as a __device__ body it changed the compiled code of the multi-column verify kernels and cost 6-7 % of MTP decode on gfx1201 (TODO ggml-org#128). - The q4_0 KV cache write fold (PR ggml-org#262): with -ctk/-ctv q4_0 the rotated K and V rows are written by the same fused rope + FWHT kernel that already served a q8_0 cache, through ggml_cuda_quantize_q4_0_group (one block from the 32 lanes of a wave, bit-identical to quantize_f32_q4_0_block: the scan's FIRST element of largest |v|, never a NaN, vmax = +0 for an all-zero group). The quantizer is a compile-time choice (the kernels' kv template value 0/1/2 -- a runtime select cost the q8_0 kernel 12.8 -> 15.1 us), wave32 only, and GGML_CUDA_KV_FOLD_Q4_0=0 is the kill switch. Worth +10.7 % tg128 / +10.2 % @4096 on gfx1201, +12.0 % / +11.3 % on gfx1100 and +2.6 % on gfx1151 on a q4_0-KV 30B-A3B, with f16 and q8_0 KV unchanged; bit-identical (the --kv q4_0 --ub 1 prefill-logit A/B reads -0.000000 / 100.000 %, the width probe matches at P=3584 and P>=4096, and greedy text is byte-identical on all three arches). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 2, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 and q4_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - The dense 1-token row concat across a K-quant / Q6_K weight pair (PR ggml-org#260): mul_mat_vec_q_ksplit_cat2 runs the Q6_K body (with that segment's own row stride) for attn_v's row blocks and the launch type's body for the rest, for the K-quant "M" mixes. GGML_CUDA_MMVQ_ROW_CONCAT_MIXED=0 is the kill switch. The ksplit body lives in mmvq-ksplit-body.inc and is #included into both, so the pre-existing kernel's source is unchanged: as a __device__ body it changed the compiled code of the multi-column verify kernels and cost 6-7 % of MTP decode on gfx1201 (TODO ggml-org#128). - The q4_0 KV cache write fold (PR ggml-org#262): with -ctk/-ctv q4_0 the rotated K and V rows are written by the same fused rope + FWHT kernel that already served a q8_0 cache, through ggml_cuda_quantize_q4_0_group (one block from the 32 lanes of a wave, bit-identical to quantize_f32_q4_0_block: the scan's FIRST element of largest |v|, never a NaN, vmax = +0 for an all-zero group). The quantizer is a compile-time choice (the kernels' kv template value 0/1/2 -- a runtime select cost the q8_0 kernel 12.8 -> 15.1 us), wave32 only, and GGML_CUDA_KV_FOLD_Q4_0=0 is the kill switch. Worth +10.7 % tg128 / +10.2 % @4096 on gfx1201, +12.0 % / +11.3 % on gfx1100 and +2.6 % on gfx1151 on a q4_0-KV 30B-A3B, with f16 and q8_0 KV unchanged; bit-identical (the --kv q4_0 --ub 1 prefill-logit A/B reads -0.000000 / 100.000 %, the width probe matches at P=3584 and P>=4096, and greedy text is byte-identical on all three arches). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 3, 2026
Also adds mmf32, the F32 counterpart of MMB: the
shapes MMB cannot take -- non-quantized (F32) weights with more than 16 token columns -- currently fall
through ggml_cuda_mul_mat_cublas() to rocBLAS, which dispatches to hipBLASLt.
Two reasons to own that path:
* correctness: hipBLASLt picks its solution per process start from a heap-ordered container, so the prefill
arithmetic (and therefore the logits) changes between fresh runs -- GREEDY-PURITY.md §44, TODO ggml-org#75: 3
logit classes in 8 starts on 35B-A3B, 3 in 18 on gemma4;
* speed: the solution the heuristic lands on is the slowest in the pool for these shapes (0.13-0.19 ms vs
0.046 ms for a well-chosen one).
mmf32 is a plain SIMT tiled GEMM (RDNA has no F32 MMA form: amd_mfma_available is CDNA-only,
amd_wmma_available is f16/bf16). 32 output rows per block, a 4x8 thread sub-tile, BN=256 for m <= 64 (the
GDN ssm_alpha/ssm_beta projections) and 64 above it (the MoE routers), and the k range split into contiguous
chunks summed in increasing z -- a fixed reduction tree, no atomics, so a run is bit-stable by construction.
No approximation: an F32 FMA accumulation in a pinned order.
Scope: F32 weights only, m <= 256, 17 <= n <= 65536, 256 <= k <= 8192, ldc == m; every other mul_mat keeps the
rocBLAS call unchanged (BF16/f16 prefill -- Flash-Next -- is untouched, as is its hipBLASLt advantage; a
full-F32 model's FFN GEMMs, m >> 256, stay on rocBLAS: a recorded limitation).
Measured on gfx1201 (35B-A3B Q4_K_M, one GPU): deterministic -- one logits class in 12/12 fresh starts (6/6 at
2 GPU -sm tensor), --chunks 8 dumps byte-identical; +4.2 % pp512 / +4.1 % pp2048, decode flat (3 interleaved
llama-bench visits); kernel 0.032 ms vs 0.046 ms for the best hipBLASLt class on 32x512x2048. Correctness:
16-shape oracle NMSE ~1e-13, and 11x closer to the CPU reference than the rocBLAS path on the
test-backend-ops cases it intercepts. Purity: judged with the family-switch gate at a confident point
(in-domain corpus, base PPL 1.43) at 0.014646 / 98.045 % against a same-kernel control of 0.018100 / 97.808 %.
Default-on for RDNA4 (GGML_CUDA_MMF32=0 disables; opt-in on RDNA3/RDNA3_5 until those boxes run the same
determinism + bench pair). GGML_CUDA_MMF32_LOG prints the resolved plans (diagnostic only).
Amended (r132): the per-arch dispatch is keyed to the device the kernel runs on, not the primary. mmb_enabled,
mmb_cfg, mmb_cfg_dump_once, mmb_dense_flag, mmb_wtype_mask and mmb_dense_tmask read
ggml_cuda_info().devices[ggml_cuda_get_device()].cc, and mmb_cfg() takes one magic static per architecture class
(mmb_arch_defaults() only discriminates RDNA4 and RDNA3_0, so every cc that reaches the fallback shares the same
pre-S11 table). ggml_backend_cuda_graph_optimize() now selects its own context's device before it consults those
predicates, so the MMB marking half agrees with the launch path under the Meta backend, where the pass is
forwarded per child from meta graph_compute and the current device is still the previously computed one.
Reported in PR ggml-org#218 (@slavap): on a mixed-arch box (gfx1100 primary + gfx1030 secondary) the policy froze at the
primary's, so the RDNA2 card ran RDNA3-tuned MMB kernels -- byte-exact zero output-projection logits (PPL ==
vocab) or garbled tail layers, depending on where the output projection sat. On a single-arch box this is
bit-for-bit the previous behaviour (validated here on 3x gfx1201: 12/12 same-seed configs byte-identical,
prefill-logit KLD 0.000000 on both recorded points, no GPU faults).
Co-authored-by: Slava P. <[email protected]>
Fold (r134, issue ggml-org#224): the width probe's n_ctx is now the prefill length plus the decode
width instead of a fixed 4096, and a purity run must pass P >= 4096. The RDNA4 band's
64-column block (query widths 5..8) is only reachable above the launcher's KV-length gate
(K->ne[1] >= 4096), and K->ne[1] is the context's used length, so the P=256 default never
reached that block: the probe reported PASS on every arm while widths 5..8 ran a geometry
that was not bit-identical to widths 1..4. At P=4096 the r126 geometry fails it
(width_purity=FAIL, worst maxdiff 0.199764 on q8_0 K/V, row-0 hash split between W=4 and
W=5), and the shipped band geometry passes with maxdiff 0.
Amended (r171): the MMB stand-down predicates are gone (TODO ggml-org#115). The two type-only helpers this
block carried -- ggml_cuda_mmb_dense_will_take() / _routed_will_take() -- answered a weight-TYPE
question while the dispatch asks a SHAPE question, so a fusion that stood down for MMB stood down for
shapes MMB does not claim at all (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block
count, a non-contiguous dst, ...) and handed the pair to another fusion instead. Worse, it disagreed
with this block's BF16-activation marking, which can leave a preempted reader's F32 buffer unwritten.
The fusion sites now ask ggml_cuda_mmb_supported_mm() / _supported_mmid(), the predicates
ggml_cuda_mul_mat() / _mul_mat_id() themselves dispatch on, and both are null-safe now so a matcher can
probe an arbitrary node pair. This block's HC16 marking also keeps a ROUTED activation's F32 output
(marking the bf16 copy instead, so the MMB reader still finds it): the gate+up MUL_MAT_ID pair reading
it can be served by a mmq fusion rather than by two individual MMB muls. Inert on the measured arms:
gfx1201 byte-identical (27B Q8_0, 35B-A3B Q4_K_M at 1 and 3 GPU, LFM2 Q6_K; prefill-logit KLD
0.000000 / top-p 100.000 % on 27B and 35B-A3B), gfx1151 identical on every arm (LFM2 Q6_K and
35B-A3B Q4_K_M; the pair and the triple produce the same greedy text).
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 3, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 and q4_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - The dense 1-token row concat across a K-quant / Q6_K weight pair (PR ggml-org#260): mul_mat_vec_q_ksplit_cat2 runs the Q6_K body (with that segment's own row stride) for attn_v's row blocks and the launch type's body for the rest, for the K-quant "M" mixes. GGML_CUDA_MMVQ_ROW_CONCAT_MIXED=0 is the kill switch. The ksplit body lives in mmvq-ksplit-body.inc and is #included into both, so the pre-existing kernel's source is unchanged: as a __device__ body it changed the compiled code of the multi-column verify kernels and cost 6-7 % of MTP decode on gfx1201 (TODO ggml-org#128). - The q4_0 KV cache write fold (PR ggml-org#262): with -ctk/-ctv q4_0 the rotated K and V rows are written by the same fused rope + FWHT kernel that already served a q8_0 cache, through ggml_cuda_quantize_q4_0_group (one block from the 32 lanes of a wave, bit-identical to quantize_f32_q4_0_block: the scan's FIRST element of largest |v|, never a NaN, vmax = +0 for an all-zero group). The quantizer is a compile-time choice (the kernels' kv template value 0/1/2 -- a runtime select cost the q8_0 kernel 12.8 -> 15.1 us), wave32 only, and GGML_CUDA_KV_FOLD_Q4_0=0 is the kill switch. Worth +10.7 % tg128 / +10.2 % @4096 on gfx1201, +12.0 % / +11.3 % on gfx1100 and +2.6 % on gfx1151 on a q4_0-KV 30B-A3B, with f16 and q8_0 KV unchanged; bit-identical (the --kv q4_0 --ub 1 prefill-logit A/B reads -0.000000 / 100.000 %, the width probe matches at P=3584 and P>=4096, and greedy text is byte-identical on all three arches). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 3, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 and q4_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - The dense 1-token row concat across a K-quant / Q6_K weight pair (PR ggml-org#260): mul_mat_vec_q_ksplit_cat2 runs the Q6_K body (with that segment's own row stride) for attn_v's row blocks and the launch type's body for the rest, for the K-quant "M" mixes. GGML_CUDA_MMVQ_ROW_CONCAT_MIXED=0 is the kill switch. The ksplit body lives in mmvq-ksplit-body.inc and is #included into both, so the pre-existing kernel's source is unchanged: as a __device__ body it changed the compiled code of the multi-column verify kernels and cost 6-7 % of MTP decode on gfx1201 (TODO ggml-org#128). - The q4_0 KV cache write fold (PR ggml-org#262): with -ctk/-ctv q4_0 the rotated K and V rows are written by the same fused rope + FWHT kernel that already served a q8_0 cache, through ggml_cuda_quantize_q4_0_group (one block from the 32 lanes of a wave, bit-identical to quantize_f32_q4_0_block: the scan's FIRST element of largest |v|, never a NaN, vmax = +0 for an all-zero group). The quantizer is a compile-time choice (the kernels' kv template value 0/1/2 -- a runtime select cost the q8_0 kernel 12.8 -> 15.1 us), wave32 only, and GGML_CUDA_KV_FOLD_Q4_0=0 is the kill switch. Worth +10.7 % tg128 / +10.2 % @4096 on gfx1201, +12.0 % / +11.3 % on gfx1100 and +2.6 % on gfx1151 on a q4_0-KV 30B-A3B, with f16 and q8_0 KV unchanged; bit-identical (the --kv q4_0 --ub 1 prefill-logit A/B reads -0.000000 / 100.000 %, the width probe matches at P=3584 and P>=4096, and greedy text is byte-identical on all three arches). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 4, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 and q4_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - The dense 1-token row concat across a K-quant / Q6_K weight pair (PR ggml-org#260): mul_mat_vec_q_ksplit_cat2 runs the Q6_K body (with that segment's own row stride) for attn_v's row blocks and the launch type's body for the rest, for the K-quant "M" mixes. GGML_CUDA_MMVQ_ROW_CONCAT_MIXED=0 is the kill switch. The ksplit body lives in mmvq-ksplit-body.inc and is #included into both, so the pre-existing kernel's source is unchanged: as a __device__ body it changed the compiled code of the multi-column verify kernels and cost 6-7 % of MTP decode on gfx1201 (TODO ggml-org#128). - The q4_0 KV cache write fold (PR ggml-org#262): with -ctk/-ctv q4_0 the rotated K and V rows are written by the same fused rope + FWHT kernel that already served a q8_0 cache, through ggml_cuda_quantize_q4_0_group (one block from the 32 lanes of a wave, bit-identical to quantize_f32_q4_0_block: the scan's FIRST element of largest |v|, never a NaN, vmax = +0 for an all-zero group). The quantizer is a compile-time choice (the kernels' kv template value 0/1/2 -- a runtime select cost the q8_0 kernel 12.8 -> 15.1 us), wave32 only, and GGML_CUDA_KV_FOLD_Q4_0=0 is the kill switch. Worth +10.7 % tg128 / +10.2 % @4096 on gfx1201, +12.0 % / +11.3 % on gfx1100 and +2.6 % on gfx1151 on a q4_0-KV 30B-A3B, with f16 and q8_0 KV unchanged; bit-identical (the --kv q4_0 --ub 1 prefill-logit A/B reads -0.000000 / 100.000 %, the width probe matches at P=3584 and P>=4096, and greedy text is byte-identical on all three arches). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 4, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 and q4_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - The dense 1-token row concat across a K-quant / Q6_K weight pair (PR ggml-org#260): mul_mat_vec_q_ksplit_cat2 runs the Q6_K body (with that segment's own row stride) for attn_v's row blocks and the launch type's body for the rest, for the K-quant "M" mixes. GGML_CUDA_MMVQ_ROW_CONCAT_MIXED=0 is the kill switch. The ksplit body lives in mmvq-ksplit-body.inc and is #included into both, so the pre-existing kernel's source is unchanged: as a __device__ body it changed the compiled code of the multi-column verify kernels and cost 6-7 % of MTP decode on gfx1201 (TODO ggml-org#128). - The q4_0 KV cache write fold (PR ggml-org#262): with -ctk/-ctv q4_0 the rotated K and V rows are written by the same fused rope + FWHT kernel that already served a q8_0 cache, through ggml_cuda_quantize_q4_0_group (one block from the 32 lanes of a wave, bit-identical to quantize_f32_q4_0_block: the scan's FIRST element of largest |v|, never a NaN, vmax = +0 for an all-zero group). The quantizer is a compile-time choice (the kernels' kv template value 0/1/2 -- a runtime select cost the q8_0 kernel 12.8 -> 15.1 us), wave32 only, and GGML_CUDA_KV_FOLD_Q4_0=0 is the kill switch. Worth +10.7 % tg128 / +10.2 % @4096 on gfx1201, +12.0 % / +11.3 % on gfx1100 and +2.6 % on gfx1151 on a q4_0-KV 30B-A3B, with f16 and q8_0 KV unchanged; bit-identical (the --kv q4_0 --ub 1 prefill-logit A/B reads -0.000000 / 100.000 %, the width probe matches at P=3584 and P>=4096, and greedy text is byte-identical on all three arches). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 5, 2026
…rastructure) The infrastructure half of the old block 10. qwen4exp, QSA and the hyper-connection ops now live in their own block (11); this block is what they are built on, and it no longer references them. Contents: - The movable-boundary slab and its arena (ggml-cuda-slab.cu, ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM reserve per device split by a movable boundary -- compute below, MoE arena above, no HIP call at runtime. Plus the narrow-band learning, the wide-phase auxiliary region, pool-wide routing, and the slab transient absorption. - The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it. - The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU split's output, which the next ubatch rewrites), default-on, and the per-origin (per host thread) ordering state of issue ggml-org#201. - Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT) matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 and q4_0 K/V cache writes folded into the rope + FWHT kernel, and the paired GDN q/k norms. - GDN / attention-gate decode fusions: the BF16 alpha/beta pair with softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108 multi-sequence fix and its model-free regression test), the q/k norm pair in the direct conv kernel, the attention gate's row-strided view read in place by the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots). - The dense 1-token row concat across a K-quant / Q6_K weight pair (PR ggml-org#260): mul_mat_vec_q_ksplit_cat2 runs the Q6_K body (with that segment's own row stride) for attn_v's row blocks and the launch type's body for the rest, for the K-quant "M" mixes. GGML_CUDA_MMVQ_ROW_CONCAT_MIXED=0 is the kill switch. The ksplit body lives in mmvq-ksplit-body.inc and is #included into both, so the pre-existing kernel's source is unchanged: as a __device__ body it changed the compiled code of the multi-column verify kernels and cost 6-7 % of MTP decode on gfx1201 (TODO ggml-org#128). - The q4_0 KV cache write fold (PR ggml-org#262): with -ctk/-ctv q4_0 the rotated K and V rows are written by the same fused rope + FWHT kernel that already served a q8_0 cache, through ggml_cuda_quantize_q4_0_group (one block from the 32 lanes of a wave, bit-identical to quantize_f32_q4_0_block: the scan's FIRST element of largest |v|, never a NaN, vmax = +0 for an all-zero group). The quantizer is a compile-time choice (the kernels' kv template value 0/1/2 -- a runtime select cost the q8_0 kernel 12.8 -> 15.1 us), wave32 only, and GGML_CUDA_KV_FOLD_Q4_0=0 is the kill switch. Worth +10.7 % tg128 / +10.2 % @4096 on gfx1201, +12.0 % / +11.3 % on gfx1100 and +2.6 % on gfx1151 on a q4_0-KV 30B-A3B, with f16 and q8_0 KV unchanged; bit-identical (the --kv q4_0 --ub 1 prefill-logit A/B reads -0.000000 / 100.000 %, the width probe matches at P=3584 and P>=4096, and greedy text is byte-identical on all three arches). - MMB and the HC16 BF16 streams: the per-context MMB state (two contexts interleaving must not share the activation cache or the marks), the BF16 activation copies, DOWN16, and the graph-optimize marking passes. - The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel), the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output matmul, the MoE down fold, and the weighted-down reduction. - The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize predicate and in the direct GDN conv. - Meta/scheduler/allocator: the split-state refusals for a straddling split, the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory generations so a graph is recaptured when the pool / FA staging / H2D ring memory it captured is freed -- including the slab work-boundary shrink of issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED). - bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16 instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu. Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED / GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve lives in src/ (not linked against the CUDA common.cuh), so it uses a local static instead of the CUDA helper. Split note (r109): this commit plus block 11 carries exactly the tree the old block 10 carried -- the net set is unchanged. What moved to block 11 is the qwen4exp model graph, the QSA/indexer ops and their kernels, the hyper-connection ops, the managed lazy reader and the keys-only indexer cache, i.e. everything that exists only because of that architecture. The pieces of the old block 10 that exist for qwen4exp but are implemented inside a general kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp weighted-down reduction, the PLE conv fusion) stay here with the TU that owns them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved to block 11 with the matchers they call. Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged. Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces. The fused GLU -> Q8_1 site's key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel and the GLU write -- validate their sources with q8_1_src_range_ok() before launching. From PR ggml-org#218 (@slavap); the rule and the validation are recorded with block 08. Co-authored-by: Slava P. <[email protected]> Amended (r171): the pair fusion's MMB stand-down asks the dispatch, not the weight type (TODO ggml-org#115). `mul_mat_q_pair` stood down for any weight type MMB supports, a superset of the shapes MMB actually claims, so on a shape MMB declines (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block count, ...) the pair had already stood down and the mmq/mmvq triple took the gate+up pair instead. It now stands down on the predicate the mmb dispatch uses (both muls claimed), which is a strict SUPERSET of the fused-GLU predicate, so the priority chain is well defined and cannot preempt an MMB claim: MMB's fused GLU -> the mmq/mmvq triple -> this pair (the fallback for shapes none of them takes) -> the two plain muls. The routed SWIGLU -> MMQ matcher's stand-down is the same exact claim (its GLU output can be marked BF16-only for an MMB reader). GGML_PAIR_ROUTED_OFF is the new A/B arm for the routed half; GGML_PAIR_OFF still means both halves. Measured neutral: gfx1151 pair vs triple (LFM2 Q6_K 3379/3399 vs 3348/3407, 35B-A3B Q4_K_M 2304/2312 vs 2296/2313 t/s at pp512, interleaved r=3, dense MMB path untouched) and byte-identical greedy text on pair == triple == unfused == GGML_CUDA_MMB=0 (LFM2 765 chars, 35B-A3B 723 chars); gfx1201 inert (routed = 0 there, so the pair already won before this change). Fold (r174, PR ggml-org#249, briansp2020): the M-RoPE section power is computed once instead of once per section arm, in `rope_multi` and in the M-RoPE arm of the fused `rms_norm_mul_rope_f32`. Every arm multiplied its position index by the same `powf(theta_scale, iw/2)`, and adjacent lanes take different arms (`sector % 3`), so the divergent arms were serialized and `powf` executed once per arm taken. It is hoisted before the branch: same input, same value, so the result is bit-identical (the non-M-RoPE path and the "no arm matched, `theta_base` stays 0" case are untouched). Measured on this box, gfx1201: `rms_norm_mul_rope_f32` 3.20 -> 2.85 us (__half dst) and 3.06 -> 2.70 us (f32 dst) per launch, greedy text byte-identical on 4B Q8_0 / 27B UD-Q4_K_XL / 35B-A3B Q4_K_M and the `-ub 1` prefill-logit A/B reads 0.000000 KLD / 100.000 % same-top-p; wall clock is inside the noise on RDNA4 (+0.0 %) and +0.25 to +0.65 % tg on gfx1100 (7900 XTX: 35B-A3B Q4_K_M 137.6 -> 138.6). The submission's other half (a GDN direct conv for 1-token decode) is NOT taken -- it adds a launch per GDN layer wherever the conv's q/k norm fold is refused and measures -1.1 % on RDNA4 dense Q8_0, +0.0 % on the submitter's own 7900 XTX arm (WORKLOG 261029.005). R175 FOLD (PR ggml-org#250, @briansp2020): the seven RDNA3 decode fusions. They sit here because this is the block that owns the fusion dispatcher, the rope matcher and the MoE multi-token kernel (mmvq-moe), so no earlier block can carry them. All default-on, each with a =0 kill switch: - FA combine publishes its output's Q8_1 (GGML_CUDA_FA_COMBINE_Q8): the attention output projection skips its quantize_q8_1 launch. Only for a contiguous F32 output whose row length is a multiple of MATRIX_ROW_PADDING. - MoE gate/up + GLU publishes the down projection's Q8_1 (GGML_CUDA_MOE_GLU_Q8), via self-resetting (slot, 32-row group) counters; the completing block also zeroes the row's padding blocks, as quantize_q8_1 writes them. - The fused K norm+rope+SET_ROWS kernel also writes the V row (GGML_CUDA_ROPE_SET_ROWS_V), so the V SET_ROWS launch goes away. - MoE GEMV takes 4 rows per block on RDNA3_0 when >= 32 blocks per WGP remain (GGML_CUDA_MOE_RPB_WIDE). - MoE down + weighted reduction in one launch (GGML_CUDA_MWR_FOLD): the last expert lane of a row block writes the reduction in moe_weighted_reduction's order and expression, 8 rows per block. - Q and K norm+rope of a layer run as one launch (GGML_CUDA_ROPE_QK_PAIR). The submitter's qwen3moe graph reorder (make the two chains adjacent) is NOT taken: it edits upstream model code for a CUDA fusion and is worth ~7 pts only on qwen3moe (a retired arch family). Without it the pair fires where the graph is already adjacent. - Dense V/K/Q projections in one launch on RDNA3_0 (GGML_CUDA_MMVQ_ROW_CONCAT), a separate row_cat template instance so the plain ksplit kernels are unchanged. - The V / K / Q projections of a Q-norm attention layer are reordered in front of the Q projection by a structural pass in graph_optimize (GGML_CUDA_QK_ROTATE), so the Q GEMV can join the row concat and the Q / K norm+rope pair fires (the allocator no longer hands V / K the Q chain's freed buffers). Same nodes, one stream, every ubatch size, idempotent. - The dense row concat also runs on RDNA4 (GGML_CUDA_MMVQ_ROW_CONCAT_RDNA4). At one token a row's dot product does not depend on the row count there (one warp per row, no small_m), and its two-rows-per-block launch only needs every segment to have an even row count; RDNA3_0 keeps its small_m / rows-per-block rule. Needs the adjacency above. Measured (release tree, 1 GPU, 2-3 alternating rounds, greedy text byte-identical, prefill-logit KLD 0.000000 / 100.000 %): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 172.3 -> 192.8 (+12.0 %), d4096 +11.7 %; dense 27B +0.5 %; gfx1201 Qwen3-30B-A3B tg128 131.4 -> 145.7 (+10.9 %), Qwen3.6-35B-A3B 102.1 -> 104.6 (+2.5 %), dense 27B +0.4 %. Width purity holds (plain == draft-mtp on 27B dense and 35B-A3B), rule-5 batched bench flat, MTP Protocol A unchanged (layer 51.6, tensor 100.5 -> 100.8). Blocks 11-14 re-cut on top; block 11's fattn-qsa.cu call site takes the new combine_results argument (the file is created by block 11). PR ggml-org#252 measured (1 GPU, alternating rounds, -sm layer -t 8, greedy text byte-identical on 30B-A3B / 35B-A3B / dense 27B / Gemma4-31B / Flash-Next -ncmoe 48 / 2-GPU -sm tensor, prefill-logit KLD 0.000000 / 100.000 % at the default ubatch and -ub 1): gfx1100 Qwen3-30B-A3B Q4_K_M tg128 194.3 -> 205.8 (+5.9 %), d4096 170.0 -> 180.2 (+6.0 %); gfx1201 the same model 152.0 -> 160.9 (+5.9 %), d4096 131.2 -> 137.2 (+4.5 %) -- the reorder alone is +3.2 % there and the RDNA4 concat adds +2.6 %. Qwen3.6-35B-A3B +1.8 % on gfx1201, flat on gfx1100; dense 27B flat on both. - The GDN small-projection gather (GGML_CUDA_MMVQ_CONCAT_REORDER) ships since r180. From the first quantized MUL_MAT of <= 256 rows it moves the later MUL_MATs that share that activation, weight type and K (at most one of them larger) directly after it, up to 3 nodes, so the row concat runs the Qwen3.5 / 3.6 GDN ssm_beta + ssm_alpha + attn_gate projections as one launch. It never moves a MUL_MAT whose output feeds a CONCAT within 8 nodes (ggml_cuda_ssm_conv_in_try_fuse skips the nodes up to its CONCAT) and never one with a Q8_0 weight (the SSM prescan matches nodes by position); both guards are load-bearing. Measured on the submitter's file (lmstudio-community Qwen3.6-35B-A3B-Q4_K_M, sha256 4ac6a06b...a410d, whose ssm_alpha / ssm_beta / attn_gate are Q4_K): gfx1201 tg128 129.4 -> 132.9 (+2.8 %), d4096 126.2 -> 129.7 (+2.8 %); 60 fewer launches per token (30 GDN layers x 2, kernel-census verified). Prefill-logit KLD 0.000000 / 100.000 % at the default ubatch, -ub 1 and -ub 8; text byte-identical on 1 / 2 / 3 devices, in both MTP split modes, and on the DFlash2 draft arm. It cannot fire where the GDN small projections are F32 (the UD quants) or Q8_0, so our own GGUF set still measures it as inert. - The 1-token router fold (GGML_CUDA_ROUTER_TOPK, PR ggml-org#253, r182): when a MoE layer's ffn_gate_inp is a 1-token F32 MUL_MAT that the dispatcher would run as mul_mat_vec_f with its 256-thread block, topk_moe_cuda computes the logits itself (the same thread-to-column map, float2 loads, ggml_cuda_mad and warp + cross-warp butterfly, so every logit keeps its bits) and the block that finishes last (a fence, then one atomic on a self-resetting counter in the last MoE-reduction slot) runs the unchanged selection, so the router launch and the topk launch become one. It does not fire with a bias, a delayed softmax, a Hadamard hint or a padded compute-buffer src0, and it steps aside on RDNA4 above 128 experts, where the one launch measured slower than the two. Measured (llama-bench -r 5, two interleaved rounds, 1 GPU, on vs off): gfx1100 Qwen3-30B-A3B tg128 205.8 -> 212.0 (+3.1 %), d4096 180.2 -> 183.1 (+1.7 %); Qwen3.6-35B-A3B (256 experts) 141.1 -> 142.8 (+1.2 %), d4096 137.5 -> 139.0 (+1.1 %); gfx1201 the 128-expert model +1.7 % (noisy) and the 256-expert model flat through the step-aside (fold on there measures -0.3..-0.5 %). Purity: greedy text byte-identical on/off; the decode-band logits (gate-prefill-logits.sh --ab GGML_CUDA_ROUTER_TOPK=0 --ub 1, i.e. every token a 1-token graph with the fold firing) measure 0.000000 KLD / 100.000 % same-top-p on 30B-A3B (gfx1201) and 35B-A3B (gfx1100); test-backend-ops -o TOPK_MOE 608/608; MTP Protocol A unchanged (51.53 t/s, acceptance 0.62134). It is inert with a speculator (a verify batch is more than one token wide) and on every router with one of the excluded shapes. GGML_CUDA_ROUTER_TOPK=0 is the kill switch; a launch aborted mid-kernel would leave the counter non-zero, the same caveat the MoE down fold's counter carries. Amended (r183): PR ggml-org#256's three GDN decode folds plus its shared-expert gate fold, and the 2D-copy guard that fixes a Flash-Next `-sm tensor` load abort. Nothing here changes an arithmetic order. - The direct GDN conv also writes the recurrent snapshot tails (GGML_CUDA_DISABLE_GDN_CONV_SNAP=1 off), so the CONCAT and the snapshot CPYs launch nothing wherever the direct conv runs. It is taken only when nothing between the CONCAT and the conv writes over state / x or touches a snapshot destination and the destinations are disjoint (a runtime byte-span check), and the batched-copy run stops at a folded snapshot CPY so cpy_batch can never swallow one. - The conv-state gather fold (GGML_CUDA_FUSE_GDN_CONV_GATHER=0 off): build_rs's GET_ROWS of the conv cache, feeding a CONCAT that the direct conv takes, is deferred like the GDN state gather and the direct kernel reads the cache row itself (row id = the gather's src[1]), holding each channel's three state values in registers before the snapshot writes because one of them is the write-back to that row. One sequence, at most 16 tokens, the CONCAT the gather's only reader, and only folded snapshot CPYs writing the cache before the conv. A CONCAT over a deferred gather that the direct conv does not take aborts rather than reading an unwritten GET_ROWS (the tripwire is asserted in write_tail and at the CONCAT). - The 1-token direct conv (GGML_CUDA_FUSE_GDN_CONV_DECODE=0 off), the ggml-org#249 re-submission: on RDNA4 / RDNA3_0 a 1-token conv takes the direct path only where it also elides the q/k norm pair (gdn_conv_norm_match() > 0) and where the decode-only ssm_prescan would not take the conv first. The data-dependent gate lives in the compute-time matchers (CONCAT, SSM_CONV, the ssm_conv_in stand-down and both folds), so they all decide the same way; graph_optimize uses the structural match (ggml_cuda_gdn_conv_pattern_at_concat), a superset, so its alloc deps cover every case the compute-time matchers take. The ssm_conv_in epilogue steps aside with `continue`, so it keeps scanning the window, and it keeps its CONCAT write where the direct conv is refused (the dense Q8_0 case that cost -1.1 % in ggml-org#249 is neutral again). - The shared-expert gate fold (GGML_CUDA_FUSE_SHEXP_GATE_SIGMOID=0 off): MUL_MAT(one gate row) -> SIGMOID -> MUL -> ADD runs in the mul_mat_vec_f launch the gate would take anyway (the same instantiation, ncols_dst and block size); every block recomputes the one gate row, and its slice of `y + x*sigmoid(g)` uses sigmoid_mul_add_f32's own op_sigmoid and its `#pragma clang fp contract(off)` expression. BF16 / F32 gate weights only (F16 can take a half accumulator), decode/verify band, and the gate, sigmoid and product may have no other reader. - The 2D memcpy fast path in ggml_cuda_cpy keeps its guard: a 2D copy of a view of a mirrored model weight is refused by the driver with "invalid argument" when the weight sits in the slab region, so the path is only taken while the padded span (height*pitch) fits the tensor's own allocation and the scalar kernels are the fallback (GGML_CUDA_SLAB=0 was the work-around). Measured (all four switches on vs all four off, one build, 1 GPU, llama-bench -r 5, two interleaved rounds; the folds are inert on a multi-device graph, GGML_CUDA_CONV_FUSION_MULTI=1 excepted): gfx1100 Qwen3.6-35B-A3B Q4_K_M tg128 142.3 -> 150.6 (+5.9 %), d4096 139.0 -> 146.9 (+5.6 %); gfx1201 Qwen3.6-35B-A3B 105.0 -> 108.4 (+3.3 %), d4096 +3.4 %; dense 27B UD-Q4_K_XL +1.7 %; Qwen3.5-4B Q8_0 neutral (103.6 vs 104.1, the ssm_conv_in epilogue keeps its CONCAT). Decomposed on gfx1201: 0003 alone +0.3 % (it is the enabler), +snapshot fold +2.2 %, +gather fold +1.0 %. The shared-expert gate fold is inert on every quantized model we hold (its gate weight must be BF16/F32) and measures +0.6 % on Flash-Next GSQ-IQ3_XXS tg128 (45.6 vs 45.3). Purity: greedy text byte-identical (35B-A3B 1 GPU, 4B Q8_0, 2-GPU -sm tensor -ncmoe 40, Flash-Next -sm layer); gate-prefill-logits.sh --ab "<all four off>" --ub 1 (the decode width, where the fold fires) 0.000000 KLD / 100.000 % same-top-p on 27B Q8_0; MTP on 35B-A3B (n_max 7) 182.4 vs 174.7 t/s with identical draft/accept counts (362/203); a --parallel 2 --kv-unified server run is clean (the multi-sequence batch declines the gather deferral). Flash-Next GSQ-IQ3_XXS `-sm tensor -ncmoe 48 -c 4096 -fa 1 -ctk q8_0 -ctv q8_0` now loads and decodes (it aborted on r182 in ggml_cuda_cpy at cpy.cu:479, device 1) and its text matches the GGML_CUDA_SLAB=0 arm.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 5, 2026
Also adds mmf32, the F32 counterpart of MMB: the
shapes MMB cannot take -- non-quantized (F32) weights with more than 16 token columns -- currently fall
through ggml_cuda_mul_mat_cublas() to rocBLAS, which dispatches to hipBLASLt.
Two reasons to own that path:
* correctness: hipBLASLt picks its solution per process start from a heap-ordered container, so the prefill
arithmetic (and therefore the logits) changes between fresh runs -- GREEDY-PURITY.md §44, TODO ggml-org#75: 3
logit classes in 8 starts on 35B-A3B, 3 in 18 on gemma4;
* speed: the solution the heuristic lands on is the slowest in the pool for these shapes (0.13-0.19 ms vs
0.046 ms for a well-chosen one).
mmf32 is a plain SIMT tiled GEMM (RDNA has no F32 MMA form: amd_mfma_available is CDNA-only,
amd_wmma_available is f16/bf16). 32 output rows per block, a 4x8 thread sub-tile, BN=256 for m <= 64 (the
GDN ssm_alpha/ssm_beta projections) and 64 above it (the MoE routers), and the k range split into contiguous
chunks summed in increasing z -- a fixed reduction tree, no atomics, so a run is bit-stable by construction.
No approximation: an F32 FMA accumulation in a pinned order.
Scope: F32 weights only, m <= 256, 17 <= n <= 65536, 256 <= k <= 8192, ldc == m; every other mul_mat keeps the
rocBLAS call unchanged (BF16/f16 prefill -- Flash-Next -- is untouched, as is its hipBLASLt advantage; a
full-F32 model's FFN GEMMs, m >> 256, stay on rocBLAS: a recorded limitation).
Measured on gfx1201 (35B-A3B Q4_K_M, one GPU): deterministic -- one logits class in 12/12 fresh starts (6/6 at
2 GPU -sm tensor), --chunks 8 dumps byte-identical; +4.2 % pp512 / +4.1 % pp2048, decode flat (3 interleaved
llama-bench visits); kernel 0.032 ms vs 0.046 ms for the best hipBLASLt class on 32x512x2048. Correctness:
16-shape oracle NMSE ~1e-13, and 11x closer to the CPU reference than the rocBLAS path on the
test-backend-ops cases it intercepts. Purity: judged with the family-switch gate at a confident point
(in-domain corpus, base PPL 1.43) at 0.014646 / 98.045 % against a same-kernel control of 0.018100 / 97.808 %.
Default-on for RDNA4 (GGML_CUDA_MMF32=0 disables; opt-in on RDNA3/RDNA3_5 until those boxes run the same
determinism + bench pair). GGML_CUDA_MMF32_LOG prints the resolved plans (diagnostic only).
Amended (r132): the per-arch dispatch is keyed to the device the kernel runs on, not the primary. mmb_enabled,
mmb_cfg, mmb_cfg_dump_once, mmb_dense_flag, mmb_wtype_mask and mmb_dense_tmask read
ggml_cuda_info().devices[ggml_cuda_get_device()].cc, and mmb_cfg() takes one magic static per architecture class
(mmb_arch_defaults() only discriminates RDNA4 and RDNA3_0, so every cc that reaches the fallback shares the same
pre-S11 table). ggml_backend_cuda_graph_optimize() now selects its own context's device before it consults those
predicates, so the MMB marking half agrees with the launch path under the Meta backend, where the pass is
forwarded per child from meta graph_compute and the current device is still the previously computed one.
Reported in PR ggml-org#218 (@slavap): on a mixed-arch box (gfx1100 primary + gfx1030 secondary) the policy froze at the
primary's, so the RDNA2 card ran RDNA3-tuned MMB kernels -- byte-exact zero output-projection logits (PPL ==
vocab) or garbled tail layers, depending on where the output projection sat. On a single-arch box this is
bit-for-bit the previous behaviour (validated here on 3x gfx1201: 12/12 same-seed configs byte-identical,
prefill-logit KLD 0.000000 on both recorded points, no GPU faults).
Co-authored-by: Slava P. <[email protected]>
Fold (r134, issue ggml-org#224): the width probe's n_ctx is now the prefill length plus the decode
width instead of a fixed 4096, and a purity run must pass P >= 4096. The RDNA4 band's
64-column block (query widths 5..8) is only reachable above the launcher's KV-length gate
(K->ne[1] >= 4096), and K->ne[1] is the context's used length, so the P=256 default never
reached that block: the probe reported PASS on every arm while widths 5..8 ran a geometry
that was not bit-identical to widths 1..4. At P=4096 the r126 geometry fails it
(width_purity=FAIL, worst maxdiff 0.199764 on q8_0 K/V, row-0 hash split between W=4 and
W=5), and the shipped band geometry passes with maxdiff 0.
Amended (r171): the MMB stand-down predicates are gone (TODO ggml-org#115). The two type-only helpers this
block carried -- ggml_cuda_mmb_dense_will_take() / _routed_will_take() -- answered a weight-TYPE
question while the dispatch asks a SHAPE question, so a fusion that stood down for MMB stood down for
shapes MMB does not claim at all (T < mmb_min_t(), n_used > 64, a K that is not a whole super-block
count, a non-contiguous dst, ...) and handed the pair to another fusion instead. Worse, it disagreed
with this block's BF16-activation marking, which can leave a preempted reader's F32 buffer unwritten.
The fusion sites now ask ggml_cuda_mmb_supported_mm() / _supported_mmid(), the predicates
ggml_cuda_mul_mat() / _mul_mat_id() themselves dispatch on, and both are null-safe now so a matcher can
probe an arbitrary node pair. This block's HC16 marking also keeps a ROUTED activation's F32 output
(marking the bf16 copy instead, so the MMB reader still finds it): the gate+up MUL_MAT_ID pair reading
it can be served by a mmq fusion rather than by two individual MMB muls. Inert on the measured arms:
gfx1201 byte-identical (27B Q8_0, 35B-A3B Q4_K_M at 1 and 3 GPU, LFM2 Q6_K; prefill-logit KLD
0.000000 / top-p 100.000 % on 27B and 35B-A3B), gfx1151 identical on every arm (LFM2 Q6_K and
35B-A3B Q4_K_M; the pair and the triple produce the same greedy text).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
There was an off-by-one bug in the line
it would copy
n_batch+1elements rather thann_batch. This PR fixes that and also switches to using STL instead of a while loop