Skip to content

Commit 9b07f09

Browse files
justinchubyCopilotCopilot
authored
Improve model integration skills from merged PRs (#482)
## Summary - distill post-single-shot lessons from the Parakeet CTC, Mage-VL, Nemotron Parse, LFM2.5, Moonshine, MiniCPM-V, Qwen Image Edit, and Muse Glimmer integrations - tighten source/config/revision fidelity, real processor and runtime contracts, semantic multi-dtype validation, exact golden testing, and weighted graph optimization evidence - add precise CI baseline triage, targeted GPU validation, linear rebase/worktree guidance, quantization schema checks, and executable diffusion pipeline requirements - shorten the duplicated multimodal float32 input section and resolve contradictory encoder/component import guidance ## Sources Direct agent retrospectives plus commit/review history for merged PRs #462-#465, #471-#473, and #475. ## Validation - documentation diff is whitespace-clean - initialized repository-pinned Ruff/lintrunner tooling - independent rubber-duck review found no blocking issues; follow-up consistency suggestions were applied No runtime code is changed. --------- Signed-off-by: Justin Chu <[email protected]> Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]> Co-authored-by: Copilot Autofix powered by AI <[email protected]>
1 parent b108254 commit 9b07f09

10 files changed

Lines changed: 206 additions & 85 deletions

File tree

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ 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
3840

3941
## Step-by-step
4042

@@ -219,6 +221,12 @@ Then add the new module to `src/mobius/_configs/per_model/__init__.py` so its
219221
side-effect registration runs at import time. The dispatcher filters hooks by
220222
the declared model_type strings, so unrelated models never see your hook.
221223

224+
Match upstream config semantics, not just field names: preserve transformation
225+
order (rounding/scaling), explicit `None`, alias precedence, zero-as-disabled
226+
sentinels, and wrapped/unwrapped composite configs. Add focused tests for each
227+
nontrivial transform. Test both trusted/custom config classes and raw pinned
228+
JSON, especially nested decoder fields such as head/layer counts.
229+
222230
### 7. Write tests
223231

224232
See the **writing-tests** skill for full details. At minimum:
@@ -281,6 +289,7 @@ see the [quality-checklist skill](../quality-checklist/SKILL.md).
281289
- [ ] ORT GenAI test added to `tests/ort_genai_test.py` (text-generation and VLM models)
282290
- [ ] CLI build works (`mobius build --model ...`)
283291
- [ ] Multi-dtype correctness verified (fp32, fp16, bf16)
292+
- [ ] Pinned revision reaches every Hub/processor/weight/golden call
284293

285294
**Note:** Default optimizer passes (CSE, deduplicate initializers, identity
286295
elimination, remove unused nodes/opsets) are applied automatically.
@@ -426,6 +435,18 @@ config-driven features for the offending subclass.
426435
> embedding table off-by-one), read
427436
> [`references/weight-preprocessing.md`](references/weight-preprocessing.md).
428437
438+
### 8. Compatibility and optional dependency traps
439+
440+
- Guard imports of symbols from unpinned dependencies when older supported
441+
versions may not define them.
442+
- If remote code imports an optional package, first prove the selected model
443+
path needs it. Scope any test-only shim to that unused import; do not add a
444+
production fallback or require an irrelevant package.
445+
- When extending a public component, append optional parameters after existing
446+
positional parameters and add a positional-call compatibility test.
447+
- Helpers with rank/shape contracts must receive a value of that rank; do not
448+
rely on incidental compatibility from a higher-rank tensor.
449+
429450
## Reference examples
430451

431452
| Complexity | File | Why |

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

Lines changed: 5 additions & 5 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

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,26 @@ Compare `named_parameters()` output with HF weight names. Use the
353353
techniques from the **weight-name-alignment** skill to minimize
354354
`preprocess_weights`.
355355

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

358378
Diffusers uses different conventions than transformers:

‎.agents/skills/multi-agent-coordination/SKILL.md‎

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,8 @@ git fetch origin && git checkout <branch> && git pull
4040

4141
## 2. Commit Coordination Protocol
4242

43-
Multiple agents committing to the same branch requires discipline to avoid divergence.
43+
Choose the branch strategy in §9 first. When multiple agents contribute to one
44+
branch, use this protocol to avoid divergence.
4445

4546
**Rules**:
4647
1. **Pull before commit**: Always `git pull origin <branch> --rebase` immediately before committing.
@@ -67,11 +68,14 @@ Checks at each stage prevent problems from compounding across agents.
6768
- Verify the branch exists and is up to date.
6869
- Run the relevant tests to establish a baseline — know what was already failing before you touched anything.
6970
- Check for uncommitted changes left by previous agents in your worktree.
71+
- Verify `inspect.getfile(mobius)` points into the agent's worktree; editable
72+
installs from another worktree invalidate all test evidence.
7073

7174
### After each commit
7275
- Run the affected tests immediately (don't batch; catch regressions early).
7376
- Verify the commit landed on the correct branch (`git log --oneline -3`).
7477
- Confirm the push succeeded.
78+
- Confirm the remote ref/PR head SHA, not just local `HEAD`.
7579

7680
### Before final review (lead audit)
7781
- Check ALL worktrees for unpushed commits or uncommitted changes.
@@ -85,6 +89,15 @@ Checks at each stage prevent problems from compounding across agents.
8589
- Final test run passes.
8690
- PR description updated with an accurate scorecard of what changed.
8791

92+
### CI failures and main refreshes
93+
- Compare the exact failing test on the exact base SHA; a red overall workflow
94+
does not prove the same job failed on base.
95+
- Keep feature scope: document unrelated baseline names/metrics instead of
96+
changing their code or tolerances.
97+
- Rebase independent PRs linearly onto `origin/main`. Resolve shared registries,
98+
exports, helpers, and guards semantically by retaining both sides; then run
99+
shared-surface tests, lint, and review before `push --force-with-lease`.
100+
88101
---
89102

90103
## 4. Task Dependency Management (DAG)
@@ -171,18 +184,14 @@ Match the agent role to the task type. Mismatched roles waste agent capacity.
171184

172185
---
173186

174-
## 9. Single-Branch Strategy
175-
176-
For large multi-agent efforts, use **one shared feature branch** rather than one branch per agent.
177-
178-
**Why**: Avoids complex multi-branch merge scenarios at the end. All agents commit to the same branch via their isolated worktrees.
179-
180-
**Trade-offs**:
181-
- More `pull --rebase` cycles per agent.
182-
- Occasional push conflicts (recoverable with rebase).
183-
- BUT: much simpler final state, single PR, linear history.
187+
## 9. Branch Strategy
184188

185-
**Alternative**: Separate branches per agent merged via separate PRs — only viable when features are truly independent and don't share files.
189+
- Use one branch only when agents contribute to one atomic PR; serialize edits
190+
to shared files and require pull/rebase before every push.
191+
- Use separate branches/PRs for independent deliverables (for example, separate
192+
model architectures). This isolates CI, review, rollback, and publication.
193+
- Never merge main into a linear-history feature branch. Rebase, resolve shared
194+
surfaces semantically, and force-push only with `--force-with-lease`.
186195

187196
---
188197

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

Lines changed: 30 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,16 @@ convention), not `vision_encoder`/`audio_encoder`.
9797
The embedding model must handle `num_image_tokens=0` (text-only input) by
9898
zero-padding `image_features` before Gather so indices stay in-bounds.
9999

100+
Input mixing must also:
101+
- compute feature offsets over the flattened batch, not restart per row;
102+
- preserve separate image/video streams or define and test an explicit packed
103+
order; and
104+
- cover two-row mixed-media prompts with distinguishable feature sentinels.
105+
106+
For cross-attentive decoders, export total-length padding masks and only caches
107+
that are actually reusable. Do not apply a generic seq2seq cross-cache contract
108+
to fixed encoder states without proving projection/cache semantics.
109+
100110
### Conditional 3-or-4-model task
101111

102112
Some models come in two tiers (e.g. Gemma4): small variants include an
@@ -219,72 +229,35 @@ models this overflows ORT's CUDA Gather kernel. **Workaround:** Split into
219229
L separate `Embedding([V, D])` tables via `nn.ModuleList`, and use `Slice`
220230
instead of `Gather` for per-layer projection indexing.
221231

222-
## Vision/audio encoder f32 input casting
223-
224-
> **This applies to ALL multimodal models and ALL inference paths** —
225-
> not just ORT GenAI, and not architecture-specific.
232+
## Processor-to-graph contract
226233

227-
Image and audio preprocessing universally produces **float32** output.
228-
This is true across all frameworks and runtimes:
234+
Run the real processor before finalizing graph I/O. Record names, shapes,
235+
dtypes, media-row ordering, sampled frame positions, and empty-media behavior;
236+
synthetic packed video layouts often differ from processor-native rows.
229237

230-
- **PIL / torchvision:** Pixel normalization outputs f32
231-
- **torchaudio / librosa:** Mel spectrograms are f32
232-
- **ORT GenAI image_processor:** Resize, normalize, tile → f32
233-
- **ORT GenAI audio_processor:** Feature extraction → f32
234-
- **ORT Python API:** Custom preprocessing pipelines → typically f32
235-
- **Foundry Local:** Uses GenAI processors → f32
236-
237-
This means vision and audio encoder ONNX graphs must accept f32 inputs
238-
even when the model is built in f16 or bf16. The encoder adds a
239-
`Cast(f32 → model_dtype)` at its graph entry point so that any runtime
240-
can feed it preprocessed data without worrying about the model's
241-
internal precision.
242-
243-
### How it works
238+
Vision/audio preprocessors emit float32. Encoder graphs therefore accept
239+
float32 at the boundary and cast once to fp16/bf16 internally:
244240

245241
```
246-
Input (f32 from ANY preprocessor — PIL, torchaudio, GenAI, etc.)
247-
↓
248-
Cast(to=FLOAT16) ← inserted automatically by mobius
249-
↓
250-
Vision/Audio encoder (weights in f16/bf16)
251-
↓
252-
Output (model_dtype)
242+
processor f32 -> Cast(model dtype) -> reduced-precision encoder
253243
```
254244

255-
Encoder weights still use the requested dtype (f16/bf16) for memory
256-
efficiency — only the graph inputs are f32. The Cast is a lightweight
257-
op with negligible overhead.
258-
259-
### Why f32 is the universal preprocessing dtype
245+
Test image-only, video-only, mixed media, two-row batches, and decode with zero
246+
new media. Build kwargs conditionally; strict processors may reject video-only
247+
arguments on image-only calls.
260248

261-
Preprocessing involves floating-point arithmetic (mean subtraction,
262-
std division, resampling interpolation) where f32 is the natural
263-
precision. Converting to f16/bf16 before these operations would lose
264-
precision in the preprocessing itself. The model's internal precision
265-
only matters after the preprocessed data enters the encoder.
266-
267-
### What mobius does
268-
269-
Mobius always builds encoder graphs with f32 inputs — this is the
270-
default behavior, not gated behind any flag. It works correctly
271-
regardless of the inference runtime:
272-
273-
- `--runtime ort-genai` → f32 inputs (GenAI processors output f32)
274-
- No `--runtime` flag → f32 inputs (ORT Python API, custom runtimes)
275-
- Foundry Local → f32 inputs (uses GenAI internally)
276-
277-
Without the Cast-at-input, ORT throws a type mismatch error:
278-
```
279-
Type Error: Type parameter (T) bound to different types
280-
(tensor(float) and tensor(float16))
281-
```
249+
For composite checkpoints, generate processor assets from the parent config
250+
even if model construction exposes an unwrapped text sub-config; test both
251+
wrapped and unwrapped resolver forms.
282252

283-
### For model authors
253+
For variable-length media, audit symbolic complexity: packed-attention metadata
254+
must scale with rows/windows, not total-patches × media-count. Keep dense masks
255+
only as a portable fallback and assert optimized CUDA/DML graphs lack the
256+
quadratic construction.
284257

285-
If you're adding a new multimodal model, you don't need to handle this
286-
manually — mobius inserts the Cast automatically for all encoder graphs.
287-
If the model dtype is already f32, no Cast is needed.
258+
Config generation is not runtime support. Execute real media through ORT GenAI;
259+
if it cannot supply a required encoder input or position-ID rank, reject export
260+
before writing artifacts and use the same evidence for any Foundry waiver.
288261

289262
## GQA for KV-shared layers (Gemma4)
290263

‎.agents/skills/onnx-export-quantization/SKILL.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,13 @@ FP32 when the model is BF16. Add `op.CastLike(result, input)` to
322322
ensure dtype consistency. See the `reusable-components` skill's
323323
section on precision behaviour.
324324

325+
### 6. Attention rewrite schema mismatch
326+
327+
Quantizers may rewrite Attention to a contrib op with fewer outputs or a
328+
different cache contract. Restrict the quantized op set when schemas do not
329+
match, then load and execute the result; successful conversion alone is not
330+
evidence. Document the narrowed recipe and unsupported rewrite explicitly.
331+
325332
## Testing quantized models
326333

327334
### L4: Golden data generation

‎.agents/skills/ort-genai-config/SKILL.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,15 @@ decoder_inputs = {name: name for name in decoder_input_names}
244244
This means the genai config automatically adapts when `RemoveDeadGraphInputsPass`
245245
removes unused inputs (e.g. `position_ids` absorbed by GQA fusion).
246246

247+
Hybrid cache metadata must preserve global layer indices across KV, convolution,
248+
and recurrent states. Derive slot count from the maximum
249+
`past_key_values.<index>.*` input index plus one; counting only `.key` inputs
250+
silently drops non-KV or sparsely indexed layers.
251+
252+
CUDA Graph capture belongs on stable-shape autoregressive decoder sessions,
253+
not one-shot variable-shape vision/embedding stages. Keep an explicit decoder
254+
opt-out and validate capture together with shared KV buffers on the real model.
255+
247256
> For the full generation flow, input routing, QwenImageProcessor output
248257
> tensors, and the multimodal processor factory, see
249258
> [`references/multimodal-pipeline.md`](references/multimodal-pipeline.md).
@@ -273,6 +282,13 @@ processor doesn't provide. Either:
273282
1. Compute them externally and inject via NamedTensors, or
274283
2. Modify the vision model to compute them from `image_grid_thw` internally
275284

285+
### Config writes successfully but runtime cannot execute
286+
287+
Config/schema success is not runtime support. Run load plus generation through
288+
the exported contract. If the runtime cannot route required feature inputs,
289+
position-ID rank, cache state, scheduler, or multimodal metadata, reject export
290+
before writing artifacts and report the exact runtime version/limitation.
291+
276292
### "input_ids size exceeds max length"
277293

278294
For image prompts, the tokenized input_ids (including image_pad tokens) can

0 commit comments

Comments
 (0)