Repository navigation
metal : dequant kv cache only for large batches - #27438
Merged
Merged
Conversation
forforever73
approved these changes
Aug 20, 2026
therealkenc
pushed a commit
to therealkenc/llama.cpp
that referenced
this pull request
Aug 24, 2026
thecodacus
pushed a commit
to thecodacus/llama.cpp
that referenced
this pull request
Sep 7, 2026
zbrad
pushed a commit
to zbrad/llama.cpp
that referenced
this pull request
Sep 10, 2026
tarruda
added a commit
to tarruda/llama.cpp
that referenced
this pull request
Sep 12, 2026
DeepSeek-V4 packed sparse prefill reserves two large Metal flash-attention scratch buffers that its selected execution path never uses. At -ub 2048, these reservations total 5392 MiB (5.265625 GiB). Skip them only where the input layout or type makes them unnecessary, while retaining the conservative reservations needed by other attention paths. Partial attention results The vector attention path splits attention across 32 GPU workgroups. Each workgroup writes a partial weighted-value result and two softmax statistics (sum and maximum) into a global scratch buffer. A separate reduction kernel combines those partial results. The matrix attention kernel instead accumulates within a workgroup and writes the final result directly to the output; it does not use this global reduction buffer. Ordinary attention can switch from the matrix kernel to the vector kernel when the token batch shrinks. Reserving reduction scratch even for a large-batch graph avoids reallocations when a later graph uses the vector kernel. Keep that behavior for ordinary attention. DeepSeek-V4 packed sparse prefill is different: src/models/deepseek4.cpp reshapes queries to [512, 64, 1, nt] and sets the row-sinks flag. The 64 attention heads become query rows, while the actual token count is in the fourth dimension. Metal selects the ordinary vector kernel only when the query-row count is below 20 and the head dimension is divisible by 32. These query rows stay at 64 when nt shrinks, so this packed layout stays on the matrix kernel. A later graph using another attention layout retains its own scratch reservation. In ggml_metal_op_flash_attn_ext_extra_tmp(), return zero only when row sinks are enabled, the ordinary vector kernel is not selected, and ggml_metal_op_flash_attn_ext_n_kv_max_sparse() returns zero. The last condition preserves scratch for the separate Metal sparse-vector path, which must not be confused with the model's packed sparse prefill path. The old reduction reservation was sizeof(float) * min(query_rows, 32) * query_heads * query_batches * 32 * (value_head_size + 2). For [512, 64, 1, 2048], this is 4 * 32 * 1 * 2048 * 32 * 514 = 4112 MiB (4.015625 GiB), although the selected matrix kernel never accesses it. F16 KV conversion The second buffer holds an F16 copy of quantized keys and values before attention. Metal only dispatches that conversion for supported quantized input types and sufficiently large query-row counts. F16, F32, and BF16 inputs do not take the conversion path. DeepSeek-V4's sparse pack operation already produces F16 keys and values, even when the underlying cache is quantized. Attention consumes the packed data directly, and values share the same view as keys. An additional F16 conversion buffer is therefore unused. At nt = 2048, 640 selected KV rows and a head dimension of 512 reserve another 2 * 512 * 640 * 2048 = 1280 MiB (1.25 GiB). In ggml_metal_op_flash_attn_ext_extra_kv_f16(), return zero for non-quantized keys. Keep the existing reservation for quantized inputs, including graphs whose current query-row count is too small to enable conversion, because a different batch size can enable it later. Scope and origin This changes allocation sizes, not attention arithmetic or kernel selection. Actual packed KV data, masks, outputs, and kernel register/threadgroup working memory remain necessary and allocated. It does not remove all memory growth from increasing -ub. Both unconditional reservation policies were already present on master when investigated. The unconditional reduction reservation came from 2606b0a (PR ggml-org#17143); the unconditional F16 conversion reservation came from 63b64a5 (PR ggml-org#27438). This branch's packed sparse prefill layout, introduced in 09174b0522, amplifies their cost. Master did not have that packed model path, so the same reservation policy there does not imply the same 5.27 GiB waste. Validation On an M1 Ultra with DeepSeek-V4-Flash-Vision-Exp-IQ3_XXS, -fa 1 -b 2048 -ub 2048 -p 2048, compute-buffer usage at depth 10000 fell from 7977.10 MiB to 2585.10 MiB (7.79 GiB to 2.52 GiB). At depth 20000 it fell from 7997.10 MiB to 2605.10 MiB. Prompt processing stayed approximately unchanged: 247.50 vs 246.91 tokens/s at depth 10000 and 239.17 vs 239.50 at depth 20000. Decode also completed at depths 0, 10000, and 20000, with no increase over the reserved compute-buffer sizes. The existing row-sinks test now exercises multiple packed query tokens with shared K/V. CPU-reference comparisons passed for 19 selected row-sinks/sparse attention cases, 16 selected float/quantized attention cases, and 240 vector attention variants. The relevant build targets passed. GGML_SCHED_DEBUG_REALLOC=1 aborts on the same graph with both the original and modified Metal libraries; this strict-check failure predates the change. Full-model logits were not bit-identical. With the original Metal library and the same 3506-token prompt, comparing -ub 512 and 2048 gave an RMSE of 0.772 and a maximum absolute difference of 3.239 over 129280 final logits. Even two original -ub 2048 runs differed (RMSE 0.358, maximum difference 1.682). All three selected the same highest-scoring token. The cause of same-size run differences was not isolated. The baseline is not bit-stable, so a failed exact comparison alone does not identify a regression; these measurements also do not independently establish numerical equivalence of the allocation change. Assisted-by: Codex
tarruda
added a commit
to tarruda/llama.cpp
that referenced
this pull request
Sep 23, 2026
DeepSeek-V4 packed sparse prefill reserves two large Metal flash-attention scratch buffers that its selected execution path never uses. At -ub 2048, these reservations total 5392 MiB (5.265625 GiB). Skip them only where the input layout or type makes them unnecessary, while retaining the conservative reservations needed by other attention paths. Partial attention results The vector attention path splits attention across 32 GPU workgroups. Each workgroup writes a partial weighted-value result and two softmax statistics (sum and maximum) into a global scratch buffer. A separate reduction kernel combines those partial results. The matrix attention kernel instead accumulates within a workgroup and writes the final result directly to the output; it does not use this global reduction buffer. Ordinary attention can switch from the matrix kernel to the vector kernel when the token batch shrinks. Reserving reduction scratch even for a large-batch graph avoids reallocations when a later graph uses the vector kernel. Keep that behavior for ordinary attention. DeepSeek-V4 packed sparse prefill is different: src/models/deepseek4.cpp reshapes queries to [512, 64, 1, nt] and sets the row-sinks flag. The 64 attention heads become query rows, while the actual token count is in the fourth dimension. Metal selects the ordinary vector kernel only when the query-row count is below 20 and the head dimension is divisible by 32. These query rows stay at 64 when nt shrinks, so this packed layout stays on the matrix kernel. A later graph using another attention layout retains its own scratch reservation. In ggml_metal_op_flash_attn_ext_extra_tmp(), return zero only when row sinks are enabled, the ordinary vector kernel is not selected, and ggml_metal_op_flash_attn_ext_n_kv_max_sparse() returns zero. The last condition preserves scratch for the separate Metal sparse-vector path, which must not be confused with the model's packed sparse prefill path. The old reduction reservation was sizeof(float) * min(query_rows, 32) * query_heads * query_batches * 32 * (value_head_size + 2). For [512, 64, 1, 2048], this is 4 * 32 * 1 * 2048 * 32 * 514 = 4112 MiB (4.015625 GiB), although the selected matrix kernel never accesses it. F16 KV conversion The second buffer holds an F16 copy of quantized keys and values before attention. Metal only dispatches that conversion for supported quantized input types and sufficiently large query-row counts. F16, F32, and BF16 inputs do not take the conversion path. DeepSeek-V4's sparse pack operation already produces F16 keys and values, even when the underlying cache is quantized. Attention consumes the packed data directly, and values share the same view as keys. An additional F16 conversion buffer is therefore unused. At nt = 2048, 640 selected KV rows and a head dimension of 512 reserve another 2 * 512 * 640 * 2048 = 1280 MiB (1.25 GiB). In ggml_metal_op_flash_attn_ext_extra_kv_f16(), return zero for non-quantized keys. Keep the existing reservation for quantized inputs, including graphs whose current query-row count is too small to enable conversion, because a different batch size can enable it later. Scope and origin This changes allocation sizes, not attention arithmetic or kernel selection. Actual packed KV data, masks, outputs, and kernel register/threadgroup working memory remain necessary and allocated. It does not remove all memory growth from increasing -ub. Both unconditional reservation policies were already present on master when investigated. The unconditional reduction reservation came from 2606b0a (PR ggml-org#17143); the unconditional F16 conversion reservation came from 63b64a5 (PR ggml-org#27438). This branch's packed sparse prefill layout, introduced in 09174b0522, amplifies their cost. Master did not have that packed model path, so the same reservation policy there does not imply the same 5.27 GiB waste. Validation On an M1 Ultra with DeepSeek-V4-Flash-Vision-Exp-IQ3_XXS, -fa 1 -b 2048 -ub 2048 -p 2048, compute-buffer usage at depth 10000 fell from 7977.10 MiB to 2585.10 MiB (7.79 GiB to 2.52 GiB). At depth 20000 it fell from 7997.10 MiB to 2605.10 MiB. Prompt processing stayed approximately unchanged: 247.50 vs 246.91 tokens/s at depth 10000 and 239.17 vs 239.50 at depth 20000. Decode also completed at depths 0, 10000, and 20000, with no increase over the reserved compute-buffer sizes. The existing row-sinks test now exercises multiple packed query tokens with shared K/V. CPU-reference comparisons passed for 19 selected row-sinks/sparse attention cases, 16 selected float/quantized attention cases, and 240 vector attention variants. The relevant build targets passed. GGML_SCHED_DEBUG_REALLOC=1 aborts on the same graph with both the original and modified Metal libraries; this strict-check failure predates the change. Full-model logits were not bit-identical. With the original Metal library and the same 3506-token prompt, comparing -ub 512 and 2048 gave an RMSE of 0.772 and a maximum absolute difference of 3.239 over 129280 final logits. Even two original -ub 2048 runs differed (RMSE 0.358, maximum difference 1.682). All three selected the same highest-scoring token. The cause of same-size run differences was not isolated. The baseline is not bit-stable, so a failed exact comparison alone does not identify a regression; these measurements also do not independently establish numerical equivalence of the allocation change. Assisted-by: Codex
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.
Overview
cont #27390
See #27390 (comment) for more info.
Requirements