Skip to content

Commit b25e6b9

Browse files
justinchubyCopilot
andcommitted
Validate Moshi depformer width at runtime
Infer the 8- or 16-step depformer width from raw and INT4 ONNX weights, validate explicit overrides in both CLI and server paths, reject unsupported exporter widths, and refresh configurable-step documentation and tests. Co-authored-by: Copilot <[email protected]> Signed-off-by: justinchuby <[email protected]>
1 parent c5f6e16 commit b25e6b9

6 files changed

Lines changed: 207 additions & 37 deletions

File tree

‎examples/personaplex/moshi_ort.py‎

Lines changed: 51 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,14 @@
1818
* **Mimi encoder** ``waveform (B,1,T) -> codes (B,8,Tf)``
1919
* **Moshi temporal** ``frame (B,17,S) -> hidden + text_logits + KV``
2020
* **Moshi depformer** ``hidden + prev_token + substep_index + KV -> logits``
21-
(stepped 16 times per frame, once per audio codebook)
21+
(stepped 8 times for public Moshi/Moshiko or 16 times for PersonaPlex)
2222
* **Mimi decoder** ``codes (B,8,Tf) -> waveform (B,1,T)``
2323
2424
The generation loop is a faithful NumPy port of Kyutai ``LMGen.step``: a ring
2525
cache with per-codebook delays, the temporal step, greedy text sampling, the
26-
16-substep autoregressive depformer, and delayed output collection. The user
27-
audio stream is fed as the 8 "other" codebooks (``k = 9..16``); the assistant
28-
(Moshi) audio is generated as codebooks ``k = 1..8`` and decoded by Mimi.
26+
configurable autoregressive depformer, and delayed output collection. The
27+
user audio stream is fed as the 8 "other" codebooks (``k = 9..16``); the
28+
assistant audio uses the first 8 generated codebooks and is decoded by Mimi.
2929
3030
Prerequisites::
3131
@@ -67,6 +67,7 @@
6767
import time
6868

6969
import numpy as np
70+
import onnx_ir as ir
7071

7172
_MODEL_ID = "nvidia/personaplex-7b-v1"
7273

@@ -165,6 +166,35 @@ def encode_persona(tokenizer, persona_text: str) -> list[int]:
165166
return list(tokenizer.encode(text))
166167

167168

169+
def _model_path(model_dir: str, name: str) -> str:
170+
path = os.path.join(model_dir, name, "model.onnx")
171+
if not os.path.isfile(path) and name.startswith("mimi_"):
172+
path = os.path.join(model_dir, name.removeprefix("mimi_"), "model.onnx")
173+
if not os.path.isfile(path):
174+
path = os.path.join(model_dir, f"{name}.onnx")
175+
return path
176+
177+
178+
def _infer_dep_q(model_path: str) -> int:
179+
"""Read the depformer step count from raw or quantized ONNX weights."""
180+
model = ir.load(model_path)
181+
widths = {
182+
int(value.shape[0])
183+
for name, value in model.graph.initializers.items()
184+
if name == "depformer_in.weight" or name.startswith("depformer_in.weight_")
185+
}
186+
if len(widths) != 1:
187+
raise ValueError(
188+
f"Cannot infer depformer width from {model_path!r}: found widths {sorted(widths)}"
189+
)
190+
dep_q = widths.pop()
191+
if dep_q not in (8, 16):
192+
raise ValueError(
193+
f"Unsupported depformer width {dep_q} in {model_path!r}; expected 8 or 16"
194+
)
195+
return dep_q
196+
197+
168198
class MoshiORT:
169199
"""Full-duplex Moshi generation driven by four ONNX Runtime sessions."""
170200

@@ -179,19 +209,23 @@ def __init__(
179209
temp_audio: float = 0.8,
180210
top_k_audio: int = 250,
181211
seed: int | None = None,
182-
dep_q: int = DEP_Q,
212+
dep_q: int | None = None,
183213
):
214+
depformer_path = _model_path(model_dir, "depformer")
215+
inferred_dep_q = _infer_dep_q(depformer_path)
216+
if dep_q is not None and dep_q != inferred_dep_q:
217+
raise ValueError(
218+
f"Requested dep_q={dep_q}, but {depformer_path!r} contains "
219+
f"{inferred_dep_q} depformer steps"
220+
)
221+
dep_q = inferred_dep_q
222+
184223
import onnxruntime as ort
185224

186225
providers = _provider(device, allow_tf32)
187226

188227
def _load(name: str):
189-
path = os.path.join(model_dir, name, "model.onnx")
190-
if not os.path.isfile(path) and name.startswith("mimi_"):
191-
path = os.path.join(model_dir, name.removeprefix("mimi_"), "model.onnx")
192-
if not os.path.isfile(path):
193-
path = os.path.join(model_dir, f"{name}.onnx")
194-
return ort.InferenceSession(path, providers=providers)
228+
return ort.InferenceSession(_model_path(model_dir, name), providers=providers)
195229

196230
self.enc = _load("mimi_encoder")
197231
self.dec = _load("mimi_decoder")
@@ -391,13 +425,13 @@ def _temporal_step(self, frame: np.ndarray):
391425
self._tpos += s
392426
return hidden[:, -1:], text_logits[0, -1]
393427

394-
# --- Depformer: 16 autoregressive substeps --------------------------
428+
# --- Depformer: 8 or 16 autoregressive substeps ---------------------
395429
def _depformer_step(self, text_token, hidden, audio_target, audio_provided):
396-
"""Generate the 16 audio codebooks for one frame.
430+
"""Generate one frame of depformer tokens.
397431
398432
``audio_target`` / ``audio_provided``: (16,) teacher-forcing of the
399-
16 audio codebooks (used for the user stream at k=9..16 and any forced
400-
Moshi tokens). Returns sampled (16,) int64.
433+
temporal audio channels (used for the user stream at k=9..16 and any
434+
forced Moshi tokens). Returns sampled ``(dep_q,)`` int64.
401435
"""
402436
past = [
403437
(
@@ -748,8 +782,8 @@ def main() -> None:
748782
"--dep-q",
749783
type=int,
750784
choices=[8, 16],
751-
default=DEP_Q,
752-
help="Depformer codebooks: 8 for public Moshi/Moshiko, 16 for PersonaPlex.",
785+
default=None,
786+
help="Expected depformer width; default infers 8 or 16 from the ONNX package.",
753787
)
754788
parser.add_argument("--save-to", default=None, help="dir to write assistant.wav")
755789
parser.add_argument("--skip-build", action="store_true", help="reuse existing --model-dir")

‎examples/personaplex/server.py‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -228,10 +228,14 @@ async def websocket_handler(request: web.Request) -> web.WebSocketResponse:
228228

229229

230230
def build_app(
231-
model_dir: str, device: str, allow_tf32: bool, tokenizer_path: str | None = None
231+
model_dir: str,
232+
device: str,
233+
allow_tf32: bool,
234+
tokenizer_path: str | None = None,
235+
dep_q: int | None = None,
232236
) -> web.Application:
233237
print(f"[server] loading Moshi ONNX models from {model_dir} on {device}...")
234-
moshi = MoshiORT(model_dir, device, allow_tf32)
238+
moshi = MoshiORT(model_dir, device, allow_tf32, dep_q=dep_q)
235239
print("[server] models loaded.")
236240

237241
tokenizer = None
@@ -270,6 +274,13 @@ def main() -> None:
270274
default=None,
271275
help="path to tokenizer_spm_32k_3.model (default: download from HF)",
272276
)
277+
parser.add_argument(
278+
"--dep-q",
279+
type=int,
280+
choices=[8, 16],
281+
default=None,
282+
help="expected depformer width; default infers it from the ONNX package",
283+
)
273284
args = parser.parse_args()
274285

275286
if not os.path.isdir(os.path.join(args.model_dir, "temporal")):
@@ -278,7 +289,13 @@ def main() -> None:
278289
"(see this file's module docstring)."
279290
)
280291

281-
app = build_app(args.model_dir, args.device, args.allow_tf32, args.tokenizer)
292+
app = build_app(
293+
args.model_dir,
294+
args.device,
295+
args.allow_tf32,
296+
args.tokenizer,
297+
dep_q=args.dep_q,
298+
)
282299
print(f"[server] listening on http://{args.host}:{args.port} (open / in a browser)")
283300
web.run_app(app, host=args.host, port=args.port, print=None)
284301

‎src/mobius/models/moshi.py‎

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@
1313
emits the post-norm hidden state plus text logits.
1414
1515
* **Depformer** (:class:`MoshiDepformerModel`): a small 6-layer transformer
16-
that autoregressively predicts the 16 audio codebooks for a single temporal
17-
step. It is *not* built here yet (added in a follow-up); this file currently
18-
implements the temporal stack and its native-checkpoint weight loader.
16+
that autoregressively predicts one frame of audio codebooks. Public
17+
Moshi/Moshiko checkpoints use 8 substeps; PersonaPlex uses 16. This module
18+
builds both variants and maps their native per-step weights.
1919
2020
The checkpoint is the native Kyutai ``safetensors`` format (no HuggingFace
2121
``config.json``); :func:`moshi_temporal_config` reproduces the fixed
@@ -233,20 +233,20 @@ def _preprocess_moshi_temporal_weights(
233233
# Depformer: autoregressive per-substep audio codebook predictor.
234234
# ===========================================================================
235235
#
236-
# The depformer predicts the 16 audio codebooks for a single temporal step,
237-
# one substep at a time. It is exported as a ONE-SUBSTEP graph: given the
236+
# The depformer predicts one frame of audio codebooks, one substep at a time.
237+
# It is exported as a ONE-SUBSTEP graph: given the
238238
# temporal hidden state, the previously sampled token, the substep index, and
239239
# the intra-frame KV cache, it produces the logits for one codebook and the
240240
# updated KV cache. The deployment loop (see the ORT example) calls this graph
241-
# 16 times per frame, feeding each substep the token sampled at the previous
242-
# substep; the KV cache is reset at the start of every temporal frame.
241+
# 8 times for Moshi/Moshiko or 16 times for PersonaPlex, feeding each substep
242+
# the token sampled previously; the cache resets at each temporal frame.
243243
#
244244
# ``weights_per_step``: the attention in/out projections, the SwiGLU gating,
245245
# the per-codebook input projection, and the output head all use a different
246-
# weight slice for each of the 16 substeps, selected by ``substep_index`` via
246+
# weight slice for each of the 8 or 16 substeps, selected by ``substep_index`` via
247247
# a runtime Gather over a stacked weight tensor. The two RMSNorms are shared
248248
# across substeps. The depformer uses NO positional embedding (no RoPE) and
249-
# full causal attention over the (at most 16) cached substeps.
249+
# full causal attention over the cached substeps.
250250

251251

252252
class _PerStepLinear(nn.Module):
@@ -330,7 +330,7 @@ class MoshiDepformerModel(nn.Module):
330330
frame.
331331
- ``prev_token``: (batch, 1) INT64 token sampled at the previous
332332
substep (the temporal text token for substep 0).
333-
- ``substep_index``: scalar INT64 in ``[0, 15]`` selecting the
333+
- ``substep_index``: scalar INT64 in ``[0, dep_q - 1]`` selecting the
334334
per-step weights and the input-embedding table.
335335
- per-layer KV cache (6 layers).
336336
@@ -349,10 +349,14 @@ def __init__(self, config: ArchitectureConfig | None = None):
349349
super().__init__()
350350
self.config = config
351351
self.dep_q = config.max_position_embeddings if config is not None else _D_Q
352+
if self.dep_q not in (8, 16):
353+
raise ValueError(
354+
f"dep_q must be 8 (Moshi/Moshiko) or 16 (PersonaPlex), got {self.dep_q}"
355+
)
352356
# Per-codebook input projection (temporal dim -> depformer dim).
353357
self.depformer_in = _PerStepLinear(self.dep_q, _T_DIM, _D_DIM)
354358
# Previous-token embeddings: text table (substep 0) + audio tables
355-
# (substeps 1..15 use audio table substep-1).
359+
# (substeps 1..dep_q-1 use audio table substep-1).
356360
self.text_emb = Embedding(_TEXT_CARD + 1, _D_DIM)
357361
self.audio_emb = nn.Parameter([self.dep_q - 1, _AUDIO_CARD + 1, _D_DIM])
358362
self.layers = nn.ModuleList([_DepformerLayer(self.dep_q) for _ in range(_D_LAYERS)])
@@ -407,9 +411,9 @@ def preprocess_weights(
407411

408412

409413
def moshi_depformer_config(dep_q: int = _D_Q) -> ArchitectureConfig:
410-
"""Fixed :class:`ArchitectureConfig` for the Moshi depformer."""
411-
if dep_q < 1:
412-
raise ValueError(f"dep_q must be positive, got {dep_q}")
414+
"""Return the fixed-size Moshi (8) or PersonaPlex (16) depformer config."""
415+
if dep_q not in (8, 16):
416+
raise ValueError(f"dep_q must be 8 (Moshi/Moshiko) or 16 (PersonaPlex), got {dep_q}")
413417
return ArchitectureConfig(
414418
model_type="moshi_depformer",
415419
hidden_size=_D_DIM,
@@ -438,6 +442,8 @@ def _preprocess_moshi_depformer_weights(
438442
``(steps * 3 * dim, in)`` for fused QKV) are reshaped to
439443
``(steps, out, in)``; the shared RMSNorm ``alpha`` tensors are squeezed.
440444
"""
445+
if dep_q not in (8, 16):
446+
raise ValueError(f"dep_q must be 8 (Moshi/Moshiko) or 16 (PersonaPlex), got {dep_q}")
441447
out: dict[str, torch.Tensor] = {}
442448

443449
# Per-codebook input projections: depformer_in.{i}.weight (1024, 4096).

‎src/mobius/tasks/_moshi.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -100,16 +100,17 @@ def build(
100100

101101

102102
class MoshiDepformerTask(ModelTask):
103-
"""Moshi depformer: one autoregressive substep with intra-frame KV cache.
103+
"""Moshi/PersonaPlex depformer substep with intra-frame KV cache.
104104
105105
The module's ``forward()`` must accept
106106
``(op, hidden, prev_token, substep_index, past_key_values)`` and return
107-
``(logits, list_of_(key, value)_tuples)``.
107+
``(logits, list_of_(key, value)_tuples)``. The graph is invoked 8 times
108+
per frame for public Moshi/Moshiko or 16 times for PersonaPlex.
108109
109110
Inputs:
110111
- hidden: [batch, 1, temporal_dim] FLOAT (temporal transformer output)
111112
- prev_token: [batch, 1] INT64 (token sampled at the previous substep)
112-
- substep_index: scalar INT64 in [0, 15]
113+
- substep_index: scalar INT64 in [0, config.max_position_embeddings - 1]
113114
- past_key_values.{i}.key / .value: [batch, num_heads, past_len,
114115
head_dim] FLOAT
115116
Outputs:

‎tests/build_graph_test.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4751,6 +4751,13 @@ def test_depformer_io(self, dep_q):
47514751
assert "present.0.key" in outputs
47524752
assert model.graph.initializers["depformer_in.weight"].shape[0] == dep_q
47534753

4754+
@pytest.mark.parametrize("dep_q", [0, 1, 2, 7, 9, 17])
4755+
def test_depformer_rejects_unsupported_width(self, dep_q):
4756+
from mobius.models.moshi import moshi_depformer_config
4757+
4758+
with pytest.raises(ValueError, match=r"dep_q must be 8 .* or 16"):
4759+
moshi_depformer_config(dep_q)
4760+
47544761

47554762
class TestBuildCodecGraph:
47564763
"""Verify codec tokenizer (Qwen3-TTS-Tokenizer-12Hz) graph construction."""

‎tests/moshi_ort_test.py‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
from __future__ import annotations
2+
3+
import importlib.util
4+
import sys
5+
from pathlib import Path
6+
from types import SimpleNamespace
7+
8+
import pytest
9+
10+
_EXAMPLE_DIR = Path(__file__).parents[1] / "examples" / "personaplex"
11+
12+
13+
def _load_example(name: str):
14+
spec = importlib.util.spec_from_file_location(name, _EXAMPLE_DIR / f"{name}.py")
15+
assert spec is not None and spec.loader is not None
16+
module = importlib.util.module_from_spec(spec)
17+
sys.modules[name] = module
18+
spec.loader.exec_module(module)
19+
return module
20+
21+
22+
moshi_ort = _load_example("moshi_ort")
23+
24+
25+
@pytest.mark.parametrize(
26+
("initializer_name", "dep_q"),
27+
[("depformer_in.weight", 8), ("depformer_in.weight_Q4", 16)],
28+
)
29+
def test_infer_dep_q_from_raw_or_quantized_weight(monkeypatch, initializer_name, dep_q):
30+
model = SimpleNamespace(
31+
graph=SimpleNamespace(
32+
initializers={initializer_name: SimpleNamespace(shape=(dep_q, 1024, 4096))}
33+
)
34+
)
35+
monkeypatch.setattr(moshi_ort.ir, "load", lambda _: model)
36+
37+
assert moshi_ort._infer_dep_q("depformer/model.onnx") == dep_q
38+
39+
40+
@pytest.mark.parametrize(
41+
"initializers",
42+
[
43+
{},
44+
{"depformer_in.weight": SimpleNamespace(shape=(1, 1024, 4096))},
45+
{
46+
"depformer_in.weight": SimpleNamespace(shape=(8, 1024, 4096)),
47+
"depformer_in.weight_Q4": SimpleNamespace(shape=(16, 1024, 512)),
48+
},
49+
],
50+
)
51+
def test_infer_dep_q_rejects_missing_unsupported_or_ambiguous_width(monkeypatch, initializers):
52+
model = SimpleNamespace(graph=SimpleNamespace(initializers=initializers))
53+
monkeypatch.setattr(moshi_ort.ir, "load", lambda _: model)
54+
55+
with pytest.raises(ValueError, match="depformer width"):
56+
moshi_ort._infer_dep_q("depformer/model.onnx")
57+
58+
59+
def test_runtime_rejects_explicit_width_mismatch_before_loading_sessions(monkeypatch):
60+
monkeypatch.setattr(moshi_ort, "_infer_dep_q", lambda _: 8)
61+
62+
with pytest.raises(ValueError, match=r"Requested dep_q=16.*contains 8"):
63+
moshi_ort.MoshiORT("model", "cpu", False, dep_q=16)
64+
65+
66+
def test_server_threads_dep_q_to_runtime(monkeypatch):
67+
class FakeRouter:
68+
def add_get(self, *_):
69+
pass
70+
71+
def add_static(self, *_):
72+
pass
73+
74+
class FakeApplication(dict):
75+
def __init__(self):
76+
super().__init__()
77+
self.router = FakeRouter()
78+
79+
fake_web = SimpleNamespace(Application=FakeApplication)
80+
monkeypatch.setitem(
81+
sys.modules,
82+
"aiohttp",
83+
SimpleNamespace(WSMsgType=SimpleNamespace(), web=fake_web),
84+
)
85+
server = _load_example("server")
86+
captured = {}
87+
88+
class FakeMoshiORT:
89+
def __init__(self, *args, **kwargs):
90+
captured["args"] = args
91+
captured["kwargs"] = kwargs
92+
93+
monkeypatch.setattr(server, "MoshiORT", FakeMoshiORT)
94+
monkeypatch.setattr(
95+
server,
96+
"load_persona_tokenizer",
97+
lambda _: (_ for _ in ()).throw(RuntimeError("not needed")),
98+
)
99+
100+
server.build_app("model", "cpu", False, dep_q=8)
101+
102+
assert captured == {
103+
"args": ("model", "cpu", False),
104+
"kwargs": {"dep_q": 8},
105+
}

0 commit comments

Comments
 (0)