Repository navigation
metal : banded flash attention for Inkling 2 (carries #404), decode kernels, quantized and mixed K/V caches - #431
Open
danielhanchen wants to merge 275 commits into
Open
danielhanchen wants to merge 275 commits into
danielhanchen wants to merge 275 commits into
Conversation
…C_F32_PEDANTIC Every caller of the deprecated ggml_mul_mat_set_prec / ggml_flash_attn_ext_set_prec now uses ggml_prec_set_acc (the macOS prebuilt leg builds with LLAMA_FATAL_WARNINGS, so the deprecation would be fatal there), and ggml_prec_set_acc accepts GGML_OP_FLASH_ATTN_EXT_BANDED. With the enum ranked, the CUDA cuBLAS compute-type gate and the CPU, spacemit and Vulkan flash-attention accumulator checks compare by rank instead of equality with GGML_PREC_F32, so a pedantic request never falls through to a lower-precision path. The CUDA mul_mat_id slice carries the acc and src precision slots, and ggml_cuda_mul_mat_id_needs_sync applies the same pedantic gate as ggml_cuda_mul_mat_id so a pedantic F32 expert matmul cannot trip its assertion.
…own lines Inkling shared its n_embd_r() check, the FALCON_H1 hybrid-memory branch and the kv-cache context declaration with the line any new hybrid architecture also edits, so every such PR (Inkling 2 in ggml-org#32217 among them) conflicts with this one. Move each into its own block; behaviour is unchanged (RWKV never sets n_embd_r_impl, and the Inkling branch is the FALCON_H1 body).
Upstream ggml-org#31617 enabled HIP's native warp sync builtins, which require a 64-bit lane mask, so the raw __shfl_sync(0xffffffff, ...) no longer compiles for ROCm. ggml_cuda_shfl passes GGML_CUDA_FULL_THREAD_MASK (0xffffffff on CUDA, 64-bit on HIP); CUDA codegen is unchanged.
Inkling 2 builds a dense relative-position bias of n_kv x n_ubatch x n_head elements per attention layer and adds it to the KQ mask. For Inkling-2-Small (48 heads) that passes 2^32 elements from about 175K tokens of context at the default ubatch of 512 (44K at -ub 2048), and the add aborts with GGML_ASSERT(s2 <= UINT32_MAX). The compute buffer also grows with it. When the bias of one call would exceed 2^29 elements for a full cache, attend in equal chunks of query rows (whole 64-row tiles, at most 64 chunks) and concatenate the outputs. The first chunk stores K and V, the distances and the F32 mask are copied to the device once per graph and each chunk views its rows. Below the budget the graph is unchanged.
With flash attention on and a position-contiguous cache, Inkling 2 now passes the relative logits inside the extent to ggml_flash_attn_ext_banded and the sink logit as per-query sinks, instead of building a dense per-head mask of n_kv x n_ubatch x n_head elements. Other caches, quantized K/V, devices without the op and ubatches of up to 32 tokens keep the chunked dense path. The rel-pos input refuses graph reuse when the banded cell count changes. ggml: FLASH_ATTN_EXT_BANDED takes per-query sinks [n_head, n_q, n_seq] on CPU and CUDA, with a split-KV decode kernel and a tensor-core prefill kernel on CUDA. test-backend-ops covers the sinks and Inkling-2-Small shapes.
…in the graph The attention residual mix rebuilt a concat chain of every earlier block, RMS-normalized all of them and copied the transposed states on every call. Normalize each block once per graph, keep its stacks (rows and transposed), and reuse the stacked rows of a mix over the same blocks and input (the loop messages of one pass share them across the core layers). The values and their order are unchanged. Also, without changing any arithmetic: - one-token graphs use the mix query directly instead of a repeat - the clip threshold tensor is filled once per device and shape - a SWA layer takes its single mixed input without a copy and normalizes it once for the loop controllers; the messages are normalized once per layer and read through views - the dynamic convolution taps read one channel-major copy of the inputs instead of one transposed copy per lag
q8_0 / q4_0 K/V were not accepted by the banded kernel, so Inkling 2 fell back to the dense relative bias (n_kv x n_tokens x n_head F32) for every quantized cache and reserved far more compute memory than the cache saves. The MMA kernel now dequantizes q8_0 / q4_0 tiles into shared memory; other quantized types and the scalar kernels use an F16 copy of K/V. GGML_CUDA_BANDED_NO_QUANT_TILES=1 forces the F16 copy. The banded op no longer reserves the F16 K/V extra of the regular FA kernels unless it delegates to them, which also drops a cache-sized compute buffer for BF16 K/V.
A quantized K cache (-ctk q8_0 / q4_0) never took the banded attention, so every ubatch built the dense relative bias (n_kv x n_tokens x n_head) and used far more compute memory than the smaller cache saves. The banded op now accepts quantized K/V where the layer's device supports it (probed per device, F16/BF16/F32 caches are unchanged); on CUDA the delegated FA kernel reads them.
Each banded layer took its own view of the n_kv x n_tokens mask, and the scheduler copied every view as a separate split input, so the compute buffer held one mask copy per full-attention layer (2 GB at 256K, 8 GB at 1M with -ub 512). The contiguous banded mask is now built once per graph and cache.
Each banded layer took its own view of the n_kv x n_tokens mask, and the scheduler copied every view as a separate split input, so the compute buffer held one mask copy per layer. The contiguous banded mask is now built once per graph and cache.
With several slots in a unified cache only the sequence starting at cell 0 took the banded attention; every other slot fell back to the dense relative bias. A sequence held in one run of cells c0 + pos is now banded too: the cells before c0 belong to other sequences and are masked, and the relative distances are unchanged cell differences.
Assisted-by: Claude Opus 5.5
…_BANDED The banded op never runs the vec kernel and supports_op refuses quantized K/V, so neither the per-workgroup reduce buffer nor the F16 copy of K and V is ever used. The F16 copy alone is 4 bytes per cell, KV head and head dim of compute buffer.
danielhanchen
added a commit
that referenced
this pull request
Dec 3, 2026
…#32989) * hexagon: CONV_2D/3D Cin chunking and cost-based tile solver - stage input channels in chunks - stage per (channel, kd) channel stride > 24-bit 2D DMA stride limit - split weight packing into work items - replace first-fit tile selection with a solver - use fastdiv for the dilation division in the per-channel stage path * hexagon: conv-2d/3d rebase and fixes (guards for corner cases, etc) * hexagon: add mixed f16/f32 inputs, improve spad allocation and cleanup kparams * hexagon: conv-2d remove replace all divs and further cleanup kparams --------- Co-authored-by: Max Krasnyansky <maxk@qti.qualcomm.com>
* ggml : bump version to 1.2.0 * authors : update
[no ci]
* llama.cpp : bump version to 1.1.1 * authors : update
Assisted-by: OpenAI Codex Assisted-by: Claude Opus 5.5
* cuda : batch contiguous concat slices in one launch * add concat test case
…org#33608) * metal : accumulate the bf16 flash attention O in bfloat The bf16 prefill kernel kept the O accumulator in half while Q/K/V are bfloat, which mixed the accumulator type with the operands. Accumulate in bfloat and rescale the O matrix in float, since Metal does not allow bfloat4 *= float. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : fix flash attention kv_rows with partial K/V chunks The kv_rows path assumed the row lists are padded to the kernel chunk (256/64/32) and asserted it, so a partial last chunk was mishandled: - the pad kernel copied cache columns instead of the gathered rows, and the pad buffer was sized/indexed per cache stream (ne13) instead of per q slice (ne03), so slices >= 1 read the wrong region - the vec path did not gather the partial chunk through the row list and read V at the wrong pad offset, dropping the last chunk - direct row reads applied the cache stream stride to a shared cache Gather the partial chunk through the row list, size the pad per slice, and zero the stream stride for direct row reads. Also allow BF16 K/V with kv_rows: the non-vec gather converts to F16 and the tensor path uses the f16 kernel over the gathered rows. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : use bfloat shared memory for the bf16 vec FA kernels The bf16 vec instantiations used the half shared-memory type set, so K/V were converted bfloat->half on load. Add FA_TYPES_BF with bfloat Q/K/V in shared memory so the vec kernels read bfloat directly through the direct K/V path, and convert Q from f32 to bfloat as the prefill bf16 kernel does. Add the tuned _q%d_ne%d bf16 variants to match the f16/quantized sets, since the fa_vec tuning selects them, and use a float4 broadcast for the zero-fill casts that bfloat4 does not accept. Add bf16 to the FA vec slice test types to cover the new path. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : gather the kv_rows K/V in their own type The non-vec kv_rows path always gathered the referenced rows into an F16 buffer, so a BF16 cache was converted to F16 and the attention ran the f16 kernels. Replace the use_kv_f16 flag with the type of the buffer that the attention reads: quantized K/V is still dequantized to F16, but the cache type is otherwise kept, so BF16 stays BF16 through the gather and the partial-chunk pad. The gather kernel is now same-type (template on T, no cast), the gather and pad sizes/strides use ggml_type_size(kv_type), and the tensor, half8x8 and vec pipeline selectors take kv_type instead of the boolean. Add BF16 gather tests for the half8x8 path with and without the pad. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : use clearer names for the FA kernel paths Replace the historical half8x8/half4x4 labels with the 8x8 simdgroup kernel and the vec kernel, matching the actual kernel families. Comment only, no functional change. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : trim redundant flash attention comments Update the kv_rows support check that still claimed a contiguous F16 copy with BF16 converted to F16, drop the duplicated kv_type, pad-per-slice, dense-op and column-order explanations, and keep only the comments that explain non-obvious behavior. Comment only, no functional change. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : simplify the flash attention K/V type helpers Make kv_type the single source of truth for the type the flash attention kernels read, and derive dequant_kv from it (quantized cache and kv_type F16). Remove use_kv_f16 - its heuristic moves into kv_type - and use kv_type in the tensor path check and the is_q flag. This also enables the tensor path for a quantized rows gather whose shape fills the GPU. Remove the stale commented-out use_kv_f16/use_vec lines as well. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
…tch or n_ubatch (ggml-org#30523) * llama : return an error instead of aborting when a batch exceeds n_batch or n_ubatch llama_decode documents -1 for an invalid batch, but a batch larger than n_batch (or n_ubatch for non-causal) hit a GGML_ASSERT and aborted the process. A causal context caps n_batch at n_ctx, so a caller that asks for n_batch > n_ctx and submits a full batch crashes. This was found in an application that embeds llama.cpp, where a small context made an audio/image prompt abort the app instead of failing the call. Return -1 with an error message instead, before any state is touched, and add the batch_big case to test-llama-context: it submits n_max + 1 tokens, expects an error and an empty memory, then decodes n_max tokens. * llama : drop the batch_big test and shorten the n_batch error message (review)
…ggml-org#33328) * ui: file a conversation away with Archive, from its menus and in bulk The "more actions" dropdown and the right-click menu of a conversation gain Archive, next to Pin. A filed-away chat leaves the sidebar's sections - Pinned, the groups and Ungrouped - and rests out of them; the search dialog is where it is found, behind a "Show N archived" toggle under the chats a query matched, its own Archived group among the results. The bulk selection bar gains the same action for a whole selection: Archive over any selection with a chat left in it, Restore once every selected chat rests in the archive. Archiving keeps a chat's pin and group, so restoring puts it back where it was, and a move that gives it a home elsewhere - a pin, a group, a drop on Pinned or on Recent - brings it back too, so such an action on a filed-away chat never reads as doing nothing. Assisted-by: Claude * ui: fix archive selection, restore path and fork families Select all, the selection count and shift or marquee ranges only take the chats the sidebar shows, and archiving drops what left the sidebar from the selection, so a bulk delete never reaches a hidden chat. Writing in an archived chat brings it back, which gives it a way back when conversation tabs are off, the default and the only option on a phone. The bulk Restore path, which no selection could reach, is gone. Archiving and restoring take the whole fork family, like moving into a group, and an archived chat no longer shows twice in search. * ui: count the whole fork family in the archive toast The bulk write takes the family, so the toast reports the family's size rather than the clicked selection, which a single chat with forks would otherwise report as one conversation while several leave the sidebar. Assisted-by: Claude --------- Co-authored-by: Pascal <admin@serveurperso.com>
…#33686) Repos shipping a bare Q4_K quant next to Q8_0 fell through to Q8_0 by default, since only Q4_K_M and Q8_0 were in the preference list. Try Q4_K between the two; the tag still matches as a full token, so Q4_K never picks a Q4_K_M file and vice versa. Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)
Signed-off-by: Aaron Teo <aaron.teo1@ibm.com>
…gml-org#33677) * convert: fix GPT-2 and StableLM conversion after generator migration * convert : drop the regression test * tests : drop the removed conversion test
…3652) * ggml-openvino : add Q2_0 and Bonsai 2 support * openvino: enable text inference for Nemotron Lightning and LFM3 Assisted-by: Codex * openvino: enable NPU host gather by default * docs : host gather is on by default * openvino: compute ELU with an accurate expm1 * ggml-openvino: compute NPU RoPE cos/sin on the host for long contexts Assisted-by: Claude Opus 5.5 * openvino: review fixes for the NPU RoPE table * openvino: replace the RoPE flags with GGML_OPENVINO_ROPE_SINCOS * docs : reorganize OpenVINO docs and add a cookbook * openvino: preserve token dimensions in Gemma 3n reductions Assisted-by: Codex * openvino: keep the compiled-model cache revision at 14 Assisted-by: Codex * openvino: reject sequence-major SSM_SCAN inputs * ggml-openvino : drop code that the ggml core does not need * openvino: add GGML_OPENVINO_SPILL_RESIDENT to cap the spilled weights kept in RAM Assisted-by: Claude Opus 5.5 * openvino: review fixes for GGML_OPENVINO_SPILL_RESIDENT * openvino: take GGML_OPENVINO_SPILL_RESIDENT as a fraction * openvino: add GGML_OPENVINO_SPILL and simplify the spill limiter * openvino: add GGML_OPENVINO_COMPILE_MEM_SPILL * openvino: clang-format fixes * openvino: unwrap comments and docs per AGENTS.md Assisted-by: Claude Code --------- Co-authored-by: Mustafa Cavus <mustafa.cavus@intel.com> Co-authored-by: Yu, Zijun <zijun.yu@intel.com> Co-authored-by: Xuejun <Xuejun.Zhai@intel.com> Co-authored-by: ravi9 <ravi.panchumarthy@intel.com> Co-authored-by: Anisha Kulkarni <anisha.dattatraya.kulkarni@intel.com>
…tor is bfloat Since the upstream bf16 K/V change the Metal flash attention kernel accumulates the bf16 O in bfloat, and two long bf16 banded cases (n_kv 4096, n_q 32 and 48) now land at ERR 5.9e-4 and 6.6e-4 on an M5 Max, just above the 5e-4 bound.
This branch has not been deployed
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.
Metal FLASH_ATTN_EXT_BANDED for Inkling 2, so the prebuilt can pin it. It carries #404 by @skeggsguy with its original commits and authors, and adds decode kernels, quantized and mixed K/V caches on top. All credit for the Metal banded kernels goes to @skeggsguy; #404 stays open as the original PR.
Why one pin and not a mirror of #404
#404 changes four lines that #378 adds to
tests/test-backend-ops.cpp(thetest_flash_attn_ext_bandedconstructor, itsvars()and the V tensor). A mirror of #404 with its commits unchanged would ship those rewrites, andpin_contractfails #378 in the merged tree (kept 76/80 of the lines this pin adds). A second pin on top that restores them would in turn rewrite the mirror's lines, which the pin model does not allow. So this PR carries #404's commits unchanged and folds the conflict in one commit of its own: the #378 lines stay exactly as #378 has them, and #404's extra test layouts move to a derivedtest_flash_attn_ext_banded_layout. Test case names are unchanged.Commits
From #404 (unchanged, authors as in the original):
58d6e4c5bmetal : add FLASH_ATTN_EXT_BANDED in both attention kernels (@skeggsguy)982dee7a2metal : do not reserve the vec and F16 K/V scratch for FLASH_ATTN_EXT_BANDED944cd7e55metal : bound the FA pad copy to the K/V row width11f7c569fMerge inkling2-attn-banded (6348de2) into metal-banded-pr1b64ef9d63metal : refuse FLASH_ATTN_EXT_BANDED when K and V have different head countsaa8d61c27metal : banded FA, require mask width == n_kv and the row layouts the kernels load675186062,6807804e0comment-only081c9bbe4metal : fix supports_op so the following don't crash for banded flash attention (@skeggsguy)New here:
777ed55f4Merge metal : add FLASH_ATTN_EXT_BANDED in both attention kernels #404 (081c9bb)c56bf5770metal : banded FA in the vec kernels, quantized K/V and BF16 rel tables235fc5071metal : mixed K/V cache types in the FA and banded FA kernels540ca0a7etests : keep the banded test constructors as model : Inkling 1 (ggml-org#25731) on b12533 for the prebuilt #378 has them, layout cases in a derived structf90e56765metal : refuse banded attention with K/V cell and query positions6600e1f7cMerge model : banded flash attention for the Inkling 2 relative bias #386 (ded02bd). One conflict,fa_common.metalFWD_TMPL/FWD_ARGS: upstream ggml-org#32677 (in model : banded flash attention for the Inkling 2 relative bias #386 through its merge of upstream239242322) derives the matrix types from the scalar ones. Kept upstream'sFWD_TMPLand added only this branch'srelargument toFWD_ARGS. Without this merge the pin did not merge on b12674.Base:
inkling2-attn-banded(#386), the same base as #404. The branch is stacked on #386 at its pinned headded02bdeb, so the diff here is only this PR's change: 17 files, +834/-120, all underggml/src/ggml-metal/plustests/test-backend-ops.cpp. No CPU, CUDA or model code changes.What it does
-ctk q8_0 -ctv q4_0,-ctk q8_0 -ctv f16and so on) in the plain and banded FA kernels. On the current pins Metal refuses those and they run on the CPU.supports_oprefuses the K/V cell and query positions (src[7],src[8]) that model : banded flash attention for the Inkling 2 relative bias #386's next head (fd9663478) adds for several sequences and a wrapped SWA cache. The kernels take the distance from the cell index, so the model takes the dense path for those ubatches instead of a wrong band.Evidence
Pin set (local,
llama_pinset.py simmerge loop +pin_contract+merge_checks, thenverify --cuda):ded02bdebpin_contract45/45,merge_checkscleanverify --cudaon this set is running; results will be added here. With #386 atfd9663478the merge is refused, but that is #386 against #378 (ggml-backend-meta.cpp), the same refusal without this PR, and is being fixed in #386.GitHub
macos-15runner (Apple M1, virtual), on235fc5071, before the test fold and before the #386 merge. The runner GPU reports MTLGPUFamilyApple5, so a CI-only, env-gated hook turns on simdgroup matrix and bfloat for the run (never committed):test-backend-ops -o FLASH_ATTN_EXT_BANDED -b MTL0: 147/147 OK, 0 FAIL, 14 refused by design (BF16 K/V or rel tables without bfloat on the runner, V with other heads or length than K, a mask wider than K, 65536 queries).test-backend-ops -o FLASH_ATTN_EXT -b MTL0: 5157/5157 OK. The base pins pass 5126/5126; the 31 new cases are the mixed K/V pairs, which the base refuses.llama-perplexity -c 256 -fa on, 10 K/V settings incl. mixed): KLD against the base pins at the floor (mean 0.000000), per-type KLD against F16 equal to the base pins.-c 32768 -ub 512, mixed q8_0/q4_0: 854 MiB on the base pins, 160 MiB here.From #404 on real hardware (@skeggsguy, Mac mini M5 Pro 64 GB, Inkling-2-Mini UD-Q8_K_XL, F16 KV): prompt processing 1.21x at depth 4096 and 2.12x at depth 32768; Metal compute buffer at
-c 2000009291 MiB to 2664 MiB.Memory
Before this PR, Inkling 2 on Metal took the dense path: a full F16 relative-bias mask per head, and for quantized K/V caches an F16 copy of the cache reserved by the op. Both are gone on the banded path, and quantized and mixed K/V caches are dequantized inline instead of copied.
-c 32768 -ub 512, q8_0 K / q4_0 V, Metal compute buffer (macOS CI)-c 200000, Metal compute buffer (Mac mini M5 Pro)The KV cache itself is unchanged, so a q8_0 or q4_0 cache now keeps its smaller size on Metal end to end, and mixed K/V settings such as
-ctk q8_0 -ctv q4_0stay on the GPU instead of running attention on the CPU.Speed (macOS CI)
GitHub
macos-15runner (Apple M1, virtual), tiny Inkling 2 (random weights, head size 128),llama-bench, this PR's pins against the same pins without it (headf44881ab6, base b12675). Report-only, 2 rounds, medians:pp512depth 0pp512depth 4096tg128depth 0tg128depth 4096pp512depth 0pp512depth 4096tg128depth 0tg128depth 4096pp512depth 0pp512depth 4096tg128depth 0tg128depth 4096Mixed K/V types ran on the CPU before this PR, which is where the largest gains come from. The gated check, plain
FLASH_ATTN_EXTdecode at 4K/16K/64K for f16 and q8_0 over 7 interleaved rounds, passes: head over base 0.98 to 1.06, inside the base A/A spread. The same run passedFLASH_ATTN_EXT_BANDED303/303, mixed K/V 45/45 andFLASH_ATTN_EXT5543/5543 onmacos-15andmacos-26, and the tiny-model KLD against the CPU is about 1e-6 for every K/V setting.Earlier field measurement on a Mac mini M5 Pro (Inkling-2-Mini UD-Q8_K_XL, F16 KV) with the banded prefill kernels: prompt processing 1.21x at depth 4096 and 2.12x at depth 32768; Metal compute buffer at
-c 2000009291 MiB -> 2664 MiB.Not tested
6600e1f7c, upstream ggml-org#32677 derived types) have not been compiled on macOS yet; the macOS numbers above are from235fc5071. A macOS staging run on this head is pending.Lifetime
This pin is dropped once the work lands upstream (with Inkling 2 support in ggml-org) and the aged base tag the nightly picks contains it.