Skip to content

cuda : Qwen4-35B-A3B decode on gfx1151, fixed-grid short-row matvec and weight prefetch (tg 50.4 -> 54.4) - #347

Merged
LaurentZuijdwijk merged 4 commits into
masterfrom
hb/qwen4-decode
Dec 5, 2026
Merged

LaurentZuijdwijk merged 4 commits into
masterfrom
hb/qwen4-decode

Conversation

@dzannotti

@dzannotti dzannotti commented Dec 4, 2026 •

Copy link
Copy Markdown
Collaborator

Overview

Single-token decode of Qwen4-35B-A3B on gfx1151 ran at 50.4 t/s, well below what its ~3 GB of weights per token allow.
Two changes take it to 54.3 t/s (+7.7%). Results are unchanged and the other models are not affected.

Qwen3.8-Flash-Next is not broken. It is the same qwen4exp arch, so both changes are active for it too. Its
output is identical to master (mean KLD 0, 100 % same top-1 at -ub 1 and -ub 4, max per-token KLD equal to master
against itself), prefill is unchanged and tg128 is 22.5 t/s against 21.5 on master (details below).

  1. Fixed-grid Q8_0 matvec for many short rows (mul_mat_vec_q8_0_fq_rows). The hyper-connection up projection
    (8192 rows, K = 256) launched 512 blocks of 16 waves, and each block re-quantized the activation before one short row
    per wave. Now 4 blocks per CU loop over the rows: they quantize the activation once and load the next row's weights
    before the dot product of the current one. The loads, dot products and reduction of a row are those of
    mul_mat_vec_q_fq<Q8_0>, so the output is bit-identical. Taken only for RDNA3.5, one column, Q8_0 without fusion,
    K <= 512 and >= 4096 rows.

  2. Decode weight prefetch into the last-level cache (qwen4exp only). Between two large weight reads (MoE experts,
    matrices >= 4 MB), a decode graph runs many small ops that leave DRAM idle, and its small matvecs wait on cold
    weights. A side stream reads the small weights of the next segment so they are in the 32 MB last-level cache when
    their matvecs run. The prefetch kernel only reads, so results do not change. It runs only when:

    • llama enables it for the context (ggml_backend_cuda_set_weight_prefetch, set for LLM_ARCH_QWEN4EXP);
    • the device is RDNA3.5;
    • no matmul in the graph has more than 4 columns (prefill is untouched);
    • no intra-graph overlap or concurrent-event region is active.

    Only weights that are contiguous, 16-byte aligned and in the device buffer of the context are read. The side
    stream joins the main stream before each CUDA graph chunk cut and at the end of the graph, and a segment that
    starts at a cut is prefetched inside the new chunk.

Measurements

Device:   Ryzen AI Max+ 395, 128 GB LPDDR5X-8000, gfx1151
OS:       Ubuntu 26.04, kernel 7.0.0-44-generic
Backend:  ROCm 10.1 (HIP), -DGGML_HIP=ON -DGPU_TARGETS=gfx1151 -DCMAKE_BUILD_TYPE=Release
Base:     master 4b4ec2dbd
Command:  llama-bench -fa 1 -ngl 99 -p 512,4 -n 128 -r 5, master and PR interleaved, two rounds (mean shown)
model test master this PR
Qwen4-35B-A3B UD-Q4_K_XL tg128 50.43 54.35
pp4 127.9 128.9
pp512 2273 2298
Qwen3.8-27B UD-Q4_K_XL tg128 12.12 12.03
pp512 336 371
Qwen3-Coder-30B-A3B Q4_K_M tg128 78.48 78.42
pp512 2022 2007
Inkling-2-Mini UD-Q4_K_XL tg128 22.44 22.48
pp512 501 492

The non-qwen4exp rows are within run-to-run noise (pp512 spreads of 5-30 t/s between rounds).

Qwen3.8-Flash-Next UD-Q4_K_XL (same arch, so the prefetch is on for it too), -ncmoe 20 to stay inside 90 GiB of
GPU memory, -r 3, two rounds:

test master this PR
tg128 20.79 +- 2.37 / 22.11 +- 0.33 22.58 +- 0.13 / 22.50 +- 0.13
pp4 51.1 / 54.2 51.2 / 50.1 (+- 4-5)
pp512 809 / 806 808 / 811

Correctness

  • test-backend-ops -b ROCm0: 57363/57363 (MUL_MAT 19225/19225 on the final commit). New cases: MUL_MAT Q8_0 with n = 1 at 4096/8192/8200 rows and K = 256/512 (the
    8200-row case has a partial last pass), and MUL_MAT_EXACT_BATCH Q8_0 n = 2..4 at the qwen4exp shapes
    260x8192, 8192x256 and 2048x4096 (n = 1 is the new kernel at 8192x256).
  • KLD of this PR against master, llama-perplexity on the four tests/corpus files concatenated, -c 512 --chunks 2,
    at -ub 1 and -ub 4 (the batch sizes these changes touch):
model ub mean KLD same top-1
Qwen4-35B-A3B 1 0.000000 100 %
Qwen4-35B-A3B 4 0.000000 100 %
Qwen3.8-27B 1 0.000000 100 %
Qwen3.8-27B 4 0.000000 100 %
Qwen3-Coder-30B-A3B 1 -0.000000 100 %
Qwen3-Coder-30B-A3B 4 -0.000001 100 %
Inkling-2-Mini 1 -0.000000 100 %
Inkling-2-Mini 4 0.000000 100 %
Qwen3.8-Flash-Next (-ncmoe 20) 1 0.000000 100 %
Qwen3.8-Flash-Next (-ncmoe 20) 4 0.000000 100 %

The maximum per-token KLD of ~5e-5 is the run-to-run noise of master itself (master against master: mean 0.000000, max 0.000052 at ub 1 and 0.000053 at ub 4 on Qwen4-35B-A3B, 0.000044 / 0.000047 on Qwen3.8-Flash-Next, the same as this PR against master).

Review fixes (2058da6, 28caec6)

Re-measured after the review fixes, master 4b4ec2d / previous head e59e505 / new head 28caec6,
llama-bench -fa 1 -ngl 99 -p 512,4 -n 128 -r 3, four interleaved rounds (mean):

test master e59e505 28caec6
tg128 50.46 54.33 54.37
pp4 127.1 127.9 127.6
pp512 2370 2367 2368

Logits after prefill and 16-32 greedy tokens at ubatch 1 are byte-identical between master, e59e505 and
28caec6 on Qwen4-35B-A3B and Qwen3.8-Flash-Next, also with GGML_CUDA_GRAPH_CHUNK_SIZE=1 and 37 (a cut at
almost every node); Qwen3-Coder-30B-A3B is byte-identical to master.

Not tested

  • Vulkan and CUDA (not changed; the new kernel and the prefetch are RDNA3.5-only).
  • --parallel > 1.

AI usage: the changes, measurements and this description were produced by an AI agent (Claude Code) under my direction, on my box.

🤖 Generated with Claude Code

dzannotti and others added 2 commits December 4, 2026 20:30
A single-column Q8_0 matvec with K <= 512 and at least 4096 rows (the
qwen4exp hyper-connection up projection, 8192 x 256) launched one block
of 16 waves per 16 rows, and every block quantized the activation again
for one short row per wave. Four blocks per CU now loop over the rows,
quantize the activation once, and load the next row's weights before the
dot product of the current one.

The loads, dot products and reduction of a row are those of
mul_mat_vec_q_fq<Q8_0>, so results are bit-identical; the new
MUL_MAT_EXACT_BATCH cases at 8192 x 256 compare it with n = 2..4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…exp)

Between two large weight reads (MoE experts, matrices >= 4 MB) a decode
graph runs many small ops that leave DRAM idle, and its small matvecs
wait on cold weights. A side stream now reads the small weights of the
next segment into the 32 MB last-level cache while the main stream runs
the small ops. The kernel only reads, so results do not change.

It runs when llama enables it for the context
(ggml_backend_cuda_set_weight_prefetch, set for LLM_ARCH_QWEN4EXP), on
RDNA3.5, when no matmul has more than 4 columns, and when no overlap or
concurrent-event region is active. The side stream joins the main stream
before each CUDA graph chunk cut and at the end of the graph.

Qwen4-35B-A3B tg128 on gfx1151: 50.4 -> 54.4 t/s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@LaurentZuijdwijk

Copy link
Copy Markdown
Member

Nice improvement and clean measurements — mul_mat_vec_q8_0_fq_rows matches mul_mat_vec_q_fq<Q8_0> cleanly and the side-stream MALL prefetch idea is great on gfx1151. A few bugs/hardening items I spotted in the diff:

Must fix

  1. ggml_cuda_prefetch_weight_bytes doesn't verify buffer device/type or contiguity (ggml/src/ggml-cuda/ggml-cuda.cu:7822-7831)
    Checking only GGML_BACKEND_BUFFER_USAGE_WEIGHTS allows through GGML_BACKEND_BUFFER_TYPE_CUDA_SPLIT (where w->data is not a flat device buffer of ggml_nbytes(w) bytes), tensors on another device, host-only buffers, and non-contiguous/strided views. Passing any of those to ggml_cuda_prefetch_kernel as (const float4 *) w->data will fault on GPU.

    • Suggest passing cuda_ctx->device and requiring w->data != nullptr, ggml_is_contiguous(w), and w->buffer->buft == ggml_backend_cuda_buffer_type(device) (or ggml_backend_buft_is_cuda_host if host-visible weights on APUs are intended).
  2. ggml_cuda_prefetch_kernel passes sink = nullptr and conditionally writes *sink = acc (ggml/src/ggml-cuda/ggml-cuda.cu:7808-7820, 8279)

    • Dereferencing nullptr on a sentinel branch is UB: if raw quantized bytes interpreted as floats ever hit 1.2345e30f it faults, and under IPA/LTO LLVM can treat sink == nullptr as making the branch unreachable and DCE the loop.
    • Also const float4 v = p[i]; acc += v.x; discards v.y/v.z/v.w while stepping every 16 B, issuing 8× more loads per 128 B RDNA3.5 MALL cache line than needed.
    • Suggest replacing the null sink with a real 4-byte scratch float on cuda_ctx (or an AMDGPU asm volatile("" : : "v"(acc)) sink on HIP), and optionally striding by 64 B / 128 B cache lines so the side stream uses fewer load instructions to pull the same lines into MALL.
  3. pf_step(i) runs before the CUDA-graph chunk-cut check (ggml/src/ggml-cuda/ggml-cuda.cu:8287-8298)
    When i == pf.start[pf_r] lands on a chunk boundary (i >= chunk_end), pf_step(i) launches the prefetch for segment [i, end) into the outgoing chunk and pf_join() immediately stalls the main stream waiting for it to finish before ending capture—before any node in [i, end) even executes.

    • Moving if (!pf.start.empty()) { pf_step(i); } to right after the chunk-cut block ensures pf_join() closes only the previous chunk's prefetch and the new segment starts inside the new chunk.

Should fix

  1. Add a static_assert coupling MMVQ_FQ_ROWS_MAX_K to MMVQ_FQ_PF (ggml/src/ggml-cuda/mmvq.cu:1948-2037)
    mul_mat_vec_q8_0_fq_rows has no K-loop and relies on a single chunk covering the full row (MMVQ_FQ_PF * (VDR_Q8_0_Q8_1_MMVQ * 32 / QI8_0) * QK8_0 == 512 >= MMVQ_FQ_ROWS_MAX_K). A static_assert prevents silent row truncation if either macro is tuned later.

  2. Batch guard in ggml_cuda_prefetch_build (ggml/src/ggml-cuda/ggml-cuda.cu:7841-7846)
    n->src[1]->ne[1]*n->src[1]->ne[2] > 4 misses ne[3] (use ggml_nrows(n->src[1]) > 4, matching ggml_cuda_ovl_plan) and doesn't check batched GGML_OP_MUL_MAT_ID with > 4 tokens.

  3. Tighten y_op check and drop unused sum in mul_mat_vec_q8_0_fq_rows (ggml/src/ggml-cuda/mmvq.cu:2004, 2052)

    • Whitelist y_op >= 0 && y_op <= 2 instead of y_op != 3 so any future y_op doesn't fall into the sigmoid branch.
    • mmvq_fq_block_sum(v, warp_size) is unused for Q8_0 (mmvq_fq_q8_0_dot only reads __low2half(bq8_1->ds)); 0.0f matches mul_mat_vec_q_fq.
  4. Minor hygiene

    • Call ggml_cuda_set_device(cuda_ctx->device) before creating pf_ev[0..1] in pf_step (matching ggml_cuda_ovl_fork).
    • Consider defining GGML_CUDA_PREFETCH_STREAM next to GGML_CUDA_SIDE_STREAM in common.cuh so stream indices stay documented in one place.

dzannotti and others added 2 commits December 5, 2026 01:13
Assert that one MMVQ_FQ_PF chunk covers MMVQ_FQ_ROWS_MAX_K, since the
kernel has no K loop. Take the kernel only for y_op 0..2, the ops it
implements. Drop the Q8_1 block sum: the Q8_0 dot product reads only the
scale, as in mul_mat_vec_q_fq<Q8_0>. Results do not change.

Assisted-by: Claude Code
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Prefetch a weight only if its data is set, it is contiguous, 16-byte
  aligned and in the CUDA buffer type of the context's device. Weights in
  host buffers (partial offload) are skipped.
- Write the kernel's sentinel result to a real 4-byte device buffer of
  the context instead of a null pointer, and use all four lanes of each
  16-byte load. Loads at a 64 B or 128 B stride lose most of the gain
  (tg128 50.9 and 50.2 against 53.0 at 16 B with 4-byte loads, master
  50.4), so the kernel keeps 16-byte loads.
- Start the prefetch of a segment after the CUDA graph chunk cut, so the
  cut joins only the prefetch of the previous chunk and the new one runs
  inside the new chunk.
- Batch guard: ggml_nrows of src1 for MUL_MAT, token count for
  MUL_MAT_ID.
- Create the events and the sink when the prefetch is enabled, with the
  device set; define GGML_CUDA_PREFETCH_STREAM next to
  GGML_CUDA_SIDE_STREAM.

Assisted-by: Claude Code
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@dzannotti

Copy link
Copy Markdown
Collaborator Author

@LaurentZuijdwijk Thanks for the careful read. I pushed two commits on top: 2058da6 (short-row matvec) and 28caec6 (prefetch). Point by point:

  1. Prefetch weight checks - taken, partly a real risk. A weight is now prefetched only if data is set, it is contiguous, 16-byte aligned and w->buffer->buft == ggml_backend_cuda_buffer_type(device) (28caec6). Two details: this fork's CUDA backend has no split buffer type, so the SPLIT case cannot happen here today. Host-visible buffers are GPU-readable on the APU, so they would not have faulted. I tried to reach the path by forcing small weights into the ROCm host buffer: the scheduler ran those matmuls on the CPU, and the prefetch launches and their total time were identical before and after the change. So the guard is defensive in current configurations, but it is correct and cheap, and it also covers other devices.

  2. Null sink - taken. The kernel now writes its sentinel result to a real 4-byte device buffer that the context allocates when the prefetch is enabled, so the store is well defined and the loop cannot be dropped. Each 16-byte load now uses all four lanes. I did not take the cache-line stride. I measured it (Qwen4-35B tg128, 4 interleaved rounds): master 50.4, old head 53.7, 4-byte loads at a 16 B stride 52.6, 64 B stride 50.9, 128 B stride 50.2. One load per line keeps almost none of the gain, so the kernel keeps 16-byte loads.

  3. pf_step before the chunk cut - taken. You are right about the order. It did not change results, because pf_join ran before the capture ended. But a segment that started at a cut was prefetched in the outgoing chunk, and the main stream then waited for it. pf_step now runs after the cut. Logits are byte-identical with GGML_CUDA_GRAPH_CHUNK_SIZE=1, 37 and the default 512. At the default size a Qwen4-35B decode graph runs as about 12 chunks, and at size 1 as about 1660 chunks, counted from hipGraphLaunch.

  4. static_assert - taken (2058da6).

  5. Batch guard - taken, with one change. MUL_MAT uses ggml_nrows(src1) > 4. For MUL_MAT_ID I check the token count (ids->ne[1] > 4) and not ggml_nrows(src1). src1 of MUL_MAT_ID is [K, n_used, n_tokens], so its row count is n_used even for one token, and that would turn the prefetch off for every decode.

  6. y_op whitelist and unused sum - both taken (2058da6). The output does not change.

  7. Hygiene - taken. GGML_CUDA_PREFETCH_STREAM is now next to GGML_CUDA_SIDE_STREAM in common.cuh. The events and the sink are now created in ggml_backend_cuda_set_weight_prefetch, with the device set. Before, they were created during graph compute, where the device was already set, so it was not a bug.

Verification on gfx1151 against master 4b4ec2d:

  • HIP build with -Werror passes, and the VGPR/SGPR spill gate passes (no new spills).
  • ctest (label main): 37/37 pass.
  • test-backend-ops -o 'MUL_MAT.*': 40175/40175 pass. With HIP_LAUNCH_BLOCKING=1 the Q8_0 subset passes 6424/6424, and the new short-row cases (Q8_0, n = 1, 4096/8192/8200 rows, K = 256/512) pass in both modes.
  • Logits after prefill plus greedy decode at ubatch 1 (and at ubatch 512 for prefill) are byte-identical between master, the previous head and the new head on Qwen4-35B-A3B and Qwen3.8-Flash-Next. Qwen3-Coder-30B-A3B is byte-identical to master.
  • llama-bench on Qwen4-35B-A3B, -r 3, 4 interleaved rounds (master / previous head / new head): tg128 50.46 / 54.33 / 54.37, pp4 127.1 / 127.9 / 127.6, pp512 2370 / 2367 / 2368.
  • Vulkan is not affected: only ggml-cuda files changed.

Written with AI assistance on behalf of the strix-llama.cpp maintainers.

@LaurentZuijdwijk
LaurentZuijdwijk merged commit 1bbb0aa into master Dec 5, 2026
10 checks passed
@LaurentZuijdwijk
LaurentZuijdwijk deleted the hb/qwen4-decode branch December 5, 2026 15:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants