Skip to content

llama: LLAMA_KV_PAD pads n_kv beyond 256 cells, so a growing context rebuilds its graphs less often - #15

Merged
lukekim merged 3 commits into
spiceai-b11803from
lukim/b11803-kv-pad
Oct 29, 2026
Merged

lukekim merged 3 commits into
spiceai-b11803from
lukim/b11803-kv-pad

Conversation

@lukekim

@lukekim lukekim commented Oct 28, 2026 •

Copy link
Copy Markdown

What this changes

LLAMA_KV_PAD=N pads n_kv to N rounded up to a power of two (256 when unset, as before), and pads the QSA indexer's key-pool count in step with it (64 pools per 256 cells), so a context that grows crosses a padding boundary N/256 times less often. Off unless set; unset, nothing changes.

It sits beside #12's LLAMA_KV_PROMPT_PAD, which pads only while a prompt is read: decode steps now use LLAMA_KV_PAD's padding, and a prompt chunk the larger of the two.

Why

A graph is built for one n_kv, and n_kv is padded to 256 cells, so a context that grows past a multiple of 256 rebuilds every graph it holds; on a tensor split over RPC a rebuilt graph costs tens to hundreds of milliseconds to build and send. In multi-turn chat on a hybrid model with the key-pool indexer, logging why held graphs of the right shape were not reused named the attention input and the key-pool input together in most cases; both compare sizes that grow with the context.

How it was measured

Three DGX Spark (GB10) nodes over 200 GbE RDMA serving GLM-5.3 (Q2_K_XL) split three ways (-sm tensor, the full-mesh all-reduce from #8), driven by the Spice runtime's llama.cpp engine with the head's own GPU reached over the NIC's RDMA loopback. Single-request decode over 8 fixed prompts, temperature 0: each prompt runs for 200 tokens and for 1 token, and the decode rate is (tokens − 1) / (T200 − T1). In the symmetric form an untimed one-token request on an unrelated prompt runs before each timed request, so both start from the same prompt-cache state; the standard form runs them back to back. Six sessions per run (one model load each), interleaved, three benches per session; every arm's replies are compared prompt by prompt.

arm build symmetric mean (range), tok/s standard mean (range), tok/s
P spiceai-b11803 at a337bb5 46.21 (45.34–47.28) 45.12 (44.58–45.65)
Z P + graph serializer/deserializer + async state read 48.86 (47.99–50.26) 46.99 (46.91–47.07)
M Z + LLAMA_KV_PAD=1024 50.14 (49.01–51.04) 48.32 (48.24–48.40)

Replies: both Z sessions are identical to P on 8/8 prompts; M differs from P on 7/8 (explained below). 8 prompts per bench is too few samples for a P99, so none is stated.

Z→M is this switch alone: +2.6% symmetric / +2.8% standard (standard ranges disjoint).

Replies change at near ties. Padding widens the attention range by masked cells, which changes reduction tiling, and M's replies differ from P's on 7 of 8 prompts. At each pair's first difference, a plain llama-server on spiceai-b11803 (no draft model, no prompt cache) was asked for its top 10 next tokens: in all 7 pairs both continuations are among its top 3, with margins of 0.24–1.27 nats. The base itself leaves that oracle's top token at margins up to 1.27 nats on the same prompts, so the switch moves near ties of the size the serving configuration already does. (First-difference check only; a whole-reply walk was not run. The KL-divergence runs under Testing measure the whole distribution.)

Testing

  • The measurements and the oracle check above.

  • Output quality, by KL divergence (llama-perplexity --kl-divergence, Qwen3-4B Q8_0, wikitext-2, -c 2048, one GB10 with CUDA). Each arm's logits are compared with the base build's (spiceai-b11803 a337bb5, padding unset). The prompt path is -ub 512, 8 chunks; the decode path is -ub 1, 4 chunks, one token per step.

    arm prompt path: mean KLD (99.9%) · same top token · PPL decode path
    base, run again 0 · 100% · 9.8330 every statistic identical to base
    this branch, unset 0 · 100% · 9.8330 identical
    LLAMA_KV_PAD=1024 0.00075 (0.034) · 99.02% · 9.8313 identical
    LLAMA_KV_PROMPT_PAD=1024 0.00075 (0.034) · 99.02% · 9.8313 identical
    both (LLAMA_KV_PAD=1024, LLAMA_KV_PROMPT_PAD=2048) 0.00077 (0.036) · 98.75% · 9.8266 identical
    control: base at -ub 256 0.00077 (0.042) · 98.89% · 9.8232 —
    control: base with flash attention off 0.00078 (0.036) · 98.97% · 9.8346 —
    control, CPU only: LLAMA_KV_PAD=1024 vs base, -ub 512, 4 chunks every statistic identical to the CPU base run again —

    Unset, nothing changes on either path. Padded one-token decode steps return the base's logits to the last printed digit. On the prompt path, padding moves CUDA's logits as much as changing the ubatch size or turning flash attention off does on the unchanged base, with perplexity unchanged. On the CPU the padded and unpadded prompt runs agree on every statistic, so the masked cells add nothing; the CUDA difference is how the kernels split a wider range. The tool's PPL(Q)/PPL(base) reads 1.006 even for the base against itself (its stored base logits are compressed), so the table gives each run's own perplexity.

  • The padding takes effect on decode steps: with LLAMA_DEBUG_REUSE=1, two chunks at -ub 1 rebuilt the graph 27 times unset and 3 times with LLAMA_KV_PAD=1024 (2040 of 2067 and 2046 of 2049 decodes with outputs reused it).

  • The pool padding stops at the cache's capacity (c3c0d05): CPU, -c 4096 -ub 512, the generated glm5-next and qwen4exp models. Before it, LLAMA_KV_PAD=1048576 grew the compute buffer from 32.88 to 932.80 MiB (glm5-next) and from 44.54 to 944.46 MiB (qwen4exp), and a perplexity pass from about 1 s to about 35 s. After it, every setting (unset, 1024, 1048576, LLAMA_KV_PROMPT_PAD=4096, both) keeps 32.88 / 44.54 MiB and about 1 s, with the same perplexity; unset, the numbers match the commit before. The GLM and Qwen3-4B runs above were made before this commit. They ran far below the cap, so by reading it doesn't change them (not re-run).

  • The new-pool list keeps the 64-pool step (4ace751). Each padded entry of that list takes a cell of its own. On LLAMA_KV_PAD's wider step, one token for each of 256 sequences in a 256-cell unified cache (llama-batched-bench -c 256 -ub 256 -npp 1 -ntg 0 -npl 256 -kvu, both generated k-pool models) asked for 320 entries and aborted at GGML_ASSERT(pad_cell < (int64_t) kv_size*n_stream_kv) with LLAMA_KV_PAD=2048; the base and 4ace751 pass. Only padded entries move, which are never read. Perplexity on both models is identical before and after under four settings, and so is graph reuse at -ub 1 and -ub 512 (11 and 3 rebuilds). A decode step's list is its bound, 1 or 2 entries, so decode graphs keep the wider padding's reuse.

  • Not run: upstream's CI suite on this branch. The windows job failed once in test_router_delete_model (Model did not finish downloading before delete test); it passed when re-run on the same commit (ddec838).

…ntext rebuilds its graphs less often

A graph is built for one n_kv, and n_kv is padded to 256 cells, so a context that grows past a multiple of 256
rebuilds every graph it holds. On a tensor split over RPC a rebuilt graph costs tens to hundreds of milliseconds. In a
multi-turn chat on a hybrid model with the k-pool indexer, logging why held graphs of the right shape were not reused
named the attention input and the k-pool input together in most cases, and both compare sizes that grow with the
context: n_kv, and the pool count padded to 64 pools. LLAMA_KV_PAD=N pads n_kv to N rounded up to a power of two, and
the pool count in step with it (64 pools for every 256 cells), so a padding boundary comes N/256 times less often, at
the cost of attending over up to N - 1 masked cells. Unset, nothing changes.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Changes to attention reduction shapes and 7 of 8 measured replies need human numerical-quality assessment beyond the first-divergence check, plus runtime validation of combined LLAMA_KV_PAD/LLAMA_KV_PROMPT_PAD settings.

No open issues 🎉

What changed in this PR

Adds opt-in LLAMA_KV_PAD padding to reduce graph rebuilds as the context grows, extending the existing prompt-only padding control to decode steps. The default remains 256 cells.

Changes:

  • Rounds the configured padding up to a power of two, capped at 1,048,576 cells.
  • Scales QSA key-pool padding with cell padding to keep graph shapes aligned.
  • Uses the larger of general and prompt-specific padding during prompt processing.
File Description
src/​llama-memory-hybrid-idx.cpp Scales key-pool padding with the configured cell padding.
src/​llama-kv-cache.h Declares the padding helper and documents its tradeoff.
src/​llama-kv-cache.cpp Parses LLAMA_KV_PAD and applies it to the visible KV range.

Review effort: Balanced

@lukekim

lukekim commented Oct 29, 2026

Copy link
Copy Markdown
Author

Addressed #15 (review):

  • Numerical quality beyond the first difference: KL divergence of the whole distribution, using Qwen3-4B Q8_0 on wikitext-2 on one GB10 with CUDA, scored against the base build's logits. The full table and controls are in the description.
    • Decode path (one token per step): every padded setting gives the base's statistics to the last printed digit. The rebuild counts below confirm the padding took effect there.
    • Prompt path: LLAMA_KV_PAD=1024 gives mean KLD 0.00075 (99.9th percentile 0.034), the same top token 99.02% of the time, and perplexity 9.8313 vs 9.8330. The unchanged base moves as far when only -ub changes (0.00077, 98.89%) or flash attention is turned off (0.00078, 98.97%).
    • On the CPU, padded and unpadded prompt runs agree on every statistic, so the masked cells add nothing. The CUDA difference comes from how the kernels split a wider range.
  • Combined LLAMA_KV_PAD + LLAMA_KV_PROMPT_PAD: ran on both paths (LLAMA_KV_PAD=1024 LLAMA_KV_PROMPT_PAD=2048). Decode results are identical to base; prompt results are mean KLD 0.00077, 98.75% same top token, perplexity 9.8266. Unset, this branch equals the base on both paths.
  • Rebuilds: with LLAMA_DEBUG_REUSE=1, two chunks of one-token decodes rebuilt the graph 27 times unset and 3 times with LLAMA_KV_PAD=1024.
  • CI: windows failed once in test_router_delete_model (Model did not finish downloading before delete test) and passed when re-run on ddec838.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Pool padding is not capped by cache capacity, which can inflate QSA mask memory from about 1 MiB to 256 MiB and risk allocation failures.

1 open issue

Review effort: Balanced

Comment thread src/llama-memory-hybrid-idx.cpp Resolved
LLAMA_KV_PAD padded the k-pool indexer's pool list in step with the cells, 64 pools for every 256 cells, but unlike
the visible cells, which stop at the cache's size, the pools had no cap. With a 4096-cell context and
LLAMA_KV_PAD=1048576 the pool list was sized for 262144 pools: on the generated glm5-next and qwen4exp models the CPU
compute buffer grew from 32.88 MiB to 932.80 MiB and from 44.54 MiB to 944.46 MiB, and one perplexity pass from
about 1 s to 35 s. The padding now stops at what the default padding gives a cache holding every pool it can, so
those runs keep 32.88 MiB and 44.54 MiB and about 1 s a pass, alone or with LLAMA_KV_PROMPT_PAD=4096. Unset, the
sizes, times and perplexities are unchanged.
Copilot AI balanced review requested due to automatic review settings October 29, 2026 00:44
@lukekim

lukekim commented Oct 29, 2026

Copy link
Copy Markdown
Author

Addressed #15 (review): the pool padding now stops at the cache's capacity (c3c0d05). Reproduced before the fix: LLAMA_KV_PAD=1048576 at -c 4096 made a 932.80 MiB compute buffer, against 32.88 MiB, and ~35 s per pass, against ~1 s. After the fix, every setting keeps the unpadded size and time, with the same perplexity. #15 (comment)

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The enlarged padding can exhaust all 256 physical cache rows during dummy re-pooling and trigger an assertion failure, so the new-pool bound must retain the original 64-pool padding.

1 open issue
1 resolved since last review

Review effort: Balanced

Comment thread src/llama-memory-hybrid-idx.cpp Resolved
Each padded entry of the new-pool list re-pools a cell of its own. Padded on LLAMA_KV_PAD's
wider step, a ubatch with one token for each of 256 sequences in a 256-cell cache asked for
320 entries and set_input_kpool asserted (pad_cell < kv_size*n_stream_kv) with
LLAMA_KV_PAD=2048. The list changes size only while a prompt is read; a decode step's list is
its bound, 1 or 2 entries, so decode graphs keep the wider padding's reuse.
Copilot AI balanced review requested due to automatic review settings October 29, 2026 06:21
@lukekim

lukekim commented Oct 29, 2026

Copy link
Copy Markdown
Author

Round on 4ace751:

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approved

No active review issues require resolution.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@lukekim
lukekim merged commit 9e04d20 into spiceai-b11803 Oct 29, 2026
12 of 13 checks passed
lukekim added a commit that referenced this pull request Oct 29, 2026
Carries the two fork PRs that landed on spiceai-b11803 after the upstream merges were cut: LLAMA_KV_PAD (#15) and the
asynchronous state read (#16). Upstream b11999 pads n_kv to a fixed 256 where #15 read the cache's n_pad, so the pad is
now the larger of 256 and LLAMA_KV_PAD's.
lukekim added a commit that referenced this pull request Oct 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants