Skip to content

feat: codec memory (cached encoder / decoder context), RFC #8 - #9

Draft
hans00 wants to merge 9 commits into
mainfrom
feat/codec-memory
Draft

hans00 wants to merge 9 commits into
mainfrom
feat/codec-memory

Conversation

@hans00

@hans00 hans00 commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

This implements the codec memory API approved in RFC #8 (as of e0d6100): a context can cache the context its encoder and/or decoder need from earlier input.

⚠ Batch output changes for Mimi-arch codecs on clips longer than 10 s (commit 287bef0, fix(mimi)!).

  • Affected: Mimi, CSM, LFM2-Audio and Moshi codecs, plus the Qwen3-TTS tokenizer's encoder, which is the Mimi encoder.
  • Why: Mimi was trained with a 250-step sliding attention window (Kyutai's context: 250, HF MimiConfig.sliding_window). The batch graphs didn't apply it, matching HF's eager/sdpa path, which ignores the setting. They now match the trained model.
  • Source of the window: the side's codec.<side>.look_back (125 codec frames = 250 steps at the transformers' 25 Hz), the same value memory uses. Old GGUFs get the same per-arch default.
  • Clips up to 10 s are bit-identical to origin/main.
  • Quality: reconstruction vs the original audio after 10 s moves only at noise level, in both directions. On 32 s of LibriSpeech, LSD per segment changes by −0.04 to +0.02 dB (Mimi 3.906→3.912 and 3.549→3.560 dB; Qwen3 tokenizer 3.686→3.704 and 3.446→3.409 dB).

Public headers

  • include/codec.h gets exactly the additions approved in the RFC. No other file in include/ or common/*.h changes.
  • The Python bindings mirror the API in the same commit: codec_cpp.Memory, Context(encoder_memory=, decoder_memory=), Model.encoder_is_causal / decoder_is_causal.

How it works

  • Planning: at context creation, each enabled side builds its graph once in planning mode (memory_plan vtable hook). That records the cache slots, which are then allocated on the context's backend.
  • In each graph: the graph reads a slot as an op's left context and writes the new context back with ggml_cpy side roots, as llama.cpp writes its KV cache.
    • conv left tails;
    • ConvTranspose overlap partial sums, taken before the bias;
    • sliding-window K/V.
  • Per-call inputs: attention positions and the validity mask. One cached graph therefore serves every chunk of the same length.
  • Saved state: the blob is self-describing (magic, versions, arch, side, SHA-256 model fingerprint, typed sections). It is validated before anything is restored.
  • Causality comes from the new GGUF keys codec.{encoder,decoder}.{look_back,look_ahead}. GGUFs without the keys use per-arch defaults, so old GGUFs load unchanged.
  • Non-causal sides get a size-0 memory that does nothing. codec_decode_batch neither reads nor updates memory.
  • Memory off: outputs are bit-identical to origin/main (checked for Mimi, Qwen3 tokenizer, MOSS-Nano, NeMo and DAC encode + decode).

Which sides have memory

Codec Encoder Decoder
Qwen3-TTS tokenizer ✓ (Mimi encoder) ✓
Mimi ✓ ✓
MOSS-Audio ✓ ✓
NeMo nano codec – ✓ (bit-exact)
DAC, WavTokenizer, others size 0 size 0
Pocket-Mimi – size 0 (not in scope)

Converters: they write the four keys (checked by converting the local Mimi, Qwen3 tokenizer, NeMo, DAC and WavTokenizer checkpoints).

Tests: tests/e2e/codec_memory_smoke.py [--seconds S] checks:

  • streamed vs batch on random hop-aligned chunks, including 1-frame chunks and a chunk longer than the window (default clip 24 s);
  • an encode whose last chunk isn't a whole hop, against batch on the same clip;
  • restoring a saved state into a fresh context continues the stream bit-exactly;
  • foreign, corrupted and truncated blobs are rejected and the cache is unchanged;
  • clear gives the same output as a fresh context;
  • codec_decode_batch bypasses memory;
  • memory on a non-causal (DAC) decoder is a size-0 no-op;
  • the look_ahead key decides causality.

All four models pass every check at the default 24 s:

Codec, side Streamed vs batch
NeMo decoder bit-exact
Mimi decoder rel. RMS 9.2e-5
Qwen3 decoder rel. RMS 5.2e-4
MOSS-Nano decoder rel. RMS 8.9e-4 (limit 1e-3)
Mimi encoder 1.8 % of codes flip; first 4 RVQ levels 0 %
Qwen3 encoder 0.16 % flip; first 4 levels 0 %
MOSS-Nano encoder 0.75 % flip; first 4 levels 0.08 %
  • Unaligned last chunk: its last frame matches batch on all three encoders.
  • Both memories on one context, encode and decode chunks interleaved: identical to single-side contexts, and clearing one side leaves the other's state unchanged.
  • Rounding, not drift: a 64 s stream in 6-frame chunks has flat per-10 s rel. RMS (Qwen3 4.8–7.4e-4, MOSS 8.3–9.0e-4).
  • MOSS-Audio full: causal on both sides; state is 169 MB per side because its windows are long.

Pixel 7 Pro (big cores, 4 threads, F32, 10 s of codes, 6-frame = 0.48 s chunks; RTF = decode time ÷ audio length):

Codec Batch RTF Memory streaming RTF #6 window (earlier)
Qwen3 decoder 1.52 2.14 (1.41× batch; 1.30× in a later hot run) 6.15
Mimi decoder 0.20 0.26 (1.30× batch) 0.83
  • Memory adds no cost of its own: stateless decodes of the same 6-frame chunks cost the same (Mimi 0.26) or more (Qwen3 2.99 against 2.63 in the same run). The overhead over batch comes from the small chunks.
  • With 12- and 25-frame chunks, Qwen3 is 1.06× and 1.02× batch.

Deviations from the RFC / open

  1. Mimi batch window: resolved by option A, as Hans decided (see the note at the top).
    • The default 24 s smoke now passes for every model.
    • The memory-off regression is bit-identical to origin/main for clips ≤ 10 s (Mimi, Qwen3 tokenizer, MOSS-Nano, NeMo, DAC).
    • Past 10 s only Mimi and the Qwen3 tokenizer encoder change.
  2. look_back units: Mimi's look_back is 125 codec frames, not 250. The RFC is fixed in docs(rfc): codec memory — streaming encode/decode state in codec_context #8 (e7abd2a).
  3. Tolerances: the RFC's 1e-4 / 0.1 % are not met by the attention models.
    • Cached attention reorders float reductions, and these models amplify rounding.
    • Batch itself differs by up to 6e-4 between clip lengths, and a single-chunk memory graph already shows the full difference.
    • The smoke uses rel. RMS ≤ 1e-3 for decode, and for encode ≤ 0.5 % flips in the first 4 RVQ levels and ≤ 5 % overall.
  4. Phone target: the RFC aimed for within 10 % of batch at 0.5 s chunks. Measured: 1.3–1.4× batch.
    • The cause isn't fully isolated: the stateless baseline rebuilds its graph on every call, while the memory path reuses it.
    • On the host, the same chunks cost 1.08× batch with memory and 1.05× stateless.
  5. DAC keys: the DAC look_* frames use the GGUF hop, so the 16 kHz model gets 10 frames until feat(audio-lm): streaming through codec memory (causal decoders), look_* windows for the rest, DAC hop fix #6's hop fix (320, not 512) lands; it should be 16.
  6. Not tested here:
    • the MOSS converter keys (no source checkpoint locally);
    • GPU backends (CPU only).
  7. State blob vs RFC §7:
    • it adds a fresh byte and per-clock position counters;
    • section kinds are numeric tags (1 conv tail, 2 convtr overlap, 3 K, 4 V);
    • one global impl_version.
  8. SNAC: the RFC table's proposed 16 / 16 default isn't in the loader. SNAC stays −1 (unbounded) until feat(audio-lm): streaming through codec memory (causal decoders), look_* windows for the rest, DAC hop fix #6 has a window for it.
  9. feat(audio-lm): streaming through codec memory (causal decoders), look_* windows for the rest, DAC hop fix #6 follow-up: feat(audio-lm): streaming through codec memory (causal decoders), look_* windows for the rest, DAC hop fix #6 isn't merged. Once it is, its streamer should take the incremental path when codec_model_decoder_is_causal, and read its window from the look_* metadata instead of src/audio_lm_window.h.

🤖 Generated with Claude Code

hans00 and others added 9 commits November 15, 2026 15:25
Implements the API of docs/proposals/codec_memory.md (RFC #8):
codec_context_params.encoder_memory / decoder_memory,
codec_get_encoder_memory / codec_get_decoder_memory, codec_memory_clear,
codec_memory_state_get_size / get_data / set_data and
codec_model_encoder_is_causal / codec_model_decoder_is_causal, mirrored in
the Python bindings (codec_cpp.Memory, Context(encoder_memory=,
decoder_memory=), Model.encoder_is_causal / decoder_is_causal).

src/runtime/memory.{h,cpp}: a memory's cache slots (conv left tails,
ConvTranspose overlap partial sums before the bias, sliding-window K/V)
are recorded by building the side's graph once in planning mode at
context creation, allocated on the context's backend and zeroed by a
clear. A graph reads a slot as an op's left context and writes the
context it leaves behind back with ggml_cpy side roots, as llama.cpp
writes its KV cache; attention positions and the validity mask are
per-call inputs, so one cached graph serves every chunk of a length.
The state blob (magic, versions, arch, side, SHA-256 model fingerprint,
typed sections) is validated before anything is restored.

Causality comes from the new GGUF keys codec.{encoder,decoder}.
{look_back,look_ahead} (look_ahead 0 = causal), with per-arch defaults
for GGUFs without them. A non-causal side's memory has size 0 and is a
no-op; codec_decode_batch neither reads nor updates memory. With memory
off, outputs are bit-identical to before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Mimi encoder (also the Qwen3-TTS tokenizer's) and decoder take an
optional codec_memory: causal conv tails (the replicate-padded downsample
seeded from the first value after a clear), ConvTranspose overlaps and
the transformers' 250-step (25 Hz) sliding-window K/V.

The batch graphs keep their unbounded causal attention
(CODEC_MIMI_BATCH_WINDOW = 0, as HF's eager / sdpa path), so streamed
output equals batch only within the first 250 transformer steps (10 s);
whether batch applies Mimi's trained 250-step window is pending review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…Audio, NeMo

The causal graphs take an optional codec_memory: causal convs read their
left padding from the cache, causal ConvTransposes carry their overlap,
sliding-window attention (Qwen3 decoder: 72 frames; MOSS: each block's
context_duration) caches K/V with absolute RoPE positions, and MOSS's
padding mask carries over. Each arch's memory_plan builds one frame of
its graph to size the slots. MOSS-Audio's look_back defaults to its
longest block context.

Streamed vs batch on hop-aligned random chunks: NeMo bit-exact; Qwen3
decoder and MOSS within float reassociation of the cached attention
rows (rel. RMS 5e-4 / 9e-4, MOSS encoder 0.75 % codes flip in the deep
RVQ levels). Memory off: bit-identical to before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
In codec frames (docs/proposals/codec_memory.md): Mimi 125 / 0 both
sides (a 250-step window at 25 Hz), Qwen3-TTS tokenizer encoder 125 / 0
and decoder sliding_window / 0, MOSS-Audio the longest block context / 0,
NeMo decoder 27 / 0; the non-causal decoders get the window a host
re-decodes around a chunk: DAC 0.32 s / 0.32 s, WavTokenizer 1.28 s /
0.32 s. GGUFs without the keys load with the same per-arch defaults.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Streamed vs batch on hop-aligned random chunks (one longer than the
attention window, several of one frame) for every causal side found
under models/, state restore into a fresh context continuing bit-exactly,
rejected foreign / corrupted / truncated blobs leaving the cache
unchanged, clear == a fresh context, codec_decode_batch bypassing memory,
a non-causal (DAC) decoder memory being a size-0 no-op, and the
look_ahead key (as a load-time override) deciding causality.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…st chunk

A chunk that is not a whole number of hops is padded on the right as the
batch op pads its clip's end; Mimi's downsample pads by repeating the last
value, which the memory path padded with zeros, so the last frame's codes
of an unaligned final chunk differed from batch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…evel criterion

Adds an encode whose last chunk is not a whole hop (compared with batch on
the same clip), a --seconds option, and judges encode flips on the first 8
RVQ levels (<= 0.5 %) and all levels (<= 5 %): the deep levels sit at
near-ties that rounding flips (Mimi's batch flips ~1 % between clip lengths).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mimi's transformers (Kyutai's `context: 250`, HF MimiConfig.sliding_window;
also the Qwen3-TTS tokenizer's encoder) were trained with a 250-step
sliding window, which the batch graphs did not apply (as HF's eager / sdpa
path, which ignores sliding_window; only its flash path applies it). The
window now comes from the side's look_back (GGUF codec.<side>.look_back,
else the per-arch default 125 codec frames) times the transformer's steps
per frame (2), the same source codec memory uses, so batch and streamed
output agree past 10 s and the memory cache stays bounded.

BREAKING CHANGE: batch encode / decode output changes for Mimi-arch codecs
(Mimi, CSM, LFM2-Audio, Moshi) and the Qwen3-TTS tokenizer encoder on clips
longer than 10 s (250 steps at 25 Hz); clips up to 10 s are bit-identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…levels

MOSS-Audio-Nano has 16 levels, so "the first 8" included deep levels where
rounding flips codes at near-ties (0.4-0.8 % on a 24 s clip).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
hans00 added a commit that referenced this pull request Nov 16, 2026
…he rest from look_*

codec_audio_lm_stream_poll, rebuilt on the codec memory API (#9):

- Causal decoders (codec_model_decoder_is_causal with memory state:
  Qwen3-TTS-Tokenizer-12Hz, Mimi, NeMo, MOSS-Audio): each poll decodes only
  the new frames, in whole chunk_ms pieces, on a second codec context with
  decoder_memory, created at the first stream. No hold-back, no cross-fade;
  the stream equals the batch decode to float rounding (Qwen3 ICL rel. RMS
  8.2e-4, CSM/Mimi 4.8e-5).
- ICL voices: the reference's codes are decoded into the memory once per voice;
  the memory state after them (codec_memory_state_get_data) is kept in the
  audio_lm context and restored for the next generation with that voice.
  Batch decodes are unchanged (they still decode reference + generation on
  the context's own codec context and cut).
- Other decoders: the stateless window of the windowed streamer, with left
  context and hold-back read from codec.decoder.look_back / look_ahead (GGUF
  keys, else the per-arch defaults) instead of a per-arch table. An unbounded
  look_back or look_ahead decodes from the first frame (exact, quadratic) and
  holds back 0.32 s, as before.

Internal only: src/audio_lm_stream.h, src/audio_lm_window.h and
src/codec_look.h are in the audio_lm objects' private include dir. No change
to include/ or common/*.h. tests/e2e/audio_lm_stream_smoke.py checks the
memory path against batch (rel. RMS <= 1e-3, a repeat stream with the restored
ICL state identical) and the windowed path (DAC) perceptually.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant