Skip to content

Commit c205048

Browse files
justinchubyCopilot
andcommitted
Merge main into Parakeet multi-talker support
Retain the multi-talker model exports and migrate its graph coverage from the removed monolithic test file into the current speech graph suite. Co-authored-by: Copilot App <[email protected]> Signed-off-by: Justin Chu <[email protected]>
2 parents 0816c51 + c8fb589 commit c205048

1,013 files changed

Lines changed: 382661 additions & 21503 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.agents/skills/adding-a-new-model/SKILL.md‎

Lines changed: 75 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,16 @@ Read these when you need deeper detail on a specific topic:
3535
- Find a small checkpoint on HuggingFace Hub for testing
3636
- Have the HuggingFace `transformers` source available to reference the
3737
PyTorch implementation
38+
- Pin the checkpoint revision before collecting configs, weights, processors,
39+
parity data, or goldens
40+
- Before a long run, smoke-test the pinned upstream loader in the exact task
41+
interpreter. Record its dependency versions and the selected CUDA provider.
42+
- Use the repository's pinned CI reference dependencies. Assert the validated
43+
layer vocabulary and supported compute dtype for raw JSON and trusted configs;
44+
validators can remap layer names or carry checkpoint storage dtypes.
45+
- If an architecture needs newer upstream code, isolate an immutable reference
46+
pin to its tests; verify installed commit provenance and replay with the
47+
unchanged shared reference dependencies.
3848

3949
## Step-by-step
4050

@@ -142,6 +152,9 @@ Standard categories: `"Text Generation"`, `"Mixture of Experts"`,
142152

143153
### 3. Identify what's different
144154

155+
Read the actual packed-QKV ordering, gate placement, and RoPE frequency/pair
156+
layout before reusing attention. Similar names or shapes do not prove equivalence.
157+
145158
Compare the HuggingFace PyTorch source against `CausalLMModel` / `DecoderLayer`.
146159
Common variations to look for:
147160

@@ -160,6 +173,8 @@ Common variations to look for:
160173
| MoE layers | PhiMoE, GPTOSS | See the **moe-models** skill |
161174
| Vision encoder | Gemma3 | See the **multimodal-models** skill |
162175
| Gated attention output | Qwen3.5 | Subclass `Attention` with doubled q_proj → Q+gate split |
176+
| Per-head attention gate | LFM3 | Separate head-sized projection; apply gate before output projection |
177+
| Zero-tail partial RoPE | LFM3 | Keep full-head frequency denominator and half-pair layout; do not use compact-prefix rotation |
163178
| Hybrid layer types | Qwen3.5 | Use `config.layer_types` list to dispatch per-layer |
164179
| Fused QKV / gate+up | ModernBERT | Split in `preprocess_weights` |
165180
| Subclass-only (weight rename) | BLIP, TrOCR | Override only `preprocess_weights` |
@@ -183,6 +198,22 @@ class MyCausalLMModel(CausalLMModel):
183198
> norms, identity folding), read
184199
> [`references/weight-preprocessing.md`](references/weight-preprocessing.md).
185200
201+
Before choosing eager preprocessing, estimate the peak memory from the source
202+
checkpoint and transformed tensors. Use an architecture-specific streaming
203+
planner when the checkpoint is large or a packed source must be converted to a
204+
different operator layout. In particular:
205+
206+
- use `StreamingWeightSource` for direct one-source/one-target bindings;
207+
- use `StreamingExpertBankSource` to assemble per-expert sources;
208+
- use `StreamingTransformedWeightSource` for lazy custom repacking;
209+
- distinguish storage semantics explicitly rather than treating every 4-bit,
210+
group-size-32 checkpoint as affine INT4.
211+
212+
The generic streaming engine belongs in `integrations/_weight_loading.py`.
213+
Model-specific source names, topology checks, and source-to-target mappings
214+
belong in `integrations/transformers/_<model>_weights.py`; graph math and tensor
215+
transforms belong in the model module.
216+
186217
### 5. Register the model
187218

188219
Add to `_create_default_registry()` in `src/mobius/_registry.py`:
@@ -219,6 +250,16 @@ Then add the new module to `src/mobius/_configs/per_model/__init__.py` so its
219250
side-effect registration runs at import time. The dispatcher filters hooks by
220251
the declared model_type strings, so unrelated models never see your hook.
221252

253+
Match upstream config semantics, not just field names: preserve transformation
254+
order (rounding/scaling), explicit `None`, alias precedence, zero-as-disabled
255+
sentinels, and wrapped/unwrapped composite configs. Add focused tests for each
256+
nontrivial transform. Test both trusted/custom config classes and raw pinned
257+
JSON, especially nested decoder fields such as head/layer counts.
258+
Preserve mapping-valued metadata (RoPE, sparse layer overrides, integer-keyed
259+
tables) when adapting config sections. Detect untagged native configs only from
260+
a distinctive complete signature; set compute dtype explicitly and test inherited
261+
`None` defaults rather than confusing checkpoint storage dtype with export dtype.
262+
222263
### 7. Write tests
223264

224265
See the **writing-tests** skill for full details. At minimum:
@@ -234,10 +275,11 @@ See the **writing-tests** skill for full details. At minimum:
234275
- `is_representative=True` if the model has unique behaviour
235276
- `is_representative=False` if it's an alias with no special config
236277

237-
Then verify: `pytest tests/build_graph_test.py -k "my_model_type"`
278+
Then verify: `pytest tests/build_graph -k "my_model_type"`
238279

239-
2. **Add a small model to `tests/integration_test.py`** if a small
240-
checkpoint exists (< 1B parameters preferred).
280+
2. **Add a small model to the appropriate focused integration suite** if a
281+
small checkpoint exists (< 1B parameters preferred). Generic causal LMs
282+
use `TEXT_MODELS` in `tests/integration/_support.py`.
241283

242284
3. **Testing large models with random weights:** Create a reduced HF model:
243285
```python
@@ -250,7 +292,7 @@ See the **writing-tests** skill for full details. At minimum:
250292

251293
4. **Test with the CLI:**
252294
```bash
253-
mobius build --model org/my-small-model mymodel/output
295+
mobius build --model org/my-small-model --output mymodel/output
254296
```
255297

256298
### 8. Documentation
@@ -269,18 +311,27 @@ see the [quality-checklist skill](../quality-checklist/SKILL.md).
269311
- [ ] Class has `default_task` and `category` attributes (if not standard text-generation)
270312
- [ ] Class has a descriptive docstring (first paragraph used in generated docs)
271313
- [ ] `preprocess_weights` handles any key mismatches
314+
- [ ] Peak checkpoint/transformation memory was assessed; large or packed-layout
315+
conversions use a fail-closed streaming planner
316+
- [ ] Quantized storage semantics are identified from authoritative metadata and
317+
checkpoint headers, not inferred from bit width alone
272318
- [ ] Registered in `_create_default_registry()`
273319
- [ ] Exported from `models/__init__.py`
274320
- [ ] Config extraction works (`ArchitectureConfig.from_transformers`)
275321
- [ ] Tiny config in `tests/_test_configs.py` (with `is_representative` flag)
276-
- [ ] L2 YAML test case in `testdata/cases/` with `test_model_id`
322+
- [ ] Registry `test_model_id` and immutable `test_revision` set; L2 passes via
323+
`python -m pytest tests/arch_validation_test.py -k "<model_type>"`
324+
- [ ] Golden YAML in `testdata/cases/` validates against its schema
277325
- [ ] L3 synthetic parity passes (`tests/synthetic_parity_test.py -k "<model_type>"`)
278-
- [ ] Integration test in `tests/integration_test.py` (if small checkpoint available)
326+
- [ ] Focused integration test in `tests/integration/` (if small checkpoint available)
279327
- [ ] L4 golden file generated and committed (`testdata/golden/`)
280328
- [ ] L5 generation golden file generated and committed
281-
- [ ] ORT GenAI test added to `tests/ort_genai_test.py` (text-generation and VLM models)
329+
- [ ] Graph-derived ORT GenAI metadata is tested; downstream load/generation is
330+
optional evidence and never an export capability gate
282331
- [ ] CLI build works (`mobius build --model ...`)
283-
- [ ] Multi-dtype correctness verified (fp32, fp16, bf16)
332+
- [ ] Each claimed dtype passes full-checkpoint parity, not only tiny tests;
333+
unsupported dtypes fail at construction and graph creation
334+
- [ ] Pinned revision reaches every Hub/processor/weight/golden call
284335

285336
**Note:** Default optimizer passes (CSE, deduplicate initializers, identity
286337
elimination, remove unused nodes/opsets) are applied automatically.
@@ -347,6 +398,10 @@ long_factor = np.array(config.rope_scaling["long_factor"])
347398
long_factor = np.array(config.rope_scaling["long_factor"], dtype=np.float32)
348399
```
349400

401+
Direct NumPy operands require explicit ONNX constants:
402+
`op.Constant(value=ir.tensor(long_factor))`. Match operator rank contracts too:
403+
ONNX RoPE positions must include the batch axis even if HF broadcasts a 1D input.
404+
350405
### 2. Normalization type mismatch (RMSNorm vs LayerNorm)
351406

352407
**Symptom:** Large max abs diff (> 0.5) from HuggingFace. Check what norm
@@ -426,6 +481,18 @@ config-driven features for the offending subclass.
426481
> embedding table off-by-one), read
427482
> [`references/weight-preprocessing.md`](references/weight-preprocessing.md).
428483
484+
### 8. Compatibility and optional dependency traps
485+
486+
- Guard imports of symbols from unpinned dependencies when older supported
487+
versions may not define them.
488+
- If remote code imports an optional package, first prove the selected model
489+
path needs it. Scope any test-only shim to that unused import; do not add a
490+
production fallback or require an irrelevant package.
491+
- When extending a public component, append optional parameters after existing
492+
positional parameters and add a positional-call compatibility test.
493+
- Helpers with rank/shape contracts must receive a value of that rank; do not
494+
rely on incidental compatibility from a higher-rank tensor.
495+
429496
## Reference examples
430497

431498
| Complexity | File | Why |

‎.agents/skills/adding-a-new-model/references/architecture-patterns.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ graphs; weight-loading may need minor adjustments:
5050
### NEVER safe as registry aliases
5151

5252
These model families have fundamentally different computation that **cannot**
53-
be represented by standard base classes, even though `build_graph_test` passes:
53+
be represented by standard base classes, even though the L1 graph suite passes:
5454

5555
| Category | Models | Why it fails |
5656
|----------|--------|-------------|

‎.agents/skills/adding-a-new-model/references/weight-preprocessing.md‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,52 @@ to weight loading or dtype problems.
1414
- **Split fused gate+up:** `Wi.weight` [2I, H] → `gate_proj`, `up_proj` (ModernBERT)
1515
- **Split fused BLIP QKV:** `in_proj_weight` [3H, H] → separate Q/K/V projections
1616

17+
## Choose eager preprocessing or a streaming adapter
18+
19+
Use `preprocess_weights(state_dict)` for checkpoints that fit comfortably in
20+
host memory and require only inexpensive rename, split, fuse, transpose, or
21+
dtype operations. The generic eager loader retains the complete state dict, so
22+
it is not appropriate when source tensors plus transformed tensors can approach
23+
available RAM.
24+
25+
Use an architecture-specific streaming planner when the checkpoint is large or
26+
the destination requires a substantial layout transformation. Keep the
27+
architecture-specific mapping in
28+
`integrations/transformers/_<model>_weights.py` and reuse the mechanisms in
29+
`integrations/_weight_loading.py`:
30+
31+
| Source type | Use when |
32+
|---|---|
33+
| `StreamingWeightSource` | One checkpoint tensor binds directly to one initializer, optionally using a supported built-in mode |
34+
| `StreamingExpertBankSource` | Multiple per-expert source matrices are assembled into one expert-major initializer |
35+
| `StreamingTransformedWeightSource` | One source tensor is lazily validated and transformed into a differently shaped or encoded target |
36+
37+
A transformed source declares both sides of the contract:
38+
39+
```python
40+
StreamingTransformedWeightSource(
41+
source_name=source_name,
42+
expected_source_shape=source_shape,
43+
expected_source_dtype=source_dtype,
44+
expected_target_shape=target_shape,
45+
expected_target_dtype=target_dtype,
46+
transform=repack_source_layout,
47+
validate_tensor=validate_source_values,
48+
)
49+
```
50+
51+
The planner must classify every source key, validate checkpoint headers against
52+
the model config, and validate target metadata against graph initializers before
53+
binding lazy tensors. The transform runs during external-data serialization so
54+
only the current source, transformation scratch space, and destination tensor
55+
need to be resident.
56+
57+
Do not infer a checkpoint storage format from `bits` and `group_size` alone.
58+
Those fields cannot distinguish, for example, affine INT4 from E2M1 MXFP4 with
59+
E8M0 block scales. Config metadata identifies the format family, safetensors
60+
headers provide the actual names/shapes/dtypes, and the model adapter bridges
61+
that source contract to the emitted operator ABI.
62+
1763
## Debugging mismatches: initializer comparison
1864

1965
Build the ONNX model, list its initializer names, and compare against

‎.agents/skills/attention-optimization/SKILL.md‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -201,8 +201,24 @@ TRT FusedRunner → MEA → Unfused
201201

202202
### Contrib GroupQueryAttention (`com.microsoft`)
203203

204-
Cascade: XQA → Flash → MEA → Unfused. **Rejects `attention_bias`
205-
entirely.**
204+
Cascade: XQA → Flash → MEA → Unfused. **None of the CUDA fused kernels
205+
(XQA/Flash/MEA) accept `attention_bias`**, so supplying one on CUDA
206+
forces the Unfused fallback.
207+
208+
> Correction (verified against stock ORT 1.29.0, CPU EP, 2026-08):
209+
> despite the above, GQA is **not** a blanket-reject op — the CPU EP
210+
> genuinely computes with both `attention_bias` and `head_sink` when
211+
> supplied (not silently ignored), confirmed by direct numerical probes
212+
> against the bundled library. "Rejects `attention_bias` entirely" was
213+
> inaccurate as a general statement about the op; it only holds for the
214+
> CUDA fused-kernel cascade below. Separately, onnx-genai's own native
215+
> CPU+CUDA kernels are a *stricter* subset of what stock ORT supports:
216+
> historically both rejected `attention_bias`, and only the CUDA kernel
217+
> implemented `head_sink` (see
218+
> [`justinchuby/onnx-genai/crates/onnx-runtime-ep-cpu/src/kernels/group_query_attention.rs`](https://github.com/justinchuby/onnx-genai/blob/main/crates/onnx-runtime-ep-cpu/src/kernels/group_query_attention.rs),
219+
> which now also implements `head_sink` on CPU; `attention_bias` remains
220+
> unimplemented there by design, matching the CUDA fused-kernel
221+
> limitation above, not an oversight).
206222
207223
| Kernel | Required conditions |
208224
|--------|---------------------|
@@ -297,8 +313,12 @@ use custom per-layer `GQAContext`s instead.
297313
`past_key`/`past_value` inputs (so it is prefill-only in the *growing*
298314
cache mode), but it is used at **every** step in the static-cache mode
299315
(full cache in the `key`/`value` slots).
300-
3. **GQA contrib op rejects `attention_bias`** — use standard ONNX
301-
`Attention` if you need bias with GQA.
316+
3. **GQA's CUDA fused kernels reject `attention_bias`** (Unfused CUDA
317+
still accepts it, and stock ORT's CPU EP genuinely supports it too —
318+
see the correction above) — use standard ONNX `Attention` if you
319+
need bias with a CUDA fused GQA kernel, or if targeting onnx-genai's
320+
own native kernels (which don't implement `attention_bias` on GQA
321+
either, CPU or CUDA).
302322
4. **SM≥8.0** (Ampere+) required for Flash on all paths.
303323
5. **Float bias is safer** than bool mask for complex attention patterns.
304324
6. **MEA requires alignment** — `total_kv % 4 == 0` for bias tensors.

‎.agents/skills/debugging-multimodal/SKILL.md‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -261,11 +261,11 @@ via `MOBIUS_ORT_LOWER_OPSET_FOR_EP=1`). See `src/mobius/_flags.py`.
261261

262262
### Encoder input dtype alignment
263263

264-
Encoder task inputs should be declared with `dtype=config.dtype` so
265-
entry tensors match the model compute dtype (float32/float16/bfloat16).
266-
In the current codebase, multimodal encoder task builders set encoder
267-
inputs directly to `config.dtype` (there is no `_cast_encoder_input()`
268-
helper in `src/mobius/tasks/_base.py`).
264+
Real vision/audio processors emit float32. Encoder graph inputs should
265+
therefore be float32 even for fp16/bf16 exports, with one Cast to
266+
`config.dtype` at graph entry. Verify this with an actual processor batch
267+
and a graph I/O dtype assertion; synthetic feeds can hide the mismatch.
268+
Some older task builders still use `config.dtype` and are not safe templates.
269269

270270
### GQA for KV-shared layers
271271

@@ -339,8 +339,9 @@ assert_logits_close(onnx_logits, hf_logits, rtol=2e-2, atol=2e-1)
339339
> extraction, integration test patterns, tolerance guidelines, weight
340340
> loading verification, and HD multi-crop verification.
341341
342-
- **Integration tests:** `tests/integration_test.py`
343-
(`TestVLFullForward`, `TestQwen25VL3Model`),
342+
- **Integration tests:** `tests/integration/vlm_test.py`
343+
(`TestVLTextForward`, `TestQwen25VL3Model`),
344+
`tests/integration/multimodal_pipeline_test.py`,
344345
`tests/phi4mm_integration_test.py`
345346
- **ORT GenAI tests:** `tests/ort_genai_test.py`
346347
- **Example scripts:** `examples/qwen25_vl_ort_genai.py`,

‎.agents/skills/diffusion-models/SKILL.md‎

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -39,15 +39,16 @@ When the CLI or `build()` encounters a model that isn't a transformers model,
3939
it checks for `model_index.json` (the diffusers pipeline descriptor):
4040

4141
```python
42-
# In _diffusers_builder.py
42+
# In integrations/diffusers/_builder.py
4343
# 1. Try transformers AutoConfig → if fails:
4444
# 2. Try loading model_index.json → if found:
4545
# 3. Parse components and build each via _DIFFUSERS_CLASS_MAP
4646
```
4747

4848
### Registering a new diffusers model
4949

50-
Add an entry to `_init_diffusers_class_map()` in `_diffusers_builder.py`:
50+
Add an entry to `_init_diffusers_class_map()` in
51+
`integrations/diffusers/_builder.py`:
5152

5253
```python
5354
def _init_diffusers_class_map():
@@ -118,7 +119,7 @@ Existing config classes:
118119
- `QwenImageVAEConfig` — QwenImage 3D causal VAE
119120
- `VideoVAEConfig` — 3D video VAE
120121

121-
All defined in `src/mobius/_diffusers_configs.py`.
122+
All defined in `src/mobius/integrations/diffusers/_configs.py`.
122123

123124
## Task classes
124125

@@ -284,7 +285,7 @@ x = op.Add(x, op.Mul(attn_out, gate_msa))
284285

285286
### 1. Create config class
286287

287-
In `_diffusers_configs.py`:
288+
In `integrations/diffusers/_configs.py`:
288289

289290
```python
290291
@dataclasses.dataclass
@@ -324,7 +325,7 @@ class MyDenoiser2DModel(nn.Module):
324325

325326
### 3. Register in _DIFFUSERS_CLASS_MAP
326327

327-
In `_diffusers_builder.py`, add to `_init_diffusers_class_map()`:
328+
In `integrations/diffusers/_builder.py`, add to `_init_diffusers_class_map()`:
328329

329330
```python
330331
_DIFFUSERS_CLASS_MAP["MyDenoiser2DModel"] = (
@@ -339,7 +340,7 @@ new task in `tasks/`. Most denoisers use the standard `DenoisingTask`.
339340

340341
### 5. Add unit test
341342

342-
In `tests/build_graph_test.py`, add a tiny config:
343+
In the appropriate `tests/build_graph` domain file, add a tiny graph test:
343344

344345
```python
345346
("my_denoiser", MyDenoiser2DModel, MyDenoiserConfig(
@@ -353,6 +354,27 @@ Compare `named_parameters()` output with HF weight names. Use the
353354
techniques from the **weight-name-alignment** skill to minimize
354355
`preprocess_weights`.
355356

357+
### 7. Prove pipeline executability
358+
359+
A component graph or metadata file is not a runnable diffusion pipeline.
360+
Before advertising runtime support, execute the complete path:
361+
362+
`image encoder/VAE -> latent packing -> denoiser loop + scheduler -> target token unpacking -> VAE decoder`
363+
364+
Verify sample/output ranks, source-vs-target token slicing, CFG semantics, and
365+
the runtime's actual scheduler identifiers/equations. Reload final metadata and
366+
verify every file path, port, preprocessing step, loop edge, and postprocess.
367+
Emit faithful component graphs and metadata even when the tested downstream
368+
runtime cannot yet express the complete dataflow. Record that runtime/version
369+
limitation separately; it must not become a Mobius export capability gate.
370+
371+
Validate required VAE statistics against latent channel count before graph
372+
construction (`len(mean) == len(std) == z_dim`, positive standard deviations).
373+
Keep model-specific component/task overrides data-driven rather than adding
374+
pipeline-name conditionals. Fold initializers after weight loading and mark
375+
denoiser/VAE roles by semantics, not names. Tests must use `os.path.join`/`Path`
376+
for temporary ONNX and profiling paths so cleanup works on POSIX and Windows.
377+
356378
## Naming conventions for diffusers models
357379

358380
Diffusers uses different conventions than transformers:
@@ -372,8 +394,8 @@ Diffusers uses different conventions than transformers:
372394

373395
| File | Contains |
374396
|------|----------|
375-
| `_diffusers_configs.py` | All diffusers config dataclasses |
376-
| `_diffusers_builder.py` | Pipeline detection, `_DIFFUSERS_CLASS_MAP`, build functions |
397+
| `integrations/diffusers/_configs.py` | All diffusers config dataclasses |
398+
| `integrations/diffusers/_builder.py` | Pipeline detection, `_DIFFUSERS_CLASS_MAP`, build functions |
377399
| `models/unet.py` | UNet2DConditionModel + all UNet blocks |
378400
| `models/vae.py` | AutoencoderKLModel + encoder/decoder blocks |
379401
| `models/dit.py` | DiTTransformer2DModel + AdaLN blocks |

0 commit comments

Comments
 (0)