# Fish S2-Pro codec: transformer and convolution state research

Inspected and CUDA-smoke-tested 2026-10-01. This is a source audit, implementation validation and experiment protocol; three listening clips are a correctness smoke test, not a substitute for the planned 60-clip quality benchmark.

## Finding

The **installed S2-Pro audio codec is causal and therefore admits genuine incremental state reuse**. Its decode-relevant transformer is the eight-layer `quantizer.post_module`, with a causal attention window of 128 codec-frame positions. KV state alone cannot eliminate all independent-window artifacts because convolution histories and transposed-convolution overlap tails also reset. Complete causal state reproduced full decoding to floating-point tolerance in the three-clip smoke test, including one-frame chunks. Overlap-add should then add little or no further quality improvement; that broader quality claim remains a hypothesis for the 60-clip experiment.

Do not conflate this transformer with the much larger Slow-AR/Fast-AR text-to-audio-token generation models. Those TTS generators are not loaded by this benchmark. The official S2 paper separately describes its causal tokenizer and the Dual-AR generator, and its SGLang/paged-KV claims concern generator serving. [Fish S2 technical report, sections 2 and 5](https://arxiv.org/html/2603.08823v2).

## Exact installed implementation

The registry pins `fish-dac-s2` to Fish repository commit `befe4001745417f8c42131739d862b8a6fdbd15a`, checkpoint repository `fishaudio/s2-pro` revision `1de9996b6be38b745688de084d87a5633f714e4e`, and `fish_speech/configs/modded_dac_vq.yaml`. `FishDACAdapter` instantiates that configuration, strictly loads learned weights (ignoring only regenerated mask/RoPE buffers), and calls `model.from_indices(codes)` for decoding. It does not initialize or retain transformer or convolution caches. Local evidence: `backend/model_registry.json:28`, `backend/codecs.py:277`, `backend/codecs.py:291`, `backend/codecs.py:311`. [Pinned configuration](https://github.com/fishaudio/fish-speech/blob/befe4001745417f8c42131739d862b8a6fdbd15a/fish_speech/configs/modded_dac_vq.yaml), [checkpoint model card](https://huggingface.co/fishaudio/s2-pro).

Decode path, in order:

1. Clamp codebook indices, look up the semantic codebook and nine residual codebooks, and sum their continuous vectors.
2. Apply `quantizer.post_module`: eight transformer layers, dimension 1024, 16 query/KV heads, head dimension 64, RoPE base 10000, causal 128-position attention. The position domain is **codec frames**, not flattened scalar codebook tokens.
3. Upsample twice by factor 2 using causal transposed convolutions, with a causal ConvNeXt block after each stage.
4. Run the causal waveform decoder: initial convolution, upsampling rates 8/8/4/2, dilated residual convolutions, final convolution and tanh.

The resulting waveform hop is `4 × 8 × 8 × 4 × 2 = 2048` samples at 44.1 kHz, or 21.533203125 codec frames/s. The 128-position attention window corresponds to about 5.94 s and includes the current frame. It therefore needs at most 127 retained previous keys/values per layer before a new frame arrives. Local evidence: `rvq.py:352`, `rvq.py:264`, `modded_dac.py:760`, `modded_dac.py:925`, configuration lines 29–49. [Pinned quantizer implementation](https://github.com/fishaudio/fish-speech/blob/befe4001745417f8c42131739d862b8a6fdbd15a/fish_speech/models/dac/rvq.py).

Important architecture traps:

- The configuration says `decoder_transformer_layers: [4, 0, 0, 0]`, and `DecoderBlock` constructs a local `transformer_module`, but that module is **commented out** of its actual `nn.Sequential` (`modded_dac.py:724` and `:742`). Do not count that apparently configured module as an active decoder transformer. The quantizer post-transformer remains active.
- `DAC.__init__` defaults to `causal=True` (`modded_dac.py:814`); this configuration does not override that default. The post-transformer explicitly uses `causal: true` (configuration line 32).
- The S2 paper describes an EVA-GAN waveform decoder, while this installed pinned configuration has no `overwrite_decoder`, and the local `DAC` chooses its `Decoder` implementation. Report the actual installed implementation and pinned weights, rather than silently substituting architecture descriptions from a paper or newer repository revision. The discrepancy is an audit limitation, not grounds to change the benchmark checkpoint.
- No TTS token generation, sampling, encoder state, or re-encoding should enter this experiment. Reuse the exact already-cached full-source code sequences so only decoder execution changes.

## Why calling `setup_caches()` is insufficient

The underlying `Transformer` exposes `setup_caches(max_batch_size, max_seq_length)` and attention can update a KV cache. However, `WindowLimitedTransformer.forward()` computes positions as `arange(current_chunk_length)` and builds a square current-chunk mask on every call (`modded_dac.py:418–435`). Calling `setup_caches()` without changing that wrapper overwrites positions from zero and fails to attend correctly to past chunks. It is not a legitimate persistent-cache implementation. [Pinned transformer source](https://github.com/fishaudio/fish-speech/blob/befe4001745417f8c42131739d862b8a6fdbd15a/fish_speech/models/dac/modded_dac.py).

A correct streaming wrapper must:

- Keep a monotonically increasing codec-frame cursor and use absolute RoPE positions.
- Maintain a separate KV history for every transformer layer, not merely cached token IDs or final hidden states.
- Build a rectangular query/key mask. For global query position `q` and global key position `k`, allow attention precisely when `q - 127 <= k <= q`.
- Preserve the original 128-position window. Allowing unlimited past context would change the trained computation and confound the test.
- Reset all state at each clip boundary and each independent experimental condition.
- Retain only the previous 127 K/V pairs after a call. The temporary attention calculation can include those pairs plus the entire current chunk; the mask handles queries early and late in that chunk.
- Use existing learned Q/K/V projections, normalization, RoPE tables, layer scales and FFN weights unchanged; inference dropout remains disabled.

PyTorch documents that Boolean SDPA masks use `True` for allowed attention. For rectangular query/key dimensions, a generic triangular mask is not automatically the desired timeline-aligned causal mask; use the explicit global-position relation above. [PyTorch SDPA documentation](https://docs.pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html).

For this model, bounded FP32 K/V tensors require approximately `8 layers × 2(K,V) × 16 heads × 127 frames × 64 channels × 4 bytes = 8,323,072 bytes`, or 7.94 MiB for batch 1, plus position metadata and convolution state. BF16 would halve the tensor component, but changing dtype is a separate experiment. A full-length cache allocated by the upstream helper scales with clip duration; it is not necessary for bounded-window inference.

Layerwise attention context is not the same as a 128-frame raw-token replay receptive field. Across eight layers, a dependency can propagate through multiple earlier windows. Therefore “redecode only the last 128 raw frames” is an approximate context-replay strategy, not proof of exact equivalence to layerwise KV state.

## Convolution and upsampling state

Both `modded_dac.py` and `rvq.py` implement causal convolutions by inserting zeros on the **left of every call**. Independent windows therefore lose real past activation context, even if the transformer is already cached. For a decode-path stride-1 convolution, retain `(kernel_size - 1) × dilation` input activations per channel and prepend them instead of new left zeros. Initial clip history is zero exactly once. Residual units use kernel 7 at dilations 1/3/9, requiring 6/18/54 local input-history positions respectively. Retain state at each layer's own temporal resolution, not just the final waveform. Local evidence: `modded_dac.py:521–554`, `modded_dac.py:599–621`, `rvq.py:58–89`.

The causal transposed convolutions call a raw `ConvTranspose1d` and trim `kernel_size - stride` samples from the right of each call (`modded_dac.py:563–580`, `rvq.py:100–117`). The trimmed tail carries legitimate contributions to the next chunk and must be saved and added to its beginning. Store the tail without convolution bias; the next raw call already contributes that bias and adding it twice is a common seam bug. Decoder stages use kernel `2 × stride`, so the overlap tail has `stride` samples. Quantizer upsamplers have kernel equal to stride and therefore no raw transconv overlap tail, but their following ConvNeXt causal depthwise convolutions still need history.

The reference streaming Mimi implementation keeps transformer state and convolution state separately, including ring KV caches and streaming convolution modules. It is useful design evidence, not a drop-in replacement for Fish's pinned weights. [Kyutai transformer implementation](https://github.com/kyutai-labs/moshi/blob/main/moshi/moshi/modules/transformer.py), [Kyutai convolution implementation](https://github.com/kyutai-labs/moshi/blob/main/moshi/moshi/modules/conv.py), [Moshi/Mimi paper](https://arxiv.org/html/2410.00037v2).

## Overlap windows must not consume tokens twice

A window covering frames `[a, a+W)` with stride `S < W` shares already-previewed frames with the next window. Naively appending the next overlapping request to a persistent cache assigns duplicate tokens new positions; keeping the end-of-window cache but resetting positions backward can expose stale or future state. Neither is a fair state-carry experiment.

Use a **commit-once** timeline:

1. Begin with the state immediately before frame `a`.
2. Decode the whole requested window for its provisional waveform.
3. Commit only the first `S` new frames; discard or roll back state for the preview suffix.
4. The next window begins at `a+S` with the state valid exactly there.
5. Place all sample windows at their global positions, apply the same normalized Hann overlap-add as the earlier study, and discard the final raw convolution tail exactly as full decoding does.

`scripts/decoder_fish_state.py` implements a safe fallback: snapshot, decode all `W`, restore, decode the first `S` solely to capture the committed state. It records `last_work_frames=W+S` when `S<W`. This preserves the original one-call-per-window semantics even in partial-state ablations; simply splitting a window into prefix and suffix would introduce a new reset at `S` for disabled components. The extra prefix pass must be included in runtime and work ratios. A production implementation could capture an intermediate state in a single call, but that optimization is not established here.

For fully stateful causal decoding, overlapping predictions for the same global samples should agree to numerical tolerance. Normalized overlap-add is then algebraically redundant, not a magical additional source of context. This provides a useful negative-control test.

## Controlled experiment matrix

Keep the same 60 paired speech sources and cached codes as the previous window study, and publish matching interactive examples on the same three previously selected listening clips.

| Condition | Transformer state | Convolution/upsample state | Purpose |
| --- | --- | --- | --- |
| Independent reset | Reset | Reset | Existing hard-join/OLA baseline |
| KV-only | Bounded persistent | Reset | Isolate attention-context benefit |
| Conv-only | Reset | Persistent | Isolate boundary activation benefit |
| Full causal state | Bounded persistent | Persistent | Test true incremental equivalence |

Run each at no overlap and normalized Hann 50%; add Hann 75% if budget permits. Window widths 1/2/4/8/16/32/64 frames span about 46 ms–2.97 s; include unequal final tails. Compare source-to-reconstruction MR-STFT/log-mel/log1p-mel and full-decoder-to-reconstruction drift. Report both total spectral-error reduction and excess error removed relative to full decoding. Bootstrap paired sources, and distinguish spectral percentages from perceptual or MOS claims.

Correctness gates before interpreting quality:

- Full-state one-frame and irregular-chunk decoding versus a genuine one-shot full call, including samples around every seam and final output length.
- Prefix independence: mutate future frames and show earlier committed waveform/state is unchanged.
- Snapshot restore/replay equality and unchanged input code hash.
- Repeated clip reset produces the same output; no state leaks between clips or ablation modes.
- Original forward methods and attention cache attributes are restored after success and after exceptions.
- State memory stabilizes after the attention window fills.
- Single-pass versus overlap commit-once agreement, with actual extra prefix work counted.

If full-state equivalence fails, do not label the result “streaming-equivalent” merely because spectral degradation decreased. Find the mask, position, convolution bias/tail, or alignment discrepancy first. Noncausal checkpoints would need a different delayed-commit or look-ahead protocol: prior deeper-layer KV representations can change when future context arrives. The Fish pinned decoder is causal, so that caveat is relevant for interpreting other codecs, not a reason to force Fish into a noncausal cache approximation.

## Implementation and validation artifacts

- Helper: `scripts/decoder_fish_state.py`; no vendor edits or weight changes.
- CPU regression suite: `tests/test_decoder_fish_state.py`, 25 tests passed on 2026-10-01 (causal convolution dilations, transconv bias/tail behavior, bounded KV monotonicity, owned state snapshots, commit-once replay work, exception restoration).
- Full-model GPU validation: `scripts/validate_decoder_fish_state.py` produced `data/decoder-state-carry/fish_state_validation.json`, passed. The three fixed listening sources contain 124, 111 and 228 codec frames. Four widths (1/2/8/32) crossed four state modes for 48 hard-join conditions, plus 24 Hann-50% overlap conditions at widths 8/32.
- Complete-state hard-join versus full: maximum sample error `7.62939453125e-6`, maximum waveform RMS drift `2.16012591396e-7`. Complete-state overlap commit-once versus full: peak `5.66244125366e-6`, RMS `2.00873835943e-7`. These are numeric waveform differences, not perceptual scores.
- Future-suffix mutation left the first eight frames unchanged (maximum sample difference exactly zero). Snapshot restore/replay was exact. Cached input tokens stayed unchanged; all original forward methods and cache attributes were restored.
- The 228-frame podcast clip exercises attention eviction; all eight layer caches ended with 127 previous positions. Full state used 8,897,216 bytes and KV-only 8,331,200 bytes, including repeated position metadata. This excludes model weights and temporary attention/activation workspace.
- Serial independent reset versus the previous batched hard-join implementation differs at most `1.06394290924e-5` peak and `2.50594084859e-7` RMS, consistent with differing floating-point kernel geometry. Baseline metric comparison should allow a documented numerical tolerance, not demand byte-identical waveforms from different batching.
