From 7389ab6b0baf940782f952b7c977e6cb7c43a38e Mon Sep 17 00:00:00 2001 From: Hans Date: Sun, 15 Nov 2026 12:46:50 +0800 Subject: [PATCH 1/6] docs(rfc): codec memory, streaming encode/decode state in codec_context Proposal only; no header changes. A context can own encoder and decoder memory (llama_memory_t-style: codec_get_memory, codec_memory_clear, codec_memory_state_get_size/get_data/set_data), so codec_encode / codec_decode continue a stream. Covers per-family semantics (Mimi, Qwen3-TTS tokenizer, MOSS, DAC, SNAC, WavTokenizer), how #6's windowed streamer becomes the internal fallback, the state blob format and versioning, thread safety and open questions. Co-Authored-By: Claude Opus 5.5 --- docs/proposals/codec_memory.md | 365 +++++++++++++++++++++++++++++++++ 1 file changed, 365 insertions(+) create mode 100644 docs/proposals/codec_memory.md diff --git a/docs/proposals/codec_memory.md b/docs/proposals/codec_memory.md new file mode 100644 index 0000000..b865ac4 --- /dev/null +++ b/docs/proposals/codec_memory.md @@ -0,0 +1,365 @@ +# RFC: codec memory (streaming encode / decode state in `codec_context`) + +Status: **proposal, not implemented**. Nothing in `include/` or `common/*.h` +changes until this document is approved. + +## 1. Summary + +A `codec_context` can optionally own *memory*: the state an encoder or decoder +carries from one call to the next, the way a `llama_context` owns its KV cache. +With memory on, each `codec_encode` / `codec_decode` call continues the stream +from the previous call instead of starting from silence, and returns only +output that is final. Encoder memory and decoder memory are separate parts, +enabled, cleared and serialized independently. One sequence per context. + +Naming follows llama.cpp's `llama_memory_t` (`llama_get_memory`, +`llama_memory_clear`, `llama_state_seq_get_size / get_data / set_data`). + +Out of scope: the LLM's own context (its KV cache) is not codec memory. It +stays in llama.cpp. + +## 2. Motivation + +Today every public call is stateless. Streaming hosts get around this in +two ways, and both are costly: + +* **Decode from frame 0 each time** (the streamer on main). Cost grows with + the square of the stream length. On a Pixel 7 Pro (4 big cores, F32), a + Qwen3-TTS reply with a reference voice took 89 s to stream against 29 s in batch. +* **Overlapping windows** (#6). Each chunk re-decodes L frames of left context + and holds back R frames of right context. The cost is linear but inflated by + (L + chunk + R) / chunk, and the output is only approximate when the codec's + reach is longer than L. The table below is from the same phone (RTF = decode + time / audio length): + + | Codec | Batch RTF | Windowed RTF, 0.5 s chunks | Windowed RTF, 2 s chunks | + |---|---|---|---| + | Qwen3-TTS 12 Hz | 1.48 | 6.2 | 3.7 | + | DAC 16 kHz | 1.11 | 2.5 | 1.6 | + | Mimi | 0.24 | 0.83 | 0.40 | + | WavTokenizer | 0.18 | 0.74 | | + + For Qwen3 and DAC, windowing pushes a decoder that is near or above real + time well past it. + +Causal codecs don't need either workaround. Their output at time t depends only +on the past, and the past is summarized by a bounded state: + +* the left tails of the convolutions; +* the overlap tails of the transposed convolutions; +* the K/V of a sliding attention window; +* the position counter. + +Carrying that state makes streaming cost the same as batch and makes the output +equal to the batch output. + +The encoder side needs the same thing: + +* **Full duplex (Moshi style)**: the user's microphone is encoded continuously + by a causal Mimi encoder and fed to the LLM frame by frame while the model + speaks. Re-encoding a growing buffer, or windowing it, wastes the same compute + as on the decode side. +* **Streaming speech-to-LLM input** (LFM2-Audio and Mimi-based audio LMs): the + same pattern without the reply audio. +* **Reference voices (Qwen3-TTS ICL)**: the reference clip's codes condition + the decoder. A decoder state computed once from those codes and then restored + per request is exactly what upstream llama.cpp keeps in `mtmd_gen_state` + (`mtmd_gen_state_set_ref`). It also removes the 2–2.8 dB stream-vs-batch gap + measured in #6, which comes from the streamer never seeing the reference + codes. + +Non-causal encoders and decoders (Whisper-style encoders, DAC, SNAC, +WavTokenizer) carry no state. For them the overlap window stays an internal +implementation detail behind the same API (§5) and never appears in it. + +## 3. API (header diff sketch) + +All additions go in `include/codec.h`. Nothing changes in `common/*.h` or +`include/codec_audio_lm.h`. + +```diff +@@ include/codec.h ++// Which parts of a context's memory: a bit set. ++enum codec_memory_type { ++ CODEC_MEMORY_NONE = 0, ++ CODEC_MEMORY_ENCODE = 1, ++ CODEC_MEMORY_DECODE = 2, ++ CODEC_MEMORY_BOTH = 3, // ENCODE | DECODE ++}; ++ ++// How a model implements a part's memory (codec_model_memory_kind). ++enum codec_memory_kind { ++ CODEC_MEMORY_KIND_NONE = 0, // not supported: enabling it fails ++ CODEC_MEMORY_KIND_STATE = 1, // carried state; output == batch output ++ CODEC_MEMORY_KIND_WINDOW = 2, // internal overlap window; == batch when the ++ // window covers the model's reach, else approximate ++}; ++ ++typedef struct codec_memory * codec_memory_t; ++ + struct codec_context_params { + int32_t seed; ++ // Parts whose state persists across codec_encode / codec_decode calls. ++ // Default CODEC_MEMORY_NONE: every call is independent, as today. ++ enum codec_memory_type memory; + }; +@@ ++enum codec_memory_kind codec_model_memory_kind(const struct codec_model * model, enum codec_memory_type part); ++ ++// NULL when the context was created with memory == CODEC_MEMORY_NONE. ++codec_memory_t codec_get_memory(const struct codec_context * ctx); ++ ++// Back to the start of a stream (silence history, position 0) for the parts ++// in `which`. The other part is untouched. ++void codec_memory_clear(codec_memory_t mem, enum codec_memory_type which); ++ ++// Serialized state of the parts in `which` (§7). get_data returns the bytes ++// written (0 = dst too small); set_data returns the bytes read, or 0 when the ++// blob does not fit this model / part, leaving the memory unchanged. ++size_t codec_memory_state_get_size(codec_memory_t mem, enum codec_memory_type which); ++size_t codec_memory_state_get_data(codec_memory_t mem, enum codec_memory_type which, uint8_t * dst, size_t size); ++size_t codec_memory_state_set_data(codec_memory_t mem, enum codec_memory_type which, const uint8_t * src, size_t size); ++ ++// Stream position of a part: frames emitted by the encoder, or frames consumed ++// by the decoder since the last clear. ++int64_t codec_memory_n_frames(codec_memory_t mem, enum codec_memory_type part); +``` + +The `codec_encode` / `codec_decode` signatures are unchanged. +`python/codec_cpp/_ffi.py` mirrors the struct field and the new functions in the +same commit. + +**Mapping to llama.cpp** + +| llama.cpp | codec.cpp | +|---|---| +| `llama_context_params` (KV types, `n_ctx`) | `codec_context_params.memory` | +| `llama_get_memory(ctx)` | `codec_get_memory(ctx)` | +| `llama_memory_clear(mem, data)` | `codec_memory_clear(mem, which)` | +| `llama_state_seq_get_size / get_data / set_data` (on ctx, per seq) | `codec_memory_state_*` (on mem, per part) | +| `llama_memory_seq_rm / cp / keep / add` | none (one sequence; see §9) | + +Unlike llama, the state functions take the memory handle. The part selector +plays the role llama's `seq_id` plays there. + +**ABI.** `codec_context_params` grows from 4 to 8 bytes and is passed by value +to `codec_init_from_model`, so binaries built against the old header must be +rebuilt. Hosts that start from `codec_context_default_params()` (all in-tree +code, llama.rn) need no source change. Everything else is additive. + +## 4. Semantics + +### 4.1 Encode with memory (`ENCODE` on) + +* `codec_encode(ctx, audio, out, p)` appends `audio` to the stream and returns + the frames that are now final, possibly zero (`out->n_frames == 0` is + success). Leftover samples, fewer than one hop, stay in the memory. +* A frame is final when all of its input is in: + * **STATE kind**: as soon as its hop of samples has arrived. Causal, no added + latency beyond one hop. + * **WINDOW kind**: once R samples of right context have also arrived. +* **Flush**: `audio->n_samples == 0` pads the tail the way batch encode pads a + clip's end and returns the remaining frames. + * After a flush, the part is *ended*. A non-empty call returns + `CODEC_STATUS_INVALID_STATE` until `codec_memory_clear`. +* **Invariant**: concatenating every call's frames, flush included, gives the + codes `codec_encode` gives in one call on the concatenated audio: + * STATE kind: identical codes, except that a rounding difference at a + quantizer decision boundary may flip a code (§8, tolerance); + * WINDOW kind: the same, when the window covers the reach. +* `audio->sample_rate` must equal the model's encode rate. Resampling in a + stream needs its own state; that is open question Q3. +* `codec_encode_latent` shares the encode part. + +### 4.2 Decode with memory (`DECODE` on) + +* `codec_decode(ctx, tokens, out, p)` appends the frames and returns the PCM + that is now final: + * **STATE kind**: all of it; + * **WINDOW kind**: everything except the last R frames, which are held back. + * The output can be empty, for example when the frames fit inside R. +* **Flush**: `tokens->n_frames == 0` returns the held-back tail (a no-op for + STATE kind) and ends the part, as for encode. +* **Invariant**: the concatenated PCM equals the batch decode of the + concatenated codes. That holds for STATE kind and for WINDOW kind with full + reach. Otherwise the gap is bounded by the per-model numbers in §5. +* Joins between WINDOW chunks crossfade internally, as #6 does today. The host + never sees a seam. +* Parameters fixed for the life of a stream: `n_q`, `speaker`, and the layout + of the token buffer. Changing one before a clear returns + `CODEC_STATUS_INVALID_ARG`. +* `codec_decode_quantized_representation` shares the decode part. +* `codec_decode_batch` on a context with DECODE memory returns + `CODEC_STATUS_NOT_SUPPORTED`. A batch holds several sequences, and memory + holds one. + +### 4.3 Lifecycle + +* Memory is allocated by `codec_init_from_model`: + * device buffers sized from the model's metadata (window lengths, channels); + * freed with the context; + * zeroed state, position 0. +* If a part's kind is NONE, `codec_init_from_model` fails and + `codec_get_last_error` names the part. +* `codec_memory_clear(mem, which)` is cheap: a buffer memset and counters reset. +* With `memory == NONE`, behaviour and numerics are byte-identical to today. + +### 4.4 Graphs + +The rule *one model = one graph per public call* still holds: + +* the state tensors are inputs of the call's graph; +* the updated state is written back in the same graph (`ggml_cpy` into the + memory buffer), as llama.cpp writes its KV cache; +* ring-buffer offsets and positions are small input tensors, so a graph is + reused for every chunk of the same length. + +The graph cache key gains the memory flag and the chunk length. Hosts get the +best cache hit rate with a fixed chunk size. + +## 5. Per codec family + +Reach below is from an impulse test on the host: one frame's codes changed, and +the change in output measured before ("look-ahead") and after ("memory") that +frame, at −40 dB. + +| Family (archs) | Encoder | Decoder | State per part | +|---|---|---|---| +| **Mimi** (`MIMI`; LFM2-Audio, Moshi; `POCKET_MIMI` for the decoder) | causal SEANet convs, stride-2 downsample, causal transformer with a 250-frame sliding window: **STATE** | mirror image, measured causal, −40 dB memory 0.24 s (Moshi's Mimi 2.0 s): **STATE** | conv / convtr tails (< 1 MB); K/V 8 layers × 250 frames × 512 × 2 ≈ 8 MB F32 (4 MB F16) per part; position; pending samples < 1920 | +| **Qwen3-TTS 12 Hz tokenizer** (`QWEN3_TTS_TOKENIZER`) | Mimi encoder (`qwen3.encoder.*`): **STATE**, same as Mimi | causal convs + 8 transformer layers, sliding window 72 frames, then causal upsampling convtr; −40 dB memory 5.8–7.7 s, reach to the end of the clip: **STATE** | K/V 8 × 71 frames; conv and convtr tails; position. The same contents as upstream llama.cpp's `mtmd_gen_state` | +| **MOSS-Audio** (`MOSS_AUDIO`; Nano, full, TTS-Realtime) | patched pretransform + causal sliding-window transformers per stage: **STATE** | mirror image; −40 dB memory 17–24 s: **STATE** | K/V per stage, window = `context_duration × stage frame rate`, so the largest state of the set; pending samples to a whole patch; Nano needs 48 kHz stereo | +| **DAC** (`DAC`) | non-causal convs, finite receptive field: **WINDOW**, exact | non-causal; reach ±0.13–0.20 s (10 frames): **WINDOW** L = R = 0.32 s, **exact** (#6 measured 0.00 dB vs batch) | the last L codes / samples and R held back; no tensors | +| **SNAC** (`SNAC`) | non-causal convs: **WINDOW**, exact | reach ±0.19 s (9 frames): **WINDOW**, exact | as DAC; three code rates, so the window is counted at the coarsest rate | +| **WavTokenizer** (`WAVTOKENIZER_LARGE`) | non-causal convs with reflect padding: **WINDOW**, exact | Vocos backbone with global attention, reach is the whole clip: **WINDOW** L 1.28 / R 0.32 s, **approximate** (1.8 dB vs batch on a 4.8 dB codec error; equal WER) | last L codes, R held back | +| NeMo nano codec | (not a streaming target) | causal conv, memory 2.2 s: **STATE** | conv tails only | +| XCodec2, NeuCodec, Chatterbox S3G, latent decoders (Soprano, Pocket-TTS, BlueMagpie), CosyVoice, XY-Tokenizer | | global attention, flow, or not measured: **NONE** for now | the streamer keeps decoding from frame 0 | + +Notes: + +* **Whisper-style encoders** (S3 tokenizers, XY-Tokenizer) are non-causal with + a fixed input window. They get WINDOW kind if someone needs them streamed. The + overlap stays internal, as Hans asked. +* **Qwen3-TTS reference voice**: + 1. decode the reference codes on a context with DECODE memory; + 2. discard the PCM; + 3. call `codec_memory_state_get_data(mem, DECODE)`; + 4. per request, call `set_data` and decode the new codes. + + The output then matches the batch decode of `ref + new` with the reference + audio trimmed off, which is the official model's ICL path. Encoding the + reference clip itself is a one-shot `codec_encode`. ENCODE memory matters there + only when the clip itself arrives as a stream. +* **Full duplex**: one context with ENCODE memory on the microphone thread and + one with DECODE memory on the playback thread (§8). + +## 6. Relation to #6 (windowed stateless streamer) + +#6 merges first, on its own terms: it changes no public header beyond a comment +and needs nothing from this RFC. Afterwards: + +1. **Phase 1, STATE kind** for Mimi, the Qwen3 tokenizer and MOSS. In + `common/audio_lm_c.cpp`, `alm_streamer` opens its codec context with DECODE + memory when `codec_model_memory_kind(model, DECODE) == STATE` and just + forwards new frames. Otherwise it keeps #6's window. Measurable win: Qwen3 + streaming on the phone goes from RTF 6.2 to the batch RTF of about 1.5. +2. **Phase 2, WINDOW kind inside the library.** #6's internal + `src/audio_lm_window.h` table and crossfade move into the codec memory as its + WINDOW implementation. `alm_streamer` is then a single path (feed frames, + flush at the end), and #6's host-side window code is deleted. +3. Decoding from frame 0 survives only for NONE-kind codecs. + +So #6 becomes the internal fallback, first in the streamer and then inside the +library, and is not exposed. Its smoke (`tests/e2e/audio_lm_stream_smoke.py`) +becomes the regression test for both kinds. + +## 7. State serialization + +The blob is little-endian and self-describing: + +``` +header char[4] "CDCM" + u32 format_version (1) + u32 arch (enum codec_arch) + u8[32] model_fingerprint (SHA-256 over tensor names, types, shapes and the + decode-relevant GGUF keys; computed once at load) + u32 parts (codec_memory_type bits present) +per part u32 part (ENCODE / DECODE) + u32 kind (STATE / WINDOW) + u32 impl_version (per-arch layout version) + i64 n_frames, i64 n_samples_pending + i32 n_q, i32 flags (ended, ...) + u32 n_sections +section u32 tag, u32 ggml_type, i64 ne[4], u64 nbytes, u8 data[nbytes] (8-byte aligned) +``` + +* Section tags name the tensors: `conv_tail[i]`, `k[l]`, `v[l]`, `ring_head`, + `pending_pcm`, `window_codes`. +* Data is copied with `ggml_backend_tensor_get`, so a blob saved on the GPU + restores on the CPU and the other way round. It is tied to the model file + through the fingerprint, not to the backend. +* `set_data` validates everything (magic, versions, arch, fingerprint, part, + section shapes) before touching the memory. Any mismatch returns 0 and leaves + the state unchanged. +* **Versioning**: no migration. State is a cache that can always be recomputed. + `format_version` changes with the header and `impl_version` with an arch's + layout. The old blob is rejected, and hosts recompute it (Qwen3: re-decode + the reference codes once). +* Size: Qwen3 decode state is about 8 × 71 × 1024 × 2 × 4 B ≈ 4.6 MB F32, plus + tails. That is small enough to keep one per saved voice. + +## 8. Thread safety and numerics + +* Thread rules are unchanged: one `codec_context` is used by one thread at a + time, and its memory is part of it. +* Calling `state_get_data` while another thread encodes on the same context is + a data race. +* Contexts of one model are independent, since each has its own backend + instance. Full duplex therefore uses two contexts: encode on one thread, + decode on another. +* One context with `BOTH` is allowed, but its encode and decode calls are + serialized because they share the scheduler and eval arena. +* The memory handle is valid until `codec_free`. It is not reference counted. +* **Numerics.** Chunked compute changes matmul tiling, so STATE kind matches + batch to rounding, not bit for bit. Smokes assert: + * PCM: max |Δ| ≤ 1e-4; + * codes: at most 0.1 % flipped, and only at quantizer ties; + * WINDOW kind: the per-model LSD limits of #6. +* State tensors keep the precision the batch graph computes them at (F32 K/V + unless the graph already uses F16). + +## 9. Open questions + +* **Q1. Flush ends the stream**, rather than letting it continue after a + flush. Proposed: ends, which is simpler and matches the "end of utterance" + use. The alternative needs a "pad but keep going" mode that no family needs + today. +* **Q2. `codec_model_memory_kind` and `codec_memory_n_frames`** are beyond the + list Hans gave. Without the first, a host can only learn the kind by failing + `codec_init_from_model`. The second gives frame alignment for full duplex. + Keep both? +* **Q3. Resampling.** Proposed: streamed input must be at the model's rate in + v1. An in-graph streaming resampler with its own tail state comes later. +* **Q4. Voice files.** Should a Qwen3 reference decode state be cached in the + `codec_speaker` / voice file (`codec_audio_lm_save_voice`)? That would touch + `include/codec_speaker.h`, and only by a separate proposal. +* **Q5. Sequence ids.** Proposed: none. One context per sequence, which is how + llama.rn uses contexts. Multi-sequence memory, as with `llama_memory_seq_*`, + would only matter for a server batching many streams through one decoder. +* **Q6. Approximate WINDOW kinds.** Should WavTokenizer stay WINDOW, which is + approximate, or report NONE unless the host opts into approximation? A + `codec_context_params` flag such as `allow_approx_memory` would make the + choice explicit. +* **Q7. Chunk-length graph cache.** Should the library pad short chunks up to + a set of bucket sizes, to cap the number of cached graphs when a host sends + irregular chunks? + +## 10. Test plan (per kind) + +* **Stream vs batch** on random chunk sizes, including 1-frame and sub-hop + chunks: Mimi encode and decode, Qwen3 decode, MOSS decode, DAC, WavTokenizer. +* **`set_data(get_data())` round trip**: the continuation is identical to an + uninterrupted stream. A blob from another model or part is rejected and the + state is unchanged. +* **`clear`** equals a fresh context, and the other part is untouched. +* **Phone benchmark** (Pixel 7 Pro): streaming RTF vs batch for Qwen3 and Mimi + with STATE kind. Target: within 10 % of batch at 0.5 s chunks. From cb634e4578278d4ca2bea9145b0c293291d1fb8d Mon Sep 17 00:00:00 2001 From: Hans Date: Sun, 15 Nov 2026 13:25:23 +0800 Subject: [PATCH 2/6] docs(rfc): codec memory caches context only, no output scheduling Per review: memory caches the context a model needs (sliding-window K/V, conv tails, convtr overlap partial sums, position) and nothing else. Removed flush, the ended state, input buffering, held-back output, the WINDOW kind and the in-library crossfade; each call returns exactly what a stateless call returns for its input. Encode chunks must be hop-aligned (the batch tail padding and the measured effect of caller zero-padding are documented). v1 supports causal models only; #6's host windowing stays the fallback. codec_model_memory_kind becomes codec_model_has_memory; codec_memory_n_frames and the speaker question are dropped (reference-voice state is a future codec_speaker proposal). Co-Authored-By: Claude Opus 5.5 --- docs/proposals/codec_memory.md | 468 ++++++++++++++++----------------- 1 file changed, 229 insertions(+), 239 deletions(-) diff --git a/docs/proposals/codec_memory.md b/docs/proposals/codec_memory.md index b865ac4..84828c1 100644 --- a/docs/proposals/codec_memory.md +++ b/docs/proposals/codec_memory.md @@ -1,81 +1,74 @@ -# RFC: codec memory (streaming encode / decode state in `codec_context`) +# RFC: codec memory (cached context in `codec_context`) Status: **proposal, not implemented**. Nothing in `include/` or `common/*.h` changes until this document is approved. ## 1. Summary -A `codec_context` can optionally own *memory*: the state an encoder or decoder -carries from one call to the next, the way a `llama_context` owns its KV cache. -With memory on, each `codec_encode` / `codec_decode` call continues the stream -from the previous call instead of starting from silence, and returns only -output that is final. Encoder memory and decoder memory are separate parts, -enabled, cleared and serialized independently. One sequence per context. +A `codec_context` can optionally own *memory*: the context a model needs from +earlier input, cached so it is not recomputed, as a `llama_context` caches K/V. +The cached context is: -Naming follows llama.cpp's `llama_memory_t` (`llama_get_memory`, -`llama_memory_clear`, `llama_state_seq_get_size / get_data / set_data`). +* the K/V of a sliding attention window; +* the left tails of convolutions and the overlap partial sums of transposed + convolutions; +* the position counter. + +With memory on, each `codec_encode` / `codec_decode` call sees the cached +context of the previous calls instead of starting from silence. + +Memory schedules no output. Each call returns exactly the output for its own +input: as many frames or samples as a stateless call on that input would +return, and the caller decides what to emit, trim or crossfade, as today. For +the models that support memory (causal ones, §5), the output of consecutive +calls equals the matching slice of the batch output. + +Encoder memory and decoder memory are separate parts, enabled, cleared and +serialized independently. One sequence per context. Naming follows llama.cpp's +`llama_memory_t`. -Out of scope: the LLM's own context (its KV cache) is not codec memory. It -stays in llama.cpp. +Out of scope: + +* the LLM's own context (its KV cache) is not codec memory; it stays in + llama.cpp; +* reference-voice decoder state (§5). ## 2. Motivation -Today every public call is stateless. Streaming hosts get around this in -two ways, and both are costly: - -* **Decode from frame 0 each time** (the streamer on main). Cost grows with - the square of the stream length. On a Pixel 7 Pro (4 big cores, F32), a - Qwen3-TTS reply with a reference voice took 89 s to stream against 29 s in batch. -* **Overlapping windows** (#6). Each chunk re-decodes L frames of left context - and holds back R frames of right context. The cost is linear but inflated by - (L + chunk + R) / chunk, and the output is only approximate when the codec's - reach is longer than L. The table below is from the same phone (RTF = decode - time / audio length): - - | Codec | Batch RTF | Windowed RTF, 0.5 s chunks | Windowed RTF, 2 s chunks | - |---|---|---|---| - | Qwen3-TTS 12 Hz | 1.48 | 6.2 | 3.7 | - | DAC 16 kHz | 1.11 | 2.5 | 1.6 | - | Mimi | 0.24 | 0.83 | 0.40 | - | WavTokenizer | 0.18 | 0.74 | | - - For Qwen3 and DAC, windowing pushes a decoder that is near or above real - time well past it. - -Causal codecs don't need either workaround. Their output at time t depends only -on the past, and the past is summarized by a bounded state: - -* the left tails of the convolutions; -* the overlap tails of the transposed convolutions; -* the K/V of a sliding attention window; -* the position counter. +Today every public call is stateless. A streaming host that wants batch-quality +output therefore either decodes from frame 0 on every chunk, whose cost grows +with the square of the stream length, or re-decodes a left window around each +chunk (#6). Both recompute context the model already computed. + +The cost on a Pixel 7 Pro (4 big cores, F32; RTF = decode time / audio length): + +| Codec | Batch RTF | #6 window, 0.5 s chunks | #6 window, 2 s chunks | +|---|---|---|---| +| Qwen3-TTS 12 Hz | 1.48 | 6.2 | 3.7 | +| Mimi | 0.24 | 0.83 | 0.40 | + +For a causal model the context is bounded and cheap to keep: + +* each convolution needs its last (k − 1) · dilation input samples; +* each transposed convolution needs the k − stride overlap it has not yet + added; +* each sliding-window attention layer needs its last W keys and values. -Carrying that state makes streaming cost the same as batch and makes the output -equal to the batch output. +Caching these makes streaming cost the same as batch, and the output is the +batch output, not an approximation. The encoder side needs the same thing: * **Full duplex (Moshi style)**: the user's microphone is encoded continuously by a causal Mimi encoder and fed to the LLM frame by frame while the model - speaks. Re-encoding a growing buffer, or windowing it, wastes the same compute - as on the decode side. -* **Streaming speech-to-LLM input** (LFM2-Audio and Mimi-based audio LMs): the - same pattern without the reply audio. -* **Reference voices (Qwen3-TTS ICL)**: the reference clip's codes condition - the decoder. A decoder state computed once from those codes and then restored - per request is exactly what upstream llama.cpp keeps in `mtmd_gen_state` - (`mtmd_gen_state_set_ref`). It also removes the 2–2.8 dB stream-vs-batch gap - measured in #6, which comes from the streamer never seeing the reference - codes. - -Non-causal encoders and decoders (Whisper-style encoders, DAC, SNAC, -WavTokenizer) carry no state. For them the overlap window stays an internal -implementation detail behind the same API (§5) and never appears in it. + speaks. +* **Streaming speech input to an audio LM** (LFM2-Audio and other Mimi-based + LMs): the same pattern without the reply audio. ## 3. API (header diff sketch) -All additions go in `include/codec.h`. Nothing changes in `common/*.h` or -`include/codec_audio_lm.h`. +All additions go in `include/codec.h`. Nothing changes in `common/*.h`, +`include/codec_audio_lm.h` or `include/codec_speaker.h`. ```diff @@ include/codec.h @@ -87,47 +80,38 @@ All additions go in `include/codec.h`. Nothing changes in `common/*.h` or + CODEC_MEMORY_BOTH = 3, // ENCODE | DECODE +}; + -+// How a model implements a part's memory (codec_model_memory_kind). -+enum codec_memory_kind { -+ CODEC_MEMORY_KIND_NONE = 0, // not supported: enabling it fails -+ CODEC_MEMORY_KIND_STATE = 1, // carried state; output == batch output -+ CODEC_MEMORY_KIND_WINDOW = 2, // internal overlap window; == batch when the -+ // window covers the model's reach, else approximate -+}; -+ +typedef struct codec_memory * codec_memory_t; + struct codec_context_params { int32_t seed; -+ // Parts whose state persists across codec_encode / codec_decode calls. ++ // Parts that cache context across codec_encode / codec_decode calls. + // Default CODEC_MEMORY_NONE: every call is independent, as today. + enum codec_memory_type memory; }; @@ -+enum codec_memory_kind codec_model_memory_kind(const struct codec_model * model, enum codec_memory_type part); ++// Whether the model supports memory for `part` (ENCODE or DECODE). ++bool codec_model_has_memory(const struct codec_model * model, enum codec_memory_type part); + +// NULL when the context was created with memory == CODEC_MEMORY_NONE. +codec_memory_t codec_get_memory(const struct codec_context * ctx); + -+// Back to the start of a stream (silence history, position 0) for the parts -+// in `which`. The other part is untouched. ++// Empty the cached context of the parts in `which` (start of a new stream). ++// The other part is untouched. +void codec_memory_clear(codec_memory_t mem, enum codec_memory_type which); + -+// Serialized state of the parts in `which` (§7). get_data returns the bytes -+// written (0 = dst too small); set_data returns the bytes read, or 0 when the -+// blob does not fit this model / part, leaving the memory unchanged. ++// Serialized cached context of the parts in `which` (§7). get_data returns the ++// bytes written (0 = dst too small); set_data returns the bytes read, or 0 when ++// the blob does not fit this model / part, leaving the memory unchanged. +size_t codec_memory_state_get_size(codec_memory_t mem, enum codec_memory_type which); +size_t codec_memory_state_get_data(codec_memory_t mem, enum codec_memory_type which, uint8_t * dst, size_t size); +size_t codec_memory_state_set_data(codec_memory_t mem, enum codec_memory_type which, const uint8_t * src, size_t size); -+ -+// Stream position of a part: frames emitted by the encoder, or frames consumed -+// by the decoder since the last clear. -+int64_t codec_memory_n_frames(codec_memory_t mem, enum codec_memory_type part); ``` -The `codec_encode` / `codec_decode` signatures are unchanged. -`python/codec_cpp/_ffi.py` mirrors the struct field and the new functions in the -same commit. +* The `codec_encode` / `codec_decode` signatures are unchanged, and so are + their parameter structs. +* No status code is added. +* `python/codec_cpp/_ffi.py` mirrors the new field and functions in the same + commit. **Mapping to llama.cpp** @@ -137,10 +121,7 @@ same commit. | `llama_get_memory(ctx)` | `codec_get_memory(ctx)` | | `llama_memory_clear(mem, data)` | `codec_memory_clear(mem, which)` | | `llama_state_seq_get_size / get_data / set_data` (on ctx, per seq) | `codec_memory_state_*` (on mem, per part) | -| `llama_memory_seq_rm / cp / keep / add` | none (one sequence; see §9) | - -Unlike llama, the state functions take the memory handle. The part selector -plays the role llama's `seq_id` plays there. +| `llama_memory_seq_rm / cp / keep / add` | none (one sequence) | **ABI.** `codec_context_params` grows from 4 to 8 bytes and is passed by value to `codec_init_from_model`, so binaries built against the old header must be @@ -149,128 +130,144 @@ code, llama.rn) need no source change. Everything else is additive. ## 4. Semantics -### 4.1 Encode with memory (`ENCODE` on) - -* `codec_encode(ctx, audio, out, p)` appends `audio` to the stream and returns - the frames that are now final, possibly zero (`out->n_frames == 0` is - success). Leftover samples, fewer than one hop, stay in the memory. -* A frame is final when all of its input is in: - * **STATE kind**: as soon as its hop of samples has arrived. Causal, no added - latency beyond one hop. - * **WINDOW kind**: once R samples of right context have also arrived. -* **Flush**: `audio->n_samples == 0` pads the tail the way batch encode pads a - clip's end and returns the remaining frames. - * After a flush, the part is *ended*. A non-empty call returns - `CODEC_STATUS_INVALID_STATE` until `codec_memory_clear`. -* **Invariant**: concatenating every call's frames, flush included, gives the - codes `codec_encode` gives in one call on the concatenated audio: - * STATE kind: identical codes, except that a rounding difference at a - quantizer decision boundary may flip a code (§8, tolerance); - * WINDOW kind: the same, when the window covers the reach. -* `audio->sample_rate` must equal the model's encode rate. Resampling in a - stream needs its own state; that is open question Q3. +### 4.1 General + +* With a part enabled, each call reads that part's cached context, computes its + input with it, and updates the cache in the same graph. +* The output shape is that of a stateless call on the same input. +* Memory never holds raw samples or frames that are waiting to be output. What + it caches is context for future input, never output that has not been + returned yet. +* The output of calls 1..n equals the slice of the batch output on the + concatenated input, to rounding (§8). This holds for every model that reports + memory support, because only causal models do (§5). +* `codec_memory_clear` returns a part to the start of a stream. The next call + behaves like the first call of a batch: same left padding, position 0. + +### 4.2 Encode + +* **Every chunk must be hop-aligned**: `n_samples % hop == 0`, where hop is the + product of the encoder's strides (`codec_model_hop_size`). Otherwise the call + returns `CODEC_STATUS_INVALID_ARG`. +* **The caller pads the last chunk.** Nothing is buffered between calls. +* **What batch encode does at the tail** (checked on Mimi, the Qwen3-TTS + tokenizer and MOSS-Audio-Nano): + * Batch encode does not zero-pad the raw input to the hop. Following the + reference (Moshi / HF `MimiConv1d`), each strided convolution right-pads its + own input to a multiple of its stride, with zeros or, for Mimi's downsample + convolution, by replicating the last value. The padding therefore happens at + every resolution, after nonlinearities. + * On hop-aligned input these extra paddings are all zero length. That is what + makes chunking exact: `encode(x[: k·hop])` equals the first k frames of + `encode(x)` bit for bit, for all three encoders (measured on a 6 s speech + clip, k = 50). + * Consequence for the caller's zero-padding of the last chunk: + * the frame count matches batch (51 frames for 50⅓ hops); + * every frame before the last is identical; + * the last frame can differ, because batch pads per layer and the caller pads + raw samples. Measured: Mimi 1.96 % of codes differ (all of them in the + last frame), Qwen3 tokenizer 0.92 %, MOSS-Audio-Nano 1.96 %. + * A host that needs batch codes for the final partial frame can re-encode that + frame's window statelessly. Q2 covers making the library do it. * `codec_encode_latent` shares the encode part. -### 4.2 Decode with memory (`DECODE` on) - -* `codec_decode(ctx, tokens, out, p)` appends the frames and returns the PCM - that is now final: - * **STATE kind**: all of it; - * **WINDOW kind**: everything except the last R frames, which are held back. - * The output can be empty, for example when the frames fit inside R. -* **Flush**: `tokens->n_frames == 0` returns the held-back tail (a no-op for - STATE kind) and ends the part, as for encode. -* **Invariant**: the concatenated PCM equals the batch decode of the - concatenated codes. That holds for STATE kind and for WINDOW kind with full - reach. Otherwise the gap is bounded by the per-model numbers in §5. -* Joins between WINDOW chunks crossfade internally, as #6 does today. The host - never sees a seam. -* Parameters fixed for the life of a stream: `n_q`, `speaker`, and the layout - of the token buffer. Changing one before a clear returns - `CODEC_STATUS_INVALID_ARG`. +### 4.3 Decode + +* `codec_decode(ctx, tokens, out, p)` returns `tokens->n_frames × hop` samples, + as a stateless call does. With memory, those samples are the matching slice + of the batch decode: + * the convolutions see the previous frames' tails instead of zero padding; + * attention sees the cached K/V window; + * the transposed convolutions' overlap from the previous chunk is added at the + start. That overlap is a partial sum (an activation), cached like a K/V + entry, and it is not held-back output. +* Batch decode trims the overlap that the last frame's transposed convolutions + would add past the end. A streaming chunk does the same, and the trimmed part + stays in the cache as context for the next chunk. +* `n_q`, the token layout and the decode parameters must stay the same within a + stream. Changing them before a clear returns `CODEC_STATUS_INVALID_ARG`. * `codec_decode_quantized_representation` shares the decode part. * `codec_decode_batch` on a context with DECODE memory returns `CODEC_STATUS_NOT_SUPPORTED`. A batch holds several sequences, and memory holds one. -### 4.3 Lifecycle +### 4.4 Lifecycle and graphs -* Memory is allocated by `codec_init_from_model`: - * device buffers sized from the model's metadata (window lengths, channels); - * freed with the context; - * zeroed state, position 0. -* If a part's kind is NONE, `codec_init_from_model` fails and - `codec_get_last_error` names the part. -* `codec_memory_clear(mem, which)` is cheap: a buffer memset and counters reset. +* `codec_init_from_model` allocates the memory: + * device buffers sized from the model's metadata (window lengths, channels, + kernel sizes); + * freed with the context. +* Creating a context fails, with `codec_get_last_error` naming the part, if a + requested part is unsupported. * With `memory == NONE`, behaviour and numerics are byte-identical to today. +* *One model = one graph per public call* still holds: + * the cache tensors are graph inputs; + * the updated cache is written back in the same graph (`ggml_cpy` into the + memory buffer), as llama.cpp writes its KV cache; + * ring offsets and positions are small input tensors, so a graph is reused + for every chunk of the same length. -### 4.4 Graphs - -The rule *one model = one graph per public call* still holds: - -* the state tensors are inputs of the call's graph; -* the updated state is written back in the same graph (`ggml_cpy` into the - memory buffer), as llama.cpp writes its KV cache; -* ring-buffer offsets and positions are small input tensors, so a graph is - reused for every chunk of the same length. - -The graph cache key gains the memory flag and the chunk length. Hosts get the -best cache hit rate with a fixed chunk size. + The graph cache key gains the memory flag. Hosts get the best cache hit rate + with a fixed chunk size. -## 5. Per codec family +## 5. Per codec family (v1 = causal models only) -Reach below is from an impulse test on the host: one frame's codes changed, and -the change in output measured before ("look-ahead") and after ("memory") that -frame, at −40 dB. +Reach is from an impulse test on the host: one frame's codes changed, and the +change in output measured before ("look-ahead") and after ("memory") that frame, +at −40 dB. -| Family (archs) | Encoder | Decoder | State per part | +| Family (archs) | Encode | Decode | What the memory caches | |---|---|---|---| -| **Mimi** (`MIMI`; LFM2-Audio, Moshi; `POCKET_MIMI` for the decoder) | causal SEANet convs, stride-2 downsample, causal transformer with a 250-frame sliding window: **STATE** | mirror image, measured causal, −40 dB memory 0.24 s (Moshi's Mimi 2.0 s): **STATE** | conv / convtr tails (< 1 MB); K/V 8 layers × 250 frames × 512 × 2 ≈ 8 MB F32 (4 MB F16) per part; position; pending samples < 1920 | -| **Qwen3-TTS 12 Hz tokenizer** (`QWEN3_TTS_TOKENIZER`) | Mimi encoder (`qwen3.encoder.*`): **STATE**, same as Mimi | causal convs + 8 transformer layers, sliding window 72 frames, then causal upsampling convtr; −40 dB memory 5.8–7.7 s, reach to the end of the clip: **STATE** | K/V 8 × 71 frames; conv and convtr tails; position. The same contents as upstream llama.cpp's `mtmd_gen_state` | -| **MOSS-Audio** (`MOSS_AUDIO`; Nano, full, TTS-Realtime) | patched pretransform + causal sliding-window transformers per stage: **STATE** | mirror image; −40 dB memory 17–24 s: **STATE** | K/V per stage, window = `context_duration × stage frame rate`, so the largest state of the set; pending samples to a whole patch; Nano needs 48 kHz stereo | -| **DAC** (`DAC`) | non-causal convs, finite receptive field: **WINDOW**, exact | non-causal; reach ±0.13–0.20 s (10 frames): **WINDOW** L = R = 0.32 s, **exact** (#6 measured 0.00 dB vs batch) | the last L codes / samples and R held back; no tensors | -| **SNAC** (`SNAC`) | non-causal convs: **WINDOW**, exact | reach ±0.19 s (9 frames): **WINDOW**, exact | as DAC; three code rates, so the window is counted at the coarsest rate | -| **WavTokenizer** (`WAVTOKENIZER_LARGE`) | non-causal convs with reflect padding: **WINDOW**, exact | Vocos backbone with global attention, reach is the whole clip: **WINDOW** L 1.28 / R 0.32 s, **approximate** (1.8 dB vs batch on a 4.8 dB codec error; equal WER) | last L codes, R held back | -| NeMo nano codec | (not a streaming target) | causal conv, memory 2.2 s: **STATE** | conv tails only | -| XCodec2, NeuCodec, Chatterbox S3G, latent decoders (Soprano, Pocket-TTS, BlueMagpie), CosyVoice, XY-Tokenizer | | global attention, flow, or not measured: **NONE** for now | the streamer keeps decoding from frame 0 | - -Notes: - -* **Whisper-style encoders** (S3 tokenizers, XY-Tokenizer) are non-causal with - a fixed input window. They get WINDOW kind if someone needs them streamed. The - overlap stays internal, as Hans asked. -* **Qwen3-TTS reference voice**: - 1. decode the reference codes on a context with DECODE memory; - 2. discard the PCM; - 3. call `codec_memory_state_get_data(mem, DECODE)`; - 4. per request, call `set_data` and decode the new codes. - - The output then matches the batch decode of `ref + new` with the reference - audio trimmed off, which is the official model's ICL path. Encoding the - reference clip itself is a one-shot `codec_encode`. ENCODE memory matters there - only when the clip itself arrives as a stream. -* **Full duplex**: one context with ENCODE memory on the microphone thread and - one with DECODE memory on the playback thread (§8). +| **Mimi** (`MIMI`; LFM2-Audio, Moshi; `POCKET_MIMI` for the decoder) | causal SEANet convs, stride-2 downsample, causal transformer with a 250-frame window: **supported** | mirror image, causal, look-ahead 0, −40 dB memory 0.24 s (Moshi's Mimi 2.0 s): **supported** | conv tails (< 1 MB), with the replicate-padded downsample cache seeded from the first input value after a clear, as batch pads; K/V 8 layers × 250 frames × 512 × 2 ≈ 8 MB F32 (4 MB F16) per part; position | +| **Qwen3-TTS 12 Hz tokenizer** (`QWEN3_TTS_TOKENIZER`) | Mimi encoder (`qwen3.encoder.*`): **supported**, same as Mimi | causal convs, 8 transformer layers with a 72-frame window, causal upsampling convtr; look-ahead 0: **supported** | K/V 8 × 71 frames × 1024 × 2 ≈ 4.6 MB F32; conv tails and convtr overlaps; position. The same contents as upstream llama.cpp's `mtmd_gen_state` | +| **MOSS-Audio** (`MOSS_AUDIO`; Nano, full, TTS-Realtime) | patched pretransform + causal sliding-window transformers per stage: **supported** | mirror image, look-ahead 0, −40 dB memory 17–24 s: **supported** | K/V per stage, window = `context_duration × stage frame rate` (the largest of the set); conv tails; position. The hop is a whole patch (3840 samples for Nano at 48 kHz stereo) | +| **NeMo nano codec** | not a streaming target | causal conv, memory 2.2 s: **supported** | conv tails only | +| **DAC, SNAC** | non-causal | non-causal, reach ±0.13–0.20 s: **unsupported** in v1 | | +| **WavTokenizer** | non-causal | global attention, whole-clip reach: **unsupported** in v1 | | +| XCodec2, NeuCodec, Chatterbox S3G, latent decoders, CosyVoice, XY-Tokenizer, Whisper-style encoders | | **unsupported** | | + +**Non-causal models.** A non-causal model's output for a frame depends on +frames after it, so cached context alone cannot reproduce batch output. The +caller's windowed re-decode (#6) stays the method: + +* right look-ahead, trimming and crossfade remain the caller's; +* memory could at most cache the left-context intermediates of the last L + frames (activations, K/V), so the re-decode does not recompute them; +* the saving is bounded by L / (L + chunk + R), and the cached left + activations of a non-causal network still depend on the old right padding, + which needs model-specific handling. + +**Proposal:** unsupported in v1, revisited per model when a host shows the +re-decode cost matters. The phone numbers say it matters most for DAC: RTF 2.5 +windowed vs 1.11 batch at 0.5 s chunks. + +**Reference voices** (Qwen3-TTS ICL): the decoder state for a reference voice +is owned by `codec_speaker`, precomputed when the speaker GGUF is built and +applied internally when a decode uses that speaker. That is a separate future +`codec_speaker` proposal, not part of this API. ## 6. Relation to #6 (windowed stateless streamer) #6 merges first, on its own terms: it changes no public header beyond a comment and needs nothing from this RFC. Afterwards: -1. **Phase 1, STATE kind** for Mimi, the Qwen3 tokenizer and MOSS. In - `common/audio_lm_c.cpp`, `alm_streamer` opens its codec context with DECODE - memory when `codec_model_memory_kind(model, DECODE) == STATE` and just - forwards new frames. Otherwise it keeps #6's window. Measurable win: Qwen3 - streaming on the phone goes from RTF 6.2 to the batch RTF of about 1.5. -2. **Phase 2, WINDOW kind inside the library.** #6's internal - `src/audio_lm_window.h` table and crossfade move into the codec memory as its - WINDOW implementation. `alm_streamer` is then a single path (feed frames, - flush at the end), and #6's host-side window code is deleted. -3. Decoding from frame 0 survives only for NONE-kind codecs. - -So #6 becomes the internal fallback, first in the streamer and then inside the -library, and is not exposed. Its smoke (`tests/e2e/audio_lm_stream_smoke.py`) -becomes the regression test for both kinds. +* For a codec where `codec_model_has_memory(model, DECODE)` is true, + `alm_streamer` (`common/audio_lm_c.cpp`) opens its codec context with DECODE + memory and decodes only the new frames each poll. The left window and the + 20 ms crossfade are then unnecessary, because consecutive outputs join + exactly. + * Expected win on the phone: Qwen3 streaming goes from RTF 6.2 to the batch + RTF of about 1.5. + * The Qwen3 ICL gap goes away once the reference voice state exists (future + `codec_speaker` proposal). +* For every other codec, #6's host-side windowing (L / R table, crossfade) + stays unchanged as the fallback, and decoding from frame 0 stays the default + for codecs with no window entry. +* Emission, trimming and crossfading stay with the streamer in both paths. The + library never takes them over. + +`tests/e2e/audio_lm_stream_smoke.py` covers both paths. With memory, the stream +must match batch to rounding. ## 7. State serialization @@ -281,31 +278,27 @@ header char[4] "CDCM" u32 format_version (1) u32 arch (enum codec_arch) u8[32] model_fingerprint (SHA-256 over tensor names, types, shapes and the - decode-relevant GGUF keys; computed once at load) + graph-relevant GGUF keys; computed once at load) u32 parts (codec_memory_type bits present) per part u32 part (ENCODE / DECODE) - u32 kind (STATE / WINDOW) - u32 impl_version (per-arch layout version) - i64 n_frames, i64 n_samples_pending - i32 n_q, i32 flags (ended, ...) + u32 impl_version (per-arch cache layout version) + i64 n_frames (position) + i32 n_q u32 n_sections section u32 tag, u32 ggml_type, i64 ne[4], u64 nbytes, u8 data[nbytes] (8-byte aligned) ``` -* Section tags name the tensors: `conv_tail[i]`, `k[l]`, `v[l]`, `ring_head`, - `pending_pcm`, `window_codes`. +* Section tags name the cached tensors: `conv_tail[i]`, `convtr_overlap[i]`, + `k[l]`, `v[l]`, `ring_head`. * Data is copied with `ggml_backend_tensor_get`, so a blob saved on the GPU restores on the CPU and the other way round. It is tied to the model file through the fingerprint, not to the backend. * `set_data` validates everything (magic, versions, arch, fingerprint, part, section shapes) before touching the memory. Any mismatch returns 0 and leaves - the state unchanged. -* **Versioning**: no migration. State is a cache that can always be recomputed. - `format_version` changes with the header and `impl_version` with an arch's - layout. The old blob is rejected, and hosts recompute it (Qwen3: re-decode - the reference codes once). -* Size: Qwen3 decode state is about 8 × 71 × 1024 × 2 × 4 B ≈ 4.6 MB F32, plus - tails. That is small enough to keep one per saved voice. + the cache unchanged. +* **Versioning**: no migration. The cache can always be recomputed by + re-feeding the input. `format_version` changes with the header and + `impl_version` with an arch's layout. Old blobs are rejected. ## 8. Thread safety and numerics @@ -316,50 +309,47 @@ section u32 tag, u32 ggml_type, i64 ne[4], u64 nbytes, u8 data[nbytes] (8-byt * Contexts of one model are independent, since each has its own backend instance. Full duplex therefore uses two contexts: encode on one thread, decode on another. -* One context with `BOTH` is allowed, but its encode and decode calls are - serialized because they share the scheduler and eval arena. +* One context with `BOTH` is allowed, but its calls are serialized because they + share the scheduler and eval arena. * The memory handle is valid until `codec_free`. It is not reference counted. -* **Numerics.** Chunked compute changes matmul tiling, so STATE kind matches - batch to rounding, not bit for bit. Smokes assert: +* **Numerics.** Chunked compute changes matmul tiling, so streamed output + matches batch to rounding, not bit for bit. Smokes assert: * PCM: max |Δ| ≤ 1e-4; - * codes: at most 0.1 % flipped, and only at quantizer ties; - * WINDOW kind: the per-model LSD limits of #6. -* State tensors keep the precision the batch graph computes them at (F32 K/V - unless the graph already uses F16). + * codes: at most 0.1 % flipped, and only at quantizer ties. +* Cached tensors keep the precision the batch graph computes them at. ## 9. Open questions -* **Q1. Flush ends the stream**, rather than letting it continue after a - flush. Proposed: ends, which is simpler and matches the "end of utterance" - use. The alternative needs a "pad but keep going" mode that no family needs - today. -* **Q2. `codec_model_memory_kind` and `codec_memory_n_frames`** are beyond the - list Hans gave. Without the first, a host can only learn the kind by failing - `codec_init_from_model`. The second gives frame alignment for full duplex. - Keep both? -* **Q3. Resampling.** Proposed: streamed input must be at the model's rate in - v1. An in-graph streaming resampler with its own tail state comes later. -* **Q4. Voice files.** Should a Qwen3 reference decode state be cached in the - `codec_speaker` / voice file (`codec_audio_lm_save_voice`)? That would touch - `include/codec_speaker.h`, and only by a separate proposal. -* **Q5. Sequence ids.** Proposed: none. One context per sequence, which is how - llama.rn uses contexts. Multi-sequence memory, as with `llama_memory_seq_*`, - would only matter for a server batching many streams through one decoder. -* **Q6. Approximate WINDOW kinds.** Should WavTokenizer stay WINDOW, which is - approximate, or report NONE unless the host opts into approximation? A - `codec_context_params` flag such as `allow_approx_memory` would make the - choice explicit. -* **Q7. Chunk-length graph cache.** Should the library pad short chunks up to - a set of bucket sizes, to cap the number of cached graphs when a host sends - irregular chunks? - -## 10. Test plan (per kind) - -* **Stream vs batch** on random chunk sizes, including 1-frame and sub-hop - chunks: Mimi encode and decode, Qwen3 decode, MOSS decode, DAC, WavTokenizer. +* **Q1. Non-causal support.** The proposal is "later, reported as unsupported + in v1" (§5). Confirm, or name a model that must be in v1. DAC is the + candidate, since its windowed re-decode costs 2.5× batch on the phone. +* **Q2. The final partial frame.** Hop-aligned input only, with the caller + zero-padding the last chunk, means the last frame's codes can differ from + batch (§4.2). The alternative: accept an unaligned last chunk, apply batch's + per-layer tail padding, and leave the part needing a clear before further + input. Is the last-frame difference acceptable, or should v1 offer that? +* **Q3. Sample rate.** Streamed encode input must be at the model's encode + rate. Resampling in a stream needs its own cached tail, so v1 leaves it to the + host. OK? +* **Q4. Graph cache with irregular chunks.** Should the library pad chunks up + to bucket sizes, to cap the number of cached graphs? Padding would conflict + with the exact-output rule, so the alternative is to tell hosts to use a fixed + chunk size and accept more graphs otherwise. + +## 10. Test plan + +* **Stream vs batch** on hop-aligned random chunk sizes down to one frame: + * Mimi encode and decode; + * Qwen3-TTS tokenizer encode and decode; + * MOSS-Audio-Nano encode and decode; + * NeMo decode. + + Tolerances are those of §8. +* **Final chunk**: caller zero-padding gives batch codes for every frame but + the last. * **`set_data(get_data())` round trip**: the continuation is identical to an uninterrupted stream. A blob from another model or part is rejected and the - state is unchanged. + cache is unchanged. * **`clear`** equals a fresh context, and the other part is untouched. -* **Phone benchmark** (Pixel 7 Pro): streaming RTF vs batch for Qwen3 and Mimi - with STATE kind. Target: within 10 % of batch at 0.5 s chunks. +* **Phone** (Pixel 7 Pro): streaming RTF vs batch for Qwen3 and Mimi decode. + Target: within 10 % of batch at 0.5 s chunks. From e9843fe01b3fbfbd19f0d5ee1c76069d39725cd3 Mon Sep 17 00:00:00 2001 From: Hans Date: Sun, 15 Nov 2026 13:35:37 +0800 Subject: [PATCH 3/6] docs(rfc): codec memory is cache + clear + save/restore only Per review, minimal change: models with no context to remember have memory size 0 and enabling it is a valid no-op (no "unsupported"); codec_model_has_memory means "non-zero memory". codec_encode/decode input handling, padding and output are unchanged; no hop-alignment rule, no new status codes, no fixed-per-stream parameters. The only restriction kept: codec_decode_batch neither reads nor updates memory (several sequences vs one). Removed all open questions (padding, sample rate, graph cache, non-causal support). Co-Authored-By: Claude Opus 5.5 --- docs/proposals/codec_memory.md | 328 ++++++++++++--------------------- 1 file changed, 118 insertions(+), 210 deletions(-) diff --git a/docs/proposals/codec_memory.md b/docs/proposals/codec_memory.md index 84828c1..563d8de 100644 --- a/docs/proposals/codec_memory.md +++ b/docs/proposals/codec_memory.md @@ -5,37 +5,46 @@ changes until this document is approved. ## 1. Summary -A `codec_context` can optionally own *memory*: the context a model needs from -earlier input, cached so it is not recomputed, as a `llama_context` caches K/V. -The cached context is: +Minimal change: a `codec_context` can optionally own *memory*, which is three +things: + +1. a cache of the context a model needs from earlier input, as a + `llama_context` caches K/V; +2. a clear; +3. state save and restore. + +What the cache holds: * the K/V of a sliding attention window; * the left tails of convolutions and the overlap partial sums of transposed convolutions; * the position counter. -With memory on, each `codec_encode` / `codec_decode` call sees the cached +With memory on, each `codec_encode` / `codec_decode` call uses the cached context of the previous calls instead of starting from silence. -Memory schedules no output. Each call returns exactly the output for its own -input: as many frames or samples as a stateless call on that input would -return, and the caller decides what to emit, trim or crossfade, as today. For -the models that support memory (causal ones, §5), the output of consecutive -calls equals the matching slice of the batch output. +Nothing else changes: + +* each call processes exactly the input it is given, as today, including the + padding it applies; +* each call returns the same output shape as today; +* the caller decides what to emit, trim or crossfade. + +For a causal model, consecutive calls then produce the matching slices of the +batch output. Encoder memory and decoder memory are separate parts, enabled, cleared and -serialized independently. One sequence per context. Naming follows llama.cpp's +saved independently. One sequence per context. Naming follows llama.cpp's `llama_memory_t`. Out of scope: -* the LLM's own context (its KV cache) is not codec memory; it stays in - llama.cpp; +* the LLM's own context (its KV cache) stays in llama.cpp; * reference-voice decoder state (§5). ## 2. Motivation -Today every public call is stateless. A streaming host that wants batch-quality +Every public call is stateless today. A streaming host that wants batch-quality output therefore either decodes from frame 0 on every chunk, whose cost grows with the square of the stream length, or re-decodes a left window around each chunk (#6). Both recompute context the model already computed. @@ -47,23 +56,19 @@ The cost on a Pixel 7 Pro (4 big cores, F32; RTF = decode time / audio length): | Qwen3-TTS 12 Hz | 1.48 | 6.2 | 3.7 | | Mimi | 0.24 | 0.83 | 0.40 | -For a causal model the context is bounded and cheap to keep: +For a causal model the context is bounded: -* each convolution needs its last (k − 1) · dilation input samples; -* each transposed convolution needs the k − stride overlap it has not yet - added; +* each convolution needs its last (k − 1) · dilation inputs; +* each transposed convolution needs the overlap it has not yet added; * each sliding-window attention layer needs its last W keys and values. -Caching these makes streaming cost the same as batch, and the output is the -batch output, not an approximation. +Caching these makes streaming cost the same as batch, with exact output. -The encoder side needs the same thing: +The same applies on the encoder side: -* **Full duplex (Moshi style)**: the user's microphone is encoded continuously - by a causal Mimi encoder and fed to the LLM frame by frame while the model - speaks. -* **Streaming speech input to an audio LM** (LFM2-Audio and other Mimi-based - LMs): the same pattern without the reply audio. +* full duplex (Moshi style), where the microphone is encoded continuously by a + causal Mimi encoder while the model speaks; +* streaming speech input to Mimi-based audio LMs such as LFM2-Audio. ## 3. API (header diff sketch) @@ -89,17 +94,18 @@ All additions go in `include/codec.h`. Nothing changes in `common/*.h`, + enum codec_memory_type memory; }; @@ -+// Whether the model supports memory for `part` (ENCODE or DECODE). ++// True when `part` (ENCODE or DECODE) of this model has context to cache ++// (non-zero memory). False for models whose output depends on no earlier input ++// beyond the call's own, or that look ahead; enabling memory on them is a no-op. +bool codec_model_has_memory(const struct codec_model * model, enum codec_memory_type part); + +// NULL when the context was created with memory == CODEC_MEMORY_NONE. +codec_memory_t codec_get_memory(const struct codec_context * ctx); + -+// Empty the cached context of the parts in `which` (start of a new stream). -+// The other part is untouched. ++// Empty the cache of the parts in `which`. The other part is untouched. +void codec_memory_clear(codec_memory_t mem, enum codec_memory_type which); + -+// Serialized cached context of the parts in `which` (§7). get_data returns the ++// Save / restore the cache of the parts in `which` (§6). get_data returns the +// bytes written (0 = dst too small); set_data returns the bytes read, or 0 when +// the blob does not fit this model / part, leaving the memory unchanged. +size_t codec_memory_state_get_size(codec_memory_t mem, enum codec_memory_type which); @@ -107,9 +113,12 @@ All additions go in `include/codec.h`. Nothing changes in `common/*.h`, +size_t codec_memory_state_set_data(codec_memory_t mem, enum codec_memory_type which, const uint8_t * src, size_t size); ``` -* The `codec_encode` / `codec_decode` signatures are unchanged, and so are - their parameter structs. -* No status code is added. +* **`codec_model_has_memory` is kept** and means "this part has non-zero + memory". A host such as the #6 streamer needs that answer before it creates a + context, to choose its path. A state size is only available from an existing + context. +* The `codec_encode` / `codec_decode` signatures, their parameter structs and + the status codes are unchanged. * `python/codec_cpp/_ffi.py` mirrors the new field and functions in the same commit. @@ -130,146 +139,56 @@ code, llama.rn) need no source change. Everything else is additive. ## 4. Semantics -### 4.1 General - -* With a part enabled, each call reads that part's cached context, computes its - input with it, and updates the cache in the same graph. -* The output shape is that of a stateless call on the same input. -* Memory never holds raw samples or frames that are waiting to be output. What - it caches is context for future input, never output that has not been - returned yet. -* The output of calls 1..n equals the slice of the batch output on the - concatenated input, to rounding (§8). This holds for every model that reports - memory support, because only causal models do (§5). -* `codec_memory_clear` returns a part to the start of a stream. The next call - behaves like the first call of a batch: same left padding, position 0. - -### 4.2 Encode - -* **Every chunk must be hop-aligned**: `n_samples % hop == 0`, where hop is the - product of the encoder's strides (`codec_model_hop_size`). Otherwise the call - returns `CODEC_STATUS_INVALID_ARG`. -* **The caller pads the last chunk.** Nothing is buffered between calls. -* **What batch encode does at the tail** (checked on Mimi, the Qwen3-TTS - tokenizer and MOSS-Audio-Nano): - * Batch encode does not zero-pad the raw input to the hop. Following the - reference (Moshi / HF `MimiConv1d`), each strided convolution right-pads its - own input to a multiple of its stride, with zeros or, for Mimi's downsample - convolution, by replicating the last value. The padding therefore happens at - every resolution, after nonlinearities. - * On hop-aligned input these extra paddings are all zero length. That is what - makes chunking exact: `encode(x[: k·hop])` equals the first k frames of - `encode(x)` bit for bit, for all three encoders (measured on a 6 s speech - clip, k = 50). - * Consequence for the caller's zero-padding of the last chunk: - * the frame count matches batch (51 frames for 50⅓ hops); - * every frame before the last is identical; - * the last frame can differ, because batch pads per layer and the caller pads - raw samples. Measured: Mimi 1.96 % of codes differ (all of them in the - last frame), Qwen3 tokenizer 0.92 %, MOSS-Audio-Nano 1.96 %. - * A host that needs batch codes for the final partial frame can re-encode that - frame's window statelessly. Q2 covers making the library do it. -* `codec_encode_latent` shares the encode part. - -### 4.3 Decode - -* `codec_decode(ctx, tokens, out, p)` returns `tokens->n_frames × hop` samples, - as a stateless call does. With memory, those samples are the matching slice - of the batch decode: - * the convolutions see the previous frames' tails instead of zero padding; - * attention sees the cached K/V window; - * the transposed convolutions' overlap from the previous chunk is added at the - start. That overlap is a partial sum (an activation), cached like a K/V - entry, and it is not held-back output. -* Batch decode trims the overlap that the last frame's transposed convolutions - would add past the end. A streaming chunk does the same, and the trimmed part - stays in the cache as context for the next chunk. -* `n_q`, the token layout and the decode parameters must stay the same within a - stream. Changing them before a clear returns `CODEC_STATUS_INVALID_ARG`. -* `codec_decode_quantized_representation` shares the decode part. -* `codec_decode_batch` on a context with DECODE memory returns - `CODEC_STATUS_NOT_SUPPORTED`. A batch holds several sequences, and memory - holds one. - -### 4.4 Lifecycle and graphs - -* `codec_init_from_model` allocates the memory: - * device buffers sized from the model's metadata (window lengths, channels, - kernel sizes); - * freed with the context. -* Creating a context fails, with `codec_get_last_error` naming the part, if a - requested part is unsupported. -* With `memory == NONE`, behaviour and numerics are byte-identical to today. -* *One model = one graph per public call* still holds: - * the cache tensors are graph inputs; - * the updated cache is written back in the same graph (`ggml_cpy` into the - memory buffer), as llama.cpp writes its KV cache; - * ring offsets and positions are small input tensors, so a graph is reused - for every chunk of the same length. - - The graph cache key gains the memory flag. Hosts get the best cache hit rate - with a fixed chunk size. - -## 5. Per codec family (v1 = causal models only) +* **Calls.** With a part enabled, `codec_encode` / `codec_encode_latent` or + `codec_decode` / `codec_decode_quantized_representation` reads that part's + cache in place of the zero history a fresh call starts from. It updates the + cache with the context its input leaves behind, in the same graph. Input + handling, padding and output shape are exactly as today. +* **Batch output.** For a model with memory, the outputs of consecutive calls + equal the matching slices of the batch output on the concatenated input, to + rounding (§7). +* **Clear.** `codec_memory_clear` empties the cache, so the next call behaves + like a call on a fresh context. Use it before input that does not continue + the previous input. One case is the caller's responsibility: after a chunk + the call padded (not a whole number of hops), the cache ends in padding, so + clear before continuing. +* **Models without memory.** When `codec_model_has_memory` is false for a part, + enabling it is valid and changes nothing: + * the state size is 0; + * get and set of the empty blob succeed; + * clear does nothing. +* **One required restriction.** `codec_decode_batch` neither reads nor updates + the memory. A batch holds several independent sequences, and memory holds + one. + +Implementation note: the cache tensors are graph inputs, and the updated cache +is written back in the same graph, as llama.cpp writes its KV cache. That keeps +*one model = one graph per public call*. + +## 5. Per codec family Reach is from an impulse test on the host: one frame's codes changed, and the change in output measured before ("look-ahead") and after ("memory") that frame, at −40 dB. -| Family (archs) | Encode | Decode | What the memory caches | +| Family (archs) | Encode memory | Decode memory | What the cache holds | |---|---|---|---| -| **Mimi** (`MIMI`; LFM2-Audio, Moshi; `POCKET_MIMI` for the decoder) | causal SEANet convs, stride-2 downsample, causal transformer with a 250-frame window: **supported** | mirror image, causal, look-ahead 0, −40 dB memory 0.24 s (Moshi's Mimi 2.0 s): **supported** | conv tails (< 1 MB), with the replicate-padded downsample cache seeded from the first input value after a clear, as batch pads; K/V 8 layers × 250 frames × 512 × 2 ≈ 8 MB F32 (4 MB F16) per part; position | -| **Qwen3-TTS 12 Hz tokenizer** (`QWEN3_TTS_TOKENIZER`) | Mimi encoder (`qwen3.encoder.*`): **supported**, same as Mimi | causal convs, 8 transformer layers with a 72-frame window, causal upsampling convtr; look-ahead 0: **supported** | K/V 8 × 71 frames × 1024 × 2 ≈ 4.6 MB F32; conv tails and convtr overlaps; position. The same contents as upstream llama.cpp's `mtmd_gen_state` | -| **MOSS-Audio** (`MOSS_AUDIO`; Nano, full, TTS-Realtime) | patched pretransform + causal sliding-window transformers per stage: **supported** | mirror image, look-ahead 0, −40 dB memory 17–24 s: **supported** | K/V per stage, window = `context_duration × stage frame rate` (the largest of the set); conv tails; position. The hop is a whole patch (3840 samples for Nano at 48 kHz stereo) | -| **NeMo nano codec** | not a streaming target | causal conv, memory 2.2 s: **supported** | conv tails only | -| **DAC, SNAC** | non-causal | non-causal, reach ±0.13–0.20 s: **unsupported** in v1 | | -| **WavTokenizer** | non-causal | global attention, whole-clip reach: **unsupported** in v1 | | -| XCodec2, NeuCodec, Chatterbox S3G, latent decoders, CosyVoice, XY-Tokenizer, Whisper-style encoders | | **unsupported** | | - -**Non-causal models.** A non-causal model's output for a frame depends on -frames after it, so cached context alone cannot reproduce batch output. The -caller's windowed re-decode (#6) stays the method: - -* right look-ahead, trimming and crossfade remain the caller's; -* memory could at most cache the left-context intermediates of the last L - frames (activations, K/V), so the re-decode does not recompute them; -* the saving is bounded by L / (L + chunk + R), and the cached left - activations of a non-causal network still depend on the old right padding, - which needs model-specific handling. - -**Proposal:** unsupported in v1, revisited per model when a host shows the -re-decode cost matters. The phone numbers say it matters most for DAC: RTF 2.5 -windowed vs 1.11 batch at 0.5 s chunks. - -**Reference voices** (Qwen3-TTS ICL): the decoder state for a reference voice -is owned by `codec_speaker`, precomputed when the speaker GGUF is built and -applied internally when a decode uses that speaker. That is a separate future -`codec_speaker` proposal, not part of this API. - -## 6. Relation to #6 (windowed stateless streamer) - -#6 merges first, on its own terms: it changes no public header beyond a comment -and needs nothing from this RFC. Afterwards: - -* For a codec where `codec_model_has_memory(model, DECODE)` is true, - `alm_streamer` (`common/audio_lm_c.cpp`) opens its codec context with DECODE - memory and decodes only the new frames each poll. The left window and the - 20 ms crossfade are then unnecessary, because consecutive outputs join - exactly. - * Expected win on the phone: Qwen3 streaming goes from RTF 6.2 to the batch - RTF of about 1.5. - * The Qwen3 ICL gap goes away once the reference voice state exists (future - `codec_speaker` proposal). -* For every other codec, #6's host-side windowing (L / R table, crossfade) - stays unchanged as the fallback, and decoding from frame 0 stays the default - for codecs with no window entry. -* Emission, trimming and crossfading stay with the streamer in both paths. The - library never takes them over. - -`tests/e2e/audio_lm_stream_smoke.py` covers both paths. With memory, the stream -must match batch to rounding. - -## 7. State serialization +| **Mimi** (`MIMI`; LFM2-Audio, Moshi; `POCKET_MIMI` decoder) | yes: causal SEANet convs, stride-2 downsample, causal transformer with a 250-frame window | yes: mirror image, causal, −40 dB memory 0.24 s (Moshi's Mimi 2.0 s) | conv tails (< 1 MB); K/V 8 layers × 250 frames × 512 × 2 ≈ 8 MB F32 per part; position | +| **Qwen3-TTS 12 Hz tokenizer** (`QWEN3_TTS_TOKENIZER`) | yes: Mimi encoder (`qwen3.encoder.*`) | yes: causal convs, 8 transformer layers with a 72-frame window, causal upsampling convtr | K/V 8 × 71 frames × 1024 × 2 ≈ 4.6 MB F32; conv tails and convtr overlaps; position. The same contents as upstream llama.cpp's `mtmd_gen_state` | +| **MOSS-Audio** (`MOSS_AUDIO`; Nano, full, TTS-Realtime) | yes: causal sliding-window transformers per stage | yes: mirror image, −40 dB memory 17–24 s | K/V per stage, window = `context_duration × stage frame rate`; conv tails; position | +| **NeMo nano codec** | | yes: causal conv, memory 2.2 s | conv tails | +| **DAC, SNAC, WavTokenizer**, XCodec2, NeuCodec, Chatterbox S3G, latent decoders, CosyVoice, XY-Tokenizer, Whisper-style encoders | no (size 0) | no (size 0) | nothing | + +* **Models that look ahead** (non-causal convs, global attention) produce + output that depends on later input. They have no earlier context to remember, + so their memory is 0 and the caller's windowed re-decode (#6) remains how they + stream. +* **Reference voices** (Qwen3-TTS ICL): the decoder state for a reference voice + belongs to `codec_speaker`. It would be precomputed when the speaker GGUF is + built and applied internally when a decode uses that speaker. That is a future + `codec_speaker` proposal. + +## 6. State save / restore The blob is little-endian and self-describing: @@ -282,74 +201,63 @@ header char[4] "CDCM" u32 parts (codec_memory_type bits present) per part u32 part (ENCODE / DECODE) u32 impl_version (per-arch cache layout version) - i64 n_frames (position) - i32 n_q + i64 position u32 n_sections section u32 tag, u32 ggml_type, i64 ne[4], u64 nbytes, u8 data[nbytes] (8-byte aligned) ``` +* For a part with no memory, the size is 0 and no bytes are written. Setting a + 0-byte blob succeeds. * Section tags name the cached tensors: `conv_tail[i]`, `convtr_overlap[i]`, `k[l]`, `v[l]`, `ring_head`. * Data is copied with `ggml_backend_tensor_get`, so a blob saved on the GPU restores on the CPU and the other way round. It is tied to the model file - through the fingerprint, not to the backend. -* `set_data` validates everything (magic, versions, arch, fingerprint, part, - section shapes) before touching the memory. Any mismatch returns 0 and leaves - the cache unchanged. -* **Versioning**: no migration. The cache can always be recomputed by - re-feeding the input. `format_version` changes with the header and - `impl_version` with an arch's layout. Old blobs are rejected. + through the fingerprint. +* `set_data` validates the blob before touching the cache. A mismatch returns 0 + and leaves the cache unchanged. +* **Versioning**: no migration. The cache can always be rebuilt by re-feeding + the input. Old `format_version` / `impl_version` blobs are rejected. -## 8. Thread safety and numerics +## 7. Thread safety and numerics * Thread rules are unchanged: one `codec_context` is used by one thread at a time, and its memory is part of it. -* Calling `state_get_data` while another thread encodes on the same context is - a data race. * Contexts of one model are independent, since each has its own backend - instance. Full duplex therefore uses two contexts: encode on one thread, - decode on another. -* One context with `BOTH` is allowed, but its calls are serialized because they - share the scheduler and eval arena. -* The memory handle is valid until `codec_free`. It is not reference counted. + instance. Full duplex uses two contexts, one per thread. +* The memory handle is valid until `codec_free`. * **Numerics.** Chunked compute changes matmul tiling, so streamed output matches batch to rounding, not bit for bit. Smokes assert: * PCM: max |Δ| ≤ 1e-4; * codes: at most 0.1 % flipped, and only at quantizer ties. -* Cached tensors keep the precision the batch graph computes them at. - -## 9. Open questions - -* **Q1. Non-causal support.** The proposal is "later, reported as unsupported - in v1" (§5). Confirm, or name a model that must be in v1. DAC is the - candidate, since its windowed re-decode costs 2.5× batch on the phone. -* **Q2. The final partial frame.** Hop-aligned input only, with the caller - zero-padding the last chunk, means the last frame's codes can differ from - batch (§4.2). The alternative: accept an unaligned last chunk, apply batch's - per-layer tail padding, and leave the part needing a clear before further - input. Is the last-frame difference acceptable, or should v1 offer that? -* **Q3. Sample rate.** Streamed encode input must be at the model's encode - rate. Resampling in a stream needs its own cached tail, so v1 leaves it to the - host. OK? -* **Q4. Graph cache with irregular chunks.** Should the library pad chunks up - to bucket sizes, to cap the number of cached graphs? Padding would conflict - with the exact-output rule, so the alternative is to tell hosts to use a fixed - chunk size and accept more graphs otherwise. - -## 10. Test plan - -* **Stream vs batch** on hop-aligned random chunk sizes down to one frame: + +## 8. Relation to #6 (windowed stateless streamer) + +#6 merges first, on its own terms: it changes no public header beyond a comment +and needs nothing from this RFC. Afterwards: + +* For a codec where `codec_model_has_memory(model, DECODE)` is true, + `alm_streamer` (`common/audio_lm_c.cpp`) opens its codec context with DECODE + memory and decodes only the new frames each poll. Consecutive outputs then + join exactly, so the left window and crossfade are unnecessary. + * Expected win on the phone: Qwen3 streaming goes from RTF 6.2 to the batch + RTF of about 1.5. +* For every other codec, #6's host-side windowing stays unchanged as the + fallback. +* Emission, trimming and crossfading stay with the streamer in both paths. + +## 9. Test plan + +* **Stream vs batch** on random hop-aligned chunk sizes down to one frame: * Mimi encode and decode; * Qwen3-TTS tokenizer encode and decode; * MOSS-Audio-Nano encode and decode; * NeMo decode. - Tolerances are those of §8. -* **Final chunk**: caller zero-padding gives batch codes for every frame but - the last. + Tolerances are those of §7. * **`set_data(get_data())` round trip**: the continuation is identical to an uninterrupted stream. A blob from another model or part is rejected and the cache is unchanged. * **`clear`** equals a fresh context, and the other part is untouched. +* **No-memory model** (DAC) with memory on: output is byte-identical to memory + off, the state size is 0, and an empty get/set succeeds. * **Phone** (Pixel 7 Pro): streaming RTF vs batch for Qwen3 and Mimi decode. - Target: within 10 % of batch at 0.5 s chunks. From da0cc6d35cd93d9e5e0f3b867060a8b5bc52748a Mon Sep 17 00:00:00 2001 From: Hans Date: Sun, 15 Nov 2026 13:49:28 +0800 Subject: [PATCH 4/6] docs(rfc): codec memory naming: codec_part, is_causal, codec_state_* Per review: codec_model_has_memory becomes codec_model_is_causal (no look-ahead; memory then makes streamed output equal batch; non-causal parts have memory size 0). enum codec_memory_type becomes the bit set enum codec_part (NONE / ENCODER / DECODER / ALL), shared by the memory field, clear's `parts` and the state calls. Save/restore moves to the context as in llama.cpp: codec_state_get_size / get_data / set_data. The #6 streamer takes the incremental path when the decoder is causal. Co-Authored-By: Claude Opus 5.5 --- docs/proposals/codec_memory.md | 77 ++++++++++++++++++---------------- 1 file changed, 41 insertions(+), 36 deletions(-) diff --git a/docs/proposals/codec_memory.md b/docs/proposals/codec_memory.md index 563d8de..0d99449 100644 --- a/docs/proposals/codec_memory.md +++ b/docs/proposals/codec_memory.md @@ -77,12 +77,12 @@ All additions go in `include/codec.h`. Nothing changes in `common/*.h`, ```diff @@ include/codec.h -+// Which parts of a context's memory: a bit set. -+enum codec_memory_type { -+ CODEC_MEMORY_NONE = 0, -+ CODEC_MEMORY_ENCODE = 1, -+ CODEC_MEMORY_DECODE = 2, -+ CODEC_MEMORY_BOTH = 3, // ENCODE | DECODE ++// Parts of a codec: a bit set. ++enum codec_part { ++ CODEC_PART_NONE = 0, ++ CODEC_PART_ENCODER = 1, ++ CODEC_PART_DECODER = 2, ++ CODEC_PART_ALL = 3, // ENCODER | DECODER +}; + +typedef struct codec_memory * codec_memory_t; @@ -90,33 +90,37 @@ All additions go in `include/codec.h`. Nothing changes in `common/*.h`, struct codec_context_params { int32_t seed; + // Parts that cache context across codec_encode / codec_decode calls. -+ // Default CODEC_MEMORY_NONE: every call is independent, as today. -+ enum codec_memory_type memory; ++ // Default CODEC_PART_NONE: every call is independent, as today. ++ enum codec_part memory; }; @@ -+// True when `part` (ENCODE or DECODE) of this model has context to cache -+// (non-zero memory). False for models whose output depends on no earlier input -+// beyond the call's own, or that look ahead; enabling memory on them is a no-op. -+bool codec_model_has_memory(const struct codec_model * model, enum codec_memory_type part); ++// True when `part`'s (ENCODER or DECODER) output for a frame depends only on the ++// current and earlier input (no look-ahead). Then memory makes streamed output ++// equal batch output. A non-causal part has memory size 0. ++bool codec_model_is_causal(const struct codec_model * model, enum codec_part part); + -+// NULL when the context was created with memory == CODEC_MEMORY_NONE. ++// NULL when the context was created with memory == CODEC_PART_NONE. +codec_memory_t codec_get_memory(const struct codec_context * ctx); + -+// Empty the cache of the parts in `which`. The other part is untouched. -+void codec_memory_clear(codec_memory_t mem, enum codec_memory_type which); ++// Empty the cache of `parts`. Other parts are untouched. ++void codec_memory_clear(codec_memory_t mem, enum codec_part parts); + -+// Save / restore the cache of the parts in `which` (§6). get_data returns the -+// bytes written (0 = dst too small); set_data returns the bytes read, or 0 when -+// the blob does not fit this model / part, leaving the memory unchanged. -+size_t codec_memory_state_get_size(codec_memory_t mem, enum codec_memory_type which); -+size_t codec_memory_state_get_data(codec_memory_t mem, enum codec_memory_type which, uint8_t * dst, size_t size); -+size_t codec_memory_state_set_data(codec_memory_t mem, enum codec_memory_type which, const uint8_t * src, size_t size); ++// Save / restore the cached context of `parts` (§6), as llama_state_*. ++// get_data returns the bytes written (0 = dst too small); set_data returns the ++// bytes read, or 0 when the blob does not fit this model / parts, leaving the ++// cache unchanged. ++size_t codec_state_get_size(struct codec_context * ctx, enum codec_part parts); ++size_t codec_state_get_data(struct codec_context * ctx, enum codec_part parts, uint8_t * dst, size_t size); ++size_t codec_state_set_data(struct codec_context * ctx, enum codec_part parts, const uint8_t * src, size_t size); ``` -* **`codec_model_has_memory` is kept** and means "this part has non-zero - memory". A host such as the #6 streamer needs that answer before it creates a - context, to choose its path. A state size is only available from an existing - context. +* **`codec_model_is_causal`** is a model property. A host such as the #6 + streamer needs the answer before it creates a context, to choose its path. + For a causal part, memory makes streamed output equal batch output. A + non-causal part has memory size 0. +* **`enum codec_part`** names a codec's parts. It is shared by the `memory` + field, `codec_memory_clear`, the state functions and `codec_model_is_causal`, + so it is not memory-specific. * The `codec_encode` / `codec_decode` signatures, their parameter structs and the status codes are unchanged. * `python/codec_cpp/_ffi.py` mirrors the new field and functions in the same @@ -128,8 +132,8 @@ All additions go in `include/codec.h`. Nothing changes in `common/*.h`, |---|---| | `llama_context_params` (KV types, `n_ctx`) | `codec_context_params.memory` | | `llama_get_memory(ctx)` | `codec_get_memory(ctx)` | -| `llama_memory_clear(mem, data)` | `codec_memory_clear(mem, which)` | -| `llama_state_seq_get_size / get_data / set_data` (on ctx, per seq) | `codec_memory_state_*` (on mem, per part) | +| `llama_memory_clear(mem, data)` | `codec_memory_clear(mem, parts)` | +| `llama_state_get_size / get_data / set_data(ctx, …)` | `codec_state_get_size / get_data / set_data(ctx, parts, …)` | | `llama_memory_seq_rm / cp / keep / add` | none (one sequence) | **ABI.** `codec_context_params` grows from 4 to 8 bytes and is passed by value @@ -152,8 +156,8 @@ code, llama.rn) need no source change. Everything else is additive. the previous input. One case is the caller's responsibility: after a chunk the call padded (not a whole number of hops), the cache ends in padding, so clear before continuing. -* **Models without memory.** When `codec_model_has_memory` is false for a part, - enabling it is valid and changes nothing: +* **Non-causal parts.** When `codec_model_is_causal` is false for a part, its + memory size is 0, and enabling memory on it is valid and changes nothing: * the state size is 0; * get and set of the empty blob succeed; * clear does nothing. @@ -171,13 +175,13 @@ Reach is from an impulse test on the host: one frame's codes changed, and the change in output measured before ("look-ahead") and after ("memory") that frame, at −40 dB. -| Family (archs) | Encode memory | Decode memory | What the cache holds | +| Family (archs) | Encoder causal (memory) | Decoder causal (memory) | What the cache holds | |---|---|---|---| | **Mimi** (`MIMI`; LFM2-Audio, Moshi; `POCKET_MIMI` decoder) | yes: causal SEANet convs, stride-2 downsample, causal transformer with a 250-frame window | yes: mirror image, causal, −40 dB memory 0.24 s (Moshi's Mimi 2.0 s) | conv tails (< 1 MB); K/V 8 layers × 250 frames × 512 × 2 ≈ 8 MB F32 per part; position | | **Qwen3-TTS 12 Hz tokenizer** (`QWEN3_TTS_TOKENIZER`) | yes: Mimi encoder (`qwen3.encoder.*`) | yes: causal convs, 8 transformer layers with a 72-frame window, causal upsampling convtr | K/V 8 × 71 frames × 1024 × 2 ≈ 4.6 MB F32; conv tails and convtr overlaps; position. The same contents as upstream llama.cpp's `mtmd_gen_state` | | **MOSS-Audio** (`MOSS_AUDIO`; Nano, full, TTS-Realtime) | yes: causal sliding-window transformers per stage | yes: mirror image, −40 dB memory 17–24 s | K/V per stage, window = `context_duration × stage frame rate`; conv tails; position | | **NeMo nano codec** | | yes: causal conv, memory 2.2 s | conv tails | -| **DAC, SNAC, WavTokenizer**, XCodec2, NeuCodec, Chatterbox S3G, latent decoders, CosyVoice, XY-Tokenizer, Whisper-style encoders | no (size 0) | no (size 0) | nothing | +| **DAC, SNAC, WavTokenizer**, XCodec2, NeuCodec, Chatterbox S3G, latent decoders, CosyVoice, XY-Tokenizer, Whisper-style encoders | no (memory 0) | no (memory 0) | nothing | * **Models that look ahead** (non-causal convs, global attention) produce output that depends on later input. They have no earlier context to remember, @@ -198,8 +202,8 @@ header char[4] "CDCM" u32 arch (enum codec_arch) u8[32] model_fingerprint (SHA-256 over tensor names, types, shapes and the graph-relevant GGUF keys; computed once at load) - u32 parts (codec_memory_type bits present) -per part u32 part (ENCODE / DECODE) + u32 parts (codec_part bits present) +per part u32 part (ENCODER / DECODER) u32 impl_version (per-arch cache layout version) i64 position u32 n_sections @@ -235,9 +239,10 @@ section u32 tag, u32 ggml_type, i64 ne[4], u64 nbytes, u8 data[nbytes] (8-byt #6 merges first, on its own terms: it changes no public header beyond a comment and needs nothing from this RFC. Afterwards: -* For a codec where `codec_model_has_memory(model, DECODE)` is true, - `alm_streamer` (`common/audio_lm_c.cpp`) opens its codec context with DECODE - memory and decodes only the new frames each poll. Consecutive outputs then +* When `codec_model_is_causal(model, CODEC_PART_DECODER)` is true, + `alm_streamer` (`common/audio_lm_c.cpp`) takes the incremental path: it opens + its codec context with `memory = CODEC_PART_DECODER` and decodes only the new + frames each poll. Consecutive outputs then join exactly, so the left window and crossfade are unnecessary. * Expected win on the phone: Qwen3 streaming goes from RTF 6.2 to the batch RTF of about 1.5. From e0d6100fe8d492cfe8bbf9f351fc7008c834cd20 Mon Sep 17 00:00:00 2001 From: Hans Date: Sun, 15 Nov 2026 14:16:07 +0800 Subject: [PATCH 5/6] docs(rfc): codec memory per side handles + look_back/look_ahead GGUF keys Per Hans's approved direction: drop enum codec_part. One memory handle per side (encoder_memory / decoder_memory params, codec_get_encoder_memory / codec_get_decoder_memory), clear and state save/restore on the handle (deliberately unlike llama_state_*(ctx)), codec_model_encoder_is_causal / codec_model_decoder_is_causal. New GGUF keys codec.{encoder,decoder}.{look_back,look_ahead} in frames, written by converters; is_causal = look_ahead == 0; -1 = unbounded; look_back on a causal side is the cached context length. Missing keys fall back to per-arch defaults (old GGUFs load); #6's window table becomes those defaults. Adds a Rollout section (published GGUFs updated in place later, each upload approved separately). Co-Authored-By: Claude Opus 5.5 --- docs/proposals/codec_memory.md | 271 +++++++++++++++++++-------------- 1 file changed, 157 insertions(+), 114 deletions(-) diff --git a/docs/proposals/codec_memory.md b/docs/proposals/codec_memory.md index 0d99449..2dd5406 100644 --- a/docs/proposals/codec_memory.md +++ b/docs/proposals/codec_memory.md @@ -5,10 +5,10 @@ changes until this document is approved. ## 1. Summary -Minimal change: a `codec_context` can optionally own *memory*, which is three -things: +Minimal change: a `codec_context` can optionally own an encoder memory and a +decoder memory. Each is three things: -1. a cache of the context a model needs from earlier input, as a +1. a cache of the context that side needs from earlier input, as a `llama_context` caches K/V; 2. a clear; 3. state save and restore. @@ -20,8 +20,8 @@ What the cache holds: convolutions; * the position counter. -With memory on, each `codec_encode` / `codec_decode` call uses the cached -context of the previous calls instead of starting from silence. +With a memory on, each `codec_encode` / `codec_decode` call on that side uses +the cached context of the previous calls instead of starting from silence. Nothing else changes: @@ -30,17 +30,16 @@ Nothing else changes: * each call returns the same output shape as today; * the caller decides what to emit, trim or crossfade. -For a causal model, consecutive calls then produce the matching slices of the -batch output. +For a causal side, consecutive calls produce the matching slices of the batch +output. -Encoder memory and decoder memory are separate parts, enabled, cleared and -saved independently. One sequence per context. Naming follows llama.cpp's -`llama_memory_t`. +Each side's context reach is recorded in the GGUF as `look_back` / +`look_ahead` frames (§5). Out of scope: * the LLM's own context (its KV cache) stays in llama.cpp; -* reference-voice decoder state (§5). +* reference-voice decoder state (§6). ## 2. Motivation @@ -77,180 +76,221 @@ All additions go in `include/codec.h`. Nothing changes in `common/*.h`, ```diff @@ include/codec.h -+// Parts of a codec: a bit set. -+enum codec_part { -+ CODEC_PART_NONE = 0, -+ CODEC_PART_ENCODER = 1, -+ CODEC_PART_DECODER = 2, -+ CODEC_PART_ALL = 3, // ENCODER | DECODER -+}; -+ +typedef struct codec_memory * codec_memory_t; + struct codec_context_params { int32_t seed; -+ // Parts that cache context across codec_encode / codec_decode calls. -+ // Default CODEC_PART_NONE: every call is independent, as today. -+ enum codec_part memory; ++ // Cache context across calls (default false: every call independent, as today). ++ bool encoder_memory; // codec_encode / codec_encode_latent ++ bool decoder_memory; // codec_decode / codec_decode_quantized_representation }; @@ -+// True when `part`'s (ENCODER or DECODER) output for a frame depends only on the -+// current and earlier input (no look-ahead). Then memory makes streamed output -+// equal batch output. A non-causal part has memory size 0. -+bool codec_model_is_causal(const struct codec_model * model, enum codec_part part); ++// True when that side's output for a frame depends only on the current and ++// earlier input: its look_ahead (GGUF codec..look_ahead) is 0. Memory ++// then makes streamed output equal batch output; a non-causal side's memory ++// has size 0. ++bool codec_model_encoder_is_causal(const struct codec_model * model); ++bool codec_model_decoder_is_causal(const struct codec_model * model); + -+// NULL when the context was created with memory == CODEC_PART_NONE. -+codec_memory_t codec_get_memory(const struct codec_context * ctx); ++// NULL when that memory is not enabled in the context params. ++codec_memory_t codec_get_encoder_memory(const struct codec_context * ctx); ++codec_memory_t codec_get_decoder_memory(const struct codec_context * ctx); + -+// Empty the cache of `parts`. Other parts are untouched. -+void codec_memory_clear(codec_memory_t mem, enum codec_part parts); ++// Empty the cache: the next call behaves as on a fresh context. ++void codec_memory_clear(codec_memory_t mem); + -+// Save / restore the cached context of `parts` (§6), as llama_state_*. -+// get_data returns the bytes written (0 = dst too small); set_data returns the -+// bytes read, or 0 when the blob does not fit this model / parts, leaving the -+// cache unchanged. -+size_t codec_state_get_size(struct codec_context * ctx, enum codec_part parts); -+size_t codec_state_get_data(struct codec_context * ctx, enum codec_part parts, uint8_t * dst, size_t size); -+size_t codec_state_set_data(struct codec_context * ctx, enum codec_part parts, const uint8_t * src, size_t size); ++// Save / restore the cache (§7). get_data returns the bytes written (0 = dst ++// too small); set_data returns the bytes read, or 0 when the blob does not fit ++// this model and side, leaving the cache unchanged. ++size_t codec_memory_state_get_size(codec_memory_t mem); ++size_t codec_memory_state_get_data(codec_memory_t mem, uint8_t * dst, size_t size); ++size_t codec_memory_state_set_data(codec_memory_t mem, const uint8_t * src, size_t size); ``` -* **`codec_model_is_causal`** is a model property. A host such as the #6 +* **One handle per side.** There is no part selector: a context has an + encoder memory, a decoder memory, both or neither, and every memory call acts + on the one handle it is given. +* **State lives on the memory handle, not on the context.** This deliberately + departs from `llama_state_*(ctx, …)`, so that it is always clear which side's + state is saved. +* **`codec_model_*_is_causal`** is a model property. A host such as the #6 streamer needs the answer before it creates a context, to choose its path. - For a causal part, memory makes streamed output equal batch output. A - non-causal part has memory size 0. -* **`enum codec_part`** names a codec's parts. It is shared by the `memory` - field, `codec_memory_clear`, the state functions and `codec_model_is_causal`, - so it is not memory-specific. * The `codec_encode` / `codec_decode` signatures, their parameter structs and the status codes are unchanged. -* `python/codec_cpp/_ffi.py` mirrors the new field and functions in the same +* `python/codec_cpp/_ffi.py` mirrors the new fields and functions in the same commit. **Mapping to llama.cpp** | llama.cpp | codec.cpp | |---|---| -| `llama_context_params` (KV types, `n_ctx`) | `codec_context_params.memory` | -| `llama_get_memory(ctx)` | `codec_get_memory(ctx)` | -| `llama_memory_clear(mem, data)` | `codec_memory_clear(mem, parts)` | -| `llama_state_get_size / get_data / set_data(ctx, …)` | `codec_state_get_size / get_data / set_data(ctx, parts, …)` | +| `llama_context_params` (KV settings) | `codec_context_params.encoder_memory` / `decoder_memory` | +| `llama_get_memory(ctx)` | `codec_get_encoder_memory(ctx)` / `codec_get_decoder_memory(ctx)` | +| `llama_memory_clear(mem, data)` | `codec_memory_clear(mem)` | +| `llama_state_get_size / get_data / set_data(ctx, …)` | `codec_memory_state_get_size / get_data / set_data(mem, …)` (on the handle, by design) | | `llama_memory_seq_rm / cp / keep / add` | none (one sequence) | -**ABI.** `codec_context_params` grows from 4 to 8 bytes and is passed by value -to `codec_init_from_model`, so binaries built against the old header must be -rebuilt. Hosts that start from `codec_context_default_params()` (all in-tree -code, llama.rn) need no source change. Everything else is additive. +**ABI.** `codec_context_params` grows (two `bool`s; 8 bytes with padding) and is +passed by value to `codec_init_from_model`, so binaries built against the old +header must be rebuilt. Hosts that start from `codec_context_default_params()` +(all in-tree code, llama.rn) need no source change. Everything else is +additive. ## 4. Semantics -* **Calls.** With a part enabled, `codec_encode` / `codec_encode_latent` or - `codec_decode` / `codec_decode_quantized_representation` reads that part's - cache in place of the zero history a fresh call starts from. It updates the +* **Calls.** With a side's memory enabled, that side's calls read its cache in + place of the zero history a fresh call starts from. Each call updates the cache with the context its input leaves behind, in the same graph. Input handling, padding and output shape are exactly as today. -* **Batch output.** For a model with memory, the outputs of consecutive calls - equal the matching slices of the batch output on the concatenated input, to - rounding (§7). -* **Clear.** `codec_memory_clear` empties the cache, so the next call behaves - like a call on a fresh context. Use it before input that does not continue - the previous input. One case is the caller's responsibility: after a chunk - the call padded (not a whole number of hops), the cache ends in padding, so - clear before continuing. -* **Non-causal parts.** When `codec_model_is_causal` is false for a part, its - memory size is 0, and enabling memory on it is valid and changes nothing: +* **Batch output.** On a causal side, the outputs of consecutive calls equal + the matching slices of the batch output on the concatenated input, to rounding + (§8). +* **Clear.** `codec_memory_clear` empties one side's cache. Use it before input + that does not continue the previous input. One case is the caller's + responsibility: after a chunk the call padded (not a whole number of hops), + the cache ends in padding, so clear before continuing. +* **Non-causal sides.** On a side with `look_ahead > 0`, enabling memory is + valid and changes nothing: * the state size is 0; * get and set of the empty blob succeed; * clear does nothing. * **One required restriction.** `codec_decode_batch` neither reads nor updates - the memory. A batch holds several independent sequences, and memory holds - one. + the decoder memory. A batch holds several independent sequences, and memory + holds one. Implementation note: the cache tensors are graph inputs, and the updated cache is written back in the same graph, as llama.cpp writes its KV cache. That keeps *one model = one graph per public call*. -## 5. Per codec family - -Reach is from an impulse test on the host: one frame's codes changed, and the -change in output measured before ("look-ahead") and after ("memory") that frame, -at −40 dB. - -| Family (archs) | Encoder causal (memory) | Decoder causal (memory) | What the cache holds | +## 5. GGUF metadata: look_back / look_ahead + +Four keys, in frames of that side (codec frames, at the hop rate), written by +the converters: + +| Key | Type | Meaning | +|---|---|---| +| `codec.encoder.look_back` | i32 | past frames of context the encoder uses | +| `codec.encoder.look_ahead` | i32 | future frames the encoder's output for a frame depends on | +| `codec.decoder.look_back` | i32 | as above, for the decoder | +| `codec.decoder.look_ahead` | i32 | as above, for the decoder | + +* **Causality.** `is_causal` ⇔ `look_ahead == 0`. The value −1 means + unbounded (global attention, flow): the side is non-causal and no window + covers its reach. +* **On a causal side, `look_back` is the cached context length**: the number + of past frames the memory keeps. + * For an attention layer that is its sliding window, so the cache holds + `look_back` frames of K/V per layer. + * Convolution tails are shorter than one look-back and are kept per layer as + the kernel needs. + * Memory size is therefore about `n_layers × look_back × kv_dim × 2 × + sizeof(type)` plus small conv tails. Caching that window exactly reproduces + batch output, even where the impulse response reaches further, because each + layer's cached K/V already folds in what came before. +* **On a non-causal side**, `look_back` / `look_ahead` are the left and right + windows a host re-decodes around each chunk without memory: #6's `left` / + `right`, in frames instead of seconds. Memory size is 0. +* **Loading old GGUFs.** When the keys are missing, the loader falls back to + per-arch defaults. New code must load old GGUFs. #6's hard-coded table in + `src/audio_lm_window.h` becomes those defaults (for non-causal sides), and + the streamer reads the metadata first. + +Per-arch values (these become the defaults; frames at each model's own rate): + +| Arch | Encoder look_back / look_ahead | Decoder look_back / look_ahead | Source | |---|---|---|---| -| **Mimi** (`MIMI`; LFM2-Audio, Moshi; `POCKET_MIMI` decoder) | yes: causal SEANet convs, stride-2 downsample, causal transformer with a 250-frame window | yes: mirror image, causal, −40 dB memory 0.24 s (Moshi's Mimi 2.0 s) | conv tails (< 1 MB); K/V 8 layers × 250 frames × 512 × 2 ≈ 8 MB F32 per part; position | -| **Qwen3-TTS 12 Hz tokenizer** (`QWEN3_TTS_TOKENIZER`) | yes: Mimi encoder (`qwen3.encoder.*`) | yes: causal convs, 8 transformer layers with a 72-frame window, causal upsampling convtr | K/V 8 × 71 frames × 1024 × 2 ≈ 4.6 MB F32; conv tails and convtr overlaps; position. The same contents as upstream llama.cpp's `mtmd_gen_state` | -| **MOSS-Audio** (`MOSS_AUDIO`; Nano, full, TTS-Realtime) | yes: causal sliding-window transformers per stage | yes: mirror image, −40 dB memory 17–24 s | K/V per stage, window = `context_duration × stage frame rate`; conv tails; position | -| **NeMo nano codec** | | yes: causal conv, memory 2.2 s | conv tails | -| **DAC, SNAC, WavTokenizer**, XCodec2, NeuCodec, Chatterbox S3G, latent decoders, CosyVoice, XY-Tokenizer, Whisper-style encoders | no (memory 0) | no (memory 0) | nothing | - -* **Models that look ahead** (non-causal convs, global attention) produce - output that depends on later input. They have no earlier context to remember, - so their memory is 0 and the caller's windowed re-decode (#6) remains how they - stream. -* **Reference voices** (Qwen3-TTS ICL): the decoder state for a reference voice - belongs to `codec_speaker`. It would be precomputed when the speaker GGUF is - built and applied internally when a decode uses that speaker. That is a future - `codec_speaker` proposal. - -## 6. State save / restore - -The blob is little-endian and self-describing: +| Mimi (12.5 Hz) | 250 / 0 | 250 / 0 | transformer sliding window (HF `sliding_window` 250), causal convs | +| Qwen3-TTS tokenizer (12.5 Hz) | 250 / 0 (Mimi encoder) | 72 / 0 | decoder `qwen3.decoder.sliding_window` 72 | +| MOSS-Audio | per-stage `context_duration` in frames / 0 | same / 0 | converter computes it from the stage windows | +| NeMo nano codec | (no encoder streaming) | 27 / 0 | conv receptive field (impulse: 2.2 s) | +| DAC 16 kHz (50 Hz) | n/a | 16 / 16 | #6 window 0.32 s / 0.32 s (reach ±10 frames) | +| WavTokenizer large (75 Hz) | n/a | 96 / 24 | #6's accepted window 1.28 s / 0.32 s | +| SNAC | n/a | 16 / 16 (proposed) | reach ±9 frames; not yet in #6 | +| XCodec2, NeuCodec, Chatterbox S3G, latent decoders | n/a | −1 / −1 | global attention or flow | + +* "n/a" encoder entries: the converter writes the measured reach of the + encoder when that side is converted. Until then, a missing encoder key on a + non-causal arch defaults to −1 / −1. +* #6's 1.28 s windows for Mimi and Qwen3 decoders do not carry over: those + decoders are causal, so the streamer takes the memory path (§9) and needs no + window. +* DAC is per file: the 24 kHz and 44 kHz variants have other frame rates, so + their converter writes their own frame counts. + +## 6. Reference voices + +The decoder state for a reference voice (Qwen3-TTS ICL) belongs to +`codec_speaker`. It would be precomputed when the speaker GGUF is built and +applied internally when a decode uses that speaker. That is a future +`codec_speaker` proposal. + +## 7. State save / restore + +Per memory handle, the blob is little-endian and self-describing: ``` header char[4] "CDCM" u32 format_version (1) u32 arch (enum codec_arch) + u32 side (0 = encoder, 1 = decoder) u8[32] model_fingerprint (SHA-256 over tensor names, types, shapes and the graph-relevant GGUF keys; computed once at load) - u32 parts (codec_part bits present) -per part u32 part (ENCODER / DECODER) u32 impl_version (per-arch cache layout version) i64 position u32 n_sections section u32 tag, u32 ggml_type, i64 ne[4], u64 nbytes, u8 data[nbytes] (8-byte aligned) ``` -* For a part with no memory, the size is 0 and no bytes are written. Setting a +* A non-causal side's memory has size 0: nothing is written, and setting a 0-byte blob succeeds. * Section tags name the cached tensors: `conv_tail[i]`, `convtr_overlap[i]`, `k[l]`, `v[l]`, `ring_head`. * Data is copied with `ggml_backend_tensor_get`, so a blob saved on the GPU - restores on the CPU and the other way round. It is tied to the model file - through the fingerprint. + restores on the CPU and the other way round. It is tied to the model file and + the side through the fingerprint and the `side` field. * `set_data` validates the blob before touching the cache. A mismatch returns 0 and leaves the cache unchanged. * **Versioning**: no migration. The cache can always be rebuilt by re-feeding the input. Old `format_version` / `impl_version` blobs are rejected. -## 7. Thread safety and numerics +## 8. Thread safety and numerics * Thread rules are unchanged: one `codec_context` is used by one thread at a - time, and its memory is part of it. + time, and its memories are part of it. * Contexts of one model are independent, since each has its own backend instance. Full duplex uses two contexts, one per thread. -* The memory handle is valid until `codec_free`. +* A memory handle is valid until `codec_free`. * **Numerics.** Chunked compute changes matmul tiling, so streamed output matches batch to rounding, not bit for bit. Smokes assert: * PCM: max |Δ| ≤ 1e-4; * codes: at most 0.1 % flipped, and only at quantizer ties. -## 8. Relation to #6 (windowed stateless streamer) +## 9. Relation to #6 (windowed stateless streamer) #6 merges first, on its own terms: it changes no public header beyond a comment and needs nothing from this RFC. Afterwards: -* When `codec_model_is_causal(model, CODEC_PART_DECODER)` is true, - `alm_streamer` (`common/audio_lm_c.cpp`) takes the incremental path: it opens - its codec context with `memory = CODEC_PART_DECODER` and decodes only the new - frames each poll. Consecutive outputs then - join exactly, so the left window and crossfade are unnecessary. +* When `codec_model_decoder_is_causal(model)` is true, `alm_streamer` + (`common/audio_lm_c.cpp`) takes the incremental path: it opens its codec + context with `decoder_memory = true` and decodes only the new frames each + poll. Consecutive outputs join exactly, so no window or crossfade is needed. * Expected win on the phone: Qwen3 streaming goes from RTF 6.2 to the batch RTF of about 1.5. -* For every other codec, #6's host-side windowing stays unchanged as the - fallback. +* Otherwise it keeps #6's windowed path. The window becomes the decoder's + `look_back` / `look_ahead`, from metadata or the per-arch default. With −1, it + decodes from frame 0 as today. * Emission, trimming and crossfading stay with the streamer in both paths. -## 9. Test plan +## 10. Rollout + +1. Approve this RFC. +2. Implement the API, the loader keys with per-arch defaults, and the cache for + the causal archs. Old GGUFs keep working through the defaults. +3. Update the converters to write the four keys. +4. Update the published GGUFs in place with the new metadata, which changes no + weights. Each upload is approved separately. + +## 11. Test plan * **Stream vs batch** on random hop-aligned chunk sizes down to one frame: * Mimi encode and decode; @@ -258,11 +298,14 @@ and needs nothing from this RFC. Afterwards: * MOSS-Audio-Nano encode and decode; * NeMo decode. - Tolerances are those of §7. + Tolerances are those of §8. * **`set_data(get_data())` round trip**: the continuation is identical to an - uninterrupted stream. A blob from another model or part is rejected and the + uninterrupted stream. A blob from another model or side is rejected and the cache is unchanged. -* **`clear`** equals a fresh context, and the other part is untouched. -* **No-memory model** (DAC) with memory on: output is byte-identical to memory - off, the state size is 0, and an empty get/set succeeds. +* **`clear`** on one side equals a fresh context for that side, and the other + side is untouched. +* **Non-causal side** (DAC decoder) with memory on: output is byte-identical to + memory off, the state size is 0, and an empty get/set succeeds. +* **Old GGUF** (no look keys): the loader gives the per-arch defaults, and the + #6 smoke output is unchanged. * **Phone** (Pixel 7 Pro): streaming RTF vs batch for Qwen3 and Mimi decode. From e7abd2a6cdf7393b06e9134b7abf30a68471d150 Mon Sep 17 00:00:00 2001 From: Hans Date: Sun, 15 Nov 2026 15:34:27 +0800 Subject: [PATCH 6/6] docs(rfc): codec memory: Mimi look_back is 125 codec frames Mimi's transformers (also the Qwen3-TTS tokenizer's encoder) run at 25 Hz, twice the 12.5 Hz codec frame rate, so their 250-step sliding window is 125 codec frames, not 250. look_back is stated in codec frames throughout; a layer's cache spans its window at its own rate. Co-Authored-By: Claude Opus 5.5 --- docs/proposals/codec_memory.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/proposals/codec_memory.md b/docs/proposals/codec_memory.md index 2dd5406..4000fe2 100644 --- a/docs/proposals/codec_memory.md +++ b/docs/proposals/codec_memory.md @@ -179,8 +179,10 @@ the converters: covers its reach. * **On a causal side, `look_back` is the cached context length**: the number of past frames the memory keeps. - * For an attention layer that is its sliding window, so the cache holds - `look_back` frames of K/V per layer. + * For an attention layer that is its sliding window, converted to codec + frames: the cache holds that window, minus the current step, of K/V per + layer, at the layer's own rate. Mimi's transformers run at twice the + codec frame rate, so their 250-step window is 125 codec frames. * Convolution tails are shorter than one look-back and are kept per layer as the kernel needs. * Memory size is therefore about `n_layers × look_back × kv_dim × 2 × @@ -199,8 +201,8 @@ Per-arch values (these become the defaults; frames at each model's own rate): | Arch | Encoder look_back / look_ahead | Decoder look_back / look_ahead | Source | |---|---|---|---| -| Mimi (12.5 Hz) | 250 / 0 | 250 / 0 | transformer sliding window (HF `sliding_window` 250), causal convs | -| Qwen3-TTS tokenizer (12.5 Hz) | 250 / 0 (Mimi encoder) | 72 / 0 | decoder `qwen3.decoder.sliding_window` 72 | +| Mimi (12.5 Hz) | 125 / 0 | 125 / 0 | transformer sliding window: 250 steps (HF `sliding_window`) at the transformer's 25 Hz = 125 codec frames; causal convs | +| Qwen3-TTS tokenizer (12.5 Hz) | 125 / 0 (Mimi encoder, same 250-step window at 25 Hz) | 72 / 0 | decoder `qwen3.decoder.sliding_window` 72 (its transformer runs at 12.5 Hz) | | MOSS-Audio | per-stage `context_duration` in frames / 0 | same / 0 | converter computes it from the stage windows | | NeMo nano codec | (no encoder streaming) | 27 / 0 | conv receptive field (impulse: 2.2 s) | | DAC 16 kHz (50 Hz) | n/a | 16 / 16 | #6 window 0.32 s / 0.32 s (reach ±10 frames) |