Skip to content

perf(moss_tts_nano): incremental decode with a K/V cache - #878

Merged
0xShug0 merged 2 commits into
0xShug0:mainfrom
SkYContact:perf/moss-tts-nano-incremental-decode
Oct 12, 2026
Merged

0xShug0 merged 2 commits into
0xShug0:mainfrom
SkYContact:perf/moss-tts-nano-incremental-decode

Conversation

@SkYContact

Copy link
Copy Markdown
Contributor

MOSS-TTS-Nano: decode with a K/V cache instead of re-running the transcript every frame

What was wrong

moss_tts_nano was the only MOSS-family model in the tree without an incremental decode path (v15 / voicegen / ttsd all drive moss_tts_delay/backbone.cpp, which keeps a TransformerKVCache). The global transformer built one big graph sized prompt_rows + max_new_frames and re-ran every row on every step, keeping only the last row's hidden state:

// global_transformer.cpp (before)
const int64_t steps = row_count;                       // grows every frame
graph_ = std::make_unique<Graph>(..., graph_rows);     // graph_rows = max(row_count, decode_capacity_)
return graph_->run(rows, row_count);                   // whole transcript forward, take row row_count-1

Two costs follow from that:

  1. O(n²) work. Per-step cost is proportional to the rows forwarded, so a 5 s utterance pays for ~1 + 2 + ... + 54 rows. Measured on an i7-14700K: 76 / 98 / 142 / 224 ms per frame for 40 / 80 / 160 / 300 encoded frames.
  2. Reserved capacity is never reclaimed. decode_capacity_ was prompt_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 59 and --max-tokens 300 produced identical audio and cost 4.99 s vs 12.08 s.

decode_graph_arena_bytes was 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}] (rows codebook + 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 with ggml_backend_alloc_ctx_tensors so addresses stay stable across steps.
  • The decode step appends its K/V with FastKVSetRowsModule (ggml_set_rows) and attends to the whole cache through ggml_soft_max_ext with 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.
  • The decode arena is now used and validated against the actual cache size (2 * layers * rows * hidden * 4 bytes) instead of being ignored.

2. Local frame decoder — one row per codebook step (local_frame_decoder.cpp)

  • One shared 18-slot frame cache (n_vq + 2 positions) plus 17 single-row graphs, one per row kind (k = 0 gate over the global hidden vector, k = 1 text row, k >= 2 embedding of the previous codebook's token).
  • Positions and cache slots are compile-time constants per row kind, and each row attends to a [0, k] view of the cache — no attention mask is needed at all (in particular the old ggml_diag_mask_inf(...,0), which would hide every key but the first for a single query row).
  • The cache is zeroed once at build time: an uninitialised slot containing a NaN pattern would survive the softmax.

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_generation keeps 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 ms

Note on phone thread counts: the streaming path degrades badly past 4 threads on this SoC (threads=6 measured 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 / 829484 differing bytes vs. the original binary, and the local change produces 0 / 829484 differing 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 (target moss_tts_nano_kv_cache_parity, needs -DENGINE_BUILD_MODEL_TESTS=ON):

    ./build/<preset>/bin/Release/moss_tts_nano_kv_cache_parity --model model.gguf --rows 32
    

    It asserts three equivalences against a one-shot prefill — chunked prefill, decode step, and cross-utterance prefix reuse — and reports max_abs = 0 for all three with native weights (f32 weights 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

include/engine/models/moss/moss_tts_nano/global_transformer.h
src/models/moss/moss_tts_nano/global_transformer.cpp     incremental decode + chunked prefill
include/engine/models/moss/moss_tts_nano/generator.h
src/models/moss/moss_tts_nano/generator.cpp              prefix reuse
include/engine/models/moss/moss_tts_nano/local_frame_decoder.h
src/models/moss/moss_tts_nano/local_frame_decoder.cpp    frame-internal incremental decode
tests/moss_tts_nano/kv_cache_parity.cpp                  new parity test
CMakeLists.txt                                           test target

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

  • The temporary instrumentation used while measuring this change (per-phase timing around prefill/step_into/generate_frame, a per-op profiler in ggml-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, and moss_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).
  • Remaining hot spots on the phone, for whoever wants the next round: the audio tokenizer decode graph (~19 % of wall, and it wants more threads than the streaming path tolerates), and the per-step memory traffic of the two transformers — the sequence is now bandwidth bound (~253 MB of q8 weights per frame at ~8 GB/s on that SoC).
  • One upstream observation worth recording: for these shapes ggml's small-M (2…64) quantized mul_mat behaves like a per-row vec_dot loop 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.

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.
@0xShug0

0xShug0 commented Oct 12, 2026

Copy link
Copy Markdown
Owner

@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:

  • Main: 4.56 s, full sentence recovered by both ASR models.
  • PR: 15.20 s, Qwen3-ASR recovers only “The harbor is”; Parakeet returns “All right.”
    A fresh run reproduces the identical failing WAV. BF16 passes this case. A 620-character test Q8 output also introduces a repeated “and the bridge,” confirmed by both ASRs.

(2) The PR incorrectly treats the 128 MiB graph arena as a limit on the K/V buffer. A valid max_tokens=2000 request succeeds on base but fails on PR with default settings. For the tested max_tokens=2000 request, K/V needs about 152 MiB. The PR rejects it because 152 exceeds 128, even though K/V data is allocated separately and does not occupy that graph arena.

Could you investigate and fix these issues?

Case Base RTF → PR RTF Peak VRAM
CUDA Q8, warmed longform 0.199 → 0.030 1,390 → 1,320 MiB
Vulkan Q8, warmed repeat 0.223 → 0.055 1,277 → 1,311 MiB
CPU Q8, first request 1.785 → 0.171 —

… 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%.
@SkYContact

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed report — both blockers are addressed in e264dae.

1. CUDA Q8 quality regression — root cause and fix

The K/V cache logic itself is provably correct: on CPU the parity test (tests/moss_tts_nano/kv_cache_parity.cpp) compares the single-row decode step against the one-shot batched prefill of the same row, and they are bitwise identical. The corruption comes from kernel selection, not from the cache:

  • With quantized weights, ggml's CUDA backend routes a matmul to the mmvq kernels when the activation batch is ≤ 8 rows (MMVQ_MAX_BATCH_SIZE), and to the mmq kernels above that. The two families are not numerically equivalent.
  • main recomputes the whole transcript every frame, so every matmul is batched (mmq) and self-consistent.
  • This PR's decode step forwards a single row, so every step runs mmvq while the prompt prefill runs mmq — a measured ~5% per-step hidden-state drift between the two halves of the same computation, which compounds over the autoregressive frame loop into the corrupted audio and the "and the bridge," repetition loop.

The batch boundary is directly visible in the parity test (CUDA, q8_0): --rows 8 (prefill batch also ≤ 8, so also mmvq) gives decode-vs-prefill ≈ 2e-7 (exact); --rows 24 jumps to ~5%.

weights (CUDA) decode vs prefill chunked prefill prefix reuse
q8_0, before fix 5.4% 4.8% 1.9%
f32 0.15% 0.58% 0.53%
f16 0.60% 0.63% 0.37%
bf16 1.5% 1.6% 0.53%

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 (resolve_transformer_weight_storage() in assets.cpp; both runtimes and the parity test go through it). The q8_0 GGUF dequantizes at load — for this 100M model that is ~+100 MB VRAM, and generation got slightly faster here (first-request RTF 0.17 → 0.125 on CUDA). CPU is untouched; the exact int8 path there is why CPU q8_0 was always clean.

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 — fixed

Agreed, that check was a category error: the K/V tensors are allocated in their own backend buffer (ggml_backend_alloc_ctx_tensors) and never occupy the graph arena, which only holds tensor metadata and graph nodes. The bogus comparison is removed; max_tokens=2000 now runs (~3.1 GB peak footprint on a 12 GB card).

Test changes

kv_cache_parity gained --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 (the decode step stays exact, but re-batching the prefill shifts quantized GEMM tilings by a few percent), and 0.02 on GPU (cublas GEMV-vs-GEMM batching residual after the f16 upgrade). With --backend cuda the pre-fix q8_0 configuration fails at ~5.4% and the fixed build passes at ~0.6%, so the regression you hit is now caught by the test.

@0xShug0
0xShug0 merged commit 8f51d3c into 0xShug0:main Oct 12, 2026
6 checks passed
@0xShug0

0xShug0 commented Oct 12, 2026 •

Copy link
Copy Markdown
Owner

@SkYContact Thanks, and PR merged! Since the issue appears to be hardware-dependent, I suggest not forcing FP16. Instead,

  • Keep Q8 weights native as before the PR.
  • Document that incremental Q8 decoding on CUDA/HIP may show hardware-dependent numerical drift.
  • Recommend using an F16 GGUF when this occurs.
  • Alternatively, recommend use moss_tts_nano.weight_type=f16 to load the Q8 values into F16 runtime storage.

Would you like to open a follow-up PR to do that?

@SkYContact
SkYContact deleted the perf/moss-tts-nano-incremental-decode branch October 13, 2026 04:01
0xShug0 pushed a commit that referenced this pull request Oct 13, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants