Skip to content

llama/HIP : lazy PLE reads on iGPUs with little RAM, sparse QSA attention on RDNA3.5 - #221

Open
zz002 wants to merge 38 commits into
AMD-Ecosystem:mai-perf-fixesfrom
zz002:qwen-ple-lazy-load
Open

zz002 wants to merge 38 commits into
AMD-Ecosystem:mai-perf-fixesfrom
zz002:qwen-ple-lazy-load

Conversation

@zz002

@zz002 zz002 commented Nov 17, 2026 •

Copy link
Copy Markdown

Long-context and memory improvements for Qwen3.8-Flash-Next (qwen4exp) on RDNA3.5 iGPUs, found while running UD-IQ4_XS and UD-Q4_K_XL on Strix Halo under Windows with a 96 GiB GPU carve-out (31.6 GiB of system RAM left).

What is optimized

Lazy PLE table reads on hosts with little RAM. The model carries a 27 GiB IQ4_NL n-gram embedding table (per_layer_token_embd), of which only a few rows are read per token. On iGPUs without mmap support, --load-mode auto turned mmap off and lazy reads with it (ggml-org/llama.cpp#28160 / #28326), so the whole table was copied into a CPU buffer that a 31.6 GiB host pages out. Now a tensor larger than a quarter of the host memory is still read lazily with row prefetch; everything else stays resident as before, so a 128 GB host (the #28160 case) keeps the table resident. On Windows, weights uploaded to the device are also dropped from the working set during and after an mmap load (VirtualUnlock), since unmap_fragment was a no-op there.

Sparse QSA attention on RDNA3.5. 12 of the 48 layers use Qwen Sparse Attention: an indexer picks ~2048 cells per token and flash attention receives a full-length mask with an n_kv_max hint. The MMA kernel's sparse gather path (only the selected K/V rows are loaded) was enabled only on NVIDIA Turing+ and CDNA, so on RDNA every QSA layer read the whole KV cache. It is now enabled on RDNA3.5 (GGML_HIP_FA_SPARSE, on by default, =0 disables) for decode, MTP verify and prompt batches, above measured KV-length crossovers. Decode and MTP verify use the narrowest WMMA sparse tile that fits (2x8, 4x8, 8x8). GQA-12 prompt batches use a 2x16 tile: all 12 heads of a KV head share one tile, so each gathered K/V row is read once, and the tile only covers the union of 2 queries (the WMMA work grows with that union; for real QSA masks the union of 2 queries is ~0.4x that of 8). This adds one (256, 256, 2, 16) MMA instance, compiled for HIP only. The 2x16 tile beats the dense kernel from 4x n_kv_max cells on, so 8K-deep prompts take the sparse path too. The sparse row lists are now sized by the queries actually in a tile, and the mask is compacted with wider blocks when there are few lists (this part applies to all backends).

QSA indexer and top-k on RDNA3.5. For every token, the QSA indexer scores all pooled keys with 4 heads of 128 dims. LIGHTNING_INDEXER has no WMMA tile for 4 heads (a head tile needs 16 rows), so prompt batches ran the float tile kernel at ~4 TFLOPS, and TOP_K then picked 512 of 8.8K to 17K pools per token with 10 radix launches. The 4 heads of 4 tokens now form the 16 rows of a WMMA tile (batches of at least 16 tokens, on by default on RDNA3.5, GGML_HIP_INDEXER_WMMA overrides), and TOP_K rows of 1025 to 32768 columns are selected by a single block that holds the row in registers (RDNA3.5, GGML_HIP_TOPK_BLOCK overrides), selecting the same set as the radix path. At 64K context the indexer and top-k of a 2048-token ubatch take ~46 ms instead of ~182 ms.

QSA memory host costs. The hybrid idx memory no longer allocates and zeroes a per-cell array on every decode call, and regroups only the edited tail of a sequence when rejected drafts are dropped, instead of rebuilding the whole k-pool layout several times per MTP round.

SSM conv input of the linear-attention layers. Each of the 36 Gated DeltaNet layers builds its conv input as concat(conv_state, transpose(qkv)), a [2051, 10240] f32 tensor per 2048-token ubatch. That CONCAT reads a non-contiguous input and ran at ~40 GB/s, about 4.2 ms per layer, several times longer than the SSM_CONV that consumes it. On CUDA/HIP, a dim 0 CONCAT whose only use is the following SSM_CONV (with the existing bias ADD and SILU fusion) is now fused into it: the conv reads the state and x in place, one thread per channel, in the same accumulation order, so the results are bit-identical. qwen4exp now writes the conv state back from a separate short concat of the last columns, so that the full conv input feeds only the convolution; decode and MTP verify batches keep the single concat. Models whose concat also feeds the state write-back do not match the fusion and are unchanged.

MoE weighted sum and F32 router on RDNA3.5. In prompt batches, the weighted sum of the 10 selected experts (moe_weighted_reduction) read one float per thread with a single load in flight and reached ~100 GB/s; it now sums 4 columns per thread with 16-byte loads (GGML_HIP_MOE_REDUCE_X4), in the same summation order, so the results are bit-identical. The F32 MoE router (512x2560) and the SSM alpha/beta projections (48x2560) of prompt batches went to hipBLAS SGEMM at ~2.5 TFLOPS; F32 matrix multiplications with 16 to 1024 rows and at least 16 tokens now run on FP16 WMMA with the activations and weights split into high and low halves and accumulated in F32 (GGML_HIP_F32_WMMA). Per 2048-token ubatch of UD-IQ4_XS the three ops take ~100 ms instead of ~246 ms: pp2048 +3% to +4%, time to first token -5% at 32K and -3% at 64K.

Shared MTP draft head, and QSA for a dense MTP block on long contexts. The shared MTP file (2.79 GB) omits \ oken_embd\ and \output. A qwen4exp draft context borrows those tensors from its target when the architecture, width and vocabulary match, and refuses to load such a file on its own; the draft then scores the target's output head instead of a second Q8_0 copy. The shared file stores the MTP block as dense attention. --spec-draft-qsa auto\ (the default) keeps dense attention while the KV cache holds fewer than 40960 cells and uses QSA from there on; \on\ and \off\ force either path. A self-contained MTP file that already stores QSA is unchanged by the option. Switching mid-request keeps the indexer state, so a short context on a long _ctx\ pays about 1 ms per round and the output stays the same. One run, chat prompts, 2048 tokens, the shared head against the self-contained Q8_0 head: UD-IQ4_XS 1K 35.19 to 37.84 tok/s (+7.5%, speculative round -2.7%), 64K 34.47 to 36.23 (+5.1%, round -2.0%, time to first token +3 s); UD-Q4_K_XL 1K +1.8% (round -1.1%), 64K round -0.2% (the +7.7% tok/s there is mostly a change in draft acceptance after the text diverges). Greedy output without MTP is identical.

Gated Residual prefill on RDNA3.5. Each hyper-connection block normalizes a [2560, 4, T] activation and then multiplies it by a 4x10240 F32 inject, rereading the same 84 MB. On RDNA3.5 prompt batches of at least 32 tokens that matmul is folded into the RMSNorm: one block per token keeps the normalized streams in shared memory and writes both the normalized activation and the scaled inject (GGML_HIP_HC_INJECT, on by default, =0 disables). The q8_0 HC down (320x10240) splits K into 4 slices per MMQ tile and adds the partials with the existing stream-k fixup (GGML_HIP_MMQ_KSPLIT, default 4, =0 disables); decode stays on MMVQ. On Strix Halo, UD-IQ4_XS pp2048 is +3.6% at depth 0 and 8K and +2.0% at 32K; tg128 is unchanged. A fused HC up plus HC_PRE kernel was slower than the separate kernels (13.8 ms vs 2.3 ms at n=2048) and is not included. test-backend-ops on ROCm0 passes the new HC_INJECT cases and the q8_0 320x10240 case. Greedy output matches except at a near-tie (1K token 28, 4097 token 80); 4100 and 32K match with and without MTP, and the draft acceptance stays in the same range. KLD against UD-Q4_K_XL on the first 20 wikitext-2 chunks of 2048 is 0.075792 +/- 0.001530, against 0.076741 +/- 0.001522 with these two opts off.

This is independent of #219 and merges with it without conflicts. With #213: its KV-tile skipping applies only to the dense path, so the two are complementary, but GGML_HIP_FA_GQA_PAD=2 would send GQA-12 decode below 16K and all MTP verify back to ncols2 = 4, where there is no sparse variant.

Results

UD-IQ4_XS and UD-Q4_K_XL on Strix Halo (Radeon 8060S, gfx1151), Windows 11, TheRock ROCm 10.0, 96 GiB carve-out / 31.6 GiB RAM, mai-perf-fixes (b1a040d) vs this PR (head 6db4d77).

End to end, llama-server, greedy, 2048 generated tokens, MTP draft (--spec-draft-n-max 2), median of 2 runs, single interleaved run, every request started below 65 C. The prompts are chat-formatted: English Wikipedia articles (wikitext-2) cut at a sentence boundary, followed by a request to write a long analytical report about them, at 1K and 64K tokens. Earlier revisions of this description used raw source code as the prompt; its 64K continuation fell into a repetition loop that inflated MTP acceptance, so those numbers are replaced.

UD-IQ4_XS

Before (mai-perf-fixes b1a040d)

Prompt Plain (tok/s) MTP (tok/s) Speedup Acceptance Tokens/verify TTFT plain (s) TTFT MTP (s)
1K 27.09 37.42 1.38x 73% 2.46 1.9 1.9
64K 17.99 23.50 1.31x 69% 2.38 165.5 185.5

After (this PR)

Prompt Plain (tok/s) MTP (tok/s) Speedup Acceptance Tokens/verify TTFT plain (s) TTFT MTP (s)
1K 27.13 38.77 1.43x 73% 2.46 1.8 1.9
64K 25.31 35.01 1.38x 71% 2.42 112.6 118.9

At 64K: plain decode +41%, MTP decode +49%, time to first token -32% (plain) / -36% (MTP). At 1K: plain unchanged, MTP +4%.

UD-Q4_K_XL

UD-Q4_K_XL is 103.7 GiB, of which ~27 GiB (the n-gram table) stays on the CPU. With default arguments, a 64K context (--ctx-size 73728) and the MTP draft head, the Before build fails to allocate a 898 MiB compute buffer on the GPU (out of memory, reproduced twice), so the Before rows were measured with --load-mode mmap; this PR runs the same command line with default arguments.

Before (mai-perf-fixes b1a040d, --load-mode mmap)

Prompt Plain (tok/s) MTP (tok/s) Speedup Acceptance Tokens/verify TTFT plain (s) TTFT MTP (s)
1K 24.31 34.51 1.42x 70% 2.39 1.7 1.7
64K 16.75 22.63 1.35x 69% 2.38 170.5 182.2

After (this PR)

Prompt Plain (tok/s) MTP (tok/s) Speedup Acceptance Tokens/verify TTFT plain (s) TTFT MTP (s)
1K 24.47 34.93 1.43x 70% 2.39 1.5 1.6
64K 22.68 32.84 1.45x 72% 2.44 118.7 124.5

At 64K: plain decode +35%, MTP decode +45%, time to first token -30% (plain) / -32% (MTP). At 1K: plain unchanged, MTP +1%.

Model load

llama-server with default arguments (64K context, no MTP), file pages not in the page cache before the load (under 0.1 GiB cached) for both builds. Before -> After:

Model Load time (s) Available RAM after load (GiB) Page file
UD-IQ4_XS 79.4 -> 28.0 2.6 -> 25.0 8.6% -> 2.9%
UD-Q4_K_XL 112.9 -> 34.0 2.7 -> 24.5 8.1% -> 2.3%
UD-Q4_K_XL (Before with --load-mode mmap) 201.0 -> 34.0 0.2 -> 24.5 2.7% -> 2.3%

Known cost of the lazy PLE path: when the table's file pages are not in the page cache, decode of the first few hundred tokens is 10 to 18% slower until the hot rows are cached (same effect as reported for ROCm/hip-ep#1222).

Correctness

  • test-backend-ops -b ROCm0 at head 6db4d77: FLASH_ATTN_EXT 4395/4395, LIGHTNING_INDEXER 204/204, TOP_K 580/580, TOP_K_MASK 38/38, SSM_CONV 60/60, CONCAT 221/221 pass.
  • test-backend-ops -b ROCm0 at head d32908b (with the MoE weighted sum and F32 router commits): MUL_MAT 2698/2698, MOE_REDUCE 13/13 pass.
  • At head 6db4d77, greedy output at the 1K prompt is identical before and after for both models, with and without MTP, and the MTP draft acceptance is identical (UD-IQ4_XS: 1223/1647 and 1206/1679 drafted tokens accepted in the two requests; UD-Q4_K_XL: 1200/1693 and 1185/1723).
  • At the 64K prompt the output diverges at a near-tie token (the two top candidates swap). Without MTP, the baseline's two runs at 64K differ from each other for both models, while this PR's two runs are identical; with MTP, the two runs differ for both builds.

AI assistance was used for profiling and for parts of the code; I reviewed and tested all changes.

amd-genmingz and others added 9 commits November 16, 2026 02:24
Assisted-by: Claude
Co-authored-by: Cursor <cursoragent@cursor.com>
Assisted-by: Claude
Co-authored-by: Cursor <cursoragent@cursor.com>
Assisted-by: Claude
Co-authored-by: Cursor <cursoragent@cursor.com>
… context

Assisted-by: Claude
Co-authored-by: Cursor <cursoragent@cursor.com>
…mmap

On devices without mmap support (iGPUs) --load-mode auto turns mmap off and --lazy-mode auto resolved to off (ggml-org#28160), so a 27 GiB engram table was copied into a regular CPU buffer. On a host with little RAM (Strix Halo with a 96 GiB carve-out leaves 31.6 GiB) this pages and halves prefill. Keep the tensors resident as before, but still read a tensor lazily when it is larger than a quarter of the host memory.

Co-authored-by: Cursor <cursoragent@cursor.com>
unmap_fragment was a no-op on Windows, so with --load-mode mmap the pages read to upload the offloaded weights stayed in the working set (~25 GiB on a 31.6 GiB host). A view cannot be unmapped in parts, so remove the pages from the working set with VirtualUnlock instead; they stay mapped and in the standby list.

Co-authored-by: Cursor <cursoragent@cursor.com>
…ad on Windows

With --load-mode mmap the pages of the offloaded weights stayed resident until the end of the load (peak working set ~25.6 GiB, ~0.1 GiB available on a 31.6 GiB host). Drop each tensor's pages right after its upload.

Co-authored-by: Cursor <cursoragent@cursor.com>
…he draft context"

This reverts commit ccecb0c. With the PLE table read lazily (ggml-org#221) the prefetch shows no gain in steady state decode.

Assisted-by: Claude
Co-authored-by: Cursor <cursoragent@cursor.com>
Assisted-by: Claude
Co-authored-by: Cursor <cursoragent@cursor.com>
@zz002 zz002 changed the title llama : read the PLE table lazily on iGPUs with little RAM, trim the mmap working set on Windows llama/HIP : read the PLE table lazily on iGPUs with little RAM, sparse QSA attention on RDNA3.5 Nov 17, 2026
zz002 and others added 6 commits November 17, 2026 18:53
A tile wider than the batch (e.g. one decode query in an 8-query tile) iterated over ncols1*n_kv_max list entries, mostly -1 padding.

Co-authored-by: Cursor <cursoragent@cursor.com>
…ists

One block scans a whole mask row in 2048-column chunks, so in decode the scan of a 64K mask was ~1 us per 1K columns. With fewer lists than SMs use 1024 threads per block.

Co-authored-by: Cursor <cursoragent@cursor.com>
…hint

Qwen QSA layers pass a full-length mask that keeps ~2K cells plus an n_kv_max
hint. The sparse gather was enabled only on NVIDIA and CDNA, so RDNA read the
whole KV cache. Small batches take the narrowest sparse WMMA tile that holds
them: 2x8 for decode, 4x8 for MTP verify, 8x8 up to 8 queries. A list holds
the union of the queries in a tile and a gathered row costs about 1.5 dense
rows, so require K >= 1.5x the list length. GGML_HIP_FA_SPARSE=0 disables it.

Add QSA eval cases for 2-8 queries and perf cases around the crossover.
GQA 12 batches of more than 8 queries went to ncols2=4, which has no sparse
variant, so every QSA layer read the whole KV cache during prefill. When the
sparse condition holds, pad GQA to ncols2=8 instead and gather with the 8x8
tile: a list is the union of 8 neighbouring queries, about 4x n_kv_max for the
real QSA masks. The dense kernel is slower per row at these sizes, so the
gather already wins at K >= 6x n_kv_max even for independent random masks.

Add QSA prompt-batch eval cases, and perf cases with selections drawn from a
shared pool of cells to mimic the overlap of neighbouring queries.
kpool_build_state stamped the pools it marks in a per-cell array that lived in the memory context, so every decode call allocated and zeroed kv_size entries (1 MiB at 262144 cells, ~0.17 ms per call, four calls per MTP round). Keep the array and its generation counter in the memory instead.
A sequence edit after the first position (e.g. dropping the rejected drafts of a speculative round) rebuilt the whole k-pool layout of the sequence from the cell set, ~0.9 ms per call at 32K context and four calls per MTP round. The cells before the edit and the pools made of them only are unchanged, so keep them and regroup from the last kept pool.
@zz002
zz002 force-pushed the qwen-ple-lazy-load branch from cdc1d75 to 2a9eb5f Compare November 18, 2026 02:05
@zz002 zz002 changed the title llama/HIP : read the PLE table lazily on iGPUs with little RAM, sparse QSA attention on RDNA3.5 llama/HIP : lazy PLE reads on iGPUs with little RAM, sparse QSA attention on RDNA3.5 Nov 18, 2026
zz002 and others added 12 commits November 18, 2026 02:18
…conv input

The conv input of the linear attention layers is concat(state, transpose(x)). Cover the shapes of Qwen3.8-Flash-Next (10240 channels, 1, 3 and 2048 tokens) and add the prefill shape to the perf cases.

Co-authored-by: Cursor <cursoragent@cursor.com>
When the CONCAT has no other use, the conv reads the state and the (transposed) x in place: one thread per channel, so the loads of x and the stores are coalesced. The non-contiguous CONCAT it replaces ran at ~40 GB/s. graph_optimize keeps both concat inputs alive until the last fused node.

Co-authored-by: Cursor <cursoragent@cursor.com>
…columns

The full conv input is then read only by SSM_CONV, so a backend can fuse the two. Decode and MTP batches (no more tokens than the state columns plus n_rs_seq) keep the single concat.

Co-authored-by: Cursor <cursoragent@cursor.com>
Eval cases for 2-8 queries and for prompt batches with partial tiles, with
independent random selections and with selections drawn from a shared pool
of cells, which mimics the overlap of neighbouring queries of the QSA
indexer. Perf cases from 8K to 64K cells for 512 and 2048 queries, and for
MTP verify / draft blocks at 32K.

Co-authored-by: Cursor <cursoragent@cursor.com>
…NA3.5

GQA 12 prompt batches used the 8x8 sparse tile: 8 queries x 8 heads, so each
KV head needed 2 tiles that both gather the union of the 8 queries (about 4x
n_kv_max for the real QSA masks). The WMMA work of a tile grows with that
union and dominates the kernel, the K/V gather is the smaller part.

Use a 2x16 tile instead: all 12 heads of a KV head in one 16-head tile (one
gather per KV head) over the union of only 2 queries, which is about 0.4x the
union of 8 at 32K-64K. The kernel is 1.6-1.8x faster than the 8x8 tile for
shared-pool masks close to the real indexer at 32K-64K cells, and it beats the
dense kernel from 4x n_kv_max cells on, so 8K-deep prompts (10K cells) now take
the sparse path too.

The (256, 256, 2, 16) MMA instance is only compiled for HIP.

Co-authored-by: Cursor <cursoragent@cursor.com>
…verify batches

Eval cases: TOP_K of 512 out of 1.5K to 32K pools for 1, 3 and 20 rows, with
ties at the threshold, with many -inf (invisible pools), and over the batch
dimensions; LIGHTNING_INDEXER with 4 heads for token counts that are not a
multiple of a WMMA token tile and key counts that are not a multiple of the
key tile, for F32 and F16 keys, with 1 to 3 streams.

Perf cases: the pooled indexer of Qwen3.8-Flash-Next at 8K, 32K and 64K
context for a 2048 token batch and a verify batch, and TOP_K of 512 of the
same pools for 1, 3 and 2048 rows.

Co-authored-by: Cursor <cursoragent@cursor.com>
The radix path of TOP_K takes 10 launches per call (4 histogram passes, 4
selects, init, gather), each re-reading the row. For the Qwen QSA indexer
that is 512 of 8.8K (32K context) to 17K (64K context) scores per token, 12
layers per ubatch, and also every decode and MTP verify step.

Hold the row (up to 32768 columns) in registers of one block instead: four
8-bit radix passes over the keys that match the prefix found so far give the
512th largest key T, then the keys above T and the lowest columns of the keys
equal to T are written. The selected set is the one of the radix path (the
lowest columns win ties, checked against the exact host top-k on 127K rows of
real 32K and 64K prompts: no difference). The order in a row is unspecified,
as before.

Only on RDNA3.5 (GGML_HIP_TOPK_BLOCK overrides), and only for rows between
1025 and 32768 columns, other cases keep their path. Kernel time at 2048 rows:
32K context pools (8768) 2.64 -> 0.60 ms, 64K (16960) 5.0 -> 1.42 ms; a single
row (decode, verify): 40 -> 8 us at 8768 and 36 -> 11 us at 16960.

Co-authored-by: Cursor <cursoragent@cursor.com>
LIGHTNING_INDEXER with 4 heads has no WMMA tile (a head tile needs 16 rows),
so prompt batches ran the float tile kernel at 4 TFLOPS: 4.8 ms per layer at
32K context and 9.8 ms at 64K, 3% to 5% of a pp2048 ubatch.

Use the 4 heads of 4 tokens as the 16 rows of the A operand, so a wave scores
a 16 key column tile for 4 tokens, 8 waves share a staged half precision key
tile (as the tile kernel, keys are rounded to half). The float queries are
split into a high and a low half and both are accumulated in float, which
keeps the float precision of the products: scores differ from the float tile
kernel only by the summation order (max 1e-5 absolute, last bits of most
scores). Rows are ordered so that a lane of the accumulator holds the 4 heads
of 2 tokens and the ReLU, weights and mask add need no cross lane reduction.

Only for RDNA3 / RDNA3.5 with F32 or F16 keys and at least 16 tokens, on by
default on RDNA3.5 only (GGML_HIP_INDEXER_WMMA overrides); smaller batches
(decode, MTP verify) keep the vector kernel. 2048 tokens at 32K / 64K context:
4.70 -> 1.17 ms and 9.0 -> 2.26 ms. On real 32K and 64K prompts the top-512 set
of a row differs from the float kernel's in 0.02% of the rows (a pool at the
512th place whose score is within a rounding error of the next).

Co-authored-by: Cursor <cursoragent@cursor.com>
Assisted-by: GPT-5.6 Sol
Co-authored-by: Cursor <cursoragent@cursor.com>
…pt and verify batches

Co-authored-by: Cursor <cursoragent@cursor.com>
…A3.5

The fused weighted reduction of the experts (MUL by the routing weights and the chain of ADDs) used one
thread per column and 4 byte loads, 100 GB/s on [2560,10,2048]. For prompt batches without a q8_1 copy
of the result, each thread now sums 4 consecutive columns with float4 loads, the loads of all experts
issued up front. The products and sums are spelled out (__fmul_rn, fmaf) in the order of the scalar
kernel, so that the result is bit for bit the same. On by default on RDNA3.5 for at least 16 tokens;
GGML_HIP_MOE_REDUCE_X4=0 / 1 turns it off / on.

Co-authored-by: Cursor <cursoragent@cursor.com>
…MMA on RDNA3.5

The router (F32 512x2560, 2048 tokens) went through hipBLAS sgemm at 2.5 TFLOPS. Both operands are split
into a high and a low half (x = x_hi + x_lo, 22 of the 24 bits) and multiplied as x_hi*w_hi + x_lo*w_hi
+ x_hi*w_lo on the WMMA units with float accumulation, 64x64 outputs per block of 4 waves. The three
products of 16 values of K are summed in a fresh accumulator and added to the running float sum, since
the accumulation inside a WMMA does not round to nearest. The error against a double precision product
is that of a float GEMM or a little smaller. Used for F32 products with at least 16 tokens, 16 rows,
K a multiple of 32 and 16 byte aligned rows; on by default on RDNA3 / RDNA3.5 devices tuned for 3.5
(GGML_HIP_F32_WMMA=0 / 1 turns it off / on).

Co-authored-by: Cursor <cursoragent@cursor.com>
amd-genmingz and others added 9 commits November 24, 2026 01:38
…om its target

The shared MTP files (qwen4exp.nextn_shared_target_tensors, 2.79 GB instead of 4.14 GB) leave token_embd and
output out, and failed to load with "token_embd.weight not found". Load the two tensors as optional when the
file has no trunk, and let the draft context borrow them from the target model through ctx_other, like the
DFlash and Eagle3 drafts: the embedding rows come from the target's token_embd and the draft logits from the
target's output, so the draft head reads the target's q6_K head instead of its own Q8_0 copy. The context
checks the target (same arch, width, vocabulary, both tensors present) and refuses to load such a head on its
own.

The shared files need two more things:
- they carry compress ratio 0 for the MTP block (dense attention), where the self-contained file says 4 (QSA).
  A dense MTP block must not build the k-pool inputs (the indexer key indexes had no buffer and set_input
  asserted) and needs no indexer cache in the draft memory;
- ctx_other is set for such a draft now, so the MTP driver must not take it for the shared KV cache of the
  gemma4 assistant: check the architecture too.

A self-contained head loads and runs as before.

Co-authored-by: Cursor <cursoragent@cursor.com>
…on long contexts, --spec-draft-qsa (default auto)

The shared MTP files store the MTP block with compress ratio 0, dense attention, where the self-contained file
says 4 (QSA). A dense draft step reads the whole KV cache, QSA only the selected blocks. Round times of the
UD-IQ4_XS sweep (verify and two draft steps, shared head, dense against QSA, 2 runs each):

  context   1K    4K    8K    16K   32K   48K   64K
  dense     59.1  59.8  61.8  61.4  63.9  66.6  69.3 ms
  QSA       60.2  61.1  63.0  62.6  63.9  65.5  67.0 ms
  prefill   -     -     -     -     +1.2  +2.9  +4.9 s longer with dense attention

QSA is 1 to 1.2 ms slower up to 16K (the indexer), equal at 32K, and faster from there on, and the draft
accepts more with dense attention at 1K.

Add llama_context_params::mtp_qsa and --spec-draft-qsa {auto,on,off} (LLAMA_ARG_SPEC_DRAFT_QSA) for such a
block, replacing the LLAMA_MTP_QSA experiment. auto (the default) attends densely while the cache holds fewer
than 40960 cells and through QSA from there on, a little above the break-even. A block that the GGUF stores
with QSA (the self-contained file) is unchanged by every setting.

Switching in the middle of a request needs the indexer state of the whole context: the indexer keys of every
cell and the pooled keys of the completed blocks. So with auto (and on) the draft memory keeps the indexer
cache and every draft decode, dense or not, writes the keys and re-pools the blocks it completes; only the
selection (the pooled key gather, the lightning indexer, the top-k and the sparse attention) is left out of a
dense step. That costs about 1 ms per round (1.6%) on a short context, with identical output, and nothing on
a context whose cache can never reach the length (n_ctx per sequence below 40960 behaves as off and keeps no
state). The k-pool input of a dense step is the light one, without the four pool inputs nothing reads: such
inputs without a consumer corrupted the draft decode at about 4.8K positions.

A request that crosses the length, in the prefill or in the generation, gives the same tokens and the same
draft acceptance as always-QSA (4096 prompt, switch in the prefill: identical 512 tokens, 297/426 drafts;
49152 prompt: identical 256 tokens, 148/213 drafts). On a 64K context the shared head with auto is 3% to 7%
faster per round than with dense attention (sweep, and matched text over 200 tokens).

Co-authored-by: Cursor <cursoragent@cursor.com>
A verify batch only stashes the target hidden rows. The next draft step decodes the accepted rows and the new token together, with logits on the last row, so the draft weights are read once.

Co-authored-by: Cursor <cursoragent@cursor.com>
Adds a 64x64 shared-memory transpose for F32 dim-0 CONCAT with a contiguous prefix and a transposed second input on RDNA3.5.
2. SCALE + SILU fusion
3. Short-row CONCAT: one thread per element
4. ADD + UNARY + MUL fusion
5. Shared expert gate multiply-add fusion
6. Up to 1024 threads for small f32 matmuls
…and the narrow q8_0 down

Co-authored-by: Cursor <cursoragent@cursor.com>
…q8_0 down

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
…the subgraph was closed; it did not explicitly validate these two data edges. This commit adds an edge check to ensure the subgraph follows the structure: sigmoid → mul → add.
@amd-genmingz

amd-genmingz commented Dec 2, 2026 •

Copy link
Copy Markdown

Test data is based on 1K input and 2K output using an MTP model; testing begins once the temperature has cooldown to 60°C, and the reported figures represent the average of three separate runs.

41f7e08257 - Batch scheduler user-input copies
Problem: A split contains many small user inputs. The old path synchronized and copied every input separately, so API and synchronization overhead accumulated.

Solution: Synchronize once before the first copy, group inputs by destination buffer, and submit them through set_tensor_n. Backends without the hook fall back to the single-tensor copy path.

Expected gain: Fewer per-input synchronizations and copy calls. Existing A/B data shows 40.82 -> 41.24 TPS, about +1.0%. Scheduler-level tests are still needed for grouping, fallback, and host-buffer lifetime.

1865469b38 - SCALE + SILU fusion
Problem: The graph launched separate SCALE and SILU kernels, writing and reading an intermediate tensor from global memory.

Solution: Use one F32 kernel to compute silu(scale * x + bias), removing the separate intermediate read and write.

Expected gain: One fewer kernel launch and one fewer global-memory round trip. The measured result is 41.60 -> 41.81 TPS, about +0.5%; the number is close to run-to-run variation, but the implementation is low risk.

a24d1d71b3 - Short-row non-contiguous CONCAT
Problem: The old kernel assigned one block to each row, while target rows had only 7 or 13 elements. Most of the 256 threads were idle.

Solution: Flatten the output and use a grid-stride loop so threads process elements across rows. Use the actual tensor strides to address non-contiguous inputs.

Expected gain: [7,10240] improves from about 23.8 to 5.4 us, and [13,10240] from 23.9 to 8.7 us. End-to-end gain is about +1.6%.

a1d3b5a29d - ADD + UNARY + MUL fusion
Problem: The delta-net gate used three small kernels for ADD, UNARY, and MUL, with intermediate global-memory traffic.

Solution: Load one bias and one scale per row, then compute op(x + bias) * scale in one kernel. SILU, SIGMOID, and SOFTPLUS are supported.

Expected gain: Fewer kernel groups and less intermediate traffic. Verify TPS improves from about 41.65 to 42.24, about +1.4%, with roughly 70 fewer kernel groups.

6c2ee26a86 - Shared-expert gate fusion
Problem: The shared-expert sigmoid, MUL, and ADD ran as separate kernels, and the MUL intermediate was written to global memory.

Solution: Keep sigmoid as a separate kernel, then compute residual + x * sigmoid(gate) in one kernel. The current branch also explicitly checks that MUL reads sigmoid and ADD reads MUL.

Expected gain: Remove one MUL kernel and intermediate traffic, reducing the gate chain's kernel groups. No independent end-to-end TPS number was reported; the gain depends on graph matching.

ebaa1e5657 - Up to 1024 threads for small F32 matvecs
Problem: Small F32 projections such as HC inject launch only 1 to 4 blocks, fewer than the GPU's SM count, making the K loop latency-bound.

Solution: On RDNA3.5, for one output column and fewer blocks than SMs, allow 512 or 1024 threads per block to shorten the K loop.

Expected gain: HC inject improves from about 7.8 to 4.0 us, called about 96 times per token; the shared-gate input improves from 3.1 to 2.8 us. End-to-end A/B is faster in all 3 pairs: 27.09 -> 27.18 TPS, about +0.3%. A wider 4x-SM threshold slowed the 48-row alpha/beta case, so the final threshold was tightened.

00c43fe984 - RDNA3.5 transposed dim-0 CONCAT
Problem: The transposed src1 made neighboring threads read addresses separated by a full row, preventing coalesced memory access.

Solution: Use a 64x64 shared-memory tile, read src1 contiguously along channels, transpose in shared memory, write dst contiguously along tokens, and copy the short prefix in the same kernel.

Expected gain: The target shape improves from about 3917.38 to 2324.37 us, about +40.7%, with effective bandwidth rising from 40.06 to 67.52 GB/s.

… F32 WMMA rows

graph_compute moved the inject matmul after gallocr, so a tensor still in use could be overwritten. Rows outside the f16 window are scaled by a power of two, and the QSA compress-ratio check is restored except for a dense MTP block.

Co-authored-by: Cursor <cursoragent@cursor.com>
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