Skip to content

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

Open
danielhanchen wants to merge 100 commits into
base/upstream-239242322from
inkling2-attn-banded
Open

danielhanchen wants to merge 100 commits into
base/upstream-239242322from
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.

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.

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).
@danielhanchen

Copy link
Copy Markdown
Member Author

#386 repin: ded02bd -> 8ee7920 (Inkling 2 banded attention for small ubatches and several sequences)

8ee7920 is a fast-forward of ded02bd (the current #386 merge probe on b12668 / b12670). It adds ten commits, eight from two branches and two that keep #378 intact, and changes 13 files (+1332 / -58):

  • Small ubatches of one sequence:
    • 566ef55ac CUDA: banded attention decode kernel for a few queries
    • 5270100b3 inkling2 : take the banded path for ubatches of 2 to 32 tokens over the padded cache
    • 56df0d226 ggml : read the banded attention mask in place when it is a view
    • bebd19fd5 kv-cache : check the position contiguity once per applied ubatch
    • 5b2da9594 CUDA: banded decode kernel reads q4_1 / q5_0 / q5_1 and mixed q8_0 K caches in place
  • Several sequences, gaps and the wrapped SWA ring:
    • d24b324c8 ggml : banded flash attention with cell and query positions
    • d262c423d inkling2 : banded attention when the cells are not the positions
    • 0c76ff63e tests : banded positions with every quantized K/V type and mixed K/V types
  • Living with model : Inkling 1 (ggml-org#25731) on b12533 for the prebuilt #378, which carries the same banded code:

With #386 at 8ee7920 and the rest of unslothai master's pr-set, llama_pinset.py sim on b12674 and b12675 merges all 44 pins (#386 clean), pin_contract finds all 44 pins intact and merge_checks is clean. At fd96634 the merge was clean too, but it rewrote lines #378 adds, so pin_contract failed on #378.

What it fixes

Before this, every ubatch of 2 to 32 tokens (DSpark verify batches, prompt tails), every ubatch of several sequences, and every SWA ubatch after the ring wrapped took the dense relative bias: n_kv x n_tokens x n_head in F32 plus F16 copies. The reserve sized the compute buffer for that at load (the 32-row dense reserve of 6510f1f, and a dense multi-sequence reserve). With quantized K/V, dense flash attention with 3 or more queries also converts the whole K/V view to F16, which is why q8_0 / q4_0 used more memory than f16 (1282 vs 770 MiB at 128K).

Now all of those take the banded kernels. One sequence spans the padded n_kv with a shifted bias table, so graphs are still reused. Several sequences and wrapped caches pass the position of each cell and query. A new decode kernel reads F16, BF16, q8_0, q4_0, q4_1, q5_0, q5_1 and mixed q8_0-K / q4_0-V and q8_0-K / f16-V caches in place. Decode steps over f16 / bf16 / q8_0 / q4_0 caches stay on the dense flash attention path, so their output is unchanged. Decode steps over q4_1 / q5_0 / q5_1 / mixed caches, which dense CUDA flash attention converts to F16 every step, take the banded kernel in the full-attention layers.

Memory (compute buffer, MiB, Inkling-2-Mini UD-IQ1_S, FA on)

Before is the current pin set (b12651 mix). After is the same mix with this change (pins + both branches). Exit equals load in every cell.

1 slot:

ctx / ub f16 before f16 after q8_0, q4_0, q4_1, q5_0, q5_1, q8_0-q4_0 before after
32K / 512 849 819 848 819
128K / 512 963 792 1282 792
256K / 512 1498 792 2522 792
1M / 512 5866 1248 9962 1248
32K / 2048 3393 3277 3392 3277
128K / 2048 3795 3169 3794 3169
256K / 2048 4331 3169 4330 3169
1M / 2048 9069 4987 13165 4987

4 slots, unified KV (-np 4 -kvu), every K/V type:

ctx ub 512 before after ub 2048 before after
32K 2681 256 5033 1027
128K 3990 352 8297 1411
256K 5526 480 13673 1924
1M 21654 1251 52841 4999

Quantized K/V gate: every quantized type is at or below f16 and below the pin set in every cell above. The one cell above f16 is mixed q8_0-K / f16-V, by 24 MiB at ub 512 and 96 MiB at ub 2048 (1 and 4 slots). A reserve-graph diff at 1M shows that the only extra nodes are the KV rotation that quantized K enables (48 Q-rotation and 48 K-rotation matmuls); the pin set carries the same term.

Process GPU peak with DSpark (2 drafts, q4_0 draft K/V), UD-IQ2_XXS, 1 slot, -ub 512, prompt filling the cache, 128 generated tokens:

case compute at load before after GPU peak before after
128K, f16 770 349 15048 14632
128K, q8_0 1282 349 13538 12604
128K, q4_0 1282 349 12454 11520
1M, f16 5866 1248 54304 49692
1M, q8_0 9962 1248 42938 34224

The memory outside the accounted buffers is the same before and after (about 2085 MiB at 128K, 7574 MiB at 1M), so decode and drafts make no F16 copy of a quantized cache. Kernel traces confirm it: with q4_1 / q5_0 / q5_1 K/V, 3- and 16-token ubatches launch 29184 and 5472 dequantize-to-F16 kernels before and none after. Prompt ubatches of more than 32 tokens with q4_1 / q5_x K/V still convert the cache to F16 in the banded MMA kernel, as before (about 4 GiB of pool at 1M); the process peak still stays below f16.

Accuracy

  • PPL is string-equal to the pin set at -ub 1 and -ub 512 (wikitext-2, -c 512, 20 chunks), UD-IQ1_S and UD-Q4_K_XL: mean KLD 0.000000, the same top-1, PPL(Q) identical to six decimals.
  • The repin itself: the b12674 pin-set simulation with model : banded flash attention for the Inkling 2 relative bias #386 at ded02bd against the same pin set with model : banded flash attention for the Inkling 2 relative bias #386 at 8ee7920 (UD-IQ1_S, -ub 512 and -ub 1) is string-equal on every chunk and the final estimate (8.4632 +/- 0.30340 and 8.4711 +/- 0.30378), with mean KLD 0.000000.
  • 4 sequences per batch (unified KV, -c 512 -b 2048), mean KLD against the same model with -fa off (F32 bias): UD-IQ1_S 0.00316 after vs 0.00340 before, UD-Q4_K_XL 0.00254 vs 0.00256.
  • Decode with the newly routed cache types (-ub 1, UD-Q4_K_XL), mean KLD against f16 K/V with -fa off: q5_1 0.00399 after vs 0.00615 before, q8_0-K / q4_0-V 0.00588 vs 0.00556. q4_1 over 64 blocks of 256 tokens: mean KLD 0.00959 after vs 0.00965 before, paired difference -0.00006 (95% block-bootstrap CI -0.00056 to +0.00040); top-1 agreement is 0.28 points lower (95.49% vs 95.77%, CI -0.51 to -0.05), a small real difference on that one type.
  • Kernel oracle against an fp64 reference at 1,048,000 cells, 1 and 3 queries, q4_1 / q5_0 / q5_1: CUDA error about 3e-7, CPU about 7e-6.
  • test-backend-ops on fd96634: FLASH_ATTN_EXT_BANDED 290 / 290, FLASH_ATTN_EXT 4430 / 4430 (CUDA vs CPU, B200). On the b12674 pin-set simulation with model : banded flash attention for the Inkling 2 relative bias #386 at 8ee7920: 290 / 290 and 4544 / 4544, and test-flash-attn-bias small / medium / pos all pass on CUDA and small / pos on CPU.
  • llama_pinset.py verify --tag b12674 --cuda with model : banded flash attention for the Inkling 2 relative bias #386 at 8ee7920: CPU gate, full CUDA build, test-chat, MUL_MAT 2897 / 2897, MUL_MAT_ID 1183 / 1183, PAD 37 / 37, GET_ROWS 361 / 361, feature matrix all 31 features on CPU and GPU.
  • Greedy text (UD-Q4_K_XL, 128 tokens, 1K / 16K / 64K prompts) is byte-identical to the pin set.

DSpark

Draft dspark-Inkling-2-Mini-Q8_0, n_max 3, greedy, UD-Q4_K_XL, f16 K/V:

  • 24 short chat prompts x 256 tokens: acceptance 0.428 after vs 0.440 before. After the first prompt, each one prefills only 12 to 25 new tokens on a cached prefix. Those ubatches used the dense F16 bias and now take the F32 banded bias, so the texts diverge at the first near-tie. Keeping them exact would mean keeping the 32-row dense reserve.
  • Random-token prompts swing acceptance between 0% and 71% on the same build (512K, three seeds: 86/121, 0/375, 57/206 before; 23/306, 0/375, 64/185 after), so they are not used for this comparison.

Speed

Exclusive B200, UD-IQ2_XXS, depth 131072, -ub 2048, run as pin set | this change | pin set. Ratio of this change to the mean of both pin-set runs; the pin set against itself shows the noise.

K/V 3-token ubatch (verify batches, tails) tg32 pin set vs pin set (3-token / tg32)
f16 1.03 0.99 0.92 / 0.97
q8_0 1.12 0.98 0.99 / 1.02
q4_0 1.37 1.01 1.01 / 1.02
q5_1 1.23 1.30 1.01 / 0.98
q4_1 1.27 1.27 1.02 / 0.98

Decode with f16 / q8_0 / q4_0 caches is unchanged. Decode with q4_1 / q5_1 caches is 27 to 30% faster because the step no longer converts the cache to F16.

Small cards

Colab T4 (16 GB) and L4 (24 GB). Both trees were built on the VM from upstream b12651 plus the pin-set diff (before), then plus this change (after). UD-IQ3_XXS, q8_0 K/V, llama-server with --fit on (default), -c 131072, 1 slot, a 4000-token prompt and 64 generated tokens. Memory in MiB.

card case layers on GPU GPU weights compute free after fit process peak prompt t/s gen t/s
T4 before 25 / 25, 3 overflowing to host 10001 1282 1129 13780 361 24.8
T4 after 25 / 25 10863 349 1201 13708 468 28.1
L4 before 25 / 25 10863 1282 7813 14742 940 43.8
L4 after 25 / 25 10863 349 8747 13808 1166 43.2

On the T4 the pin set has to leave part of three layers' weights in host memory (about 860 MiB) to fit 128K; with this change the whole model fits on the card.

L4, 4 slots, -kvu, -c 32768, --fit on: compute buffer 2681 before vs 256 after, process peak 14778 vs 12348 MiB.

llama-bench, q8_0 K/V, all layers on the GPU, two rounds (before, after, before, after), t/s:

card test before after
T4 pp512, depth 0 520 / 446 449 / 441
T4 tg64, depth 0 30.6 / 27.3 27.5 / 27.3
T4 pp512, depth 32K 268 / 274 320 / 320
T4 tg64, depth 32K 20.4 / 20.5 20.6 / 20.5
L4 pp512, depth 0 1416 / 1382 1385 / 1344
L4 tg64, depth 0 47.9 / 47.0 47.4 / 46.6
L4 pp512, depth 32K 776 / 762 1014 / 999
L4 tg64, depth 32K 39.0 / 38.4 38.7 / 38.2

The first T4 round of the pin set ran on a cold card and is faster than every later run on the same card; the second round shows depth 0 unchanged. At depth 32K, prompt processing is 18% (T4) to 31% (L4) faster: after the SWA ring wraps, its layers took the dense bias before and now take the banded kernel with cell positions. Generation is unchanged.

Not covered

  • Metal, Vulkan and ROCm: the new decode kernel and routing are CUDA only; other backends keep their previous paths (banded where they support the op, dense otherwise).
  • Prompt ubatches above 32 tokens with q4_1 / q5_x K/V still convert the cache to F16 in the banded MMA kernel. Removing that needs MMA tile readers for those types.
  • iq4_nl and f8 K/V are not read in place by the new kernel.

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Nov 24, 2026
… bytes (builds on unslothai#19148) (unslothai#19249)

Builds on unslothai#19148 (includes its commits); merging this merges unslothai#19148.

## Problem

unslothai#19148 prices the large compute reserve that unslothai/llama.cpp#386
added in `b12649-mix`. The next llama.cpp prebuild may ship the fix to
that reserve. In the fixed build, several slots run the banded kernel
over cell positions, and short ubatches run banded over the padded
cache. The reserve then drops to almost nothing:

| Inkling-2-Mini, 1 slot, 1M context, ub 512 | `b12649-mix` | fixed
build |
|---|---|---|
| f16 K/V | 5866 MiB | 1248 MiB |
| q8_0 K/V | 9962 MiB | 1248 MiB |

With unslothai#19148 alone, Studio would keep pricing the fixed build with the
`b12649-mix` reserve. On the measured points that overestimates the
compute buffer by 0.2 to 55 GB, so Studio would place fewer layers on
the GPU than fit. This PR prices the fixed build separately, which makes
unslothai#19148 safe to merge.

## Fix

- Detect the fixed build by two graph input names it adds to `libllama`:
`attn_inp_k_pos_swa` (several slots, banded over cell positions) and
`attn_inp_rel_shift_swa` (short ubatches over the padded cache). No
earlier build has either name. Both survive `strip`. Both must be
present.
- Price its reserve as the f16 KQ mask over the padded cache (2 bytes
per cell per ubatch token, twice with `--swa-full`) plus 160 KiB per
ubatch token, for any slot count and K/V type. A layer split adds its
mask copies as before.
- Keep only the CUDA pool margin (256 KiB per ubatch token) in
`--fit-target`, as unslothai#19148 does for `b12649-mix`. The markers identify
the build even when its build number cannot be read.
- `b12649-mix` and the merge-only rebuild of #386 keep unslothai#19148's pricing.
Older builds keep the pricing on `main`.
- Split a `--fit off` multi-GPU load by bytes when llama.cpp's split by
layer count would overflow a card. Unsloth Dynamic quants keep some
layers at higher precision: the last four layers of Inkling-2-Mini
UD-Q8_K_XL are about 2 GB each, against 0.6 GB for the rest, so a split
by count can put several GB more on the smaller card than it holds.
Studio now emits a `--tensor-split` whose layer runs fit each card. When
no split fits, it lets `--fit on` place the model with the slots the
user asked for, not a count cut only to fit every layer on the GPUs. A
load whose count split already fits keeps llama.cpp's own split.

Which pricing each build gets (`grep -c` of each string in the built
`libllama`):

| Build | `inkling2_loop: %zu cache slots exceed` | `attn_inp_k_pos_swa`
| `attn_inp_rel_shift_swa` | Pricing |
|---|---|---|---|---|
| `b12631-mix` | 1 | 0 | 0 | as on `main` (build below 12649) |
| `b12649-mix` | 1 | 0 | 0 | unslothai#19148 |
| #386 merge-only rebuild | 1 | 0 | 0 | unslothai#19148 |
| fixed build (#386 plus the banded-position fix) | 1 | 1 | 1 | this PR
|

## Accuracy

Compute buffer at load from `llama-server`, Inkling-2-Mini, flash
attention, B200, on the fixed build. The table is a sample of 116
points: 1 to 64 slots, ub 256 to 2048, f16 / bf16 / q8_0 / q4_0 / q4_1 /
q5_0 / q5_1 / mixed K/V, 4K to 1M context, with and without
`--swa-full`, and with a DSpark drafter.

| Setup | Measured (MiB) | This PR (MiB) | unslothai#19148 (MiB) |
|---|---|---|---|
| 4 slots, 32K, ub 512 | 256 | 298 | 3050 |
| 4 slots, 256K, ub 512, q5_1 | 480 | 522 | 6506 |
| 4 slots, 1M, ub 2048, q8_0 | 4999 | 5156 | 60388 |
| 1 slot, 512K, ub 512 | 734 | 773 | 3429 |
| 1 slot, 1M, ub 512, q4_0, DSpark | 1248 | 1285 | 10597 |
| 1 slot, 415,488, ub 2048, q4_0, `--swa-full` | 4124 | 4292 | 10932 |
| 4 slots, 274,688, ub 512, q4_0, `--swa-full` | 758 | 803 | 18577 |
| 64 slots, 64K, ub 512 | 352 | 440 | 9496 |

Across all 116 points the estimate is 1.01x to 1.25x the measurement
(+14 to +184 MiB) and never under it. The highest ratio is 64 slots at
64K, where the flat estimate's output rows lead.

After two concurrent 13.5K-token prompts at ub 2048 with 4 slots, the
compute buffer grew by 120 MiB past the load reserve. The 512 MiB pool
margin in `--fit-target` covers that.

## unslothai#19137 on the fixed build

The unslothai#19137 setup with Inkling-2-Mini UD-Q8_K_XL: 2 GPUs, 32K context, 4
slots requested, the Windows reserve floor. Studio's planner ran for
each free VRAM pair. The command it produced then ran on two B200s, with
`cudaMemGetInfo` capped to that pair. The cap only changes what
llama.cpp sees as free memory; it does not stop an allocation. So for
every load, the table checks llama.cpp's own per-card memory (weights,
cache, compute, unaccounted) against the card. Every load answered two
concurrent 13.5K-token prompts.

| Free VRAM | `main` | unslothai#19148 | This PR |
|---|---|---|---|
| 14848 + 11264 MiB | `--fit on`, target 3714: 12.3 GiB of weights on
GPU | `--fit on`, target 1536: 16.6 GiB on GPU | same command as unslothai#19148
|
| 15360 + 11264 MiB | `--fit on`, target 3714: 12.8 GiB on GPU | `--fit
on`, target 1536: 16.6 GiB on GPU | same command as unslothai#19148 (4 slots,
`--fit on`, target 1536) |
| 16384 + 12288 MiB | all layers on GPU, 4 slots, split by count: 13.5
GB on the 12 GB card, so it fails at load | all layers on GPU, 1 slot,
split by count: 13.9 GB on the 12 GB card, so it fails at load | all
layers on GPU, 4 slots, `--tensor-split 19.5,5.5`: 15.0 GB and 11.1 GB,
under 16 and 12 GB |

Decode speed, median of 5 runs of 256 tokens after a warmup, in tok/s.
These numbers are noise-dominated: the host CPU was shared with other
jobs, and loads with every layer on the GPUs measured anywhere from 91
to 698 tok/s across rounds of the same setup. They do not rank the
versions; the placement above is the result.

| Free VRAM | `main` | unslothai#19148 | This PR |
|---|---|---|---|
| 14848 + 11264 MiB | 134 | 155 | same command as unslothai#19148 |
| 15360 + 11264 MiB | 155 | 208 | same command as unslothai#19148 |
| 16384 + 12288 MiB | 110 (would not load on the real cards) | 184
(would not load on the real cards) | 91 |

`main` on the fixed build reproduces the report: 11.6 and 7.9 GB used of
the two cards with expert weights on the CPU, as in the Task Manager
readings in unslothai#19137. With 16 + 12 GB free, this PR keeps the whole model
on the GPUs and loads. `main` and unslothai#19148 plan the same placement but
split by layer count, so the 12 GB card cannot hold its share.

The 1024 MiB per-device overhead matches what llama.cpp reports as
unaccounted per device (0.8 to 1.3 GB), so this PR leaves the multi-GPU
margins as they are.

## Boundaries

- The byte split shares the cards by the lowest fill they can all hold,
in device order. With three or more cards it can leave a middle card
lightly used.
- `llama-completion` reserves a logit row per ubatch token, so its
single-slot buffers are larger than `llama-server`'s at the same
settings (819 vs about 252 MiB at 32K, ub 512). Studio launches
`llama-server`, which is what this PR prices.
- The DSpark drafter's own compute buffer (203 MiB with f16 draft K/V
and 663 MiB with q4_0 at 128K) is unchanged by the fix and priced as
before.

## Tests

- `test_inkling2_banded_quant_kv.py` adds:
- the marker detection, including each marker alone, a longer name, an
unknown build number and an older build number;
  - 48 measured points, plus mixed K/V types;
  - context monotonicity, with no slot or K/V type dependence;
  - the layer-split mask copies;
  - the `--fit-target` margin;
- the dense fallback with flash attention off or ubatches of 32 or
fewer.
- `test_byte_balanced_layer_split.py` covers:
  - an even model keeping llama.cpp's split;
- the unslothai#19137 rows split by bytes at 16 + 12 GB, and handed to the fitter
at 15 + 11 GB;
  - each run fitting its card, the positional order over three cards;
- the planner path from the layout, and the launch falling back to
`--fit on`.
- a slot cut whose pin has no layer split that fits: the launch keeps
the 4 slots asked with `--fit on`.
- The 31 Studio planner suites give the same failing test IDs on `main`,
unslothai#19148 and this PR. All 321 come from this host's CUDA probe guard (a
CPU test reaching `torch.cuda` on a GPU host without a queried device),
not from these changes.

---------

Co-authored-by: oobabooga <[email protected]>
@danielhanchen

Copy link
Copy Markdown
Member Author

Moved one step further to 01f7959 (fast-forward of 8ee7920): the two checks that the cell and query positions are mirrored (src[7] / src[8]) now sit just before the op switch in ggml-backend-meta.cpp, under if (tensor->op == GGML_OP_FLASH_ATTN_EXT_BANDED), outside the banded split handler #378 carries. The handler itself stays byte-identical to #378's.

At 01f7959, with the rest of unslothai master's pr-set: sim on b12674 and b12675 merges all 44 pins (#386 clean), all 44 intact, merge_checks clean. verify --tag b12674 --cuda passes (CPU gate, CPU and GPU feature matrix 31/31, CUDA build, test-chat, MUL_MAT 2897/2897, MUL_MAT_ID 1183/1183, PAD 37/37, GET_ROWS 361/361). FLASH_ATTN_EXT_BANDED 290/290 and FLASH_ATTN_EXT 4544/4544 on the merged tree; PPL against the ded02bd set is string-equal at -ub 512 and -ub 1 (mean KLD 0.000000).

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 01f79590f7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Upstream b12635 added an op and moved the RPC check to GGML_OP_COUNT == 101 with
RPC_PROTO_PATCH_VERSION 2. This branch adds GGML_OP_FLASH_ATTN_EXT_BANDED on top, so the
count is 102 and GGML_RPC=ON builds stop at the static_assert. Bump the check to 102 and
the patch version to 3.
ggml_prec_set_acc() stores the accumulator precision of GGML_OP_FLASH_ATTN_EXT_BANDED in op param 3 and
ggml_flash_attn_ext_get_prec() reads it, but the generic getter returned GGML_PREC_UNDEFINED for the banded op.
test-flash-attn-bias checks the round trip.
…h with the main label

Both were plain add_test() entries without a label, so ctest -L main skipped them.
…_bias

The banded op reuses the FA MMA kernel and tagged it with max_bias < 0, but ggml_flash_attn_ext() accepts a
negative max_bias (no ALiBi), so an ordinary call with max_bias < 0 read the sinks as a relative-bias table.
m0 of an ordinary call is a power of 2 and never negative. Add FLASH_ATTN_EXT cases with max_bias = -2.
…A path

The switch only gated the standalone banded MMA kernel; a no-sink op still delegated to the FA MMA kernel.
A row without a visible cell has a zero rowsum, the MMA kernel and the stream-k fixups divided 0 by 0. The
CPU and the other banded CUDA kernels return 0. Add banded cases with a fully masked query (mask_kind 4),
which the op delegates to the FA MMA kernel without sinks.
The local index rejects a tensor in a shard the index does not assign it to and a name that two tensors map to
after filtering. --remote overwrote both silently: check the shard in SafetensorRemote and the filtered name in
index_tensors().
… early return

A pure NVFP4 checkpoint returned from dequant_model() before the check, keeping the packed experts.
…probe every cache type

The reserve context reports the full span as contiguous, so the reserved graph of a unified multi-sequence context
was banded while such ubatches run dense. Take the banded op for one-sequence ubatches only, as inkling2 does,
and ask the layer's device for F32 / F16 / BF16 caches too, not only for quantized ones.
With LLAMA_INKLING_BANDED_POS=0 a cache whose cells are not the positions is dense, so reserve the full-attention
layers dense too, not only a wrapping SWA cache. A unified multi-sequence context decodes one token dense, while
its tg reserve of n_seq_max tokens is banded: reserve that graph as well.
The FA kernels read F16 K/V in place with 16-byte loads, so a K/V view whose rows are padded off that boundary
(a 129-wide backing tensor) was mis-addressed. Keep such ops on the banded kernels, which read any row stride.
Add the kv_layout cases: padded K/V rows, a mask wider than K and K/V head counts that differ.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 6249123b1f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: a8ca6dab00

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: abcfe87aad

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

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