Skip to content

Commit 4f7e5c8

Browse files
justinchubyCopilot
andauthored
Derive Qwen3-TTS codec conv encoder from config instead of hardcoding widths (#552)
## The bug `_MimiConvEncoder` in `src/mobius/models/qwen3_tts_tokenizer.py` took **no config at all** and hardcoded its channel widths and kernels (`1→64→128→256→512→1024→512`). Its output fed `CodecEncoderTransformerModel(hidden_size=config.codec_encoder.hidden_size)`, which has no input projection — so the conv output width and `hidden_size` had to agree, and nothing checked that they did. When they disagreed, the builder happily emitted a malformed graph: ``` Conv encoder/encoder/layers/14/conv weight [512,1024,3] -> [batch, T, 512] LayerNormalization weight [32] bias [32] over a 512-wide tensor <-- malformed MatMul q_proj [32,32] vs 512 -> "Incompatible MatMul contraction dimensions: 512 vs 32" ``` ## Why it was invisible `SymbolicShapeInferencePass` catches inference errors and logs `"Symbolic shape inference failed (upstream bug); skipping"` — a deliberate generic guard. The tiny config in `TestBuildCodecGraph._codec_config()` set `codec_encoder.hidden_size=32`, so **the codec tests were building a broken graph and passing**. ## The fix The hardcoded widths were not dictated by the checkpoint — HF's `MimiEncoder.__init__` derives the entire stack from config, and mobius's literals were just that derivation inlined with `num_filters=64`, `upsampling_ratios=[8,6,5,4]`, `num_residual_layers=1`, `kernel_size=7`, `last_kernel_size=3`. So rather than adding a validation guard, this parameterizes the stack and eliminates the mismatch class: - **`CodecEncoderConfig`**: added the missing HF fields (`audio_channels`, `num_filters`, `num_residual_layers`, `kernel_size`, `last_kernel_size`, `residual_kernel_size`, `compress`, `upsampling_ratios`) with HF's own defaults, extracted in `ArchitectureConfig.from_transformers`. - **`_MimiConvEncoder`**: builds by HF's derivation. The parameterless ELU slots are preserved so `encoder.encoder.layers.*` numbering still matches the checkpoint exactly. `kernel = ratio * 2` and the trailing conv's out-channels is `hidden_size`, both derived. - **`_EncoderResBlock`**: inner width is now `dim // compress` with a configurable kernel. ## Also fixed: the encoder RVQ could not load the real checkpoint This one is a **weight-loading correctness fix, not just a shape-consistency fix**, which is why it belongs here despite being adjacent to the original scope. `_EncoderSplitRVQ` used `input_dim=codebook_dim` and `dim=codebook_dim // 2`. The real checkpoint has `encoder.quantizer.*.input_proj.weight [256, 512, 1]` and `codebook.embed_sum [2048, 256]`, with `encoder_config.codebook_dim=256`. So the old code built `Conv1d(256→128)` projections and 128-wide codebooks: **the encoder could never have loaded the real checkpoint's weights**, independently of the malformed-graph issue. It only happened to be self-consistent on the `enc is None` fallback path, where `codebook_dim` defaulted to 512. Now it projects `hidden_size → codebook_dim`, matching HF `MimiResidualVectorQuantizer`. ### The encoder/decoder asymmetry is intentional — please don't unify these paths The two sides interpret `codebook_dim` differently, and both are correct: | | config value | RVQ input | codebook dim | checkpoint `input_proj` | |---|---|---|---|---| | encoder | `codebook_dim=256` (Mimi semantics: the codebook dim itself) | `hidden_size=512` | 256 | `[256, 512, 1]` | | decoder | `codebook_dim=512` (the RVQ *input* dim) | 512 | `512 // 2 = 256` | `[256, 512, 1]` | So the decoder's `// 2` convention in `SplitResidualVectorQuantizer` is right and is left untouched; only the encoder path was misreading its field. A future "cleanup" that unifies the two would reintroduce this bug. ## Verification **Symbolic-shape-inference failures across `TestBuildCodecGraph`** (measured by temporarily instrumenting `infer_symbolic_shapes`, since the pass swallows them — instrumentation not committed): | | failures | |---|---| | before | **6** | | after | **0** | **Default config reproduces the real checkpoint exactly** — verified against the safetensors header of `Qwen/Qwen3-TTS-Tokenizer-12Hz`: all 14 conv-stack weights match by name and shape, including the ResBlock `layers.N.block.1/.3` names and the `0,1,3,4,6,7,9,10,12,14` numbering, as do both RVQ `input_proj`/`output_proj` pairs and the codebooks. This is asserted by tests, so indexing or width drift (which would otherwise surface far away at weight-load time) fails loudly. **Tiny test config** keeps the real depth and only shrinks widths (`num_filters=4`, `hidden_size=32` → `1→4→8→16→32→64→32`), so it exercises the same weight-name structure the real model depends on. Codec test runtime: 2.05s (4 tests) → ~2.1s (9 tests). **Suite**: `pytest tests/build_graph_test.py tests/cli_test.py src/ -k "not phi4mm and not apply_weights_unknown" -n auto` → 8 failed, 4613 passed — the same 8 pre-existing failures on `main` (onnx_genai jsonschema drift + one qwen_image golden). `lintrunner` clean. ## New tests - `test_default_config_conv_stack_matches_checkpoint` — asserts derived parameter **names** and shapes against the real checkpoint. - `test_tiny_config_keeps_checkpoint_layer_names` — tiny config has identical naming, narrower tensors. - `test_conv_stack_indices_follow_config` — 2 ratios → final conv at `layers.8`; 4 ratios × 2 residual layers → `layers.18`. - `test_hidden_size_drives_conv_output_width` — direct regression guard for the original bug. - `test_default_config_rvq_projections_match_checkpoint` — asserts `input_proj (256, 512, 1)`, `output_proj (512, 256, 1)` and `(2048, 256)` codebooks, guarding the weight-loading fix. ## Decoder conv stack Checked: the codec **decoder** does **not** have the mirrored conv problem. `Qwen3TTSCodecDecoderModel` already derives everything from config (`latent_dim`, `decoder_dim`, `upsample_rates`, `upsampling_ratios`), and `CodecDecoderTransformerModel` has an `input_proj`/`output_proj` pair that adapts `latent_dim ↔ hidden_size`, so no width can be stranded. No change needed there. ## Scope Limited to the codec tokenizer model, its config, and its tests. Does not touch `reuse.py`, `_ssm.py`, `_mamba_block.py`, the onnx_genai integration (covered by #551), or `SymbolicShapeInferencePass`. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent e5d337b commit 4f7e5c8

6 files changed

Lines changed: 401 additions & 56 deletions

File tree

‎src/mobius/_configs/_base.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1125,6 +1125,14 @@ def from_transformers(cls, config, parent_config=None) -> ArchitectureConfig:
11251125
max_position_embeddings=getattr(ec, "max_position_embeddings", 8000),
11261126
num_quantizers=getattr(ec, "num_quantizers", 32),
11271127
num_semantic_quantizers=getattr(ec, "num_semantic_quantizers", 1),
1128+
audio_channels=getattr(ec, "audio_channels", 1),
1129+
num_filters=getattr(ec, "num_filters", 64),
1130+
num_residual_layers=getattr(ec, "num_residual_layers", 1),
1131+
kernel_size=getattr(ec, "kernel_size", 7),
1132+
last_kernel_size=getattr(ec, "last_kernel_size", 3),
1133+
residual_kernel_size=getattr(ec, "residual_kernel_size", 3),
1134+
compress=getattr(ec, "compress", 2),
1135+
upsampling_ratios=list(getattr(ec, "upsampling_ratios", [8, 6, 5, 4])),
11281136
)
11291137

11301138
# Model dtype

‎src/mobius/_configs/_base_test.py‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,3 +79,108 @@ def test_list_intermediate_size_collapses_to_first_element():
7979
out = ArchitectureConfig.from_transformers(cfg)
8080
assert out.intermediate_size == 8192
8181
assert isinstance(out.intermediate_size, int)
82+
83+
84+
def _codec_hf_config(**encoder_overrides):
85+
"""A Qwen3-TTS-Tokenizer-style HF config with nested encoder/decoder."""
86+
encoder = {
87+
"codebook_dim": 256,
88+
"codebook_size": 2048,
89+
"hidden_size": 512,
90+
"intermediate_size": 2048,
91+
"num_hidden_layers": 8,
92+
"num_attention_heads": 8,
93+
"num_key_value_heads": 8,
94+
"head_dim": 64,
95+
"num_quantizers": 32,
96+
"num_semantic_quantizers": 1,
97+
"audio_channels": 1,
98+
"num_filters": 64,
99+
"num_residual_layers": 1,
100+
"kernel_size": 7,
101+
"last_kernel_size": 3,
102+
"residual_kernel_size": 3,
103+
"compress": 2,
104+
"upsampling_ratios": [8, 6, 5, 4],
105+
}
106+
encoder.update(encoder_overrides)
107+
return _FakeHFConfig(
108+
model_type="qwen3_tts_tokenizer_12hz",
109+
hidden_size=512,
110+
num_attention_heads=8,
111+
num_hidden_layers=8,
112+
vocab_size=2048,
113+
decoder_config={"hidden_size": 512, "codebook_dim": 512},
114+
encoder_config=encoder,
115+
)
116+
117+
118+
def test_codec_encoder_conv_fields_extracted_from_nested_config():
119+
"""Nested ``encoder_config`` values drive the derived conv stack.
120+
121+
These fields are read with ``getattr`` off a nested config, so a wrong
122+
key or default would silently fall back to the checkpoint defaults and
123+
build the wrong architecture.
124+
"""
125+
out = ArchitectureConfig.from_transformers(_codec_hf_config())
126+
127+
enc = out.codec_encoder
128+
assert enc is not None
129+
assert enc.audio_channels == 1
130+
assert enc.num_filters == 64
131+
assert enc.num_residual_layers == 1
132+
assert enc.kernel_size == 7
133+
assert enc.last_kernel_size == 3
134+
assert enc.residual_kernel_size == 3
135+
assert enc.compress == 2
136+
assert enc.upsampling_ratios == [8, 6, 5, 4]
137+
138+
139+
def test_codec_encoder_conv_fields_honor_non_default_values():
140+
"""Non-default nested values must survive extraction unchanged."""
141+
out = ArchitectureConfig.from_transformers(
142+
_codec_hf_config(
143+
hidden_size=64,
144+
audio_channels=2,
145+
num_filters=8,
146+
num_residual_layers=3,
147+
kernel_size=5,
148+
last_kernel_size=1,
149+
residual_kernel_size=7,
150+
compress=4,
151+
upsampling_ratios=[4, 2],
152+
)
153+
)
154+
155+
enc = out.codec_encoder
156+
assert enc is not None
157+
assert enc.hidden_size == 64
158+
assert enc.audio_channels == 2
159+
assert enc.num_filters == 8
160+
assert enc.num_residual_layers == 3
161+
assert enc.kernel_size == 5
162+
assert enc.last_kernel_size == 1
163+
assert enc.residual_kernel_size == 7
164+
assert enc.compress == 4
165+
assert enc.upsampling_ratios == [4, 2]
166+
167+
168+
def test_codec_encoder_conv_fields_fall_back_to_checkpoint_defaults():
169+
"""A config omitting the conv fields still yields the real architecture."""
170+
out = ArchitectureConfig.from_transformers(
171+
_FakeHFConfig(
172+
model_type="qwen3_tts_tokenizer_12hz",
173+
hidden_size=512,
174+
num_attention_heads=8,
175+
num_hidden_layers=8,
176+
vocab_size=2048,
177+
decoder_config={"hidden_size": 512},
178+
encoder_config={"hidden_size": 512},
179+
)
180+
)
181+
182+
enc = out.codec_encoder
183+
assert enc is not None
184+
assert enc.num_filters == 64
185+
assert enc.upsampling_ratios == [8, 6, 5, 4]
186+
assert enc.num_residual_layers == 1

‎src/mobius/_configs/_sub_configs.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,18 @@ class CodecEncoderConfig:
148148
max_position_embeddings: int = 8000
149149
num_quantizers: int = 32
150150
num_semantic_quantizers: int = 1
151+
# Mimi convolutional encoder shape (HF ``MimiConfig`` defaults). The conv
152+
# stack is derived from these: 1 leading conv, then per upsampling ratio
153+
# ``num_residual_layers`` residual blocks + ELU + a strided conv that
154+
# doubles the channel count, then a trailing ELU + conv to ``hidden_size``.
155+
audio_channels: int = 1
156+
num_filters: int = 64
157+
num_residual_layers: int = 1
158+
kernel_size: int = 7
159+
last_kernel_size: int = 3
160+
residual_kernel_size: int = 3
161+
compress: int = 2
162+
upsampling_ratios: list[int] = dataclasses.field(default_factory=lambda: [8, 6, 5, 4])
151163

152164

153165
@dataclasses.dataclass

0 commit comments

Comments
 (0)