Skip to content

voxcpm2: size KV step caches to the request, cut per-request zero-fills and per-token round trips - #921

Closed
sander110419 wants to merge 2 commits into
0xShug0:mainfrom
sander110419:voxcpm2-kv-perf
Closed

sander110419 wants to merge 2 commits into
0xShug0:mainfrom
sander110419:voxcpm2-kv-perf

Conversation

@sander110419

@sander110419 sander110419 commented Oct 15, 2026 •

Copy link
Copy Markdown

Closes #917.

Summary

The voxcpm2 decode loop sized both KV caches at config.max_length (8192, f32) and attended over the full cache every token, and TransformerKVCache.import_state zero-filled and uploaded the whole capacity twice per request (reset + prefill import). This PR sizes the step graphs to each request's real need, zeroes caches once at build, imports only the valid prefix, and trims several per-token host round trips in the generator. No behavior change: output is bit-identical before/after (see below).

Root cause

  • Step attention ran over 8192 f32 rows per token per layer regardless of sequence length: full-cache ggml_cont after the transpose, f32->f16 conversion inside the fattn vec path, then a masked pass over all rows. On the VoxCPM2 config (28+8 layers, 2 KV heads x 128 ch) that is ~67 MB of traffic per layer-token, ~2.4 GB/token total.
  • import_state wrote cache_steps * step_elems zeros per layer per request; ~1.2 GB moved per request for a few hundred valid rows.
  • Text embedding ran one graph compute + sync per prompt token; the projection call downloaded 8 outputs and used 2-3; DiT re-uploaded constant conditioning every step; AudioVAE snake ops materialized a full-size ggml_repeat per activation.

Changes

  • VoxCPM2MiniCPMStepRuntime: ensure_capacity(prefill_rows + max_tokens) per request, 256-step buckets, rebuild only when a request needs more than the built capacity. max_length remains the hard cap.
  • TransformerKVCache: new reset_counters() and opt-in import_prefix_only (f32, non-ring; default path unchanged for other model families). voxcpm2 step runtimes zero caches once at build, then reset by counters and import only the valid prefix.
  • Batched text embedding: one get_rows graph per request (bucketed by 16) instead of a synced single-token compute per prompt token.
  • Step projection split into emit/advance subset graphs over the same context: per-patch call downloads 3 outputs (DiT conditioning + stop logits), per-token advance call downloads 2 (fsq_hidden + residual_input).
  • CFM: mu/cond uploaded once per patch; the t/dt sinusoidal schedule computed once per request.
  • AudioVAE decoder: snake alpha and sample-rate conditioning use broadcast mul/div instead of ggml_repeat copies.

Update (second commit): added a small LRU of per-length prompt-prefill graphs in VoxCPM2PromptPrefillRuntime. Rebuilding the prefill graph on every text-length change turned out to perturb ulp-level numerics enough to flip the autoregressive draw: on-device, the first request after a length change produced a shorter, faster, off-voice generation, while steady repeats were stable and reproducible. With the cache, mixed-length traffic stays on the warm draw: same input text now returns byte-identical audio regardless of what preceded it (verified across short/paragraph/medium alternation, per-sample diff). This also removes the per-length rebuild cost (~50-135 ms) from requests that revisit a recent length.

Validation

Backend: CUDA, Jetson Xavier NX (Volta sm_72, CUDA 11.4, unified memory), voxcpm2 Q4_K GGUF (audio-cpp/audio.cpp-gguf), AudioVAE f16, streaming session, fixed seed 1234. Also compile-checked on x86_64 (CPU build), and transformer_kv_ring_test passes (ring + non-ring regression paths).

Parity: output PCM bit-identical before/after (per-sample diff, maxdiff=0) on both a short text and a ~15 s paragraph, same fixed seed.

Long-lived session, same voice preset, multiple sequential requests including a long-form paragraph through the text chunker; step-cache capacity logged via the voxcpm2.lm_step_cache_capacity trace scalar (256 for the short requests, 768 for the paragraph) and reused across requests. Numbers are the median-looking steady state with an unrelated whisper.cpp server resident on the board:

request before after
warm short reply (2.7 s audio) 5.29 s wall, 0.96 s to first audio 3.28 s wall, 0.62 s to first audio
paragraph, 15.2 s audio 25.4 s (RTF 1.67) 16.2-16.6 s (RTF 1.07-1.09)
cold start (lazy load + first request) ~29 s 17.5 s
KV cache allocation per request ~605 MB 19-38 MB

The lower allocation also removed the per-request spike that was getting the server OOM-killed on this 6.8 GB board with other services resident.

Known limits: CUDA graphs stay off on sm_72 (ggml disables them by arch; force-enabling crashes at cudaGraphInstantiate on Tegra), so the per-token sync count is reduced but not eliminated. f16 KV storage was left out deliberately: after this change the remaining attention traffic is small and f32 keeps the numerics untouched.

@0xShug0

0xShug0 commented Oct 15, 2026

Copy link
Copy Markdown
Owner

@sander110419 The optimization does reduce memory: CUDA clone-stream peak drops 5,396 -> 4,160 MiB, but corrupted output (default path) in my tests.

Backend Main audio PR audio Main RTF PR RTF
CUDA 6.72 s 17.92 s 0.186 0.145
Vulkan 6.72 s 17.92 s 0.362 0.308
CPU 6.88 s 17.92 s 3.658 2.671

before_main_cuda_correct.wav
after_pr921_cuda_corrupted.wav

Restoring only per-step conditioning uploads makes all six CUDA outputs byte-identical to the working mem_saver=false path.

…lls, trim per-token round trips

- VoxCPM2MiniCPMStepRuntime: build step graphs at the request's real need
  (prefill rows + max_tokens, 256-step buckets) instead of config.max_length;
  attention no longer runs over 8192 f32 rows per token regardless of content
- TransformerKVCache: add reset_counters() and opt-in import_prefix_only;
  step runtimes zero caches once at build and import only the valid prefix
  (was: full-capacity zero fill + upload on reset and again after prefill)
- batched text embedding (one get_rows per request instead of one synced
  single-token graph per prompt token)
- step projection: split into emit/advance subset graphs; each call computes
  and downloads only the outputs it consumes (3 resp. 2 of 8)
- CFM/DiT: upload mu/cond once per patch; precompute the sinusoidal step
  schedule once per request instead of per patch per step
- AudioVAE: broadcast mul/div for snake alpha and sr-conditioning instead of
  materializing a full-size ggml_repeat copy per activation
- prompt prefill: keep a small LRU of per-length graphs instead of rebuilding
  in place on every length change; a fresh rebuild perturbs ulp-level numerics
  enough to flip the autoregressive draw (observed as a shorter, faster,
  off-voice first request after any length change), so caching makes repeated
  same-length requests reproducible
@sander110419

Copy link
Copy Markdown
Author

@sander110419 The optimization does reduce memory: CUDA clone-stream peak drops 5,396 -> 4,160 MiB, but corrupted output (default path) in my tests.

Backend Main audio PR audio Main RTF PR RTF
CUDA 6.72 s 17.92 s 0.186 0.145
Vulkan 6.72 s 17.92 s 0.362 0.308
CPU 6.88 s 17.92 s 3.658 2.671
before_main_cuda_correct.wav after_pr921_cuda_corrupted.wav

Restoring only per-step conditioning uploads makes all six CUDA outputs byte-identical to the working mem_saver=false path.

Yeah you are indeed correct, I'll fix it

Hoisting mu/cond uploads to once per patch corrupted output on the default
path in review testing (see PR discussion); restore the estimator's original
per-call upload semantics. The request-invariant sinusoidal step schedule
cache stays. Verified on-device: output remains byte-identical to the
pre-hoist build on CUDA (Jetson, mem_saver=false), and the emit/advance split,
KV sizing, prefix-only import, batched embedding and VAE broadcast changes are
unaffected.
@sander110419

Copy link
Copy Markdown
Author

Thanks for the careful test — that was the decisive clue. I've pushed a commit that restores per-step mu/cond uploads in the CFM loop (the estimator keeps its original per-call upload semantics); the request-invariant sinusoidal schedule cache stays since it is pure CPU-side precompute. On my Jetson (CUDA, mem_saver=false) output remains byte-identical across the revert, so if your six-path matrix is easy to rerun, could you check this version on the default path? Everything else in the series is untouched: KV sizing, prefix-only import, batched embedding, emit/advance split, VAE broadcast ops.

@0xShug0

0xShug0 commented Oct 15, 2026

Copy link
Copy Markdown
Owner

@sander110419 New regression... Cached prefill graphs corrupt A -> B -> A requests with voxcpm2.mem_saver=false

Request Base Updated PR
First A 5.60 s, correct sentence 5.44 s, correct sentence
A after B 5.60 s, correct sentence 0.64 s: “What.”
A after cache eviction 5.60 s, correct sentence 5.44 s, correct sentence

after_pr921_cuda_a_repeat_corrupted.wav
before_base_cuda_a_repeat_correct.wav
diagnostic_positions_refresh_cuda_a_repeat_correct.wav

@sander110419

Copy link
Copy Markdown
Author

I'll spend some more time on it, seems to indeed cause new issues

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.

voxcpm2 decode path: attention runs over the full max_length KV cache every token, plus ~1.2 GB of per-request cache zero-fills

2 participants