Skip to content

qwen4exp : QSA with chunking - #30815

Closed
sanmai wants to merge 41 commits into
ggml-org:masterfrom
sanmai:feat/QSA-indexer
Closed

sanmai wants to merge 41 commits into
ggml-org:masterfrom
sanmai:feat/QSA-indexer

Conversation

@sanmai

@sanmai sanmai commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Overview

This is just a prototype. No review is needed.

Additional information

Benchmarks with UD-Q4_K_XL:

ub chunk CUDA0 compute MiB CUDA_Host compute MiB max cache MiB VRAM peak MiB
4096 off 5046 717 17700 32043
4096 2048 4076 717 18700 32073
8192 off 9237 1430 13400 32049
8192 2048 6885 1430 15750 32045
ub chunk prefill t/s decode t/s
4096 off 1271 (1201-1284) 54.7 (52.9-61.0)
4096 2048 1287 (1235-1296) 57.6 (54.4-62.5)
8192 off 1829 (1821-1861) 45.6 (41.4-49.2)
8192 2048 1869 (1861-1887) 52.2 (51.0-52.4)
run mean KLD same top
chunk 2048, ub4096 0.0145 96.5%
chunk 1024, ub4096 0.0150
chunk off, ub4096 0 100%
chunk off, ub2048 0.0168
chunk off, ub8192 0.0164

KLD changes with batching and chunking is just one more batch shape

Requirements

am17an and others added 7 commits October 16, 2026 11:35
The selection mask and the indexer scores of a QSA layer are [n_kv, n_tokens]
and [n_pool, n_tokens]. Score, select and attend 2048 query tokens at a time,
so the chunks of a layer reuse one chunk worth of memory. The views of the
token inputs are shared by the layers, so each slice is uploaded once.

LLAMA_QSA_CHUNK sets the chunk size for tests, 0 disables the split.
A [n_kv, 1, 1, 1] mask applies to every token and gives a [n_kv, n_tokens]
result, so a selection that is causal on its own does not need a dense
[n_kv, n_tokens] mask as its source.
Like llm_graph_input_attn_kv, do not fill a mask that no op reads.
A token sees only the pools that end at or before it and the tail up to
itself, all of its own sequence, so every kept cell is already visible in
the kq_mask and the selection is causal on its own. Keep a zero row
instead of the kq_mask cells, then no op reads the dense [n_kv, n_tokens]
mask, and the graph does not allocate or upload it.
@github-actions github-actions Bot added model Model specific testing Everything test related ggml changes relating to the ggml tensor library for machine learning CUDA Related to the CUDA backend labels Oct 19, 2026
Master has the final PR 30640, which renames ggml_kpool_mask to
ggml_top_k_mask and broadcasts the mask natively; take its version of the
op and call it with the zero row from qwen4exp.
@sanmai

sanmai commented Oct 21, 2026

Copy link
Copy Markdown
Contributor Author

@dagbdagb Replying here. Asked one of the agents to benchmark and find the best setting.

@am17an am17an left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the main problem here at long context? i.e. uploading the kq mask?

@dagbdagb

Copy link
Copy Markdown

Not entirely sure if that question was directed at me or not.

If it is: The help-text for --moe-cache-mib N has 0 guidance for sizing N. Unless one is very deep into the matter or developed the feature, one can only resort to guess-work. Or automated testing. Certainly not the only such parameter in the README, but still.

@am17an

am17an commented Oct 22, 2026

Copy link
Copy Markdown
Contributor

@dagbdagb it was not for you. Re the guidance, yes I will make some changes there soon

@sanmai

sanmai commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor Author

These are ideas pulled straight from Strata, with the goal to reduce memory footprint of work buffers:

  • QSA query chunking (c391f0f) goes like this:

    • Take the first 2048 tokens of the batch.
    • Build the mask, only a quarter of full 8192 batch
    • Run the attention
    • Free that mask and reuse
    • Join the outputs, and since chunks attend to the same kv cache the result is same
  • Removal the kq_mask from QSA (2020bb6, 72e03e1) that frees about 2 GiB at ub 4096 and about 4 GiB at ub 8192, so we all can use a larger expert cache and get better overall perf at ubatch 8192

Shrinking pool_mask is also an option.

And there's a bug with CUDA top_k tie ordering - haven't looked into it.

ub Before #30640 Now │
ub 4096 1180 / 48.5 t/s at cache 16700 1160 / 50 t/s at cache 18700 │
ub 8192 1660 / 38.5 t/s at cache 11500 1750 / 47 t/s at cache 15500 │

1750 t/s pp is the major win here

@sanmai

sanmai commented Oct 22, 2026

Copy link
Copy Markdown
Contributor Author

@am17an Feel free to slice and dice this thing into pieces as much as you want or need.

Comment thread src/models/qwen4exp.cpp Resolved
@am17an

am17an commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Okay so this is because the kq_mask being the largest user of the compute buffer at these ub sizes. But do we need to allocate the kq_mask for this model since we're using sparse attention? cc @ServeurpersoCom if you have a good idea.

EDIT: maybe I'm not correct and need to measure again.

@sanmai

sanmai commented Oct 22, 2026

Copy link
Copy Markdown
Contributor Author

all 12 attention layers are QSA so we should not need kq_mask

ggml_top_k_mask with a single keep row returns [n_kv, n_tokens], while
build_attn_qsa expects the kq_mask layout [n_kv, n_tokens/n_stream, 1, n_stream].
With several streams the shape assert failed at graph reserve.
@am17an

am17an commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

@dagbdagb maybe try the script in #30966

@github-actions github-actions Bot added the Vulkan Issues specific to the Vulkan backend label Oct 24, 2026
@sanmai sanmai changed the title qwen4exp : QSA without the kq_mask + chunking qwen4exp : QSA with chunking Oct 25, 2026
@am17an

am17an commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

it looks it may help with large ubatch on dsv4.1/glm5.3 as well

PapyKahan added a commit to PapyKahan/llama.cpp that referenced this pull request Oct 28, 2026
Upstream's version is kept wherever it does what the branch did; the branch's stays where upstream has none:
- MoE cache: the constructor takes upstream's no_alloc flag beside the CPU share, buffers come from
  llama_memory_bufs::alloc_buf; phases and host mode as before.
- build_moe_ffn: the branch's experts lambda (cache slots, host mode, shared batches) with upstream's DeepSeek-4.1
  and Laguna changes.
- qwen4exp: the selection is built over the cache cells as upstream now does (ggml-org#30965, ggml-org#31243), the branch keeps
  its query chunks (ggml-org#30815's earlier version); upstream's hc_mix outputs and merged tensors.
- CUDA MMQ: the tile map of active MoE tiles also launches upstream's fused gate/up/GLU kernel (ggml-org#31188, ggml-org#29948);
  the fused paths zero the rows of negative ids as ggml_cuda_mul_mat_id does.
- CPU MUL_MAT_ID: upstream's -1 skip (ggml-org#26631) and the branch's two-pass grouping agree, negative ids are skipped.
- tests: the QSA chunk tests move with upstream's archs tests; a MUL_MAT_ID result marked by
  ggml_mul_mat_id_set_negative_ids runs on CUDA again, only unmarked ones are excluded ([TAG_MUL_MAT_ID_SKIP]).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01P3vd8iuiuxiev7wMPyJmSf
# Conflicts:
#	src/llama-graph.cpp
#	src/models/models.h
#	src/models/qwen4exp.cpp
#	tests/CMakeLists.txt
LLAMA_QSA_CHUNK is read at each graph build, so one process can compare
contexts with chunking on and off. The existing chunk tests compare CPU
against GPU with the same chunks, so a misplaced chunk passes them.
The empty QSA chunk has one mask row and zero top-k rows, which the
original asserts accept. Only set_rows and the meta backend need the
empty-shape changes: without them the unfused selection (Vulkan, SYCL)
divides by zero and the meta backend asserts on the empty concat source.
5127cc1 dropped it by mistake, the meta device of test-llama-archs needs it.
@StormstoutLau

StormstoutLau commented Nov 16, 2026 •

Copy link
Copy Markdown

Data point from a 2-node Strix Halo (gfx1151) Vulkan+RPC setup, 1M context with GLM-5.3-Flash. Adjacent to your chunked QSA work, so posting here instead of a separate issue.

Setup

  • 2 nodes, Ryzen AI Max+ 395 (RADV gfx1151), 128 GB UMA each (~124 GiB usable).
  • llama-server (head) + ggml-rpc-server (worker), Vulkan, -DGGML_RPC=ON, Release.
  • Model: GLM-5.3-Flash UD-IQ4_XS (5 shards, 156,822,111,200 B, general.architecture = glm5-next).
  • Flags: -c 1048576 -fa on --n-cpu-moe 8 -t 16 --tensor-split 0.60,0.40.
  • vulkaninfo: maxMemoryAllocationSize = maxBufferSize = 0xFFFFFFFC (4 GiB − 4 B).

Not a minimal repro: the model needs both nodes, so RPC is part of the setup, not a variable I can remove.

Results

build graph_reserve total outcome
v0.7.0 (620d2225) 11,057,251,712 4.00 GiB single alloc fails
v1.0.0 (b12359) 9,933,178,240 still 4.00 GiB

v1.0.0 log:

W [ggml_backend_rpc_buffer_type_alloc_buffer] ... device: 0, size: 4.00 GiB -> failed
E ggml_gallocr_reserve_n_impl: failed to allocate RPC0[...] buffer of size 9933178240
E graph_reserve: failed to allocate compute buffers

With a temporary ≥2 GiB allocation log (op/shape/sources), the remaining large tensors are the k-pool update gathers:

[GIANT] node_442 op=GET_ROWS ne=[256,4194304,1,1] src0=cache_idx_k_l3 (view)/VIEW
[BIGALLOC] tensor=indexer_score-3 size=2147614720 (2.00 GiB)

node_442 is kpool_cache.gather_key_gate(new_pool_idxs) → [2*n_embd_indexer, kpool*n_new] with kpool = 4 and ne[1] = 4,194,304 = 4 × 1,048,576, i.e. n_new ≈ n_kv (inferred from the shape, not read back from cache state). The same 4 GiB copies also appear on the local Vulkan device, so this is not an RPC-only limit.

Local WIP chunking

Splitting the token axis (256 tokens per chunk, per-chunk attention, prev_sel as a vector) and the pool axis (65,536 new pools per gather/score chunk, per-chunk top-k merged across chunks) removes every 4 GiB tensor — the largest allocation drops to 1026 MiB.

At 1M it then hangs after graph_reserve: /health returns 503 for >15 min, CPU low, head GTT stable at ~110 GiB, no error and no model loaded. I did not capture a stack trace, so this is one observation without a diagnosis, not a claim about the scheduler.

Context limits: the 512k run that loads and answers used v0.7.0 + the token-axis patch; vanilla v1.0.0 was not tested at 512k, and master (b12428) was not tested at all. So 512k-vs-1M is not a clean same-build comparison.

Environment note (not a request)

Capping the RPC worker with MemoryMax=80G did not protect the machine: the watchdog reported GTT 72G at 20:45:46, then at 20:46:19 containerd invoked oom-killer, and the box hung with no Killed process persisted. I did not snapshot MemAvailable/GTT at the OOM instant, so "GTT + page cache exceeded 124 GiB" is an inference. It does show that cgroup memory.max is not a sufficient guard for this workload; whether dmem.max / amdgpu.gttsize actually caps GTT is unverified.

Questions

  1. Is the 4 GiB gather_key_gate / indexer_score requirement at 1M a known limitation, and is pool-axis chunking planned for glm5-next (analogous to qwen4exp : QSA with chunking #30815 for QSA)?
  2. Any recommended n_ctx ceiling for Vulkan devices with a 4 GiB single-allocation limit? 512k is fine here, 1M is not.
  3. For the hang: is there a known interaction between many per-chunk ggml_concat / ggml_top_k nodes and the scheduler (vbuffer chunk count / fused ops), or a better chunk granularity to try?

I can share the WIP patch (~320 lines) and full logs if useful. No action requested — just a data point.

@sanmai

sanmai commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #32883 and #32884

@sanmai sanmai closed this Nov 23, 2026
@sanmai
sanmai deleted the feat/QSA-indexer branch November 23, 2026 14:46
@sanmai

sanmai commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

@StormstoutLau glm5-next feature is here if you can test it: #32887

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CUDA Related to the CUDA backend ggml changes relating to the ggml tensor library for machine learning model Model specific testing Everything test related Vulkan Issues specific to the Vulkan backend

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants