# Decoder state carry, context replay, and overlap-add: research and experiment protocol

Research date: 2026-10-01. Scope: reconstruction from **unchanged, complete-clip encoded tokens**, not text-to-speech token generation. Target installed codecs: `fish-dac-s2` (Fish S2-Pro tokenizer checkpoint) and `qwen3-tts-tokenizer-12hz`. This document is methodology/research, not a claim that a particular streaming adapter has passed correctness checks or that quality improves before measurement.

## Main recommendation

Test whether preserving decoder history improves small-chunk reconstruction, while separating attention history from convolution history. Both target codec decoders are causal; a correct incremental implementation should approach their own full-decode output. A transformer cache alone is not the whole decoder state. Compare independently reset decoding, genuine KV-only carry, replayed left context, and—if independently validated—complete pipeline carry, each with hard assembly and normalized Hann 50% overlap-add. Use the same existing 60 speech clips, tokens, precision, metric definitions, and paired statistics.

The decisive practical question is not just “does adding a cache help?” It is “which state must survive, how much quality is recovered, and at what measured compute, memory, and algorithmic delay?” Do not rename token replay as KV caching; do not obtain cached overlap-add by appending the same overlap tokens twice to a persistent sequence.

## 1. What primary sources establish

### The relevant transformer is in the codec, not only in the TTS model

Fish’s technical report separates the Slow/Fast autoregressive speech-token generator from the RVQ audio tokenizer. Its tokenizer uses causal convolutions and causal sliding-window transformer bottlenecks around quantization, with an EVA-GAN-style waveform generator and 2048× total downsampling. The installed benchmark does not invoke the language model, so its TTS-serving KV cache cannot directly repair a reconstructed waveform. [Fish Audio S2 technical report, architecture §2.1–2.2](https://arxiv.org/html/2603.08823v1#S2).

Qwen’s report distinguishes the 25 Hz block-wise diffusion tokenizer from the installed 12.5 Hz tokenizer. The latter is a pure-left-context causal decoder; the former requires future blocks. Accordingly, the 25 Hz DiT lookahead protocol is not applicable to this experiment. The published 12 Hz configuration uses 16 quantizers and 80 ms token frames. [Qwen3-TTS technical report, §2.2 and §3.4](https://arxiv.org/html/2601.15621v1#S2.SS2).

The official Fish source implements `WindowLimitedTransformer`; its normal forward constructs local positions starting at zero. Merely enabling the inherited cache setup does not establish that window offsets, masks, and other decoder stages are streaming-correct. [Official Fish codec source](https://github.com/fishaudio/fish-speech/blob/main/fish_speech/models/dac/modded_dac.py).

The official Qwen decoder’s transformer accepts `past_key_values`, but the surrounding waveform decoder normally calls it without a retained cache. `chunked_decode` prepends left-context codes and discards the corresponding audio: this is replay, not persistent transformer state. [Official Qwen tokenizer decoder source](https://github.com/QwenLM/Qwen3-TTS/blob/main/qwen_tts/core/tokenizer_12hz/modeling_qwen3_tts_tokenizer_v2.py).

### A working streaming codec preserves several kinds of state

Mimi is a pertinent architectural precedent for causal codec streaming, rather than proof that either selected implementation already streams correctly. Its official transformer module tracks a ring KV cache with absolute positions and reset state. Its convolution module separately maintains causal convolution inputs and transposed-convolution overlap buffers. These illustrate why attention caching and waveform-generator state are distinct. [Moshi/Mimi paper](https://arxiv.org/abs/2410.00037), [official transformer implementation](https://github.com/kyutai-labs/moshi/blob/main/moshi/moshi/modules/transformer.py), [official streaming convolution implementation](https://github.com/kyutai-labs/moshi/blob/main/moshi/moshi/modules/conv.py).

Hugging Face’s versioned caching documentation explains growing versus sliding caches, how cache positions differ from sequence length under padding, and why attention masks must cover past plus current tokens. Retain monotonic positions even when stored KV tensors are trimmed. [Transformers 4.57.3 cache explanation](https://huggingface.co/docs/transformers/v4.57.3/en/cache_explanation).

PyTorch SDPA documents a causal-mask alignment caveat for nonsquare attention matrices. In a chunk with past keys, an unqualified `is_causal=True` must not be assumed to describe the desired absolute query/key relation. Explicitly validate that query at position `q` can attend to `k <= q`, including the model’s left-window restriction. [PyTorch SDPA API](https://docs.pytorch.org/docs/2.14/generated/torch.nn.functional.scaled_dot_product_attention.html).

### Which metrics are established and what they cannot prove

Multi-resolution spectral losses are established waveform-generation diagnostics: Parallel WaveGAN trains with spectral convergence and log-magnitude losses at multiple resolutions. This motivates retaining the existing MR-STFT family, but its numerical loss is not an opinion score. [Parallel WaveGAN](https://arxiv.org/abs/1910.11480).

Descript’s DAC paper evaluates high-fidelity waveform reconstruction and introduces improved reconstruction/adversarial objectives. It supports treating acoustic reconstruction fidelity separately from the accuracy of an upstream generative model. [High-Fidelity Audio Compression with Improved RVQGAN](https://arxiv.org/abs/2306.06546).

Qwen’s codec evaluation reports PESQ, STOI, UTMOS, and speaker similarity on LibriSpeech test-clean. These are useful secondary endpoints for whole-clip acoustic/perceptual/intelligibility characterization, not specific tests of streaming-state correctness. They cannot replace a sample-aligned full-decode comparison or reveal a sparse seam by themselves. [Qwen3-TTS tokenizer evaluation, §4.1.2](https://arxiv.org/html/2601.15621v1#S4.SS1.SSS2).

ViSQOL is a full-reference perceptual speech/audio quality estimator with documented applicability limits; UTMOS is a learned MOS predictor from the VoiceMOS challenge. They can complement a listening test but do not turn a 50% spectral-error increase into “50% perceptual damage.” [ViSQOL v3 paper](https://arxiv.org/abs/2004.09584), [official ViSQOL implementation](https://github.com/google/visqol), [UTMOS paper](https://arxiv.org/abs/2204.02152).

MUSHRA is a standardized subjective comparison method for intermediate-quality audio systems. A browser with labeled players is a useful listening explorer, not automatically a standards-compliant listening experiment. Hidden references/anchors, blinding, listener screening, randomization, and statistical analysis would be necessary before presenting subjective MUSHRA scores. [ITU-R BS.1534-3](https://www.itu.int/rec/R-REC-BS.1534-3-201510-I/en).

CUDA operations are asynchronous; PyTorch recommends synchronization or CUDA events for accurate device timing. Allocated and reserved GPU memory are distinct, so cache tensor storage and whole-process peak allocations must be documented separately. [PyTorch CUDA semantics](https://docs.pytorch.org/docs/2.14/notes/cuda.html).

## 2. Evidence from the installed benchmark (local inspection)

The following details are observations of local files, not inferred from model marketing:

- `scripts/benchmark_decoder_degradation.py` defines genuine full decoding and independent hard windows. Qwen uses direct `model.decoder(codes)`, bypassing its public contextual wrapper. Fish clones codes because its public API mutates/clamps them.
- Both experiments reuse complete-clip codes with checkpoint/source hashes, all codebooks, and sample-zero alignment. Changing encoding or quantizer count would confound this extension.
- `scripts/benchmark_decoder_overlap_add.py` uses a half-sample positive Hann taper, or uniform weights, and divides the waveform weighted sum by the sum of weights. Its last windows are shortened; taper length is the actual decoded sample length.
- Existing independent windows can be grouped and batched. Stateful chunks within one clip are temporally dependent; any speed comparison must explicitly distinguish this from independent-window batching.
- Qwen’s installed decoder configuration has eight attention layers, 16 KV heads, head dimension 64, and sliding window 72 at the 12.5 Hz code rate. Before the transformer it has a kernel-3 causal convolution; after it, convolutional upsampling and waveform generation add their own history requirements. An isolated transformer cache is therefore an ablation.
- The installed Fish source’s `WindowLimitedTransformer.forward` derives local positions and a square mask from the current tensor. A correct adapter needs its own globally consistent positions and past/current mask. The completed checkpoint-specific audit identifies the active decode transformer as the eight-layer quantizer post-module with a 128-frame causal window. The apparently configured waveform-decoder transformer is omitted from the actual Sequential path; it must not be counted as active. The paper’s EVA-GAN description also differs from this pinned implementation. See `FISH_STATE_RESEARCH.md` for exact source pins and the discrepancy.

Use the architecture agent’s checkpoint-specific inspection as the authority for exact Fish stage dimensions and cache capacity. A finite attention window at every layer does **not** imply that replaying just that many raw input codes reproduces the deep network’s output: stacked receptive fields and the pre/post-convolutional receptive fields must be accounted for.

## 3. Name state policies accurately

| Policy | Retained history | What this identifies |
|---|---|---|
| Reset | None; each window starts clean | Existing independent-chunk baseline |
| KV-only | Actual projected per-layer K/V and absolute positions; convolutions still reset | Contribution of transformer history, including the consequences of corrupted reset pre-convolution inputs |
| Replay left context | Earlier code indices are decoded again; warmup audio discarded | A practical stateless fallback; additional compute rather than a genuine cache |
| KV + convolution replay | KV survives; bounded pre/post-transformer convolution inputs or latent context are replayed | Hybrid state strategy; disclose which stages replay and which cache |
| Complete decoder state | KV, convolution input history, transpose-convolution overlaps, offsets, and any resampler state | Potential near-equivalence to full causal decoding |
| Full-prefix replay | Decode all tokens from zero through current chunk, keep newly emitted audio | Causal reference oracle; expensive and not bounded-cost streaming |

Only advertise “full state carry” if all relevant stages are actually stateful and validated. A memory of token IDs, a cached full waveform, or an offline complete transformer activation tensor is not the same thing as online KV state. Full-prefix replay can be a correctness oracle without serving as a practical recommendation.

For future bidirectional codecs, deeper-layer K/V of older tokens can change when new right context arrives. Reusing those stale vectors is generally approximate; add lookahead/recomputation or measure the approximation. This caveat is not a reason to impose future lookahead on the two current causal models.

## 4. Practical matched experiment

### Core factorial design

Freeze the existing 60-clip selection: 20 Cartoon Voices, 20 LibriSpeech Other, 20 Podcast. Do not choose clips after inspecting state improvements. Keep native decoding rates, checkpoint hashes, all codebooks, float32 precision/TF32 policy, and the existing final 24 kHz metric domain.

Predeclare tested window widths, for example `2, 4, 8, 12, 16, 24, 32, 48, 64` code frames; optionally retain one-frame hard chunks as an extreme stress test. For each width compare Reset, KV-only, left-context replay, and validated complete/hybrid carry under:

1. Hard concatenation, stride `S=W`.
2. Hann 50% overlap-add, stride `S=max(1, floor(W/2+0.5))`.

Retain the exact old Hann geometry to allow direct comparison with prior results. Full-decode and full-prefix controls do not acquire artificial windows just to inflate their condition count. Conditions with `T <= W` contain no independent seam and should be shown as controls rather than aggregated into chunk degradation.

A useful bounded replay ladder is 4, 8, 16, and 32 left code frames, with a model-aware longer setting if inexpensive. Qwen’s documented public default replay is 25 frames; it is a practical reference, not a guaranteed full-context receptive field. Do not optimize replay lengths on the same measurements used to declare a winner.

### Two comparisons are needed

**Equal window width:** reproduces the prior experiment and asks whether carry repairs the same input window. OLA has more calls, more repeated frames, and shorter stride.

**Equal output stride / packet duration:** hard uses `W=S`; OLA uses approximately `W=2S`. This answers a deployment question under matched newly emitted audio per step. Even then, OLA has different finalization delay and compute, so include those axes rather than claiming an entirely matched latency experiment.

### State carry plus OLA must not duplicate the timeline

For windows beginning at `0,S,2S,...`, carry state immediately before each start. Decode `[start, start+W)` from a branch/snapshot of that state. Commit history only through the next stride boundary, not through the entire overlapping window. Reusing a cache that already contains `[start,start+W)` and then appending `[start+S,start+S+W)` inserts overlap tokens twice and is invalid.

Possible valid implementations include a causal sequential trunk plus forked waveform windows, or snapshot/restore at every start with explicit committed offsets. Describe whether overlapping transformer states are recomputed or reused; count snapshot bytes and copy time. A cache reconstructed by offline full-prefix prefill may be useful as an oracle, but must not be presented as end-to-end online throughput.

Correct complete causal carry should make overlapping predictions of the same sample almost identical. If adding OLA still substantially helps that policy, investigate incomplete convolution state, resampler boundary handling, chunk-end trimming, or cache-mask bugs before attributing the improvement to transformer uncertainty.

## 5. Quality and boundary metrics

### Preserve existing whole-clip diagnostics exactly

Let `x` be source audio, `y_full` its full-code reconstruction, and `y_p` the treatment. Compute the existing three errors both for `(x,y_p)` and `(y_full,y_p)`:

- Log-mel L1: `mean(abs(ln(M_a+1e-5)-ln(M_b+1e-5)))`.
- Log1p-mel L1: `mean(abs(ln(1+M_a)-ln(1+M_b)))`; no independent gain normalization.
- MR-STFT: average over FFT sizes 512/1024/2048 of spectral convergence plus log-magnitude L1, hop `FFT/4`, the same Hann windows, centering, and epsilon as the previous script.

`x` comparison measures overall reconstruction error; `y_full` comparison isolates chunk/state drift. Keep absolute values and per-clip distributions, not just a relative percentage. Report added error `100*(mean E_p / mean E_full - 1)` and matched Reset-to-carry improvement. Do not clamp negative added errors: a treatment can accidentally move closer to source while diverging from its own full decoder.

### Add local seam diagnostics (explicitly custom, not validated perceptual scores)

Use a **fixed duration**, e.g. ±40 ms around every stride boundary, excluding clip endpoints; union overlapping boundary intervals. Define positions in native samples and map once to the final metric sample rate. Report the mask’s coverage fraction and count. Tiny strides can cover the whole clip, so interior error then has no support and is `null`, not zero.

1. Boundary waveform drift RMS and peak: compare `y_p-y_full` only inside the union. Also report interior RMS with its support count.
2. Excess seam jump: at every seam `b`, measure `abs((y_p[b]-y_p[b-1])-(y_full[b]-y_full[b-1]))`. This removes the full decoder’s natural sample transition. Report median/p95/max, not just an average.
3. Boundary log-mel/log1p error: extract features for the entire waveform first, then select feature centers falling inside the boundary mask. Never concatenate discontinuous cropped regions before taking STFTs.
4. Boundary MR-STFT component diagnostics: select full-waveform STFT columns whose centers lie in the mask, then recompute masked convergence/log-magnitude terms. Note that FFT windows span up to ~85 ms at 24 kHz, so this is a localized time-frequency diagnostic, not a sample-exact artifact detector.
5. Offset-from-boundary error profile: mean/p95 waveform absolute drift versus signed time from the seam; stratify by model, width, and state policy. Merge/avoid double-counting densely overlapping bands or visibly state the weighting.

Silence can make ratios unstable: include absolute errors, epsilon definition, denominator counts, and reference energy. A source-normalized jump may be shown secondarily with a disclosed energy floor; it must not replace the absolute drift diagnostic. Never independently time-align treatments to conceal delay introduced by an incorrect streaming adapter.

Whole-clip UTMOS/ViSQOL/STOI/ASR can be added as optional secondary tests after core correctness and spectral measurement. They should use all selected clips if reported as cohort results. Do not infer intelligibility changes from log-mel alone, or claim codec-generated speech metrics directly validate seam artifacts.

## 6. Compute, memory, and latency reporting

Measure single-stream sequential decoding separately from batched independent-window throughput. Reset and replay methods also need a batch-1 path for apples-to-apples latency. If batching clips for speed, every clip has independent state and offsets; never mix histories between lanes.

Record CUDA-synchronized end-to-end decoding and assembly after warmup, median and p95 chunk latency, overall audio-seconds / wall-seconds (× realtime), first decode packet time, cache initialization, and state snapshot costs. Exclude model loading, source IO, scoring, and audio export from the main decode time, but state the excluded components. Repeat benchmark sweeps rather than treating one timed quality pass as robust throughput.

Separate algorithmic buffering from measured GPU execution. A width `W` and hop `h` at sample rate `f_s` require `W*h/f_s` available token duration in the basic window schedule. With overlapping predictions, samples cannot be finalized until all windows covering them have arrived; first-packet duration, holdback, and tail flush must be documented for the actual assembler. A causal model does not make an OLA scheduling holdback disappear. Codec tokens are precomputed here, so TTS LM first-token time is out of scope.

Work counters should include every stage where possible: transformer query steps, attended key steps, code lookup frames, waveform-generator frames, replay frames, and overlap frames. The old decoded-frame ratio remains useful but understates the savings of partially reused transformer states and the cost of cache copies. Token storage is unchanged; runtime state memory is not encoded bitrate.

Report actual cache tensor bytes as `numel * element_size`, separating K/V, convolution history, overlap buffers, and fork/snapshot storage. Also report GPU peak allocated memory minus a model-loaded baseline, with allocator-reserved memory labeled separately. Theoretical KV bytes are `2 * batch * sum_layers(KV_heads * head_dim * retained_positions * bytes_per_value)`; stage-specific frame rates matter.

## 7. Statistics, eligibility, and correctness gates

Use 10,000 paired clip bootstrap replicates, ratios of arithmetic means, the existing seeded convention, and pointwise 95% CIs. For overall analysis, a stratified bootstrap sampling 20 clips within each dataset preserves the intended balanced mixture; label it if this differs from the prior pooled bootstrap. Per-dataset distributions and p10/median/p90 protect against average improvements hiding damaged clips. Do not count many seams from one clip as independent subjects.

Predeclare the difference-in-differences interaction for lower-is-better errors: `(E_KV,OLA - E_KV,hard) - (E_reset,OLA - E_reset,hard)`. A near-zero OLA effect under validated complete carry is expected; a weaker or negative KV-only gain remains informative. Avoid universal “best” claims from pointwise multiple-width comparisons; threshold crossings require the same conservative all-larger-tested-points rule as the prior report and may be unresolved.

Before the full run require:

- Whole-clip adapted decoder equals the native API within measured repeat-run numerical tolerance.
- Streaming output has exactly the intended `T*hop` geometry before source cropping; no missing or repeated samples and no fabricated token padding.
- Global positions and masks are correct for chunks of 1, 2, odd widths, and tails; validate past keys and current intra-chunk causal attention separately.
- Changing an unavailable future token cannot change an already committed causal output.
- Reset clears every clip’s state; decoding A then B equals decoding B from fresh state.
- Cache size plateaus for bounded-window policies; evict only after all current queries have seen their permitted past.
- Overlapping branches use the state at the declared start, not a state advanced through their overlapping tail.
- Full state carry is tested versus the full waveform on representative clips, including convolution transients and final flush, not merely one transformer hidden tensor.
- No precision, dropout/eval mode, normalization, book count, encoder inputs, or checkpoint change is hidden inside a state policy.
- Export 24 kHz FLOAT WAV and reread exactly, retain waveform hashes, and recompute selected published sample metrics after export.

## 8. Report and interactive listening recommendations

Report charts for absolute source error, excess error versus full decode, boundary drift, cache memory, work, and latency; include token-frame and readable-duration axes. Keep a result status for every planned condition: complete, structurally no-seam, unsupported, or failed validation. Never make unsupported state carry look like a zero-error measurement.

The listening page should offer the same original and full reconstruction while switching between Reset hard, Reset OLA, KV hard, KV OLA, and available replay/full-state controls at one fixed selected width. Keep audio positions synchronized, show stride and actual overlap, expose baseline/treatment/drift values, and allow a short loop centered on a seam. Select listening clips before evaluating outcomes or clearly distinguish deliberately worst-case examples from representative fixed examples. A cache-on badge must explain whether it means genuine KV, replay, or complete pipeline state.

## Concise decision

Proceed with a validated **KV-only × assembly** factorial first, plus left-context replay and a full-prefix causal oracle. Add complete/hybrid convolution state if the implementation can pass waveform equivalence gates. Preserve old spectral measurements and add sample-aligned boundary diagnostics. Treat OLA with state as a timeline/snapshot problem, not a simple cache flag. Publish bounded-work and delay tradeoffs alongside quality, and explicitly distinguish measured effects from the theoretically expected equivalence of a correctly stateful causal decoder.
