Skip to content

Commit 4ee4580

Browse files
justinchubyCopilot
andauthored
Add exact Qwen4Exp text core (#655)
## Summary - add the pinned `qwen4_exp_text` decoder for `Qwen/Qwen3.8-Flash-Next@f5d08274bafd880402bd16f5e3e6c514136ec06c` and Transformers `598d8ba8baaec7fec5a22da0e2844c7bf4ea20e1` - implement the 3:1 Gated-DeltaNet/QSA schedule, hyper-connections, routed plus shared MoE, PLE hashing/convolution, and heterogeneous cache ABI - preserve the BF16 checkpoint contract by keeping DeltaNet recurrence and recurrent state in float32 - make QSA exact for non-contiguous masks and validate official packed experts, deterministic hash buffers, and all PLE shards fail-closed - register the standalone text route while rejecting unsupported multimodal export and dedicated MTP embeddings ## Validation - targeted Qwen4Exp/DeltaNet/build/weight tests: `37 passed, 7 skipped, 1857 deselected` - exact pinned Transformers reduced-model parity: prefill, token-by-token decode, and non-contiguous-mask parity passed - broad serial suite: `8377 passed, 64 skipped, 12 deselected, 1 subtest passed` - `lintrunner init && lintrunner f --output oneline --all-files && lintrunner -a`: no lint issues - GPT-5.6 Sol medium review: no significant findings - pinned checkpoint index verified: 31 ignored `mtp.*` tensors, 128 PLE shards, and official packed expert/shared-gate names ## Fail-closed guards - rejects invalid heterogeneous schedules, linear head ratios/dimensions, QSA dimensions/budgets, PLE dimensions/sharding, non-float32 recurrent state, and dedicated MTP embeddings - rejects malformed packed expert tensors, changed deterministic hash buffers, missing/extra PLE shards, and wrong reconstructed PLE table shapes - composite `qwen4_exp` export requires `text_only=True`; multimodal export is not silently aliased ## Waivers - Full-checkpoint L2/L4/L5 and CLI export were not run locally: the pinned model includes a roughly 95 GiB PLE embedding table and is not a practical local golden fixture. The independently instantiated pinned Transformers reduced model provides full-logit L3 parity. - BF16 execution was structurally validated through the graph/state ABI. Stock local ORT CPU cannot execute BF16 MatMul and expands standard BF16 Attention through an unsupported mixed-type internal Add; no CUDA runner was available. - The MTP sidecar and multimodal wrapper are intentionally out of scope. The pinned official causal runtime ignores `mtp.*`; unsupported contracts fail closed rather than exporting approximate behavior. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent 20e00b0 commit 4ee4580

25 files changed

Lines changed: 2927 additions & 29 deletions

‎docs/design/index.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ Detailed design notes and proposals for `mobius` subsystems.
88
../design
99
config-redesign
1010
deepseek-v4-flash-export
11+
qwen4-exp-text-core
1112
gguf-support-proposal
1213
golden-infra-design
1314
multi-tier-testing-strategy

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

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# Qwen4-Exp text core
2+
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`.
6+
7+
The implementation is pinned to:
8+
9+
- `Qwen/Qwen3.8-Flash-Next@f5d08274bafd880402bd16f5e3e6c514136ec06c`
10+
- `huggingface/transformers@598d8ba8baaec7fec5a22da0e2844c7bf4ea20e1`
11+
12+
Exported models record that pin as `mobius.semantic_reference_revision` and
13+
record the caller's requested checkpoint revision separately as
14+
`mobius.source_revision` (`unpinned` when no revision was supplied).
15+
16+
## Exported architecture
17+
18+
The ONNX graph includes the repeating three-linear/one-QSA attention
19+
schedule, full-kernel Gated-DeltaNet convolution state, recurrent delta-rule
20+
state, four-stream gated residual hyper-connections, exact softmax-first
21+
top-k routed MoE plus the sigmoid-gated shared expert, QSA block pooling and
22+
token selection, and PLE hashed n-gram embeddings with their dilated
23+
convolution and token-context states. The pinned BF16 checkpoint keeps
24+
DeltaNet recurrent math and recurrent cache state in float32, while convolution
25+
state, projections, sparse-attention caches, and logits remain in model dtype.
26+
Official safetensors are loaded through a bounded-memory transform: packed
27+
experts are sliced lazily and the PLE table is allocated once, then populated
28+
one checkpoint shard at a time.
29+
30+
The flattened cache ABI is:
31+
32+
```text
33+
past_position_ids -> present_position_ids
34+
linear layer:
35+
conv_state, recurrent_state
36+
PLE linear layer:
37+
conv_state, recurrent_state, ple_conv_state, ple_context
38+
QSA layer:
39+
key, value, index_key
40+
```
41+
42+
QSA uses standard ONNX operators to reproduce the selected-token mask, then
43+
runs ordinary dense attention under that mask. This is numerically faithful,
44+
including contiguous left padding, but it does not provide the memory savings
45+
of a dedicated sparse-attention runtime kernel.
46+
47+
## Guarded features
48+
49+
The pinned official Transformers implementation explicitly ignores `mtp.*`
50+
checkpoint tensors and does not define the `fc_embedding`/`fc_hidden`
51+
combination equation or a flattened NextN cache ABI. Mobius follows that
52+
ordinary-decoder behavior: it preserves the source MTP metadata, warns while
53+
dropping sidecar-only tensors, and exports the same next-token causal model.
54+
Configurations with dedicated MTP embeddings fail closed because omitting
55+
those embeddings could change the decoder contract. A future standalone
56+
NextN sidecar requires an authoritative execution equation and cache ABI.
57+
58+
FP8/NVFP4 checkpoint lowering, GGUF import, and the multimodal wrapper are
59+
outside this text-core implementation. The nested `qwen4_exp_text`
60+
configuration and architecture registration are present so a later
61+
multimodal wrapper can reuse the existing Qwen3/Qwen3.5 vision and embedding
62+
components without aliasing this decoder.

‎src/mobius/__main__.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,15 @@ def _resolve_static_cache_task(model_type: str) -> ModelTask:
370370
raise
371371
model_type = hf_config.model_type
372372
parent_config = hf_config
373+
from mobius.integrations.transformers._builder import (
374+
_is_qwen4_exp_composite,
375+
)
376+
377+
if _is_qwen4_exp_composite(parent_config):
378+
raise SystemExit(
379+
"Error: local Qwen4-Exp composite configs cannot be silently "
380+
"exported as text-only. Use --model <hf-id> --features text-only."
381+
)
373382
if hasattr(hf_config, "text_config"):
374383
hf_config = hf_config.text_config
375384
config = _config_from_hf(hf_config, parent_config=parent_config)

‎src/mobius/_configs/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
NemotronParseConfig,
6262
ParakeetCTCConfig,
6363
Plamo2Config,
64+
Qwen4ExpConfig,
6465
Qwen35MtpConfig,
6566
Sam2Config,
6667
SegformerConfig,
@@ -147,6 +148,7 @@
147148
"ParakeetCTCConfig",
148149
"Plamo2Config",
149150
"QuantizationConfig",
151+
"Qwen4ExpConfig",
150152
"Qwen35MtpConfig",
151153
"RoPEConfig",
152154
"Sam2Config",

‎src/mobius/_configs/_base.py‎

Lines changed: 233 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,8 @@
2929
DEFAULT_INT = -42
3030

3131

32-
def _resolve_dtype(config) -> ir.DataType | None:
33-
"""Extract model dtype from a HuggingFace config.
34-
35-
Handles string dtypes (e.g. "float16"), torch.dtype objects,
36-
and the "auto" sentinel (returns None).
37-
"""
38-
torch_dtype = getattr(config, "dtype", None)
32+
def _resolve_dtype_value(torch_dtype) -> ir.DataType | None:
33+
"""Convert a HuggingFace dtype value to an ONNX IR dtype."""
3934
if torch_dtype is not None and torch_dtype != "auto":
4035
if isinstance(torch_dtype, str):
4136
torch_dtype = getattr(torch, torch_dtype, None)
@@ -44,6 +39,11 @@ def _resolve_dtype(config) -> ir.DataType | None:
4439
return None
4540

4641

42+
def _resolve_dtype(config) -> ir.DataType | None:
43+
"""Extract model dtype from a HuggingFace config."""
44+
return _resolve_dtype_value(getattr(config, "dtype", None))
45+
46+
4747
def _resolve_hidden_act(config, model_type: str) -> str | None:
4848
"""Resolve the hidden activation function from HF config patterns.
4949
@@ -1531,6 +1531,232 @@ class CausalLMConfig(ArchitectureConfig):
15311531
"""
15321532

15331533

1534+
@dataclasses.dataclass
1535+
class Qwen4ExpConfig(CausalLMConfig):
1536+
"""Exact text-core configuration for experimental Qwen4/Qwen3.8 Flash-Next."""
1537+
1538+
hc_count: int = 4
1539+
hc_lowrank: int = 320
1540+
ple_layer_ids: list[int] | None = None
1541+
ple_embed_dim: int | None = None
1542+
ple_conv_kernel_size: int = 4
1543+
ngram_size: int = 3
1544+
heads_per_ngram: int = 8
1545+
ngram_vocab_size_base: int = 20_000_000
1546+
make_ngram_vocab_size_divisible_by: int = 128
1547+
seed: int = 1234
1548+
split_ngram_parts: int = 512
1549+
indexer_n_heads: int | None = None
1550+
indexer_kv_heads: int | None = None
1551+
indexer_head_dim: int | None = None
1552+
indexer_budget: int | None = None
1553+
indexer_compress_ratio: int | None = None
1554+
output_gate_type: str | None = None
1555+
linear_qk_l2norm_eps: float = 1e-6
1556+
mamba_ssm_dtype: ir.DataType = ir.DataType.FLOAT
1557+
mtp_num_hidden_layers: int = 0
1558+
mtp_use_dedicated_embeddings: bool = False
1559+
1560+
def __post_init__(self) -> None:
1561+
self.ple_layer_ids = sorted(set(self.ple_layer_ids or []))
1562+
if self.ple_embed_dim is None:
1563+
self.ple_embed_dim = self.hidden_size
1564+
if self.layer_types is None:
1565+
interval = self.full_attention_interval or 4
1566+
self.layer_types = [
1567+
"linear_attention" if (index + 1) % interval else "qwen_sparse_attention"
1568+
for index in range(self.num_hidden_layers)
1569+
]
1570+
else:
1571+
self.layer_types = [
1572+
"qwen_sparse_attention" if layer_type == "full_attention" else layer_type
1573+
for layer_type in self.layer_types
1574+
]
1575+
self._validate_architecture()
1576+
1577+
def _validate_architecture(self) -> None:
1578+
layer_types = self.layer_types or []
1579+
if len(layer_types) != self.num_hidden_layers:
1580+
raise ValueError(
1581+
"Qwen4-Exp layer_types must contain exactly num_hidden_layers entries "
1582+
f"(expected {self.num_hidden_layers}, got {len(layer_types)})"
1583+
)
1584+
unsupported = sorted(set(layer_types) - {"linear_attention", "qwen_sparse_attention"})
1585+
if unsupported:
1586+
raise ValueError(f"Unsupported Qwen4-Exp layer types: {unsupported}")
1587+
output_gate_type = self.output_gate_type or self.hidden_act
1588+
if output_gate_type not in {"sigmoid", "silu"}:
1589+
raise ValueError(
1590+
f"Unsupported Qwen4-Exp output gate activation: {output_gate_type}"
1591+
)
1592+
if self.hc_count <= 1:
1593+
raise ValueError(f"Qwen4-Exp requires hc_count > 1, got {self.hc_count}")
1594+
if self.hc_lowrank <= 0:
1595+
raise ValueError(f"Qwen4-Exp requires hc_lowrank > 0, got {self.hc_lowrank}")
1596+
if self.mamba_ssm_dtype != ir.DataType.FLOAT:
1597+
raise ValueError(
1598+
"Qwen4-Exp requires mamba_ssm_dtype=float32 for the pinned "
1599+
"Gated-DeltaNet recurrence"
1600+
)
1601+
if self.rope_interleave:
1602+
raise ValueError("Qwen4-Exp uses half-split RoPE; rope_interleave must be false")
1603+
if not self.num_local_experts or self.num_local_experts <= 0:
1604+
raise ValueError("Qwen4-Exp num_local_experts must be > 0")
1605+
if not self.num_experts_per_tok or not (
1606+
0 < self.num_experts_per_tok <= self.num_local_experts
1607+
):
1608+
raise ValueError("Qwen4-Exp num_experts_per_tok must be in [1, num_local_experts]")
1609+
if not self.moe_intermediate_size or self.moe_intermediate_size <= 0:
1610+
raise ValueError("Qwen4-Exp moe_intermediate_size must be > 0")
1611+
if (
1612+
not self.shared_expert_intermediate_size
1613+
or self.shared_expert_intermediate_size <= 0
1614+
):
1615+
raise ValueError("Qwen4-Exp shared_expert_intermediate_size must be > 0")
1616+
if "linear_attention" in layer_types:
1617+
linear_fields = {
1618+
"linear_num_key_heads": self.linear_num_key_heads,
1619+
"linear_num_value_heads": self.linear_num_value_heads,
1620+
"linear_key_head_dim": self.linear_key_head_dim,
1621+
"linear_value_head_dim": self.linear_value_head_dim,
1622+
"linear_conv_kernel_dim": self.linear_conv_kernel_dim,
1623+
}
1624+
if any(value is None or value <= 0 for value in linear_fields.values()):
1625+
raise ValueError(
1626+
f"Qwen4-Exp linear-attention config values must be positive: {linear_fields}"
1627+
)
1628+
assert self.linear_num_key_heads is not None
1629+
assert self.linear_num_value_heads is not None
1630+
if self.linear_num_value_heads % self.linear_num_key_heads:
1631+
raise ValueError(
1632+
"Qwen4-Exp linear_num_value_heads must be divisible by "
1633+
"linear_num_key_heads"
1634+
)
1635+
1636+
qsa_fields = {
1637+
"indexer_n_heads": self.indexer_n_heads,
1638+
"indexer_kv_heads": self.indexer_kv_heads,
1639+
"indexer_head_dim": self.indexer_head_dim,
1640+
"indexer_budget": self.indexer_budget,
1641+
"indexer_compress_ratio": self.indexer_compress_ratio,
1642+
}
1643+
if any(value is not None for value in qsa_fields.values()):
1644+
missing = [name for name, value in qsa_fields.items() if value is None]
1645+
if missing:
1646+
raise ValueError(f"Qwen4-Exp QSA config is missing required fields: {missing}")
1647+
if any(value is not None and value <= 0 for value in qsa_fields.values()):
1648+
raise ValueError(f"Qwen4-Exp QSA config values must be positive: {qsa_fields}")
1649+
if self.indexer_kv_heads != 1:
1650+
raise ValueError("Qwen4-Exp QSA requires indexer_kv_heads=1")
1651+
assert self.indexer_budget is not None
1652+
assert self.indexer_compress_ratio is not None
1653+
if self.indexer_budget % self.indexer_compress_ratio:
1654+
raise ValueError(
1655+
"Qwen4-Exp indexer_budget must be divisible by indexer_compress_ratio"
1656+
)
1657+
rotary_dim = int(self.head_dim * (self.partial_rotary_factor or 1.0))
1658+
assert self.indexer_head_dim is not None
1659+
if rotary_dim > self.indexer_head_dim:
1660+
raise ValueError(
1661+
"Qwen4-Exp attention RoPE dimensions must fit the QSA index head: "
1662+
f"rotary_dim={rotary_dim}, indexer_head_dim={self.indexer_head_dim}"
1663+
)
1664+
elif "qwen_sparse_attention" in layer_types:
1665+
raise ValueError("Qwen4-Exp sparse-attention layers require a complete QSA config")
1666+
1667+
if self.ple_layer_ids:
1668+
ngram_heads = (self.ngram_size - 1) * self.heads_per_ngram
1669+
assert self.ple_embed_dim is not None
1670+
if ngram_heads <= 0 or self.ple_embed_dim <= 0 or self.ple_embed_dim % ngram_heads:
1671+
raise ValueError(
1672+
"Qwen4-Exp ple_embed_dim must be positive and divisible by the "
1673+
f"number of n-gram heads ({ngram_heads})"
1674+
)
1675+
invalid = [
1676+
layer_id
1677+
for layer_id in self.ple_layer_ids
1678+
if layer_id < 1 or layer_id > self.num_hidden_layers
1679+
]
1680+
if invalid:
1681+
raise ValueError(
1682+
"Qwen4-Exp ple_layer_ids must be one-indexed decoder layer ids; "
1683+
f"invalid ids: {invalid}"
1684+
)
1685+
non_linear = [
1686+
layer_id
1687+
for layer_id in self.ple_layer_ids
1688+
if layer_types[layer_id - 1] != "linear_attention"
1689+
]
1690+
if non_linear:
1691+
raise ValueError(
1692+
"Qwen4-Exp PLE is only supported on linear_attention layers; "
1693+
f"got PLE on layers {non_linear}"
1694+
)
1695+
if self.eos_token_id is None or (
1696+
isinstance(self.eos_token_id, list) and not self.eos_token_id
1697+
):
1698+
raise ValueError("Qwen4-Exp eos_token_id must be set when PLE is enabled")
1699+
if self.ple_conv_kernel_size <= 0:
1700+
raise ValueError("Qwen4-Exp ple_conv_kernel_size must be > 0")
1701+
if self.ngram_vocab_size_base < 2:
1702+
raise ValueError("Qwen4-Exp ngram_vocab_size_base must be >= 2")
1703+
if self.make_ngram_vocab_size_divisible_by <= 0:
1704+
raise ValueError("Qwen4-Exp make_ngram_vocab_size_divisible_by must be > 0")
1705+
if self.split_ngram_parts <= 0:
1706+
raise ValueError("Qwen4-Exp split_ngram_parts must be > 0")
1707+
1708+
if self.mtp_use_dedicated_embeddings:
1709+
raise ValueError(
1710+
"Qwen4-Exp dedicated MTP embeddings are unsupported: the pinned "
1711+
"official runtime defines no MTP execution or NextN cache ABI"
1712+
)
1713+
1714+
@classmethod
1715+
def from_transformers(cls, config, parent_config=None) -> Qwen4ExpConfig:
1716+
text = _as_attribute_config(getattr(config, "text_config", None)) or config
1717+
parent = parent_config or (config if text is not config else None)
1718+
base = ArchitectureConfig.from_transformers(text, parent)
1719+
fields = _shallow_fields(base)
1720+
mamba_ssm_dtype = _resolve_dtype_value(getattr(text, "mamba_ssm_dtype", "float32"))
1721+
if mamba_ssm_dtype is None:
1722+
raise ValueError(
1723+
"Qwen4-Exp mamba_ssm_dtype must be a recognized floating-point dtype"
1724+
)
1725+
layer_types = getattr(text, "layer_types", None)
1726+
if layer_types is not None:
1727+
layer_types = [
1728+
"qwen_sparse_attention" if value == "full_attention" else value
1729+
for value in layer_types
1730+
]
1731+
fields.update(
1732+
model_type="qwen4_exp_text",
1733+
layer_types=layer_types,
1734+
hc_count=getattr(text, "hc_count", 4),
1735+
hc_lowrank=getattr(text, "hc_lowrank", 320),
1736+
ple_layer_ids=list(getattr(text, "ple_layer_ids", None) or []),
1737+
ple_embed_dim=getattr(text, "ple_embed_dim", None),
1738+
ple_conv_kernel_size=getattr(text, "ple_conv_kernel_size", 4),
1739+
ngram_size=getattr(text, "ngram_size", 3),
1740+
heads_per_ngram=getattr(text, "heads_per_ngram", 8),
1741+
ngram_vocab_size_base=getattr(text, "ngram_vocab_size_base", 20_000_000),
1742+
make_ngram_vocab_size_divisible_by=getattr(
1743+
text, "make_ngram_vocab_size_divisible_by", 128
1744+
),
1745+
seed=getattr(text, "seed", 1234),
1746+
split_ngram_parts=getattr(text, "split_ngram_parts", 512),
1747+
indexer_n_heads=getattr(text, "indexer_n_heads", None),
1748+
indexer_kv_heads=getattr(text, "indexer_kv_heads", None),
1749+
indexer_head_dim=getattr(text, "indexer_head_dim", None),
1750+
indexer_budget=getattr(text, "indexer_budget", None),
1751+
indexer_compress_ratio=getattr(text, "indexer_compress_ratio", None),
1752+
output_gate_type=getattr(text, "output_gate_type", None),
1753+
mamba_ssm_dtype=mamba_ssm_dtype,
1754+
mtp_num_hidden_layers=getattr(text, "mtp_num_hidden_layers", 0),
1755+
mtp_use_dedicated_embeddings=getattr(text, "mtp_use_dedicated_embeddings", False),
1756+
)
1757+
return cls(**fields)
1758+
1759+
15341760
@dataclasses.dataclass
15351761
class Jais2Config(CausalLMConfig):
15361762
"""Normalize the published Jais2 projection and LayerNorm configuration."""

‎src/mobius/_inspect.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,13 @@ 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+
)
8996

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

‎src/mobius/_inspect_test.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,18 @@ 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):
55+
_patch_autoconfig(
56+
monkeypatch,
57+
SimpleNamespace(
58+
model_type="qwen4_exp",
59+
architectures=["Qwen4ExpForConditionalGeneration"],
60+
),
61+
)
62+
with pytest.raises(ValueError, match="multimodal component inspection is unavailable"):
63+
inspect_components("fake/qwen4")
64+
65+
5466
def test_vlm_returns_decoder_vision_embedding(monkeypatch):
5567
_patch_autoconfig(monkeypatch, SimpleNamespace(model_type="llava"))
5668
components = inspect_components("fake/llava")

0 commit comments

Comments
 (0)