Repository navigation
perf(moss_tts_nano): incremental decode with a K/V cache - #878
Conversation
The global transformer re-forwarded the whole transcript on every generated frame
(rows = prompt rows + max_new_frames, all of them recomputed each step) and the
local frame decoder rebuilt and re-ran its whole plan per frame, so synthesising an
utterance cost O(n^2) work. Both now run incrementally:
* The global runtime keeps a per-layer K/V cache (`TransformerKVCache` style:
persistent K/V tensors written in-graph from the fresh rows via
`FastKVSetRowsModule`, explicit causal+fresh-row mask, RoPE positions read from
the cache in graph mode, so prefill and decode share one graph shape).
* The prompt is forwarded once by the new `prefill()`; every later frame appends a
single row through `step_into()`.
* K/V rows shared with the previous prompt are reused (`prefill(..., reuse_rows)`),
which removes the ~70-row chat template from the 2nd utterance of a session on.
* The local frame decoder keeps its per-codebook graphs and an incremental frame
cache, so a frame costs one forward per codebook instead of re-running the frame
decoder per codebook.
Measured on 54 frames of audio (i7-14700K desktop / Redmi Note 17 Pro):
desktop: RTF 4.5 -> 0.17 (--threads 16)
phone: RTF 5.85 -> 0.82 (--threads 3; >=6 threads is much slower)
prompt prefill, 2nd+ utterance in a session:
54.6 ms -> 7.4-11.4 ms (desktop), 204 ms -> 41-70 ms (phone)
Single-utterance output is byte-identical to the previous build; prefill, chunked
prefill, decode steps, prefix reuse and prompt changes are covered by the new
`moss_tts_nano_kv_cache_parity` test (passes with native weights at max_abs = 0).
The `on_frame` streaming callback added in #870 is preserved.
|
@SkYContact Thanks for the PR. The perf gain is crazy, however there are two merge blockers: (1) CUDA Q8 quality regression. With input “The harbor is quiet this morning,” reference a.wav, seed 1234, and max_tokens=300:
(2) The PR incorrectly treats the 128 MiB graph arena as a limit on the K/V buffer. A valid Could you investigate and fix these issues?
|
… CUDA Address both review blockers on the K/V cache change: 1. Q8 audio corruption on CUDA: with quantized weights, the single-row decode matmuls select the mmvq kernels (batch <= 8) while batched prefill selects the mmq kernels, and the two families are not numerically equivalent. Measured on the parity test: ~5% per-step hidden-state drift (decode vs prefill) on CUDA with q8_0, bitwise exact on CPU, ~0.15% with f32 weights; the drift compounds over the autoregressive frame loop into the reported corrupted audio and repetition loops. The transformers now upgrade quantized weight storage to f16 on CUDA/HIP (resolve_transformer_weight_storage), which brings the drift down to ~0.6%, below the bf16 configuration that was already verified to pass. 2. max_tokens=2000 was rejected because begin_generation compared the K/V cache size against the 128 MiB decode graph arena. The K/V data is allocated in its own backend buffer (ggml_backend_alloc_ctx_tensors) and never touches the graph arena, so the bogus check is removed; a max_tokens=2000 request now succeeds (~3.1 GB peak footprint). The parity test gains --backend cpu|cuda|vulkan and a backend/storage aware default tolerance: 0.001 on CPU with unquantized weights (bitwise exact there), 0.05 on CPU with quantized weights (decode stays exact but re-batched prefill shifts quantized GEMM tilings by a few percent), 0.02 on GPU (cublas GEMV-vs-GEMM batching residual after the f16 upgrade). With --backend cuda the pre-fix q8_0 run fails at ~5.4% and the upgraded run passes at ~0.6%.
|
Thanks for the detailed report — both blockers are addressed in e264dae. 1. CUDA Q8 quality regression — root cause and fixThe K/V cache logic itself is provably correct: on CPU the parity test (
The batch boundary is directly visible in the parity test (CUDA, q8_0):
Since bf16 passes your checks, drift up to ~1.5% is survivable for this model. The fix: the moss_tts_nano transformers now upgrade quantized weight storage to f16 on CUDA/HIP ( One honest caveat: I could not reproduce the audible corruption on my GPU (RTX 5070 Ti Laptop, Blackwell sm_120, CUDA 13.0). Your exact harbor case (a.wav, seed 1234, max_tokens=300) and a 620-char clone both come out clean on the pre-fix build here — kernel selection also varies by compute capability, so the drift apparently doesn't tip these cases into collapse on sm_120. The 5% drift itself is present on my card too (table above), and with the fix it drops to ~0.6%, below the bf16 configuration you already verified. Could you re-run your repro on your hardware against e264dae? 2. max_tokens=2000 rejection — fixedAgreed, that check was a category error: the K/V tensors are allocated in their own backend buffer ( Test changes
|
|
@SkYContact Thanks, and PR merged! Since the issue appears to be hardware-dependent, I suggest not forcing FP16. Instead,
Would you like to open a follow-up PR to do that? |
…l for quantized GPU runs, q8/CUDA docs follow-up (#885) * docs(moss_tts_nano): keep q8 native, document CUDA/HIP incremental drift Follow-up to #878 per review: keep quantized weights native (the automatic f16 upgrade is reverted) and document that incremental Q8 decoding on CUDA/HIP may drift numerically from the batched prefill path in a hardware-dependent way, with f16 GGUFs or moss_tts_nano.weight_type=f16 as the recommended mitigation. - docs/models/moss_tts_nano.md: new 'Quantized weights on CUDA/HIP' section and a pointer from the weight_type option row - loader.cpp: session-option help describes the drift and the f16 mitigations instead of the removed upgrade - kv_cache_parity: auto tolerance is storage-aware on GPU too (0.1 for quantized, where the drift is expected behavior; 0.02 otherwise) - assets.{h,cpp}, global_transformer.cpp, local_frame_decoder.cpp: drop resolve_transformer_weight_storage and load the requested type directly * feat(moss_tts_nano): prefill_mode=single_row option for quantized GPU runs Adds moss_tts_nano.prefill_mode=batched|single_row (default batched). single_row forwards prompt rows one at a time through the single-row decode graph instead of a batched prefill graph, so with quantized weights the whole trajectory — prompt rows and generated frames — runs through the same batch-1 matmul kernels and stays numerically self-consistent on backends whose batched and single-row quantized kernels differ (CUDA/HIP mmvq vs mmq; see the docs section). Verified on CUDA q8_0: single-row chaining is bitwise exact on every backend tested (parity 'single-row chain vs full' = 0), and end-to-end clone runs stay clean with RTF essentially unchanged (0.146 vs 0.170 short / 0.061 vs 0.055 long) — the prebuilt decode graph avoids the per-call batched-graph construction that paid for the extra launches. - global_transformer: MossTTSNanoPrefillMode ctor param + single-row branch in prefill() reusing step_into - session/loader: option parsing, whitelisting, and help text - kv_cache_parity: new single-row chaining check (exact everywhere) - docs/models/moss_tts_nano.md: document the option as the no-extra- memory mitigation alongside the f16 recommendations * perf(moss_tts_nano): keep the encoded reference across requests prepare() encoded the speaker reference on every request, so a session that kept one voice re-ran the audio tokenizer encoder once per utterance -- a full encoder forward, and the dominant part of preparing a cloning request. prepare() now only records the reference and invalidates the codes when the audio actually changes; reference_codes_for_request() keeps the result and encodes on demand, so the encoder runs once per distinct voice instead of once per utterance. The reuse rules are two free functions (invalidate_reference_codes_if_changed / reference_codes_reusable), which lets them be covered by a model-free test that runs without a downloaded model. Verified on Android arm64: builds, moss_tts_nano_reference_cache_test passes, kv_cache_parity still passes, and the chunked cloning path keeps its prefix reuse (179 -> 26 forwarded rows). * feat(moss_tts_nano): declare prefill_mode in the model spec prefill_mode was handled by session.cpp and advertised by the loader, but the model spec's reference option table did not list it, so the published spec and the reference option table disagreed with what the model accepts. Declared as a session enum (batched|single_row, default batched) next to the weight-storage options, using the same description the loader advertises. model_spec_system_test validates the option table of every shipped spec: PASS. moss_tts_nano_kv_cache_parity and moss_tts_nano_reference_cache_test are unaffected and still PASS. --------- Co-authored-by: SkYContact <[email protected]>
MOSS-TTS-Nano: decode with a K/V cache instead of re-running the transcript every frame
What was wrong
moss_tts_nanowas the only MOSS-family model in the tree without an incremental decode path (v15/voicegen/ttsdall drivemoss_tts_delay/backbone.cpp, which keeps aTransformerKVCache). The global transformer built one big graph sizedprompt_rows + max_new_framesand re-ran every row on every step, keeping only the last row's hidden state:Two costs follow from that:
decode_capacity_wasprompt_rows + max_new_frames(default 300), so every step recomputed ~300 rows even when the utterance ended after 54. With a fixed seed and 54 frames,--max-tokens 59and--max-tokens 300produced identical audio and cost 4.99 s vs 12.08 s.decode_graph_arena_byteswas already plumbed through the session and then dropped ((void) decode_graph_arena_bytes;), so the decode graph slot existed but was never implemented.The local frame decoder had the same shape of problem: each codebook step re-forwarded
[global_hidden, text, tok_0 .. tok_{q-1}](rowscodebook + 2) instead of appending one row.What this does
1. Global transformer — persistent K/V cache, one row per step (
global_transformer.cpp)begin_generation(max_positions)builds a single-row decode graph and a per-layer{1, cache_steps, heads, head_dim}f32 K/V cache, allocated once withggml_backend_alloc_ctx_tensorsso addresses stay stable across steps.FastKVSetRowsModule(ggml_set_rows) and attends to the whole cache throughggml_soft_max_extwith a cached-prefix mask.prefill()is a chunked prefill: it appends the chunk's K/V in-graph and attends to[0, reuse_rows + steps), so a reused prefix and a fresh forward are the same computation.2 * layers * rows * hidden * 4bytes) instead of being ignored.2. Local frame decoder — one row per codebook step (
local_frame_decoder.cpp)n_vq + 2positions) plus 17 single-row graphs, one per row kind (k = 0gate over the global hidden vector,k = 1text row,k >= 2embedding of the previous codebook's token).[0, k]view of the cache — no attention mask is needed at all (in particular the oldggml_diag_mask_inf(...,0), which would hide every key but the first for a single query row).3. Prompt template prefix reuse (
generator.cpp)The chat template is 70+ rows of the ~90-row prompt and never changes within a session. The generator remembers the previous prompt, takes the longest common row prefix, and passes it as
reuse_rows, so only the text/assistant rows are forwarded.begin_generationkeeps the existing graph and cache when the capacity is sufficient (it used to rebuild and clear on every utterance), and clears automatically whenever it has to grow.Measurements
Same text, same seed, CPU backend. Before is the unmodified implementation.
Desktop (i7-14700K, 16 threads, MSVC, Windows):
case | before | after -- | -- | -- 54 frames (4.32 s audio), --max-tokens 59 | 4993 ms, RTF 1.16 | 1081 ms, RTF 0.25 same 54 frames, --max-tokens 300 | 12083 ms, RTF 2.8 | 1259 ms, RTF 0.29 64 frames, global / local split | 96.3 ms/frame (global 85.8) | 9.5 ms/frame (global 5.1, local 4.4) prompt prefill, 2nd+ utterance | 54.6 ms | 7.4 – 11.4 msNote on phone thread counts: the streaming path degrades badly past 4 threads on this SoC (
threads=6measured 617 ms/frame for the local decoder alone); 3–4 is the sweet spot.Correctness
Byte-identical output. Each step was checked against the previous build with a fixed seed: the global change produces
0 / 829484differing bytes vs. the original binary, and the local change produces0 / 829484differing bytes vs. the global-only build. A multi-utterance batch (3 texts, reuse rows 0 / 71 / 72) is byte-identical to running each text in its own process.New regression test
tests/moss_tts_nano/kv_cache_parity.cpp(targetmoss_tts_nano_kv_cache_parity, needs-DENGINE_BUILD_MODEL_TESTS=ON):It asserts three equivalences against a one-shot prefill — chunked prefill, decode step, and cross-utterance prefix reuse — and reports
max_abs = 0for all three withnativeweights (f32weights land at ~2e-3 abs / 5.8e-4 rel, inside the default--tolerance 0.001). Two sensitivity guards keep the test from passing vacuously: the comparison must see a changed prompt (max_abs ≈ 3.5) and must see a cached prefix that does not match the prompt (max_abs ≈ 1.8). The latter is exactly the failure mode of the first cut of this change, which forwarded only the uncached rows and never read the cache — single-utterance output was fine, reused prefixes were wrong.compare()also refuses empty/size-mismatched inputs.Files
Suggested split if it helps review: (a) the two incremental decode changes + the test, (b) prefix reuse, which is small and depends on (a).
Notes and follow-ups
prefill/step_into/generate_frame, a per-op profiler inggml-cpu.c, a per-layer stack bisect hook) has been removed from the final diff. What remains is reporting only, in the style of the neighbouring models:moss_tts_nano.gen.prompt_rows/.prefix_reuse_rows,moss_tts_nano.global.decode.rows/.kv_cache_bytes/.arena_bytes, andmoss_tts_nano.global.prefill.total_rows/.reuse_rows/.forward_rows.reset_cache()is exposed on the runtime for callers that want to drop the cache explicitly (the generator does not need it:begin_generation()clears whenever it has to rebuild).ggml's small-M (2…64) quantizedmul_matbehaves like a per-rowvec_dotloop with no weight reuse (prompt prefill costs ~0.59 ms/row, i.e. ~18x a single-row step for an 18-row chunk, and the old multi-row local decoder was slower per row than the M=1 GEMV path). An efficient small-M quantized GEMM would cut the prefill and the local frame decoder several-fold on both desktop and phone.