# Qwen3-TTS 12 Hz decoder state audit

This experiment concerns the **audio tokenizer decoder**, not the text-to-speech
language model that predicts audio codes. No text generation, new model weights,
package upgrade or checkpoint modification is required.

## Primary-source research

The official paper describes the 12.5 Hz tokenizer as fully causal, including its
waveform reconstruction path, whereas the separate 25 Hz tokenizer uses blockwise
flow matching and lookahead. Thus the 25 Hz architecture must not be used to
reason about the installed 12 Hz checkpoint. Its reported 97 ms synthesis latency
is an end-to-end system result, not a benchmark of this wrapper.
[Qwen3-TTS technical report, sections 2.2 and 3.4](https://arxiv.org/html/2601.15621v1)

The released checkpoint has 16 codebooks, a 1,920-sample output hop at 24 kHz,
eight decoder transformer layers, 16 KV heads with 64 elements/head, and a
72-frame sliding attention window per layer. These are the pinned configuration's
values, not the Python class defaults.
[Pinned Qwen configuration](https://huggingface.co/Qwen/Qwen3-TTS-Tokenizer-12Hz/blob/7dd38ad4e9bad454aae9cd937d0cd577604fe229/config.json)

The repository exposes cache arguments in the pre-transformer. Its public
chunked waveform helper instead slices a left-context prefix, recomputes it, and
crops its waveform. That helper is **context replay, not persistent state**.
[Official decoder source](https://github.com/QwenLM/Qwen3-TTS/blob/main/qwen_tts/core/tokenizer_12hz/modeling_qwen3_tts_tokenizer_v2.py)

KV caching is valid for causal inference because a past frame's representation
does not change when future frames arrive. Cache positions must represent actual
sequence positions even when a sliding cache evicts old tensors. Masks must cover
the retained history and new frames, and each layer carries its own keys/values.
[Transformers 4.57.3 cache documentation](https://huggingface.co/docs/transformers/v4.57.3/en/cache_explanation)

The installed package is qwen-tts 0.1.1, using Transformers 4.57.6 and existing
Torch 2.12.0+cu130. This local inspection, rather than an unpinned future upstream
version, is authoritative for the actual measured experiment. Installed modeling
source SHA-256: `844e8dd8c0182ef9c6463c874631c22ef3c5a4fd1899dd657016164cc5379628`.
Installed configuration source SHA-256:
`9e30c24394b00cb0366d7da3482b7436468acc1cd3da1a6fe614a1d34653a5e3`.

## What the local code actually does

The inspection of the installed implementation found that the code-to-waveform
graph is: RVQ lookup, causal pre-convolution, sliding causal pre-transformer,
transpose upsampling/ConvNeXt blocks, then causal convolutional waveform synthesis
with SnakeBeta nonlinearities and a final [-1,1] clamp. Each decoder convolution
is stride one; transpose convolutions have either kernel=stride or kernel=2stride.
The pre-transformer accepts `past_key_values`, `use_cache`, `cache_position` and
`position_ids`, creates the original causal/sliding masks, and uses original
rotary embeddings. A checkpoint's existing causal semantics can therefore be
preserved; introducing a different mask is neither necessary nor permitted.

An important local audit finding is that saving KV state alone is not equivalent
to carrying the entire decoder. The pre-convolution influences the transformer
input, and subsequent convolutional state influences waveform continuity.
Transformer layers also compose: a per-layer 72-frame window is not a guarantee
that replaying only 72 raw code frames reproduces the full stack.

## Exact state implementation and ablations

`scripts/decoder_qwen_state.py` is isolated from the installed package. It shares
the original decoder's weights and performs the original quantizer lookup,
transformer forward, nonlinearities and clamp. It stores the original supported
Transformers cache object, providing absolute positions explicitly. Causal
Conv1d modules retain their left-input history, including dilations. Transpose
convolutions retain the cropped right output tail and add it at the beginning of
the next output. The saved tail excludes the convolution bias so that bias is
not added twice. These are state-carry operations, not replay of source codes.

| Boundary policy | Transformer state | Convolution state |
| --- | --- | --- |
| Reset | Fresh | Fresh |
| KV only | Retained | Fresh |
| Convolution only | Fresh | Retained |
| All state | Retained | Retained |

Fresh/retained is evaluated at each **window boundary**. If a window is split
internally for an overlap snapshot, both kinds of state are retained between its
prefix and suffix; otherwise the split itself would manufacture an extra seam.
The all-state policy should reproduce the full causal decoder to floating-point
tolerance, including one-frame chunks, once equivalence is verified. The partial
policies intentionally remove information and are experimental ablations.

## Overlap without corrupting history

When width W exceeds stride S, appending each complete window to a live cache
would insert repeated overlap frames, advancing rotary positions incorrectly.
The wrapper instead processes S frames, snapshots all resulting state, processes
the W-S speculative suffix, then restores the snapshot. Only S frames become
committed history. Both cache tensors and cumulative sliding-cache counters are
copied. The final short window uses its actual length and commits at most S frames.

Normalized Hann overlap-add remains a waveform assembly operation performed by
the experiment runner. With all-state carry, overlapping contextual predictions
should agree except for numerical rounding, so overlap-add is not expected to
offer a large further quality gain. For partial-state ablations, overlap-add can
still blend differing predictions; its benefit must be measured rather than
assumed. Snapshot copying and suffix recomputation consume additional work and
memory, so report their implementation cost separately from optimized production
streaming. This is correct experimental rollback, not an optimized cache server.

## API and validation

```python
state = QwenStateDecoder(adapter.model.decoder)
wave = state.decode_chunk(codes, carry_kv=True, carry_conv=True)
# codes [1,16,T], wave [1,1,T*1920]; commit the entire chunk.
wave = state.decode_window(codes, commit_frames=stride,
                           carry_kv=True, carry_conv=False)
# Return the full window, but commit only its stride-prefix.
saved = state.snapshot()
state.restore(saved)
state.reset()  # REQUIRED between unrelated source clips.
info = state.state_info()  # Resident KV/convolution tensor bytes, not allocator peak.
```

The wrapper supports one independently managed stream at a time. Temporary
instance-level convolution forward replacements are restored even on exceptions;
concurrent calls sharing the same decoder are unsupported. It does not alter the
running web API process, upstream packages, weights or attention configuration.
CPU tests instantiate a tiny real Qwen decoder with random nonconstant RVQ
codebooks and test one/two/eight/16/32-frame chunks, sliding eviction, uneven
tails, exact owned snapshots, selective resets, and untouched original methods.

CUDA smoke validation is in `scripts/validate_decoder_qwen_state.py`; it uses the
three already-published listening clips' cached codes, checks checkpoint and
source hashes, disables TF32, and records peak/RMS waveform disagreement and
single-pass costs. The experiment runner must independently check its actual
60-clip workload rather than treating these smoke examples as pooled evidence.
Source-spectral metrics are not MOS and full-decode-equivalence is distinct from
quality relative to the original audio: any codec quantization loss remains.

### Completed smoke results

All five CPU tests pass. CUDA validation also passed all 48 ordinary chunk
conditions (three clips × four widths × four state policies), plus nine
all-state overlap/rollback sequences. The clips contain 72, 65 and 133 frames,
so the last source crosses the checkpoint's 72-frame sliding window. Across
ordinary all-state cases the largest waveform peak difference from full decoding
was `7.0929527e-6`, and the largest RMS difference was `1.6689563e-7`. The untouched
stock decoder remained bit-identical before and after helper calls. Neither
KV-only nor convolution-only carry was equivalent to full decoding.

The settled resident KV tensors occupy 4,653,056 bytes, with convolution histories
using another 565,888 bytes. This does not include decoder weights, allocator
reserved memory, transient activations, or overlap snapshot duplicates. The
sliding implementation retains 71 historical frames before adding new frames;
its cumulative position counter still correctly reaches frame 133.

One-frame all-state smoke runs yielded approximately 7.62–8.44× realtime, versus
52.9–56.1× at eight frames and 124.2–147.6× at 32 frames. These are descriptive
single-pass costs including Python dispatch and state bookkeeping, **not warmed
throughput measurements or end-to-end synthesis latency**. See the JSON artifact
for the individual timings and all partial-state waveform disagreements.
