Repository navigation
Block KV cache streaming: bound VRAM at long context via a shared CUDA phase arena - #357
Conversation
|
@TheTom that took a while but I think I am done. |
|
Read the whole thing at b08b515b9, src side and CUDA side separately, with flag-off as the deciding question. The good news first: with Needs changes before it can land:
Concerns, none individually blocking:
I'll run the GB10 gates (default build flag-off sweeps, FA_ALL_QUANTS build with |
|
One more from CI, and it is not the runner flake this time. The Windows arm64 cmake-pkg job fails at link: Those are internal libllama functions with no |
Ports the pure-logic core of RaymondHuang210129/llama.cpp-adaptive-kv-streaming's phase-arena KV streaming implementation (feature/kv-stream-phase-arena), onto this fork's clean feature/turboquant-kv-cache base rather than patching the broken block-KV-streaming stub in PR TheTom#326. - llama-kv-stream-plan.{h,cpp}: page/region allocator, adaptive resident/ring partition sizing (deadline-miss/copy-busy driven hysteresis), prefetch dispatch. Ported verbatim - backend-agnostic, no TurboQuant-specific concerns. - llama-kv-stream-softmax.{h,cpp}: online-softmax merge for combining resident-chunk and streamed-chunk partial attention results. Ported verbatim. - llama-kv-stream-config.{h,cpp}: ported with one reconciliation - upstream's validate() hard-rejects any architecture other than Qwen3.5 (a literal allowlist, not an inert flag). Replaced that gate with this fork's existing unified_kv_cache check (excludes MLA/ hybrid-SWA/recurrent caches, not just non-Qwen3.5 archs) and kept a type_pair_supported gate, since v1 of this port only wires up streaming for standard GGML K/V types - turbo2/3/4 must still be rejected here, not silently accepted. All upstream test files (test-kv-stream-plan/config/softmax/bench-config and the three CUDA test files) copied over as-is; the config test was adjusted to reference unified_kv_cache/type_pair_supported instead of arch_qwen35 so it compiles against the reconciled struct, and to isolate the arena-below-minimum case from the kv_offload case it was incidentally also exercising. Wires the three pure-logic tests into tests/CMakeLists.txt; the CUDA and bench-config test files are copied but not yet wired in since their dependencies (CUDA kv-stream runtime, kv-stream-bench tool) land in later commits on this branch. Assisted-by: Claude Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
…rows staging Ports the CUDA implementation of RaymondHuang210129/llama.cpp-adaptive-kv-streaming's phase-arena block KV streaming (feature/kv-stream-phase-arena) onto this fork's attention/backend code, reconciled with TurboQuant's existing turbo2/3/4 dequant paths, WHT rotation, and MLA/hybrid-SWA cache handling. ggml-cuda.cu / ggml-cuda.h: - New phase arena (one bounded CUDA allocation shared between compute workspace, resident KV pages, and an async transfer ring), resident cache, and transfer-ring buffer type, replacing nothing on this branch (no prior kv-stream implementation existed here). - ggml_backend_cuda_device_supports_buft now recognizes the new kv-stream buffer type as CUDA0-affine - this is the direct fix for the scheduler CPU/CUDA0 thrashing (74 splits/eval instead of 2) measured against PR TheTom#326's implementation this session. - GGML_OP_SET_ROWS/FLASH_ATTN_EXT dispatch in ggml_cuda_compute_forward route through the new staged/streamed paths only when a kv_stream runtime is actually attached to the tensor - turbo tensors (which never get a runtime attached, since v1 gates streaming to standard types only) fall through to the exact same code path as before, unchanged. fattn.cu / fattn.cuh / fattn-common.cuh / fattn-mma-f16.cuh / fattn-vec.cuh: - New kv_stream transfer ring, resident cache, per-type capability table (ggml_backend_cuda_kv_stream_get_type_capabilities/ get_attention_mode - classifies only standard GGML types for v1; turbo2/3/4 fall through to UNSUPPORTED, same as any other type this doesn't recognize, gracefully excluding them rather than crashing), and ggml_cuda_flash_attn_ext_streamed (chunked attention over resident+streamed KV pages, merged via the online-softmax layer ported earlier). - Added an `output_partial` template parameter (default false) to flash_attn_ext_f16_process_tile/flash_attn_ext_f16 and a launch_fattn(..., partial_dst, partial_meta) overload, both as trailing defaulted parameters so every existing TurboQuant call site (which doesn't know about partial output) compiles unchanged. ggml_cuda_flash_attn_ext_mma_f16_case_impl gets two thin wrappers: the original name (output_partial=false, used by the existing DECL_FATTN_MMA_F16_CASE instantiation macro) and a new _partial_case for the streamed path. - Fixed a bug the port exposed rather than introduced: several `extern DECL_FATTN_VEC_CASE(...)` call sites for TurboQuant's cross-type (turbo x f16/q8_0/turbo) instances only put `extern` on the first of the macro's two statements once DECL_FATTN_VEC_CASE started emitting a _partial_case instantiation alongside the original - the second statement silently became a real definition, colliding with the same definition in each instance .cu file at link/compile time. Switched those sites to the existing EXTERN_DECL_FATTN_VEC_CASE macro, which extern-qualifies both. set-rows.cu / set-rows.cuh: - Threaded a `dst_row_base` offset through the standard-type set_rows kernel/dispatch chain (k_set_rows, the raw-pointer and ggml_backend_cuda_context overloads, including the two explicit half/int32_t and half/int64_t specializations) and added ggml_cuda_op_set_rows_staged, which stages new K/V rows through a pooled device buffer before copying into the (now host-resident) destination and optionally mirroring into the resident cache. Fixed one call site (IQ4_NL) the source patch didn't cover, which needed the same dst_row_base threading as its neighbors. - Turbo-specific set_rows_cuda_turbo{2,3,4} dispatch is untouched - turbo K/V never reaches the staged path in v1. Regression-tested: turbo3 and q8_0 K/V generation (no --kv-stream) produce sane output at normal throughput; the three pure-logic kv-stream unit tests still pass. --kv-stream-arena-mib itself isn't wired up yet (llama-context.cpp/llama-kv-cache.cpp/common/arg.cpp come next) so the new code paths aren't reachable yet - only build/link integration and standard-type/turbo dispatch coexistence have been verified so far. Assisted-by: Claude Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
…struction
Ports the llama_context/llama_kv_cache/llama_model wiring from
RaymondHuang210129/llama.cpp-adaptive-kv-streaming (feature/kv-stream-phase-arena),
reconciled with this fork's broader architecture zoo and the
unified_kv_cache generalization already made in the config layer.
- include/llama.h: new llama_context_params.kv_stream_arena_mib field
and the llama_decode_phase enum + llama_set_decode_phase() API (used
by the phase arena to distinguish prefill from decode-style
microbatches and pick the right resident/ring split immediately
instead of waiting several tokens for feedback to react).
- llama-context.{h,cpp}: phase arena bootstrap (validate config, probe
per-layer page/workspace geometry, create the arena, publish its
buffer type into llama_memory_params) replacing nothing (no prior
kv-stream code existed on this branch). Removed the source's
`arch == LLM_ARCH_QWEN35` gate on the *wiring* itself (only ever
passing real values through for that one architecture) - replaced
with a real unified_kv_cache computation mirroring this fork's
MLA/indexer/recurrent exclusion set (MINIMAX_M3, GLM_DSA,
DEEPSEEK32/4, recurrent archs, DFLASH only when dsv4_hc_mult>0),
the same set the config layer's `unified_kv_cache` gate was already
designed for. iSWA dual-cache and the specialized DSA/DSV4/MSA
caches are still excluded (matching the source, which never wires
kv-stream through their constructors either) - kv_base-only iSWA
support stays a follow-up.
- llama-kv-cache.{h,cpp}: constructor gains kv_stream_stage_bytes/
kv_stream_phase_arena/kv_stream_maximum_pool_bytes as defaulted
trailing parameters (after the existing name_tag, which already had
a default) rather than inserted where the source's diff placed them
(right after `share`) - this fork's constructor already had a
`name_tag` param the source's fork doesn't have, and every one of
the 13 existing call sites across llama-kv-cache-dsa/dsv4/msa.cpp,
llama-memory-hybrid*.cpp and llama-model.cpp needed to keep
compiling unchanged. kv_stream_runtime_owner (the function-pointer
table + adaptive resident/ring repartitioning in kv_stream_adapt)
ported as-is.
- llama-model.cpp: wired both call sites that ever construct a plain
llama_kv_cache directly with the model's real type_k/type_v - the
llama_memory_hybrid attention sub-cache (source's only wired call
site) and, generalizing past the source's single-architecture scope,
the plain non-hybrid/non-SWA llama_kv_cache construction used by
ordinary dense models. Every other call site (DSA/DSV4/MSA/iSWA/MTP
drafts) is left passing the new parameters' defaults (disabled),
matching the config layer's architecture exclusions.
- llama-memory-hybrid.{cpp,h}: threaded the same three parameters
through to the inner llama_kv_cache construction, passing an
explicit "" for this fork's name_tag parameter that sits between
`share` and the new parameters.
- llama-memory.h: llama_memory_params gains the three kv_stream fields
create_memory() reads.
- llama-cparams.h: cparams.kv_stream_arena_mib mirrors the public
llama_context_params field.
Test fix: removed the type_pair_supported field and gate I'd added to
llama_kv_stream_config in the previous commit. It duplicated a check
the source implementation already does correctly and more precisely -
llama_kv_cache's constructor queries the actual per-layer (type_k,
type_v) backend capability via a proc-address lookup once the real
device is known, which this fork's earlier, coarser context-level
config can't replicate meaningfully before that point. Updated
test-kv-stream-config.cpp to match.
Regression-tested: q8_0 K/V generation (no --kv-stream) still produces
sane output; all three pure-logic kv-stream unit tests pass (104
assertions). --kv-stream-arena-mib CLI flag wiring (common/arg.cpp)
is next - the arena still isn't reachable from the command line yet.
Assisted-by: Claude
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Wires common_params.kv_stream_arena_mib through to llama_context_params.kv_stream_arena_mib, and adds the --kv-stream-arena-mib flag (--kv-stream-stage-mib kept as a compatibility alias, matching the source's own naming history). Also ports common_params_should_fit_device_memory(), which skips the device-memory auto-fit pass entirely whenever a nonzero arena is explicitly configured. This is the actual fix for the -fit crash TheTom found on PR TheTom#326 and we reproduced empirically this session (-ngl 10 --kv-stream auto threw "not supported for this K/V cache type pair" because a CPU-placed layer failed the streaming gate mid fit-search): the fit search's per-candidate probing is what hit that gate in the first place, and an explicit arena size makes the probing unnecessary - the arena's layout is already fully determined by the user's own -c/--kv-stream-arena-mib, not something -fit needs to search for. speculative.cpp: MTP/draft contexts get kv_stream_arena_mib=0 unconditionally (the source's own choice - the streaming pool doesn't yet support two contexts sharing it). Assisted-by: Claude Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
…dated config
Both ported verbatim in earlier commits, both latent bugs in
RaymondHuang210129/llama.cpp-adaptive-kv-streaming itself that never
surface for its one validated target (Qwen3.8-27B, always hybrid
memory, always head_dim==KV_STREAM_HEAD_DIM==256) but do the moment
this fork's broader model support actually exercises the streaming
path end to end:
1. llama-context.cpp: kv_stream_switch_phase() hard dynamic_cast'd to
llama_memory_hybrid and errored ("phase arena requires hybrid
attention memory") for anything else. Since this fork also wires
the arena through a plain llama_kv_cache (the non-hybrid,
non-SWA branch in llama-model.cpp, generalized in the previous
commit), added a fallback: try the hybrid wrapper first, then a
direct llama_kv_cache cast. Both paths reach the same
kv_stream_resize_pool() call, which doesn't care how it was reached.
2. ggml-cuda.cu: the GGML_OP_FLASH_ATTN_EXT dispatch in
ggml_cuda_compute_forward routed to the streamed kernel whenever
K or V merely had a kv-stream runtime attached, without checking
ggml_cuda_kv_stream_fattn_fits() first - unlike supports_op's
FLASH_ATTN_EXT case a few thousand lines down, which already does
check it. For a streamed cache on a model whose head_dim isn't
exactly 256 (ggml_cuda_flash_attn_ext_streamed_supported hard-codes
Q->ne[0] == KV_STREAM_HEAD_DIM), this reached
GGML_ASSERT(ggml_cuda_kv_stream_fattn_fits(dst)) inside
ggml_cuda_kv_stream_fattn() and aborted instead of falling back.
Added the same fits check to the dispatch condition, matching
supports_op - a streamed cache on an incompatible head_dim now
silently uses plain attention (the streaming kernel's head_dim
restriction stays a real limitation; only the crash is fixed).
End-to-end verified on Qwen3-8B.Q5_K_M (head_dim 128, plain non-hybrid
cache, --kv-stream-arena-mib 512, -ctk/-ctv q8_0):
- No crash; coherent generation output.
- GGML_SCHED_DEBUG=2 shows 2 scheduler splits/eval after the arena
activates - matching the no-streaming baseline exactly, versus the
74 splits/eval measured against PR TheTom#326's implementation earlier
this session. The supports_buft fix from an earlier commit is
confirmed working under real inference, not just at the API level.
- Generation throughput is lower than baseline for this model (head_dim
128 can't use the actual streamed kernel per the limitation above,
so this only exercises the memory-placement change, not the real
page-streaming path) - expected until the KV_STREAM_HEAD_DIM
restriction is generalized, a follow-up beyond this port.
Assisted-by: Claude
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
…aining tests Ports tools/kv-stream-bench/ (pinned-host vs cudaMallocManaged H2D bandwidth probe, arg parsing, dry-run/--execute modes) verbatim - fully self-contained, no dependency on anything reconciled earlier in this port. Wires it into tools/CMakeLists.txt behind GGML_CUDA, matching the source. Also wires the four remaining copied-but-unwired test files now that their dependencies exist: - test-kv-stream-bench-config.cpp (the bench tool's arg parser) - test-kv-stream-cuda-buffer.cpp, test-kv-stream-cuda-attn.cpp, test-kv-stream-cuda-set-rows.cpp (CUDA runtime/kernel tests) One test needed reconciling: "KV stream quant types are classified" in test-kv-stream-cuda-set-rows.cpp iterates every quantized/f32/f16/bf16 ggml_type and asserts ggml_backend_cuda_kv_stream_get_type_capabilities classifies all of them - true on the source's vanilla fork, but this fork's GGML_TYPE_COUNT also includes 8 TurboQuant-specific types (turbo2/3/4, tq3_1s/tq4_1s, q5/6/8_cr) that v1 deliberately leaves unclassified (same graceful-fallback-to-UNSUPPORTED behavior as any other type the capability table doesn't recognize). Excluded those 8 from the loop rather than changing the capability table itself. All 7 kv-stream test binaries pass: 101 tests, 1373 assertions. Assisted-by: Claude Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Ports benchmarks/ from RaymondHuang210129/llama.cpp-adaptive-kv-streaming verbatim - benchmark_kv_stream.py (arena-size auto-probing sweep driving llama-server), benchmark_kv_type_matrix.py, and their own unit tests (pure argument-parsing/resume-signature logic, no GPU or model needed). No reconciliation needed: they drive the CLI by flag name (--kv-stream-arena-mib, --cache-type-k/v) and HTTP, none of which differ from what's already wired up on this branch. Verified: all four scripts byte-compile; the scripts' own test suites pass (11 passed, 1 skipped). This completes the full port planned in /home/jabbatheduck/.claude/plans/lively-forging-platypus.md - core plumbing, CUDA kernels, llama_context/llama_kv_cache wiring, the CLI flag, and now benchmark tooling, all landed on feature/kv-stream-phase-arena and verified end-to-end (KLD ~0 against baseline on both a fallback-path model and the real streaming-kernel target, scheduler split count fixed, dynamic phase switching observed live). Assisted-by: Claude Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Wires TurboQuant's turbo2/3/4 cache types into the F16-conversion
attention mode already used by every other non-direct-attention type:
they get real backing storage, a working online writer
(set_rows_cuda_turbo{2,3,4}), and a to_fp16 dequantizer, so no new CUDA
kernels are needed. Q is unconditionally pre-rotated at the graph level
whenever K/V is turbo, and turbo's dequantize deliberately doesn't
invert that rotation, so the F16 round-trip is correct as-is.
Also fixes two real gaps found while wiring this in:
- ggml_cuda_kv_stream_page_bytes()/workspace_bytes() sized rows off the
raw model head_dim, but turbo storage zero-pads non-128-aligned head
dims to the next multiple of 128 (llama-kv-cache.cpp). Streaming
pages would have been undersized for any non-128-aligned-head-dim
turbo model.
- ggml_cuda_kv_stream_staged_set_rows_range() gated purely on the
online_write capability flag, which would have routed turbo writes
into the true page-staging fast path relying on a dst_row_base
offset that set_rows_cuda_turbo{2,3,4} doesn't support - silent data
corruption rather than a crash. Turbo writes are now forced through
the existing online_write mirror fallback instead.
Separately, found and fixed a pre-existing mismatch between the
streaming bootstrap pre-scan (llama-context.cpp) and the actual
llama_kv_cache construction: turbo's auto-asymmetric feature upgrades
K to q8_0 on high-GQA-ratio models, but the pre-scan sized its
bootstrap pool off the raw requested type, not the upgraded one. This
made the streaming runtime's internal page-count arithmetic
inconsistent and broke turbo streaming outright on any GQA>=6 model
with symmetric turbo K+V - the default case for this fork's actual
users. The auto-asymmetric decision is now a shared helper
(llama_kv_cache_resolve_stream_type_k) called from both places.
Verified: full kv-stream test suite and the broader test suite pass
(one unrelated pre-existing tokenizer-vocab test failure aside).
Functional smoke tests (turbo3/turbo3, mixed q8_0 K/turbo2 V) stream
without crashing. KLD comparison of turbo3/turbo3 streaming (2GB
arena, forcing real page eviction) against non-streaming at 4096
context: mean KLD 0.003, matching the near-zero bar already met for
standard types.
Assisted-by: Claude
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
kv_stream_unified_kv_cache was a pure architecture-name blacklist that
never checked hparams.is_swa_any(). Any non-blacklisted SWA
architecture (e.g. Gemma-style iSWA models, or this fork's own Laguna)
with --kv-stream-arena-mib set would build a real CUDA phase arena,
then hard-crash in kv_stream_switch_phase() once both its dynamic_casts
fail against llama_kv_cache_iswa ("failed to activate shared CUDA
arena prefill phase").
This turns that crash into the existing clean
llama_kv_stream_config_validate() rejection, whose error message
already (until now, falsely) claimed SWA dual-cache architectures were
excluded. Real streaming support for iSWA is tracked as a follow-up;
this exclusion should be narrowed again once that lands, or iSWA
models will get a clean rejection instead of real streaming.
Assisted-by: Claude
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Turbo already has a full native decode-inline CUDA attention kernel
(fattn-vec.cuh's VEC template, plus a fused MMA path in
fattn-mma-f16.cuh) used unconditionally by the ordinary non-streaming
FA dispatch - the streaming capability table just never marked it
direct_attention-eligible, so streamed turbo attention always paid for
a dequantize-to-F16 round trip even when a native kernel was available.
Wires this up (all gated behind GGML_CUDA_FA_ALL_QUANTS, which stays
off by default - documented in docs/build.md as also controlling this
path now):
- get_type_capabilities(): turbo2/3/4 now set direct_attention.
- kv_stream_resolve_native_partial_for_v<type_K>()/
kv_stream_resolve_native_partial(): route to the real
ggml_cuda_flash_attn_ext_vec_partial_case instantiations, which only
exist for turbo paired with {f16, q8_0, turbo2/3/4} - every other
pairing is compile-time excluded (if constexpr) to avoid taking the
address of a template specialization nobody instantiated.
- get_attention_mode(): direct_attention is a per-type capability flag,
but turbo isn't fully pairwise-connected to the original direct set
the way F16/Q4_0/.../Q8_0 are with each other. Added an explicit
pairwise check (kv_stream_direct_attention_pair_supported) so e.g.
(Q4_0, TURBO2_0) - both individually direct_attention-eligible, but
with no instantiated kernel for that specific pair - correctly falls
back to ATTENTION_F16 instead of hitting the DIRECT-mode assert with
a null kernel pointer.
Added a dedicated test for turbo's actual native pairs (self, f16,
q8_0) rather than folding it into the existing "all native CUDA KV
pairs" test, which assumes a fully-connected type set that turbo isn't
part of.
While extending the bounded-fallback test to also cover turbo paired
with non-companion types (Q4_0 etc., which correctly route to
ATTENTION_F16), found the addition triggers a false-positive mismatch:
the shared test harness's decode-row-update simulation writes a
rotation-agnostic row into the plain-F16 reference tensor while the
real turbo-typed cache correctly stays in the WHT-rotated domain,
desyncing the two. Confirmed via direct comparison that the underlying
CPU and GPU turbo dequantize implementations agree closely (~1e-4,
F16-rounding level) - this is a test-harness limitation, not a
streaming or dequantization bug, and not a configuration this fork's
design pairs turbo with in practice. Left out of the fallback test
with a comment explaining why, rather than papering over it.
Assisted-by: Claude
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
ggml_cuda_kv_stream_page_bytes()/workspace_bytes() unconditionally reserved both a K and a V region, sized off head_dim_k/head_dim_v. MLA-shaped layers (llama_kv_cache's has_v == false) have no separate V cache tensor at all - V is a graph-time view/reconstruction over the K/KV-latent tensor (see llama-graph.cpp) - so streaming would have silently reserved a full, entirely unused V region for every MLA layer, doubling the real page/pool size. head_dim_v == 0 now means "no separate V storage, size off K alone" instead of being treated as invalid input. The two call sites (llama-context.cpp's pre-scan, llama-kv-cache.cpp's constructor) pass 0 for MLA layers (hparams.is_mla()) instead of the raw n_embd_head_v(il) - no signature changes needed, head_dim_v was already a plain uint32_t everywhere. This is prep work for exercising the MLA/DSA streaming paths (DSA's kv_mla sub-cache inherits the same K-only shape) - plain MLA (DeepSeek-V2/V3-style) already isn't excluded from streaming today, but was never actually geometry-correct until now. Assisted-by: Claude Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
…x dormant decode-phase switch Adds llama_memory_i::get_kv_stream_targets() and llama_memory_context_i::get_kv_stream_active_targets() - both default to empty, so no unrelated memory type changes - as the uniform way to ask "which sub-cache(s) of this memory object have a CUDA phase-arena streaming runtime attached". Implemented for llama_kv_cache (itself, once it has a runtime) and llama_memory_hybrid (forwards to its attention sub-cache). This replaces the two-case dynamic_cast<llama_memory_hybrid*>/dynamic_cast<llama_kv_cache*> in kv_stream_switch_phase() with a single, extensible lookup - laying the groundwork for iSWA/DSA/MSA/DSV4's sub-caches to report themselves the same way, without hardcoding more per-architecture casts here. Fixes a real, independently significant bug found while doing this: process_ubatch() gated the entire per-ubatch kv_stream_switch_phase() + kv_stream_adapt() call behind dynamic_cast<llama_memory_hybrid*> with no fallback - unlike kv_stream_switch_phase() itself, which already had one. For a plain (non-hybrid) llama_kv_cache - what every model validated on this fork so far actually uses (Qwen3-8B, Qwen3.8-27B) - this meant the phase arena switched into its prefill layout once at construction and NEVER switched to the decode layout, and the adaptive deadline-miss/copy-busy resident:ring feedback loop never ran at all, for the entire lifetime of every context. Confirmed via temporary instrumentation: before this fix, only the one construction-time switch call ever fired; after, a second real switch fires the first time a ubatch enters generation phase. Re-ran the turbo3/turbo3 streaming-vs-non-streaming KLD comparison after this fix (same methodology as the previous phase): mean KLD dropped from 0.003064 to 0.000000 (max KLD 0.000059), combining the benefit of this fix with the native-kernel wiring from the previous commit. Decode now gets the resident-KV allocation the design actually intended instead of running with the prefill layout for the whole session. Assisted-by: Claude Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
llama_kv_cache_iswa (Gemma-style models, and this fork's own Laguna arch) holds two independent llama_kv_cache instances - kv_base (non-SWA layers, full context length) and kv_swa (SWA layers, window-bounded and therefore small by construction, unless swa_full makes it full-length too). Neither constructor overload accepted the streaming triplet at all, so streaming was structurally unreachable through this class regardless of the architecture exclusion list. Both constructors now accept (kv_stream_stage_bytes, kv_stream_phase_arena, kv_stream_maximum_pool_bytes), defaulted to (0, nullptr, 0). kv_base always receives them; kv_swa only receives them when size_swa == size_base (the swa_full case) - otherwise it stays always-resident, since streaming a cache that's already small by construction buys nothing. get_kv_stream_targets()/ get_kv_stream_active_targets() (from the previous commit's generalized interface) concatenate whichever of the two sub-caches actually got a runtime - today that's just kv_base in the common case, with the interface already correct for the swa_full N=2 case once the CUDA arena's single-lease design is generalized (tracked separately, not needed yet since no caller reaches swa_full+streaming today). llama_memory_hybrid_iswa (recurrent+SWA-attention hybrids) gets the same treatment, forwarding into its internal llama_kv_cache_iswa. llama-model.cpp's default-branch iSWA call sites (the actual Gemma/Laguna-shaped case, both the plain and GEMMA4_ASSISTANT-share variants) and the hybrid-iswa call site now thread params.kv_stream_* through. With real streaming support landed, the SWA blanket exclusion added earlier (to prevent the hard crash from an un-plumbed iSWA memory type) is removed - kv_stream_switch_phase's target resolution now fails closed with a clean error for any memory type that still isn't wired up (e.g. llama_memory_hybrid_idx), rather than needing every future case pre-emptively blacklisted here. Verified end-to-end against a real local iSWA model (/mnt/storage/models/laguna/xs/laguna-xs-2.1-nvfp4.gguf, arch=laguna, confirmed via GGUF metadata to have real SWA layers and route through this exact default-branch iSWA path): confirmed via temporary instrumentation that streaming is genuinely enabled (not silently falling back), ran to completion with no crash, and a streaming-vs-non-streaming KL-divergence comparison shows mean KLD ~0.000000 (max 0.000041) and 99.99% same-top-token agreement - streaming is numerically faithful. (The model's own baseline perplexity is anomalously high on this build/quant independent of streaming - flagged separately as unrelated to this work.) Assisted-by: Claude Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
…wasn't the cause, keep it excluded Wires kv_csa (DSV4's compressed KV cache, the sub-cache that scales with context length and is worth streaming - kv_raw's actual per-layer attention runs entirely on its window-bounded SWA half, not its base half, despite the base half's own class comment suggesting otherwise) with the streaming triplet, following the same pattern as MLA/DSA's K-only shape. While validating this against a real local DeepSeek-V4-Flash model (previous work in this area had no real model to test against), found a large, real correctness regression: mean KLD 0.07 (max 4.3) between streaming and non-streaming output, versus ~0.000000 for every other architecture validated this way (turbo, iSWA). The initial hypothesis was a bug in the K-only page-geometry special-case added earlier this branch (ggml_cuda_kv_stream_page_bytes()'s head_dim_v==0 handling): DSV4's compressed-cache attention (models/deepseek4.cpp, build_attn_mha called with k_all passed as both K and V) always needs a real V-shaped region in the streamed page, even though the persistent cache is K-only and that geometry code was treating "K-only cache" as "no V region needed anywhere" - a real, understandable-in-hindsight confusion between "the cache doesn't persist V" and "the attention op doesn't consume V". Tested that hypothesis directly: reverted the head_dim_v==0 special-casing entirely (both in fattn.cu and its two call sites) and re-ran the same KL-divergence comparison. Result was bit-identical (0.071177 mean KLD, unchanged to 6 decimal places) - the geometry special-case was NOT the cause. Kept the revert anyway, since it removes an assumption now proven wrong without any demonstrated benefit, and re-excluded LLM_ARCH_DEEPSEEK4 in the architecture blacklist rather than shipping known-broken streaming for it. The actual root cause is still unidentified - likely somewhere in DSV4's online-compression bookkeeping (comp_plan's state_pos/ state_persist_*/state_snapshot_* row addressing) not surviving the resident-cache/ring-buffer model, but this needs dedicated investigation into that machinery, not more guessing. DSA's kv_mla and plain MLA use the same K-only cache shape as kv_csa; since neither has been empirically tested against a real model either, both should be treated as similarly unverified rather than assumed safe by extension of the (inspection-only) conclusion reached for MLA earlier. The kv_csa constructor plumbing is left in place (harmless, currently unreachable dead code via the restored exclusion) so whoever root-causes this doesn't have to redo it - see the comments in llama-context.cpp and llama-kv-cache-dsv4.cpp for the full context. Assisted-by: Claude Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
…check The pre-scan that sizes the streaming bootstrap pool scanned every attention layer indiscriminately and required them all to share identical page geometry. For iSWA-shaped models this is too strict: kv_swa's layers don't get a streaming runtime at all (unless swa_full), so their geometry is irrelevant to what's actually being sized - and some real models (Gemma-family) have genuinely different per-layer dimensions between SWA and full-attention layers (separate key_length/key_length_swa in the GGUF), which made the pre-scan reject them outright with "block KV streaming requires uniform attention-layer geometry" even though the layers that actually stream (kv_base's) are perfectly uniform among themselves. Now skips SWA layers here the same way it already skips recurrent ones, unless swa_full is set (in which case kv_swa becomes full-context-length too and does get a runtime - see llama-kv-cache-iswa.cpp). Verified against a real local Gemma-family model (/mnt/storage/models/gemma/Gemma4-26B-A4B-QAT-Uncensored-HauhauCS-Balanced-Q4_K_M.gguf, arch=gemma4, confirmed via GGUF metadata to have distinct key_length/key_length_swa and value_length/value_length_swa - exactly the non-uniform-geometry case this fixes): previously failed to load with streaming enabled at all; now loads cleanly, streaming genuinely active (confirmed via temporary instrumentation), and a streaming-vs-non-streaming KL-divergence comparison shows mean KLD 0.000000 (max 0.00006) and 99.99% same-top-token agreement. Re-verified Laguna (iSWA, previously-validated) and Qwen3.8-27B (turbo, plain cache) are unaffected. Assisted-by: Claude Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
…h streaming For an iSWA-shaped cache, --swa-full makes kv_swa full-context-length too, so both kv_base and kv_swa attach a streaming runtime to the same single-lease CUDA phase arena. Previously this was silently accepted by validation and only failed deep in cache construction, whichever sub-cache lost the race to bind the arena, with a generic "failed to create CUDA block KV streaming runtime" error that gives no hint --swa-full is the actual cause. Verified empirically (Laguna, --swa-full + --kv-stream-arena-mib): the failure is a clean, caught exception at context construction, not a crash - so this was never unsafe, just confusing. Adds swa_full_conflict to llama_kv_stream_config so this now fails with a clear, specific reason at the same validation layer as every other known-incompatible combination (SWA architecture exclusion, MTP/draft contexts, non-unified cache, etc). Assisted-by: Claude Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Covers arena-size propagation, the legacy --kv-stream-stage-mib alias, and negative-value rejection - gaps flagged in review against the reference implementation, which had these in its own test suite. "Disabling streaming for draft contexts" (the other gap flagged) isn't testable at this pure CLI-parsing layer - it's speculative.cpp's runtime zeroing of kv_stream_arena_mib for the draft context (common/speculative.cpp:2805), which needs a live model to exercise; already verified manually this session (draft acceptance stats confirm MTP keeps working with streaming enabled on the target context). Assisted-by: Claude Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Previously streaming was documented only in benchmark material and one build-flag note - no single place explained arena semantics, requirements, supported architectures, or known limitations. Consolidates everything found empirically this session: why -np 1 is a real design constraint (not just an unvalidated gate), the two distinct VRAM-boundary failure modes (clean startup failure vs a hard process abort mid-request), which architectures actually work vs are excluded and why, and the --swa-full conflict fixed in the previous commit. Cross-linked from build.md and benchmarks/README.md. Assisted-by: Claude Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
… alone Reverts the cross-link added to benchmarks/README.md in the previous commit - keep that file scoped to the benchmark tooling only. docs/kv-stream.md (linked from build.md) is the place for the feature's semantics, requirements, and limitations. Assisted-by: Claude Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
A no_alloc llama_context (e.g. common_get_device_memory_data_with_parent's
dry-run pass to size the parent model for MTP) never allocates real backend
buffers, so llama_kv_cache's streaming-attach loop already skips attaching a
runtime to it (see the !hparams.no_alloc guard in llama-kv-cache.cpp). The
context-level phase-arena construction had no matching guard, so it built a
real CUDA arena anyway, then kv_stream_switch_phase found no cache attached
to it and failed with a confusing "requires a memory type with a streamable
KV cache" error on every MTP+streaming startup. The failure was caught and
logged as a warning ("[spec] failed to measure MTP context memory") and the
real target context loaded fine moments later, but the error looked fatal.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Measured: llama_set_decode_phase() is never called from the server, so speculative-decoding verification batches (multi-token) always classify as "prompt" phase instead of "generation" - the arena stays in its compute-heavy/KV-light layout almost the entire time MTP is active. Real but modest at 22K context (+2.2% resident pages, +20% ring slots vs the true generation layout). Documented rather than fixed: a real fix needs to resize the generation-phase compute reservation for multi-token speculative batches, not just relax the existing TG1-only guard. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
|
Tried this on a 24 GB laptop card, which is roughly the situation the feature targets. The VRAM Setup: RTX 5090 Laptop (sm_120), driver 616.56, Windows 11, MSVC 14.51, branch at Totals
Off-arena figures are the mean of three clean runs (1167.95/1160.78/1160.50 prefill, Prefill is quadratic with the arena onCumulative rate from the server's own
Off-arena stays flat at ~1340 t/s, i.e. linear prefill. With the arena the cumulative rate falls A bigger arena is much slowerThis is the part that looks wrong rather than merely expensive. At the same 12330-token mark:
7.4x slower with twice the resident capacity. The 4096 run was still at 91% of the prompt For completeness, the arena has a lower bound too — Note on the baselineOn this model What I did not checkWhether output stays correct under streaming — I compared throughput only. Also single arena 🤖 Generated with Claude Code |
…, vector allocs) - Refuse kv_stream_arena construction if TURBO_LAYER_ADAPTIVE is active (mixed types) - Mark internal plan/config tests as static-only (NOT BUILD_SHARED_LIBS) to fix Windows link - Add has_kv_stream_targets() interface to avoid process_ubatch vector allocation when off - Add explicit unsupported throws to seq_rm, seq_cp, and seq_add (K-shift) when streaming
|
I've pushed a commit addressing the remaining feedback items:
Regarding @tmark00's report of quadratic prefill that worsens with a larger arena: |
Conflicts were in three files: - ggml/src/ggml-cuda/fattn-vec.cuh: base added the D=512 decode-only vec case and its DECL_FATTN_VEC_CASE_D512 macro, while this branch changed DECL_FATTN_VEC_CASE to also declare the partial (streamed) case. Both kept. Base's `extern DECL_FATTN_VEC_CASE(...)` form does not work for a two-declaration macro, so the EXTERN_DECL_FATTN_VEC_CASE wrapper on this branch stays; the D512 declarations use base's `extern DECL_...D512` form because that macro is still a single declaration. - ggml/src/ggml-cuda/ggml-cuda.cu: base added ggml_cuda_host_weights_enabled() to the host-buffer allowances in the debug asserts and in supports_buft. Folded into this branch's device-identity check, which also accepts the kv-stream buffer family. - src/llama-context.cpp: both hunks were base-side improvements over reformatting only on this side (the MoE expert-size scan now records the largest expert before the threshold test, and graph_max_nodes gained a DFlash2 selector case). Took base. Also excludes qwen4exp from the streaming gate when it has no SWA. In that shape it builds llama_memory_hybrid_idx, which does not carry the streaming parameters, so the gate would pass and nothing would stream. With SWA it takes the hybrid-iswa path, which does. Verified: llama, llama-bench, llama-cli and llama-server build clean; test-kv-stream-config (11 tests, 47 assertions) and test-kv-stream-plan (37 tests, 241 assertions) pass; test-llama-archs exits 0 with 290 rows and no failures. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FChUMME2m5ZoswFJs2fkQ4
…tators Three cleanups, no intended behaviour change. Remove the region/extent/prefetch planner. llama_kv_stream_plan_make, _extent_make, _regions_make, _prefetch_dispatch and _pool_layout_make had no caller outside their own tests: the phase-arena planner (llama_kv_stream_phase_plan_make) replaced them and the predecessor was never deleted. Only llama_kv_stream_partition_adapt and llama_kv_stream_feedback_delta_make are live, so the headers, sources and test blocks for the rest go, along with the includes and helpers they alone needed. Collapse resident_cache_resize, _reconfigure, _repartition and _set_decode_layout into one _reshape. All four computed a layout and invalidated the resident pages; they differed only in which of the pool size, scratch boundary and decode working set they held fixed, which KV_STREAM_KEEP_BYTES and KV_STREAM_KEEP_PAGES now express. They had also drifted apart: _repartition alone kept mutable_pages across a layout change and _set_decode_layout alone never reset stats. The unified version clears mutable_pages whenever the layout moves, matching the other three (callers re-establish it through mark_dirty_rows on the next ubatch, and the repartition entry point clears runtime dirty rows in the same call), and resets stats when the pool or scratch boundary moved. A repartition that changes only the layout now keeps its stats counters, which is what the other layout-only path already did. Move the seven accessors no llama code calls - stage_bytes, stage_slots, resident_pages_per_layer, pool_bytes, get_stats, stage_upload and stage_download - plus the stats struct out of the installed ggml-cuda.h into ggml-cuda-kv-stream-testing.h, so they stay available to the CUDA tests without sitting on the backend's public ABI. Net 1353 lines removed against 44 added. Verified on CPU: llama, llama-bench, llama-cli, llama-server and test-llama-archs build clean; test-llama-archs produces 290 arch rows byte-identical to before the change with no failures; llama-bench runs prompt and generation on a synthetic qwen3 model unchanged; test-kv-stream-softmax and the surviving config and plan tests pass (config 9 tests/39 assertions, plan 14/64, softmax 3/21, no failures). The fattn.cu, fattn.cuh and ggml-cuda.cu changes are NOT compile-checked: this environment has no nvcc. They need a CUDA build and the test-kv-stream-cuda-* suite on real hardware. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FChUMME2m5ZoswFJs2fkQ4
|
@TheTom I might be able to make this code lighte rweight and and better. |
Hardware verification of
|
| Run | Arena | Resident vs active | PPL |
|---|---|---|---|
| No streaming | — | — | 2.6771 +/- 0.03311 |
| Streaming | 1024 MiB | 31 vs 64 pages/layer | 2.6771 +/- 0.03310 |
LLAMA_KV_STREAM_TRACE=1 confirms the partition controller — the code path _reshape feeds — running every eval (kv_stream_adapt: active 16384, resident 31, ring 23). Roughly half the working set is genuinely coming off host RAM, and perplexity is unchanged to four decimals.
Unit tests: test-kv-stream-plan 14 tests / 64 assertions, test-kv-stream-config 9 / 39, all passing. ctest -R kv-stream: 4/5 (see the known failure below).
VRAM and RAM savings — yes, they are real
-c 131072, same model, from llama.cpp's own common_memory_breakdown_print plus sampled nvidia-smi / VmHWM peaks:
| No streaming | Streaming, 2 GiB arena | Delta | |
|---|---|---|---|
CUDA0 KV (context) |
8341 MiB | 149 MiB | −8192 MiB |
| CUDA0 self (model+ctx+compute) | 25928 MiB | 17736 MiB | −8192 MiB |
| Host KV buffer | 0 | 8192 MiB (CUDA_KV_Stream_Host) |
+8192 MiB |
| Peak process VRAM | 26518 MiB | 19760 MiB | −6758 MiB (−25%) |
| Peak host RSS | 65581 MiB | 73772 MiB | +8191 MiB |
The KV cache moves off the GPU essentially in full: 8341 MiB of device KV becomes 149 MiB, and an 8192 MiB host buffer appears. Peak VRAM drops by 6.8 GiB rather than the full 8.2 GiB because the 2 GiB arena itself lives in VRAM — the saving is KV_bytes − arena_bytes, so it scales with how small an arena you are willing to run. Host RSS rises by 8191 MiB, within a MiB of the host KV buffer, i.e. the cost is the KV cache and nothing else.
Worth noting for the docs: the trade is not free at any arena size — a 6 GiB arena at 16k context showed the cache fully resident (95 resident pages vs 64 active), which is all upside on latency but zero VRAM saving.
Two things blocking wider validation (both predate the cleanup)
1. test-kv-stream-cuda-attn fails on this branch.
tests/test-kv-stream-cuda-attn.cpp:292: GGML_ASSERT(ggml_backend_supports_op(backend, updated_k)) failed
test: "all native CUDA KV pairs preserve streamed prefill results"
I reproduced this at 03eb5ecec (the merge of feature/turboquant-kv-cache), i.e. one commit before the cleanup, and the same test passed on my build at 5738dd601 plus the equivalent cleanup. So it arrived with the base-branch merge — most likely one of the six CUDA commits it brought in (ee8280b8f "cuda: fix FA long-context OOM with compute-buffer f16 KV temp" is the obvious suspect, since it changed how FA's f16 KV temps are allocated). Not bisected further.
2. llama-server and llama-cli cannot run with --kv-stream-arena-mib at all.
got exception: seq_rm is not supported while block KV streaming is active
The guard at src/llama-kv-cache.cpp:827 (added in 5738dd601) throws on every seq_rm. The server calls it on the first task via prompt_clear() (server-context.cpp:478), and common_context_can_seq_rm probes it at startup, so no request ever completes. llama-perplexity is the only usable path today because it uses llama_memory_clear exclusively — which is why all measurements above are perplexity runs.
Returning false instead of throwing does not fix it: common_context_seq_rm (common.cpp:1596) turns a false into GGML_ABORT. This needs a real decision — support full-sequence removal while streaming, or teach the server to treat a streaming context as no-prompt-reuse. Happy to take that on if you want it in this PR rather than a follow-up.
The host-weights gate in ggml_backend_cuda_device_supports_op rejects any op with a source in pinned host memory, admitting only GET_ROWS (and the opted-in MoE expert path). Block KV streaming builds the destination-row index for its SET_ROWS writes in pinned host memory, so every streamed KV write started failing supports_op once that gate landed, taking test-kv-stream-cuda-attn's "all native CUDA KV pairs preserve streamed prefill results" down with it: tests/test-kv-stream-cuda-attn.cpp:292: GGML_ASSERT(ggml_backend_supports_op(backend, updated_k)) failed Admit src[1] of SET_ROWS, which is the index. The reasoning is the one already written above the gate: an index is a few KiB read once per row, not a tensor streamed across PCIe. The value source (src[0]) and the destination (src[2]) are still rejected. ctest -R kv-stream: 5/5 on an RTX 5090, was 4/5. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
llama_kv_cache::seq_rm threw unconditionally while streaming, which made --kv-stream-arena-mib unusable outside llama-perplexity: the server calls seq_rm on the first task through prompt_clear(), and common_context_can_seq_rm probes it during startup, so every request died with got exception: seq_rm is not supported while block KV streaming is active Returning false instead is not an option either - common_context_seq_rm turns a false into GGML_ABORT. seq_rm is safe here. It only edits cell bookkeeping: which positions and sequence ids a slot holds. No K/V bytes move, so the host cache stays authoritative and the resident GPU mirror stays valid. A freed slot is not attended again until some later ubatch writes it through set_rows, which marks the row dirty and refreshes the mirror exactly as it does for a slot that was never used. seq_cp and seq_add (K-shift) keep refusing: the first aliases one slot into a second sequence, the second rewrites K in place on the GPU. Also stop the server from retrying prompt-cache saves on a context that cannot serialize its KV cache. State saving is still refused under streaming by design, and prompt_save was calling into it on every request, logging two errors each time and spending a cache slot on an entry prompt_load could never restore. Now it warns once and disables the save. Verified on an RTX 5090 with Qwen3.8-27B-Q5_0, arena 1024-2048 MiB: llama-server completes requests (70 t/s generation), output is byte-identical to a non-streaming server for three prompts plus a 9748-token one that streams for real (39 active vs 31 resident pages per layer), and llama-cli runs again. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Both blockers from the previous comment are fixed —
|
…l cost
A build without GGML_CUDA_FA_ALL_QUANTS (the default) compiles out the
direct_attention branch of get_attention_mode entirely, so every streamed
K/V pair falls back to dequantizing each page to F16 on every ubatch. That
cost scales with the KV already in the cache, so prefill goes from flat to
roughly O(n^1.7) the moment an arena is enabled - it is not the fixed
factor docs/kv-stream.md described.
Measured on an RTX 5090 (32 GiB, Linux) with Qwen3.8-27B-Q5_0,
-c 65536 -b 2048 -ub 512, identical prompts and flags in both builds,
prefill t/s at arena 1024 MiB:
tokens flag on flag off
3902 3293 1743
11193 3336 975
17490 3171 700
39511 2810 352
Arena off is flat near 2900-3300 t/s in both builds, so with the flag on
streaming costs 4-6% at 40K tokens and without it the same run is 8x
slower than its own baseline, widening with context. Arena size is not the
variable: 4096 MiB lands within 3% of 1024 MiB at every length in both
builds.
Nothing told the user which path they were on, which is how the fallback
gets benchmarked by mistake and read as the feature being slow. Add a
type_pair_direct proc address alongside the existing type_pair_supported,
and have llama_kv_cache log one warning naming the K/V pair that fell back
and the flag to rebuild with. Update the docs section with the table above.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
|
@tmark00 thanks for the report — I reproduced your prefill collapse, and the A/B settles it: your build was missing Two builds of
Arena-off is flat in both builds. With the flag on, an arena costs 4-6% of prefill at 40K tokens. Without it, the same run is 8x slower than its own baseline and still degrading — tokens x10.1 gives time x50, i.e. ~O(n^1.7), which is the curve in your tables. Point-by-point on your report
You noted you did not check correctness. Covered now: streaming output is byte-identical to non-streaming for four server prompts including a 9748-token one, and perplexity is identical (2.6771 +/- 0.03310 vs 2.6771 +/- 0.03311 at Changes pushed
Verified: fires once on a default build, silent with the flag on. |
Ready for another look — @TheTom @tmark00Four commits since the last review round, all verified on real hardware (RTX 5090 32 GiB, Linux, CUDA build with
Verification
Known limitations, unchanged and documented
I think this is ready. Happy to split anything out or dig further into the arena-size cliff if you want it chased on a 24 GiB card. |
|
Fresh pass through the four new commits at 71e3921. The cleanup is a real improvement, the pinned-host I rebuilt One remaining docs change before I clear the review: put the operational limitations near the top of
Those are large enough behavioral differences that a server operator needs to see them before enabling the arena. Once that is in and the fresh CI is green, I’m good with merging this. Thanks for doing the cleanup and, especially, for rerunning the actual 5090 matrix instead of treating the earlier numbers as settled. |
Nothing said how speculative decoding and block KV streaming compose, and the question came up: does the arena take the draft cache too, and does streaming cost MTP its speedup? Neither, as it turns out, but it was only knowable by reading common/speculative.cpp. State it plainly: the draft context is forced to kv_stream_arena_mib = 0, so the MTP draft KV cache stays in ordinary VRAM and only the target streams, and rejected draft tokens roll back through seq_rm, which is bookkeeping-only and safe under streaming. Add the numbers behind that, measured on an RTX 5090 with Qwen3.8-27B-Q5_0 plus its Q4_0 MTP draft, two repetitions per cell. The arena is free while the working set is resident and costs 3-4% once pages genuinely stream; MTP is worth 1.6x at short context, 1.87x at a 9748-token prompt that still fits resident, and 1.28x with the cache actively streaming. Draft and accept counts are identical with and without the arena at a given context, so the draft path itself is untouched. Also record a sharper symptom of the phase-classification gap already documented below: under real streaming pressure the MTP request collects zero decode deadline samples and holds 22 resident pages/layer where the same request without MTP collects 26 samples and settles at 31. The partition controller never adapts because a verification batch is never classified as generation. It costs throughput MTP could have had; it does not cause a regression. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
MTP + block KV streaming: tested, documented in
|
| config | no arena | arena 2048 MiB |
|---|---|---|
| no MTP | 70.3 / 69.8 | 70.7 / 71.5 |
| MTP depth 1 | 101.5 / 104.8 | 101.8 / 104.1 |
| MTP depth 4 | 111.4 / 112.4 | 113.0 / 112.4 |
9748-token prompt, arena 1024 MiB — 39 active vs 54 resident pages/layer, still resident:
| config | no arena | arena 1024 MiB |
|---|---|---|
| no MTP | 69.0 / 69.1 | 67.7 / 68.4 |
| MTP depth 4 | 127.1 / 126.4 | 129.3 / 129.4 |
9748-token prompt, arena 512 MiB — genuinely streaming (39 active vs 22-31 resident pages/layer, copy busy 24.2% on the no-MTP run):
| config | arena 512 MiB |
|---|---|
| no MTP | 66.4 |
| MTP depth 4 | 85.1 |
The arena is free while the working set is resident and costs 3-4% once pages actually stream. MTP is worth 1.6x short-context, 1.87x at 9748 tokens resident, 1.28x with the cache actively streaming. Draft/accept counts are identical with and without the arena at a given context (132/61, 136/60 at arena 1024), so streaming does not perturb drafting.
One finding worth a reviewer's eye
The phase-classification gap already documented in docs/kv-stream.md has a sharper symptom than the "+2.2% resident pages" previously recorded. On the arena-512 runs, the no-MTP request reports samples 26, copy busy 24.2% and settles at 31 resident pages/layer; the MTP request reports samples 0, misses 0, copy busy 0.0% and holds 22. A verification batch is never classified as generation, so no decode deadline feedback is collected at all and the partition controller never adapts off its prefill-shaped split. MTP still wins 1.28x, so this is throughput left on the table rather than a regression — but it means the adaptive partition controller is effectively inert for any speculative workload, which seems worth knowing before the controller's hysteresis logic gets tuned further.
Fixing it still needs the generation-phase compute reservation resized to the true speculative width first, or the TG1 without speculative batches guard at llama-context.cpp:2186 turns the inefficiency into a hard decode failure.
Review asked for the behavioural differences a server operator meets to be visible before they enable the arena, not only in PR discussion. Add an "Operational limitations" section directly after "Enabling it", covering the three features that are unavailable while streaming - prompt caching and llama_state_* serialization, context shift, and seq_cp - with what each one actually does at runtime and why. Note that seq_rm is supported, so ordinary request turnover and speculative rollback are unaffected, and that the re-prefill cost makes the arena a poor fit for chat-style traffic that would otherwise hit a warm prompt cache. Writing that down turned up a gap behind the context-shift row: get_can_shift() did not know about streaming. A model whose shifting is otherwise supported would have passed the startup probe with an arena attached, enabled --context-shift, and then failed mid-request the first time the context filled and seq_add threw. (My own check missed it at first because Qwen3.8 reports n_pos_per_embd() > 1 and so disables shifting for an unrelated reason.) Report shifting as unsupported whenever a streaming runtime is attached, so common_init_from_params disables it at startup with its usual warning. Verified: server with --context-shift and an arena logs "KV cache shifting is not supported for this context, disabling KV cache shifting" at startup and serves requests normally. ctest -R kv-stream 5/5. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
|
@TheTom done in The docs changeNew "Operational limitations" section sits directly after "Enabling it", before "Requirements", as a table of what an operator actually hits:
Plus the practical consequence stated plainly: re-prefilling every request can outweigh the decode-side win at long context, so the arena suits single-shot and long-generation workloads rather than chat traffic that would otherwise hit a warm prompt cache — measure both. And a note that The bug it exposed
I nearly wrote the docs row as "auto-disabled" on the strength of seeing exactly that warning in a test — but it was disabled for an unrelated reason (Qwen3.8 reports Verified: server with Thanks for the Metal-side runs — that covers the half I can't test here. |
ggml_backend_cuda_kv_stream_get_attention_mode() only returns DIRECT in GGML_CUDA_FA_ALL_QUANTS builds, as docs/kv-stream.md describes. The set-rows test expected DIRECT for every native pair regardless, so ctest failed it with 51 assertions on a default build (GB10, sm_121). Read the build option through the backend feature list, the same probe test-kv-stream-cuda-attn.cpp uses, and expect F16 for every pair when it is off. FA_ALL_QUANTS builds keep the old expectations.
TheTom
left a comment
There was a problem hiding this comment.
GB10 (sm_121) results on 461e61a merged onto the current base (92e0cb5, after #372 and #373). This is a default build, so FA_ALL_QUANTS is off, which is the one configuration your 5090 runs didn't cover.
test-backend-ops -b CUDA0, base against this branch:
| op | base | #357 |
|---|---|---|
| FLASH_ATTN_EXT | 8774/8774 | 8774/8774 |
| SET_ROWS | 159/159 | 159/159 |
| GET_ROWS | 119/119 | 119/119 |
| CPY | 256/256 | 256/256 |
| MUL_MAT | 1697/1697 | 1697/1697 |
| MUL_MAT_ID | 979/979 | 979/979 |
The full sweep with CUDA graphs off is 19643/19643 on this branch.
Qwen3.6-35B-A3B Q4_K_M, q8_0 K and turbo3 V, 2 x 16384 tokens: PPL 2.9903 +/- 0.0488 with no arena and 2.9954 +/- 0.0490 with a 1024 MiB arena. The arena run streamed (291 of 1024 pages resident per layer) through the F16 fallback, as the log said it would.
I pushed one fix, b59f340. On this build test-kv-stream-cuda-set-rows failed 51 assertions, because it expected DIRECT streamed attention for every native pair, and ggml_backend_cuda_kv_stream_get_attention_mode() only returns DIRECT in FA_ALL_QUANTS builds, as docs/kv-stream.md says. The fix reads the build option through the same backend feature probe test-kv-stream-cuda-attn.cpp already uses, and expects F16 for every pair when the option is off. FA_ALL_QUANTS builds keep the old expectations. With it, ctest -R 'kv-stream|arg-parser' is 6/6 here (the plan and config tests only build with static libs, so they weren't in this run).
The docs change covers what I asked for, and making get_can_shift() return false under streaming is the right fix for the bug you found. Approving, and I'll merge once CI is green on the new head.
a3d5603
into
TheTom:feature/turboquant-kv-cache
#357 (kv-stream phase arena) added a set of helpers that enumerate the KV cache types the streaming runtime understands. turbo5_0/turbo6_0 were added on a branch that predates it, so they were missing from all of them: - fattn.cu: kv_stream_resolve_native_partial{,_for_v} (K switch and V switch plus the k_is_turbo gate), the classified/online_write/decode_f16/ direct_attention capability switches, kv_stream_direct_attention_pair_ supported and ggml_cuda_kv_stream_padded_head_dim (turbo5/turbo6 pad head dims to a multiple of 128 exactly like turbo4). - ggml-cuda.cu: ggml_cuda_kv_stream_staged_set_rows_range must reject turbo5/turbo6 too. set_rows_cuda_turbo5/6 ignore the row-base offset the page-staging path passes, so without this the staged path would have written every dirty row at the wrong offset. - llama-kv-cache.cpp: llama_kv_cache_resolve_stream_type_k and the llama_kv_cache_turbo_layer_adaptive_type_k/_v helpers the streaming bootstrap pre-scan calls. - tests/test-kv-stream-cuda-attn.cpp: turbo5/turbo6 in the turbo direct-attention pair test (HEAD_DIM is 256, one of the two head dims they have vec instances for), and backend_supports_plain_kv_pair now mirrors ggml_cuda_fattn_turbo56_pair_supported so default builds skip pairs with no instance instead of failing. Also fix fattn-vec.cuh: #357 made DECL_FATTN_VEC_CASE expand to two explicit instantiations (the ordinary case plus the new partial_case), so the turbo5/turbo6 `extern DECL_FATTN_VEC_CASE(...)` lines made the partial_case an explicit instantiation definition in a header. Use the new EXTERN_DECL_FATTN_VEC_CASE for all 48 of them.
Block KV cache streaming: bound VRAM at long context via a shared CUDA phase arena
Summary
Adds experimental block KV cache streaming, ported and generalized from
Raymond Huang's
feature/kv-stream-phase-arena(https://github.com/RaymondHuang210129/llama.cpp-adaptive-kv-streaming). His
implementation is Qwen3.5-only; this generalizes the same shared CUDA
phase-arena design to any architecture with a standard, uniform-per-layer KV
cache (plain dense/MoE,
llama_memory_hybrid, iSWA), wires it intoTurboQuant's native
direct_attentionkernels (turbo2/3/4), and validates itagainst real local models rather than by inspection.
With streaming on, only a resident subset of KV pages plus the active
compute workspace live in one bounded CUDA allocation; the rest of the KV
cache lives in host RAM and streams on demand. Enabled with
--kv-stream-arena-mib N;0(default) disables it and behavior isunchanged.
All raw evidence (results.csv/.jsonl for every sweep and llama-perplexity
logs for every correctness check - every number in the tables below comes
straight from these) is committed at
benchmarks/results/kv-stream-pr-evidence/(excludes the multi-GB saved-logits
.kldfiles - regenerable with--save-all-logitsif needed).What's new since the port
direct_attentionpath (measured ~2xprefill speedup on Qwen3.8-27B: ~1390 -> ~2930 t/s). This wiring benefits
ordinary non-streamed attention unconditionally, but streamed
attention only takes the
direct_attentionpath when ggml-cuda is builtwith
GGML_CUDA_FA_ALL_QUANTS(off by default) - without it, everystreamed KV pair falls back to a slower F16-dequant path (measured
~2840 -> ~1200 t/s streamed prefill at 8K context, same model/types).
See "Attention dispatch: direct vs F16 fallback" in
docs/kv-stream.md.process_ubatch()never switched the phasearena into decode layout for any plain (non-hybrid)
llama_kv_cache-every model tested had been running decode with the prefill layout for
its entire lifetime. Fixing it dropped streaming-vs-non-streaming mean
KL-divergence from 0.003 to ~0.000000.
dynamic_caststo
llama_memory_i::get_kv_stream_targets(), so an unsupported memorytype fails closed with a clear error instead of a hard crash.
Gemma-family, this fork's own
lagunaarch): the full-attention(
kv_base) sub-cache streams, the sliding-window sub-cache staysresident (small by construction).
correctness regression (mean KLD 0.07 vs ~0.000000 for every other
architecture) and reverted it rather than ship it. DSA/MSA/MLA remain
excluded or unverified for the same reason - see
docs/kv-stream.md.
--swa-fullsilently conflicted with streaming (both iSWA sub-cachestried to bind the same single-lease arena); now rejected explicitly
with a named reason instead of a generic construction failure.
no_allocdry-run context (used by-fit's auto-probe and by MTP'sparent-memory-sizing pass) built a real CUDA arena anyway, then failed
with a confusing "requires a memory type with a streamable KV cache"
error - benign (the real context loads fine moments later) but
alarming. Now skipped cleanly for
no_alloccontexts.docs/kv-stream.md: requirements, architecture support matrix, whysingle-sequence-only is a design limitation and not a validation gate,
arena sizing guidance, and a known-inefficiency note (see below).
benchmarks/benchmark_kv_memory.py: sweeps context length andrecords GPU VRAM + host process RSS, with a same-context no-streaming
baseline at every point (including past the point where the baseline
OOMs), and plots both. Unlike the throughput sweep it needs no
prefill/decode pass, so it's cheap enough to cover much wider ranges.
Architecture support
llama_kv_cache)llama_memory_hybrid(recurrent + attention, e.g. Qwen3.5)laguna)Benchmarks
All runs: single RTX 5090-class GPU (32 GiB),
-ctk q8_0 -ctv turbo4 -fa on --parallel 1, fixed 8192 MiB shared arena, ggml-cuda built withGGML_CUDA_FA_ALL_QUANTS=ON, viabenchmarks/benchmark_kv_stream.py(prompt = context - 256 tokens, decode 256 tokens, prompt not cached). A
default build (flag off) gets materially lower streamed prefill throughput
at the same context/arena size - see "Attention dispatch: direct vs F16
fallback" in
docs/kv-stream.md.Qwen3.8-27B (dense/hybrid, no speculative decoding)
17 points, 8K -> 262K context. Smooth, continuous decline in both prefill
and decode throughput as context grows - no cliff, no crash, right through
the model's native 262K training context.
VRAM grows only ~1 GiB (28.1 -> 29.1 GiB, ~3.5%) across a 32x increase in
context (8K -> 262K) - the fixed 8192 MiB arena plus a small amount of
bookkeeping overhead that scales with layer/page counts, not with total
context. Full per-point data:
qwen3.8-27b-throughput/results.csv.Correctness (streaming vs non-streaming), this checkpoint:
Mean KLD is at the numerical noise floor at both scales. 32K is the more
meaningful check: host RSS measurements (see "VRAM and host RAM" below)
confirm real page streaming is active by that point, not just a
fully-resident no-op. Full methodology and a larger-scale attempt (and the
tooling limitation it hit) are in "Correctness: PPL and KL-divergence, at
increasing scale" below. Raw logs:
kld-logs/.Qwen3.8-27B + MTP speculative decoding (
--spec-type draft-mtp --spec-chain 8)5 points, 8K -> 106K context. Streaming coexists cleanly with MTP on the
target context (MTP's own draft context never streams - see docs). Draft
acceptance on this benchmark's synthetic repeated-filler prompt was
measured at ~100%, so these decode numbers are a best-case ceiling, not a
typical-prompt expectation - treat the shape of the curve as
representative, not the absolute numbers.
Full per-point data:
qwen3.8-27b-mtp-throughput/results.csv.Required a small fix to
benchmarks/benchmark_kv_stream.py: its exactprompt/decode token-count check had never been run against speculative
decoding before, and MTP's chunked verification (up to
spec_chain+1tokens per step) can clip the last chunk a few tokens short of the target
right at the context boundary. Added a bounded tolerance derived from
--spec-chain; the reporteddecode_tpsis unaffected either way (it'sthe server's own measured rate, not derived from the target count).
Gemma-4-26B-A4B-It (MoE, iSWA)
6 points, 8K -> 131K context, using the proper instruction-tuned checkpoint
(
gemma-4-26B-A4B-it-UD-Q5_K_S, Unsloth dynamic quant - an earlier passused a community "Uncensored" merge; see the correctness section below for
why it was swapped). Prefill is much faster than Qwen (MoE, ~4B active
params/token vs Qwen's dense 27B). Decode falls off far more steeply than
Qwen's dense/hybrid curve.
Full per-point data:
gemma4-it-throughput/results.csv.Numbers are within noise of the earlier (worse-quant) checkpoint's run,
which rules out quantization/merge quality as the cause of the steep decode
falloff - it's reproduced almost exactly across two unrelated checkpoints of
the same architecture. VRAM is flat (27.8 -> 28.2 GiB) across the whole
16x context range - same arena-boundedness result as Qwen, on a
structurally different (MoE + iSWA) architecture. Streaming itself is
stable (no crash, no errors) through the whole sweep; the falloff looks
architectural (MoE expert routing and/or the mixed full+SWA cache
structure) rather than a streaming-specific regression, but hasn't been
root-caused against a non-streaming Gemma4 baseline - flagging as an open
question rather than asserting a cause.
VRAM and host RAM: where the data actually goes, and what happens without streaming
benchmarks/benchmark_kv_memory.py(new in this PR - see "What's new")sweeps context length and records GPU VRAM and host process RSS, with a
same-context no-streaming run alongside the streaming one at every point.
It's cheap (no prefill/decode needed - the buffers are sized at context
construction) so it can cover a much wider range than the throughput sweep.
Qwen3.8-27B-AD, 131K -> 786K context (YaRN-scaled past the 262K
training context, 4x,
--rope-scale 4 --yarn-orig-ctx 262144):No-streaming hits a real
CUDA error: out of memoryabort at 393K (fullgdb-style backtrace:
qwen3.8-27b-memory/logs/baseline-393216.log-inside the server's own warmup decode, not a clean pre-flight allocation
failure, an in-flight kernel abort, matching the "hard process abort near
the VRAM ceiling" failure mode in
docs/kv-stream.md). Streaming keepsgoing another 6x further (to 786K, the max tested) with VRAM pinned to
~28.3 GiB throughout, while host RSS absorbs the growth (4.4 -> 20.6 GiB).
Full per-point data:
qwen3.8-27b-memory/results.csv.Gemma-4-26B-A4B-It, 65K -> 393K context:
No-streaming never hit its ceiling in this range (21.4 -> 25.4 GiB, still
under budget at 393K) - most of Gemma4's layers are small fixed-window SWA
attention that doesn't grow with context, so its non-streaming footprint
grows much more slowly than Qwen's dense/hybrid cache. Streaming stays flat
at ~28 GiB across the same range. Not every architecture needs streaming at
the same context threshold, but streaming costs nothing extra either way.
Full per-point data:
gemma4-it-memory/results.csv.Correctness: PPL and KL-divergence, at increasing scale
A short check is a weak check here. The mechanism this PR is actually
about - page residency, eviction, and ring-buffer streaming - only
activates once the resident window is a real fraction of the total
context. An early pass validated at
-c 4096against an 8192 MiB arena,which likely fits entirely resident with little real eviction exercised.
Repeated at increasing scale, on the exact checkpoints benchmarked above
(
llama-perplexity, wikitext-2-raw, non-streaming logits saved via--kl-divergence-base, compared against a streaming--kv-stream-arena-mib 8192run of the same chunks):Mean KLD stays at the numerical noise floor at every scale tested, and
same-top-token stays at ~100% - streaming reproduces each model's own
output distribution, at a context large enough (32K) that host RSS
measurements above confirm real page streaming is active, not just a
fully-resident no-op. A 131K attempt on Qwen hit a tooling limitation in
llama-perplexity's own KL-divergence machinery (failed reading log-probs for chunk 0against a 27 GB saved-logits file, failing immediately ratherthan partway through - looks like a pre-existing limit unrelated to
streaming, not something this PR introduced) rather than a real finding
either way; flagging as an open item rather than a validated result at
that scale. Raw log:
kld-logs/qwen-streaming-131k-FAILED-tooling-limitation.log.Gemma4-It's raw PPL is unusually high on wikitext for both runs equally
(confirmed coherent in normal chat use - see
kld-logs/gemma4-it-coherence-check.log)poorly on raw non-chat continuation, a known effect, not a fork bug. Ruled
out turbo K/V quantization and Flash Attention as causes by reproducing the
same result with plain f16 KV cache and with
-fa off(seekld-logs/gemma4-it-f16-check.logandkld-logs/gemma4-it-nofa-check.log).KLD - the metric that actually measures streaming fidelity, independent of
whether the base distribution is "good" at modeling wikitext - shows no
divergence regardless.
Gemma4 + MTP: not applicable
Confirmed on two independent checkpoints (the community merge and the
official instruct release) - neither has
nextntensors (checked viadirect GGUF metadata read), so
--spec-type draft-mtpfails outright onboth:
context type MTP requested but model doesn't contain MTP layers.This is an architecture-wide limitation (the Gemma4 family wasn't trained
with an MTP/NextN head in these public releases), not a streaming
limitation or a quant/merge quality issue. No streaming-specific finding
here either way.
Known limitations (see docs/kv-stream.md for full detail)
-np 1). Not a conservative gate - theresident-page design indexes pages by absolute buffer offset, the decode
fast path assumes exactly one query token, and the adaptive
repartitioning loop tracks one global counter. Real multi-sequence
support needs a sequence dimension added to all three; not attempted.
common/speculative.cpp- the draft/target contexts don't yet share onepool). Streaming on the target context is unaffected and verified
working with MTP active (see benchmarks above).
generation layout (server never calls
llama_set_decode_phase()).Measured: 89 of 90 decode steps in a real MTP+streaming session ran in
the prompt-phase layout (1246 resident pages/layer, 10 ring slots)
instead of the generation layout (1273 resident pages/layer, 12 ring
slots) - a real but modest gap at this context size. Fixing it requires
resizing the generation-phase compute reservation for multi-token
speculative batches, not just relaxing the existing TG1-only guard.
Documented, not fixed, to avoid touching stable repartitioning logic for
an unmeasured-at-scale win.
one CUDA device today.
Testing
test-kv-stream-config: 11 tests / 47 assertions, 0 failures.test-arg-parser: full suite passes, including new coverage for--kv-stream-arena-mib/--kv-stream-stage-mib(legacy alias), negativerejection, and 0-disables-cleanly.
llama-perplexity --kl-divergence-base/--kl-divergence) on everysupported architecture: mean KLD ~0.000000, >99% same-top-token for
turbo/iSWA. DSV4 was the one architecture that failed this bar (0.07
mean KLD) and is excluded as a result. Re-verified against the exact
Qwen3.8-27B-AD and Gemma-4-26B-A4B-It checkpoints used in the benchmarks
above at increasing context (4K and 32K for Qwen, 4K for Gemma4) - see
"Correctness: PPL and KL-divergence, at increasing scale" - mean KLD at
the noise floor at every scale tested, confirmed at a context (32K)
large enough that host RSS growth shows real page streaming is active.
benchmark_kv_memory.py(new): VRAM stays flat while no-streaming growsuntil a real CUDA OOM abort at 393K context (Qwen3.8-27B) - streaming
ran 6x further with no VRAM growth. Full backtrace in
qwen3.8-27b-memory/logs/baseline-393216.log.llama-serverinvocation (mmproj +MTP +
-c 226000+ streaming) served real chat completions withmeasured MTP draft acceptance for 2+ hours without incident.
Credits
Original shared-phase-arena design and its Python benchmark tooling by
Raymond Huang (https://github.com/RaymondHuang210129/llama.cpp-adaptive-kv-streaming).
This PR generalizes it beyond Qwen3.5 to TurboQuant's supported
architectures and turbo K/V quantization types, and adds the fixes and
validation described above.