Skip to content

model : banded flash attention for the Inkling 2 relative bias - #386

Open
danielhanchen wants to merge 165 commits into
base/upstream-0df40737cfrom
inkling2-attn-banded
Open

danielhanchen wants to merge 165 commits into
base/upstream-0df40737cfrom
inkling2-attn-banded

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

Banded flash attention for the relative bias, on top of #378 (GGML_OP_FLASH_ATTN_EXT_BANDED) and #385 (chunked relative-bias attention). The base is the upstream commit #378 uses, so the diff also shows #378 and #385 at their pinned commits. In the pin set this goes after both of them.

Speed

All against upstream Inkling 2 (dense relative-bias attention), same build otherwise.

Long-context prefill, pp2048 at -ub 512 on an Inkling-2-Small-shaped test model (shared card, so read as relative):

depth before with this PR speedup
0 4,692 t/s 11,081 t/s 2.4x
32K 1,855 t/s 3,490 t/s 1.9x
98K 694 t/s 4,073 t/s 5.9x
256K 282 t/s 2,057 t/s 7.3x

Inkling-2-Mini on smaller cards, where the smaller compute buffer changes what fits:

card / setting before with this PR
T4 16 GB, UD-IQ3_XXS, 128K context, q8_0 KV: compute buffer 1,282 MiB (3 layers left on the host) 349 MiB (whole model on the GPU)
same, decode 24.8 t/s 28.1 t/s (+13%)
same, prompt 361 t/s 468 t/s (+30%)
pp512 at 32K depth +18% on T4, +31% on L4
1M context, 4 slots: compute buffer 52,841 MiB 4,999 MiB

On B200 the tensor-core banded prefill kernel runs pp512 at 32K depth at about 22K t/s against about 5.8K t/s dense (3.8x). Upstream also aborts on long prompts (GGML_ASSERT(s2 <= UINT32_MAX), from about 44K tokens at -ub 2048); with this PR they complete.

Newer commits on this branch (not in the current pin, they go in with the next base):

  • Quantized K/V prefill: the next K/V tile is loaded while the tensor-core products run. B200, Inkling-2-Mini UD-Q4_K_XL, pp512 at 32K depth, 4 interleaved rounds: q8_0 3,335 -> 3,711 t/s (+11.3%, A/A spread 0.09%), q4_0 3,390 -> 3,746 t/s (+10.5%), f16 unchanged. Output identical (PPL string-equal, mean KLD 0).
  • One sequence with a causal cache derives causality from the cell distance and builds no mask: compute buffer at 1M context, -ub 512, 1248 / 1039 MiB (GPU / pinned host) -> 224 / 15 MiB, and at -ub 2048 4987 / 4148 -> 891 / 52 MiB. PPL string-equal, mean KLD 0. LLAMA_INKLING_BANDED_CAUSAL=0 turns it off.

Single-token decode at short context stays on the regular path (banding it was about 30% slower), so decode only gains where memory changes what fits, as in the T4 case. Measured on CUDA (B200, T4, L4) and CPU; Metal is in a separate pin, ROCm and Vulkan were not timed.

Memory

Upstream builds the relative-position bias as a dense F32 tensor [n_kv x n_tokens x n_head] per attention layer and casts it to an F16 per-head mask (about 6 bytes per element live; for Inkling-2-Small at 98K context and -ub 2048 that is about 59 GB). The banded kernel computes the bias inside the band from the small relative tables, so none of that is allocated.

Compute buffer, Inkling-2-Mini (-fa on):

setting upstream (dense bias) with this PR
1M context, 4 slots (-kvu), -ub 512 21,654 MiB 1,251 MiB
1M context, 4 slots (-kvu), -ub 2048 52,841 MiB 4,999 MiB
32K context, 4 slots, L4 2,681 MiB 256 MiB
128K context, 1 slot, UD-IQ3_XXS, q8_0 KV (T4 and L4) 1,282 MiB 349 MiB

On a 16 GB T4 that is the difference between Inkling-2-Mini UD-IQ3_XXS at 128K context running fully on the GPU and leaving 3 layers on the host. The KV cache itself is unchanged; quantized K/V caches (q8_0, q4_0) keep their size and the compute buffer is the same for every KV type.

With the newer causal no-mask commit (next base), one sequence also drops the attention mask input, which was the largest remaining item at long context. UD-IQ3_XXS plus the F16 vision projector, q8_0 KV, 1 slot, compute buffer GPU / pinned host:

context, -ub before causal path
128K, 512 349 / 139 MiB 221 / 11 MiB
128K, 2048 1,399 / 561 MiB 887 / 49 MiB
1M, 512 1,248 / 1,039 MiB 224 / 15 MiB
1M, 2048 4,987 / 4,148 MiB 891 / 52 MiB

Worked out from those buffer sizes for a 16 GB card (UD-IQ3_XXS plus vision projector, q8_0 KV), the largest context that fits goes from about 192K to about 203K at -ub 512, and from about 132K to about 163K at -ub 2048. Several slots keep the mask, so their memory is unchanged. Compute at exit equals compute at load in every cell above (no growth at runtime).

Change

  • src/models/inkling2.cpp: when flash attention is on and the cache is position-contiguous (get_n_kv_pos_contiguous), the relative logits inside the extent go to ggml_flash_attn_ext_banded and the sink logit goes in as per-query sinks. No dense per-head mask is built. Everything else uses the chunked dense path: other cache layouts, quantized or scaled K/V, head sizes other than 64/128, devices that do not support the op, and ubatches of up to 32 tokens. Small ubatches stay dense so the graph can be reused while decoding.
  • src/llama-graph.cpp/.h: the rel-pos input refuses graph reuse when the banded cell count changes.
  • ggml, extending model : Inkling 1 (ggml-org#25731) on b12533 for the prebuilt #378's op:
    • ggml_flash_attn_ext_add_sinks accepts FLASH_ATTN_EXT_BANDED, with sinks [n_head] or per query [n_head, n_q, 1 or n_seq];
    • the CPU kernel reads per-query sinks;
    • CUDA gets per-query sinks, a split-KV decode kernel and a tensor-core prefill kernel that both handle sinks. model : Inkling 1 (ggml-org#25731) on b12533 for the prebuilt #378's existing MMA path, which passes rel in the sinks slot, is skipped when sinks are set.
  • test-backend-ops: banded cases with per-head and per-query sinks, plus Inkling-2-Small shapes (48/8 heads, extent 1024, decode, speculative and prefill rows).

Tests

  • test-llama-archs (CPU): 155/155.
  • test-backend-ops -o FLASH_ATTN_EXT_BANDED -b CPU: 53/53.
  • test-backend-ops CUDA0 vs CPU (B200, sm_100): FLASH_ATTN_EXT_BANDED 53/53, FLASH_ATTN_EXT 4430/4430, MUL_MAT_ID 1060/1060, GET_ROWS 228/228, CONCAT 221/221, CPY 285/285, SET_ROWS 179/179.
  • HIP compile (ggml-hip + llama, gfx90a and gfx1151): passes.
  • Inkling-2-Small UD-IQ1_S, wikitext-2 -c 512 --chunks 8, experts on CPU, -fa on, compared with plain b12549:
    • -b 512 (one sequence, banded path): PPL 3.6358 vs 3.6310, mean KLD 0.006934, same top token 96.96%. For comparison, b12549 itself at -b 2048 against -b 512 gives mean KLD 0.006184 and 97.40% same top token, so the change is within the batch-layout noise of the existing kernels.
    • -b 2048 (four sequences, dense fallback): PPL 3.622135, the same as b12549; mean KLD 0.000000, same top token 100%.
  • Long prompt, llama-perplexity -c 51200 -b 2048 -ub 2048 --chunks 1 -fa on on an Inkling-2-Small-shaped test model (48 heads, random weights): completes. b12549 aborts there with GGML_ASSERT(s2 <= UINT32_MAX).

Quantized K/V and a shared banded mask (15b7c1a)

  • 7db4a7064: the CUDA banded kernel dequantizes q8_0 / q4_0 K/V in-tile. Before, a quantized cache fell back to the dense relative-bias path and reserved an extra F16 copy of K/V, so q8_0 used more memory than F16. Inkling-2-Mini q8_0 peak at 256K: 14876 -> 13528 MiB after both changes; q8_0 prefill at 128K is 2.3x faster.
  • 493fc82c2: one banded mask per graph shared by every layer. Compute buffer at 256K: 2400 -> 560 MiB; at 1M: 9312 -> 2096 MiB.
  • 291a63e3d, 2f96ddbbb, 15b7c1ae4: --no-ff merges of the three model : Inkling 1 (ggml-org#25731) on b12533 for the prebuilt #378 commits this branch carries.
  • F16 output identical to before at -c 512 and -c 32768; q8_0 / q4_0 KLD unchanged. Cross-platform base vs head: HIP gfx1151 Linux and Windows, CPU, Vulkan lavapipe and Metal (macos-15), no regression.

Graph dedupe (0edf1d6)

It removes repeated work in the Inkling 2 graph; results are bit-identical:

  • normalized block stacks are shared per graph and device, so there is no concat chain, full re-norm or transposed copy per mix
  • mix rows are reused across one loop pass, and T=1 uses the query without a repeat
  • the clip threshold and the zero sinks of the dense attention are filled once per device
  • the SWA layer input is used without a copy and normalized once for the controllers
  • messages are normalized once and read by views
  • the dynamic conv taps come from one channel-major copy

It edits the lines this PR and #385 added to src/models/inkling2.cpp and src/models/models.h, so it belongs here and not in a separate pin.

Evidence (B200, one exclusive card, ABBA): on its own, +5 to +7% pp512/pp4096 and +8 to +10% tg128 on Inkling-2-Mini; decode 7328 -> 6653 kernels per token. test-llama-archs inkling2.* 6/6. llama-perplexity KLD against the pin set (UD-IQ1_S, UD-Q4_K_XL, Mainline_Support UD-IQ1_S, -ub 1 / -ub 4, -sm layer -ts 1,1): PPL string equal, mean KLD 0, top-1 100%.

Update: two more commits (fast-forward 6348de2 to 4fff29a)

  • graph : build the dense relative bias in F16 for flash attention. With flash attention the per-head relative bias was made contiguous in F32, the mask cast to F32, both added in F32 and the sum cast to F16. The bias is now converted to F16 in one copy and the F16 mask added. The mask is 0 or -inf, so the result is bit-identical, with two kernels fewer per dense attention layer.
  • inkling2 : expand the short convolution inputs and outputs in order. cur and the dynamic taps are expanded before the conv and the conv result right after it, so the chain from the concat to the scale is consecutive in the graph and a backend can fuse it (the CUDA short-convolution fusion pin needs this order). Only the node order changes.

Both are graph-only. With these two commits and every CUDA decode pin switched off by its kill switch, the stack is bit-identical to #399 (which has the previous #386 head) on B200, T4, L4, A100 and RTX PRO 6000: KLD at -c 512, -c 4096, -ub 4 and -ub 1, PPL string equal, mean KLD 0.

Update: the compute buffer now covers the dense relative-bias path

While testing #407 we found that Inkling 2 could grow its CUDA compute buffer far past the size reserved at load, which ends in an OOM in the middle of a generation. Two causes combined:

  1. The graph reserved at load took the banded path, but several runtime cases still build the dense bias: a ubatch of several sequences in a unified cache (-kvu), a single-sequence ubatch whose cells are not one run, ubatches of 32 tokens or less, and the SWA layers once the positions pass the SWA cache and it wraps.
  2. In the dense path the F16 bias was made with ggml_cpy into a tensor from ggml_new_tensor_4d. That tensor is a graph leaf, and the allocator keeps leaves for the whole graph, so the bias of every chunk and every dense layer stayed allocated at once and the chunking bounded nothing. The chunk outputs, kept until a final concatenation, also split the region the next chunk's bias reused.

On this branch (#385):

  • The chunk height is sized once per cache size, in whole 64-row tiles within the 2^29 element budget and at most 64 chunks per layer. It no longer gets smaller for a longer ubatch, so the graph reserved for a full cache and a full ubatch holds the largest chunk any later ubatch builds.
  • The chunks write their rows into one output allocated before them.

On #386 (same code merged, plus the banded reserve):

  • A ubatch of several sequences takes the dense path, so a context with several sequences reserves the dense graph.
  • The reserve graph also covers the dense cases one sequence still takes: the bias of 32 rows over the full cache, and the SWA layers when the SWA cache is smaller than the full one.
  • The F16 bias is a ggml_cast node instead of a copy into a leaf.

Results on a B200, Inkling-2-Mini UD-IQ1_S, CUDA0 compute buffer in MiB, reserved at load and largest at runtime. Each case prefills one sequence to 4352 tokens short of the context, then runs a ubatch split over two sequences (two-slot cases), a 32-token batch, a full ubatch and one token per sequence:

context, KV ubatch slots before: reserved / runtime after: reserved / runtime
131072, f16 128 1 197 / 1959 648 / 648
131072, f16 512 1 788 / 1959 963 / 963
131072, f16 2048 1 3151 / 13121 3795 / 3795
131072, f16 128 2, -kvu 197 / 7910 2469 / 2469
131072, f16 2048 2, -kvu 3151 / 121155 8273 / 8273
524288, q4_0 128 1 264 / 9061 4592 / 4592
524288, q4_0 512 1 1055 / 9061 5002 / 5002
524288, q4_0 2048 1 4225 / 15654 6669 / 6669
524288, q4_0 128 2, -kvu 494 / 32891 6181 / 6181
524288, q4_0 2048 2, -kvu 4273 / OOM (asked for 442828) 26705 / 26705

A single slot at Studio settings (f16 KV, -np 1) reserves a little more at load:

context -ub 512 -ub 2048
32768 792 -> 849 (+56) 3169 -> 3393 (+223)
131072 788 -> 963 (+175) 3151 -> 3795 (+643)

The ggml-org#32804 case (-c 172032 -kvu -npl 2 -npp 80000 -ub 2048) still completes. It reserved 3834 MiB and grew to 17285 MiB at runtime; it now reserves 10673 MiB and stays there.

Output is unchanged: wikitext-2 PPL strings are identical to the base at -c 512 and -c 4096, with one sequence per batch and with several in a unified cache, mean KLD 0.000000 and the same top-1 agreement as the base against itself. The logits of a ubatch split over two sequences are bit-identical to the base at 131072 (one chunk) and 524288 (two chunks). test-backend-ops -o FLASH_ATTN_EXT_BANDED passes 71/71 on CUDA0, and test-llama-archs passes for inkling2 and inkling2_loop.

The extra reserve nodes are added only to the graph built at load. Every runtime graph has the same node count as before (11035 per decode token at -ub 1, 10870 for a 512-token ubatch), and a counter on the reserve condition read 0 on every real ubatch: decode, 33 to 2048-token prefill, a ubatch over two sequences that share a position, and llama-server with two slots. llama-bench pp512 and tg128 are within noise of the base. Context shift and --cache-reuse are not available for this model (llama_memory_can_shift is false), so they cannot reach the dense path.

Update: few-token ubatches

This head adds two commits:

  • CUDA: the banded vec kernel splits its cells finer when there are only a few queries. Chunks can now be a single tile, with a target of 2 blocks per SM. A 3-token speculative verify spent 32 us per layer in it, against 13 us for decode. Prefill (512 queries) is unchanged.
  • Inkling 2: ubatches of 2 to 8 tokens take the dense attention with the indexed relative bias, like single-token decode already does. Larger ubatches stay banded. So do the cache types that dense CUDA FA converts every step. LLAMA_INKLING_DENSE_NMAX=1 restores the old routing, and LLAMA_INKLING_DENSE_KV_MAX caps it by cache size (default: no cap). On a B200 the dense path wins at every measured depth up to 1M cells.

Numerics: prefill and decode are bit-identical to the previous head. At -ub 3 the KLD against the previous head is 0.002 to 0.003. That is the size of the existing difference between ubatch sizes, and the result is as close to a BF16 reference as the banded path. llama-bench pp3 @ d1024 on a B200 (Inkling-2-Mini UD-Q4_K_XL): 221 -> 262 t/s, which also includes the few-channel MUL_MAT pin.

danielhanchen and others added 30 commits July 18, 2026 08:09
Hybrid attention model: 55 sliding-window plus 11 global layers, banded
content-dependent relative position bias instead of RoPE, per-layer short
convolution state, fine-grained MoE (256 experts top-6 plus 2 shared),
attention log-scaling past 128K, 1M context.

Includes the GGML_OP_FLASH_ATTN_EXT_BANDED operator (CPU and CUDA, fused
into the MMA flash attention kernel with an fp16 accumulator overflow
guard), HF to GGUF conversion, chat template with typed content block
parsing (interleaved thinking, narration and tool calls), mmproj vision
and audio support, and backend op tests at production shapes.
# Conflicts:
#	ggml/src/ggml-cuda/mmq.cuh
#	src/llama-model-saver.cpp
#	src/llama-vocab.h
Upstream 910196f renamed common_chat_params::thinking_end_tag to
thinking_end_tags and changed it from std::string to a vector, so
data.thinking_end_tag = END_MESSAGE no longer compiles.
# Conflicts:
#	src/llama-arch.cpp
# Conflicts:
#	ggml/include/ggml-rpc.h
#	ggml/src/ggml-backend-meta.cpp
#	ggml/src/ggml-cuda/ggml-cuda.cu
#	src/llama-model-saver.cpp
#	tests/test-llama-archs.cpp
# Conflicts:
#	ggml/src/ggml-rpc/ggml-rpc.cpp
Resolves the two conflicts left by upstream ggml-org#27764 (chat parsers split into
common/parsers) and ggml-org#26675 (ggml_prec rework):

- common_chat_params_init_inkling moves to common/parsers/inkling.cpp,
  registered in parsers.h and sources.cmake; chat.cpp keeps only the
  template detection branch.
- GGML_PREC_F32_PEDANTIC joins the new ranked ggml_prec scale at 5, below
  GGML_PREC_F32, since it is the stricter contract; ggml_flash_attn_ext_banded
  keeps its declaration next to the flash attention API.
…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.
Squash of the 56 commits since 3870aa4 (merges of master up to 8ca5a80, plus):
- chat : port the Inkling parser to the refactored chat API
- convert : check stacked ModelOpt NVFP4 experts after dequant
- inkling : trim comments
…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).
… path

Since the FA bias cleanup (b12859) a dense KQ bias is cast to the mask type
and added to the mask, and the mask is F16 whenever flash attention is
enabled. Inkling routes multi-sequence ubatches through this path with an
F32 bias, so rounding it to F16 moved its outputs (Inkling-Small wikitext-2
-c 512: KLD 0.196, top-1 83.5%). Cast the mask to F32 instead for Inkling,
which restores the previous numbers exactly.
From ggml-org b12878 (one thread per row for soft_max on short rows) CUDA
computes rows of up to 8 on a new kernel whose rounding differs from the
block kernel by an ulp. Inkling's router softmax over 6 routed + 2 shared
experts is 8 wide, and on Inkling-Small IQ1_S that ulp grows to KLD 0.17
over the layers. Append a -inf column on CUDA layers so the row stays on the
block kernel, which then returns the same bits as before; other backends
and models are unchanged.
…OCm, MUSA and Vulkan

ggml-org b12916 (ggml-org#33197) gave Vulkan the same one-thread-per-row soft_max for
rows of up to 8 that CUDA got in b12878, and the CUDA kernel is also built for
ROCm and MUSA. Pad the router row on those backends too, so their results stay
the same as before the short-row kernels.
danielhanchen added a commit that referenced this pull request Dec 2, 2026
danielhanchen added a commit that referenced this pull request Dec 2, 2026
@danielhanchen
danielhanchen changed the base branch from base/upstream-288115043 to base/upstream-aa631e031 December 2, 2026 15:08
danielhanchen added a commit that referenced this pull request Dec 2, 2026
#378, #385, #386 and #431 merge upstream aa631e0 (FA bias API cleanup,
b12859); #378 also keeps the Inkling router soft_max off the new short-row
kernels (CUDA b12878, Vulkan b12916). #448 merges b12922 (few-row MMQ for
NVFP4 adds a dst argument to ggml_cuda_should_use_mmq_few).

feature-checks: add inkling2-expert-scales (MUL_MAT_ID with weight scales).
… b12878

ggml-org#33187 (b12878) also gave Metal a one-thread-per-row soft_max for rows
of up to 8 columns. Before it, Metal ran the 8-wide router row on its float4
kernel, which it only picks when the width is a multiple of 4, so a single
-inf column would move it to the scalar kernel and still change the sum
order. Pad to 12 on Metal (9 when the width is not a multiple of 4); the
other backends keep the single -inf column and an unchanged graph.
oobabooga pushed a commit to oobabooga/llama.cpp that referenced this pull request Dec 3, 2026
… layouts

Pin ggml-org#32704 and repin ggml-org#32218 at 8ea4363 (DSpark taps by visit on
the loop graph). Add unslothai#395 (earlier looped layout loads as inkling2_loop),
unslothai#396 (looped layers: placement by weight layers, host weight views) and
unslothai#397 (DSpark fuse weights stay F32 in llama-quantize). Repin unslothai#385
and unslothai#386 after merging b12600. Drop unslothai#389 and unslothai#390, which
ggml-org#395, ggml-org#396 and ggml-org#397 replace.
danielhanchen added a commit that referenced this pull request Dec 3, 2026
@danielhanchen
danielhanchen changed the base branch from base/upstream-aa631e031 to base/upstream-0df40737c December 3, 2026 20:33
danielhanchen added a commit that referenced this pull request Dec 3, 2026
fix #396, pin #469 #470 (#473)

* pr-set : pin #464, default a missing NVFP4 / FP8 weight scale to 1.0

* pr-set : repin #378 #385 #386 #431 #448 for upstream b12859..b12927

#378, #385, #386 and #431 merge upstream aa631e0 (FA bias API cleanup,
b12859); #378 also keeps the Inkling router soft_max off the new short-row
kernels (CUDA b12878, Vulkan b12916). #448 merges b12922 (few-row MMQ for
NVFP4 adds a dst argument to ggml_cuda_should_use_mmq_few).

feature-checks: add inkling2-expert-scales (MUL_MAT_ID with weight scales).

* pr-set : repin #378 to keep the Inkling router soft_max on the pre-b12878 Metal kernel

* pr-set : repin #378 #386 #431 for b12939 (rpc SUPPORTS_OP, BF16 supports_op), comment-only repins of #241 #243

* pr-set : drop #462, upstream took the same short conv fusion in b12942

* pr-set : pin #469 (greedy argmax of the logits row)

* pr-set : repin #418 for the upstream flat CONCAT kernel in b12957

* pr-set : pin #470 (CPU multi-row MUL_MAT_ID for few-row experts)

* pr-set : repin #396 (the model saver writes a shared host weight once)

* feature-checks : keep cuda-short-conv-in-place with owner null, upstream b12942 carries it

* pr-set : pin upstream's Qwen4 model support until the aged base carries it (b12969)
…d add_sinks

add_sinks is a deprecated wrapper that calls set_sinks, so behavior is identical; the
deprecated call fails macOS builds with -Werror -Wdeprecated-declarations.
danielhanchen added a commit that referenced this pull request Dec 3, 2026
* pr-set : repin #386 (set_sinks instead of the deprecated add_sinks)

* pr-set : repin #470 (zero-init per-row accumulators for gcc -Werror)

This branch has not been deployed

No deployments
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.

3 participants