Skip to content

Commit 939f73d

Browse files
justinchubyCopilot
andauthored
Add Qwen4Exp multimodal pipeline (#657)
## Summary - add the Qwen3.8 Flash-Next/Qwen4Exp three-model image-language package (`decoder`, `vision_encoder`, `embedding`) - reuse the source-identical no-DeepStack Qwen3/Qwen3.5 vision tower with a 2560-wide merger - preserve independent lexical `ple_input_ids`, fused `inputs_embeds`, four-channel text + M-RoPE positions, and every heterogeneous recurrent/KV/QSA/PLE state - cast processor float32 patches once at the BF16 vision boundary - emit explicit `mobius.state_manifest` and `mobius.unsupported_token_ids` contracts for direct ONNX Runtime orchestration ## Bounded multimodal streaming Both `qwen4_exp` and `qwen4_exp_text` use the bounded safetensors path; the eager `_download_weights` route is unreachable. One shard index validates config-derived deterministic PLE buffers and plans decoder, embedding, and vision bindings. Each graph is cloned, lazily bound, and initializer-folded in isolation; the package is updated only after every staged component succeeds. Missing tensors, corrupt PLE hash buffers, or fold failures leave the original package untouched. Parameter payloads remain `LazyTensor`s and no source state dict is retained. The approximately 95 GiB PLE table is allocated once only when materialized/serialized and populated one checkpoint shard at a time. Loader accounting reports model/initializer/lazy counts, deterministic bytes validated eagerly, and zero retained source tensors. ## Enforced image-only boundary The checkpoint's source video token is validated, then removed from normalized runtime metadata. Explicit configs requesting video capability fail closed and the embedding graph exposes no `video_features` input. It sanitizes any source video token before vocabulary lookup, computes a runtime `has_video`, and reshapes one zero element to `[1 + has_video]`. Valid requests reduce/add zero; video requests demand two elements and fail ONNX Reshape's element-count invariant before an EP executes. ORT CUDA uses the shared `ReshapeHelper` for this check (`onnxruntime@b1f76d58`, `cuda/tensor/reshape.h`), avoiding CUDA Gather's out-of-range zero-fill behavior. Optimized CPU is exercised locally and the same test executes CUDA when available; processor-native mixed input also fails through the guard. ## Runtime workflow boundary onnxruntime-genai and the current ONNX GenAI workflow schema cannot represent Qwen4Exp's `ple_input_ids`, four-axis positions, and heterogeneous state membership. Both exporters reject before writing artifacts. ONNX GenAI detection checks package config, explicit config, and the structural decoder ABI, so a non-Qwen override cannot bypass preflight or modify an existing output directory. Direct ONNX Runtime users consume `mobius.state_manifest` instead. ## Source pins - `Qwen/Qwen3.8-Flash-Next@f5d08274bafd880402bd16f5e3e6c514136ec06c` - `huggingface/transformers@598d8ba8baaec7fec5a22da0e2844c7bf4ea20e1` ## Final-base rebase Lower-layer PR #656 was squash-merged to `main` as `8f902ac2`. This branch replays only #657's multimodal work onto that commit; no pre-squash lower-layer or GGUF implementation files remain in the PR diff. ## Validation - final Qwen4 loader/multimodal/synthetic suite: 47 passed, 6 skipped - full runtime exporter suites: 263 passed - pinned HuggingFace image parity plus real image/video boundary tests: 3 passed - post-rebase GGUF report/shard/runtime regression suite: 831 passed - Qwen4 component inspection and review-thread regressions: passed - pinned lintrunner format + lint: clean - independent GPT-5.6 Sol CUDA-guard rereview: no findings ## Waivers - **L4/L5 real-weight golden:** the 512-expert checkpoint requires a large GPU; the immutable YAML case records the CI skip. - **Released runtime workflows:** ORT GenAI and ONNX GenAI metadata export fail closed as described above. - **Full checkpoint CUDA generation:** checkpoint scale makes this impractical in this session; CUDA's shared Reshape validation is source-pinned and the guard regression runs on CUDA whenever that EP is available. This PR targets `main`, is intentionally non-draft, and must not be merged by this session. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent 8f902ac commit 939f73d

23 files changed

Lines changed: 2319 additions & 331 deletions

‎docs/design/qwen4-exp-text-core.md‎

Lines changed: 52 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1-
# Qwen4-Exp text core
1+
# Qwen4-Exp multimodal pipeline
22

3-
Mobius implements the text decoder identified by Hugging Face
4-
`model_type=qwen4_exp_text`, including the composite
5-
`Qwen4ExpForConditionalGeneration` route when `text_only=True`.
3+
Mobius implements both the `qwen4_exp_text` decoder and the
4+
`Qwen4ExpForConditionalGeneration` composite published as
5+
`Qwen/Qwen3.8-Flash-Next`. The composite exports a standard three-model package:
6+
`decoder`, `vision_encoder`, and `embedding`. `text_only=True` selects the same
7+
decoder without the vision stages.
68

79
The implementation is pinned to:
810

@@ -25,9 +27,11 @@ token selection, and PLE hashed n-gram embeddings with their dilated
2527
convolution and token-context states. The pinned BF16 checkpoint keeps
2628
DeltaNet recurrent math and recurrent cache state in float32, while convolution
2729
state, projections, sparse-attention caches, and logits remain in model dtype.
28-
Official safetensors are loaded through a bounded-memory transform: packed
29-
experts are sliced lazily and the PLE table is allocated once, then populated
30-
one checkpoint shard at a time.
30+
Official safetensors are loaded through a bounded-memory package transaction:
31+
decoder, embedding, and vision bindings are all validated from one shard index
32+
before any graph is mutated; parameter payloads remain lazy and no source state
33+
dict is retained. The PLE table is allocated once when serialized, then
34+
populated one checkpoint shard at a time.
3135

3236
The flattened cache ABI is:
3337

@@ -41,27 +45,46 @@ QSA layer:
4145
key, value, index_key
4246
```
4347

48+
The multimodal decoder takes fused `inputs_embeds` and the original lexical
49+
`ple_input_ids` as independent inputs. Position state has shape `[4, B, S]`:
50+
channel 0 is the text/causal sequence axis, while channels 1–3 carry temporal,
51+
height, and width M-RoPE positions used by both sparse attention and QSA.
52+
53+
## Vision and embedding reuse
54+
55+
The checkpoint's vision config proves identity with the no-DeepStack Qwen3.5
56+
tower: 27 blocks, hidden size 1152, intermediate size 4304, 16 heads, patch
57+
size 16, temporal patch size 2, spatial merge size 2, and 2304 learned position
58+
embeddings. Mobius reuses the Qwen3 vision implementation with DeepStack
59+
disabled and the merger projected to the decoder width of 2560.
60+
61+
The embedding graph scatters `image_features` at token 248056 while preserving
62+
the original token IDs for PLE. The processor contract is the pinned Qwen3
63+
image processor with vision start/end tokens 248053/248054. This package is
64+
explicitly image-only: config extraction validates the checkpoint's video token
65+
but removes it from runtime metadata, the embedding graph exposes no video
66+
feature input, and direct configs that request video support fail closed. The
67+
embedding graph also publishes `mobius.unsupported_token_ids` and carries a
68+
dynamic ONNX Reshape guard: any source video token is sanitized before
69+
vocabulary lookup and then requests two output elements from a one-element
70+
tensor. ONNX's element-count invariant is enforced before every ORT EP executes,
71+
so direct graph execution cannot silently treat `<|video_pad|>` as ordinary
72+
text. This deliberately avoids out-of-range Gather, which CUDA zero-fills.
73+
4474
QSA uses standard ONNX operators to reproduce the selected-token mask, then
4575
runs ordinary dense attention under that mask. This is numerically faithful,
4676
including contiguous left padding, but it does not provide the memory savings
4777
of a dedicated sparse-attention runtime kernel.
4878

4979
## Guarded features
5080

51-
The pinned official Transformers implementation explicitly ignores `mtp.*`
52-
checkpoint tensors and does not define the `fc_embedding`/`fc_hidden`
53-
combination equation or a flattened NextN cache ABI. Mobius follows that
54-
ordinary-decoder behavior: it preserves the source MTP metadata, warns while
55-
dropping sidecar-only tensors, and exports the same next-token causal model.
56-
Configurations with dedicated MTP embeddings fail closed because omitting
57-
those embeddings could change the decoder contract. A future standalone
58-
NextN sidecar requires an authoritative execution equation and cache ABI.
59-
60-
FP8/NVFP4 checkpoint lowering and the multimodal wrapper remain outside this
61-
text-core implementation. The nested `qwen4_exp_text` configuration and
62-
architecture registration are present so a later multimodal wrapper can reuse
63-
the existing Qwen3/Qwen3.5 vision and embedding components without aliasing
64-
this decoder.
81+
The pinned ordinary Transformers forward preserves MTP metadata but does not
82+
execute its `mtp.*` sidecar. Mobius mirrors that next-token route and does not
83+
publish an MTP task. Dedicated MTP embeddings fail closed because no flattened
84+
NextN cache ABI exists. Alternative vision geometries and nonempty DeepStack
85+
configurations also fail closed.
86+
87+
FP8/NVFP4 checkpoint lowering remains outside this implementation.
6588

6689
## GGUF header support and payload guard
6790

@@ -90,3 +113,11 @@ dequantization is also rejected because the PLE table alone expands beyond the
90113
bounded single-tensor materialization policy. The exact header/config/mapping
91114
support is therefore a fail-closed foundation for future runtime ABI work, not
92115
a quantized execution claim.
116+
117+
Released onnxruntime-genai and the current ONNX GenAI workflow schema cannot
118+
represent Qwen4-Exp's `ple_input_ids`, four-axis position state, and
119+
heterogeneous per-layer PLE/QSA membership. Both metadata exporters therefore
120+
fail closed instead of emitting missing bindings, unsupported semantic keys, or
121+
lossy `%d` cache templates. The decoder graph carries a separate
122+
`mobius.state_manifest` metadata document with explicit role-to-layer
123+
membership for direct ONNX Runtime orchestration.

‎src/mobius/_configs/_base.py‎

Lines changed: 71 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1533,7 +1533,7 @@ class CausalLMConfig(ArchitectureConfig):
15331533

15341534
@dataclasses.dataclass
15351535
class Qwen4ExpConfig(CausalLMConfig):
1536-
"""Exact text-core configuration for experimental Qwen4/Qwen3.8 Flash-Next."""
1536+
"""Exact configuration for experimental Qwen4/Qwen3.8 Flash-Next."""
15371537

15381538
hc_count: int = 4
15391539
hc_lowrank: int = 320
@@ -1556,6 +1556,7 @@ class Qwen4ExpConfig(CausalLMConfig):
15561556
mamba_ssm_dtype: ir.DataType = ir.DataType.FLOAT
15571557
mtp_num_hidden_layers: int = 0
15581558
mtp_use_dedicated_embeddings: bool = False
1559+
unsupported_video_token_id: int | None = None
15591560

15601561
def __post_init__(self) -> None:
15611562
self.ple_layer_ids = sorted(set(self.ple_layer_ids or []))
@@ -1717,6 +1718,68 @@ def from_transformers(cls, config, parent_config=None) -> Qwen4ExpConfig:
17171718
parent = parent_config or (config if text is not config else None)
17181719
base = ArchitectureConfig.from_transformers(text, parent)
17191720
fields = _shallow_fields(base)
1721+
is_multimodal = (
1722+
getattr(parent, "model_type", None) == "qwen4_exp"
1723+
and getattr(parent, "vision_config", None) is not None
1724+
)
1725+
if is_multimodal:
1726+
if getattr(parent, "language_model_only", False):
1727+
raise ValueError(
1728+
"Qwen4-Exp multimodal export requires language_model_only=false"
1729+
)
1730+
if base.video_token_id != 248057:
1731+
raise ValueError(
1732+
"Unsupported Qwen4-Exp video token contract: expected source "
1733+
f"video_token_id 248057, got {base.video_token_id}"
1734+
)
1735+
vision = base.vision
1736+
if vision is None:
1737+
raise ValueError("Qwen4-Exp multimodal config requires vision_config")
1738+
expected = {
1739+
"num_hidden_layers": 27,
1740+
"hidden_size": 1152,
1741+
"intermediate_size": 4304,
1742+
"num_attention_heads": 16,
1743+
"in_channels": 3,
1744+
"patch_size": 16,
1745+
"temporal_patch_size": 2,
1746+
"spatial_merge_size": 2,
1747+
"num_position_embeddings": 2304,
1748+
"out_hidden_size": 2560,
1749+
"hidden_act": "gelu_pytorch_tanh",
1750+
}
1751+
actual = {
1752+
"num_hidden_layers": vision.num_hidden_layers,
1753+
"hidden_size": vision.hidden_size,
1754+
"intermediate_size": vision.intermediate_size,
1755+
"num_attention_heads": vision.num_attention_heads,
1756+
"in_channels": vision.in_channels,
1757+
"patch_size": vision.patch_size,
1758+
"temporal_patch_size": vision.temporal_patch_size,
1759+
"spatial_merge_size": vision.spatial_merge_size,
1760+
"num_position_embeddings": vision.num_position_embeddings,
1761+
"out_hidden_size": vision.out_hidden_size,
1762+
"hidden_act": vision.hidden_act,
1763+
}
1764+
mismatches = {
1765+
name: (actual[name], value)
1766+
for name, value in expected.items()
1767+
if actual[name] != value
1768+
}
1769+
if mismatches:
1770+
raise ValueError(
1771+
"Unsupported Qwen4-Exp vision variant; expected the pinned "
1772+
f"Qwen3/Qwen3.5 tower, got mismatches {mismatches}"
1773+
)
1774+
if vision.deepstack_visual_indexes:
1775+
raise ValueError(
1776+
"Unsupported Qwen4-Exp vision variant: DeepStack must be disabled"
1777+
)
1778+
if base.hidden_size != 2560:
1779+
raise ValueError(
1780+
"Unsupported Qwen4-Exp multimodal projection width: "
1781+
f"expected text hidden_size 2560, got {base.hidden_size}"
1782+
)
17201783
mamba_ssm_dtype = _resolve_dtype_value(getattr(text, "mamba_ssm_dtype", "float32"))
17211784
if mamba_ssm_dtype is None:
17221785
raise ValueError(
@@ -1729,7 +1792,7 @@ def from_transformers(cls, config, parent_config=None) -> Qwen4ExpConfig:
17291792
for value in layer_types
17301793
]
17311794
fields.update(
1732-
model_type="qwen4_exp_text",
1795+
model_type="qwen4_exp" if is_multimodal else "qwen4_exp_text",
17331796
layer_types=layer_types,
17341797
hc_count=getattr(text, "hc_count", 4),
17351798
hc_lowrank=getattr(text, "hc_lowrank", 320),
@@ -1754,6 +1817,12 @@ def from_transformers(cls, config, parent_config=None) -> Qwen4ExpConfig:
17541817
mtp_num_hidden_layers=getattr(text, "mtp_num_hidden_layers", 0),
17551818
mtp_use_dedicated_embeddings=getattr(text, "mtp_use_dedicated_embeddings", False),
17561819
)
1820+
if is_multimodal:
1821+
# The current package is explicitly image-only. Preserve validation
1822+
# of the source token above, but do not publish runtime video support
1823+
# until a video producer/preprocessor route exists.
1824+
fields["video_token_id"] = None
1825+
fields["unsupported_video_token_id"] = base.video_token_id
17571826
return cls(**fields)
17581827

17591828

‎src/mobius/_configs/_vision_defaults.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,13 +94,17 @@ def apply_vision_defaults(config, parent_config, model_type: str, fields: dict)
9494
deepstack_visual_indexes=getattr(vc, "deepstack_visual_indexes", None),
9595
fullatt_block_indexes=getattr(vc, "fullatt_block_indexes", None),
9696
window_size=getattr(vc, "window_size", None),
97+
hidden_act=getattr(vc, "hidden_act", None),
9798
use_clipped_linears=getattr(vc, "use_clipped_linears", False),
9899
position_embedding_size=getattr(vc, "position_embedding_size", None),
99100
)
100101
# This runs before per-model hooks, so plain assignment is safe — any
101102
# per-model hook may overwrite later via fields.update(...).
102103
fields["mm_tokens_per_image"] = getattr(vision_source, "mm_tokens_per_image", None)
103104
fields["image_token_id"] = getattr(vision_source, "image_token_id", None)
105+
fields["video_token_id"] = getattr(vision_source, "video_token_id", None)
106+
fields["vision_start_token_id"] = getattr(vision_source, "vision_start_token_id", None)
107+
fields["vision_end_token_id"] = getattr(vision_source, "vision_end_token_id", None)
104108

105109
# MRoPE section — only for composite VL models (parent_config != config).
106110
if parent_config is not None and parent_config is not config:

‎src/mobius/_inspect.py‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -86,13 +86,6 @@ def _resolve_task_model_type_and_config(
8686
) from None
8787

8888
model_type = hf_config.model_type
89-
from mobius.integrations.transformers._builder import _is_qwen4_exp_composite
90-
91-
if _is_qwen4_exp_composite(hf_config):
92-
raise ValueError(
93-
"Qwen4-Exp multimodal component inspection is unavailable in the "
94-
"text-core implementation; inspect qwen4_exp_text explicitly."
95-
)
9689

9790
# model_type adjustments that affect task selection (subset of build()):
9891
# Qwen3.5-MoE ships the same model_type for text-only and VL checkpoints.

‎src/mobius/_inspect_test.py‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,16 +51,28 @@ def test_single_component_llm_returns_one_component(monkeypatch):
5151
assert components == [ComponentInfo(name="model", role="decoder")]
5252

5353

54-
def test_qwen4_composite_inspection_fails_closed(monkeypatch):
54+
def test_qwen4_composite_inspection_reports_all_component_sources(monkeypatch):
5555
_patch_autoconfig(
5656
monkeypatch,
5757
SimpleNamespace(
5858
model_type="qwen4_exp",
5959
architectures=["Qwen4ExpForConditionalGeneration"],
6060
),
6161
)
62-
with pytest.raises(ValueError, match="multimodal component inspection is unavailable"):
63-
inspect_components("fake/qwen4")
62+
components = {component.name: component for component in inspect_components("fake/qwen4")}
63+
assert {name: component.role for name, component in components.items()} == {
64+
"decoder": "decoder",
65+
"vision_encoder": "encoder",
66+
"embedding": "embedding",
67+
}
68+
assert components["decoder"].source_paths == (
69+
"model.language_model.layers",
70+
"model.language_model.rotary_emb",
71+
"model.language_model.hyper_connection_mixer",
72+
"lm_head",
73+
)
74+
assert components["vision_encoder"].source_paths == ("model.visual",)
75+
assert components["embedding"].source_paths == ("model.language_model.embed_tokens",)
6476

6577

6678
def test_vlm_returns_decoder_vision_embedding(monkeypatch):

‎src/mobius/_registry.py‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,7 @@
127127
Qwen3VLCausalLMModel,
128128
Qwen3VLTextModel,
129129
Qwen4ExpCausalLMModel,
130+
Qwen4ExpForConditionalGeneration,
130131
Qwen25VLCausalLMModel,
131132
Qwen25VLTextModel,
132133
Qwen35CausalLMModel,
@@ -667,11 +668,12 @@ def _detect_fallback_registration(hf_config) -> ModelRegistration | None:
667668
"qwen3_moe": ModelRegistration(MoECausalLMModel),
668669
"qwen3_next": ModelRegistration(Qwen3NextCausalLMModel),
669670
"qwen4_exp": ModelRegistration(
670-
Qwen4ExpCausalLMModel,
671-
task="qwen4-exp-text-generation",
671+
Qwen4ExpForConditionalGeneration,
672+
task="qwen4-exp-vision-language",
672673
config_class=Qwen4ExpConfig,
674+
test_model_id="Qwen/Qwen3.8-Flash-Next",
673675
family="qwen",
674-
variant="moe+gdn+qsa+ple",
676+
variant="multimodal+moe+gdn+qsa+ple",
675677
test_revision="f5d08274bafd880402bd16f5e3e6c514136ec06c",
676678
),
677679
"qwen4_exp_text": ModelRegistration(
@@ -683,11 +685,12 @@ def _detect_fallback_registration(hf_config) -> ModelRegistration | None:
683685
test_revision="f5d08274bafd880402bd16f5e3e6c514136ec06c",
684686
),
685687
"Qwen4ExpForConditionalGeneration": ModelRegistration(
686-
Qwen4ExpCausalLMModel,
687-
task="qwen4-exp-text-generation",
688+
Qwen4ExpForConditionalGeneration,
689+
task="qwen4-exp-vision-language",
688690
config_class=Qwen4ExpConfig,
691+
test_model_id="Qwen/Qwen3.8-Flash-Next",
689692
family="qwen",
690-
variant="text-core",
693+
variant="multimodal",
691694
test_revision="f5d08274bafd880402bd16f5e3e6c514136ec06c",
692695
),
693696
"qwen3_omni_moe": ModelRegistration(MoECausalLMModel),
@@ -1047,8 +1050,7 @@ def _create_default_registry() -> ModelRegistry:
10471050
"qwen3_5_moe_vl": "qwen3_5_moe_text",
10481051
"qwen3_5_moe_text": "qwen3_5_moe_text",
10491052
# Qwen3.8 Flash-Next is published as a multimodal qwen4_exp composite.
1050-
# This PR supports its exact text core only; callers must opt into the
1051-
# existing text-only extraction path until the wrapper is implemented.
1053+
# text_only=True selects the same exact decoder without the vision stages.
10521054
"qwen4_exp": "qwen4_exp_text",
10531055
"qwen4_exp_text": "qwen4_exp_text",
10541056
}
@@ -1454,6 +1456,8 @@ def _create_default_registry() -> ModelRegistry:
14541456
"qwen3_5": "qwen",
14551457
"qwen3_5_moe_vl": "qwen",
14561458
"qwen3_5_vl": "qwen",
1459+
"qwen4_exp": "qwen",
1460+
"qwen4_exp_text": "qwen",
14571461
"qwen3_omni_moe": "qwen",
14581462
"qwen3_asr": "qwen",
14591463
"qwen3_forced_aligner": "qwen",

‎src/mobius/integrations/onnx_genai/auto_export.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -849,6 +849,24 @@ def write_onnx_genai_config(
849849
from ``kwargs`` or discovered from the package; ``num_inference_steps`` /
850850
``scheduler`` / ``guidance_scale`` set the loop.
851851
"""
852+
package_config = getattr(pkg, "config", None)
853+
config_types = {
854+
getattr(candidate, "model_type", None)
855+
for candidate in (package_config, config)
856+
if candidate is not None
857+
}
858+
decoder = pkg.get("decoder") or pkg.get("model")
859+
decoder_inputs = (
860+
{value.name for value in decoder.graph.inputs} if decoder is not None else set()
861+
)
862+
qwen4_signature = {"ple_input_ids", "past_position_ids"} <= decoder_inputs
863+
if config_types & {"qwen4_exp", "qwen4_exp_text"} or qwen4_signature:
864+
raise ValueError(
865+
"onnx-genai cannot represent Qwen4-Exp's required ple_input_ids "
866+
"and four-axis position state. Use ModelPackage.save() and the "
867+
"decoder's mobius.state_manifest metadata; refusing to write an "
868+
"incomplete workflow."
869+
)
852870
os.makedirs(output_dir, exist_ok=True)
853871
if is_shared_state_pixel_flow_package(pkg):
854872
resolved_config = config if config is not None else getattr(pkg, "config", None)

0 commit comments

Comments
 (0)