From c1adc08037b158da887f04f73b71510c01646567 Mon Sep 17 00:00:00 2001 From: Zijun Li Date: Thu, 3 Dec 2026 12:32:12 +0800 Subject: [PATCH 1/3] feat(mtp): add Qwen3.5-MoE native predictor support --- .../qwen3_6_35b_a3b_mtp_draft_config.json | 97 +++++++++++ aspec/models/draft/mtp.py | 104 ++++++++++-- tests/cpu/test_native_mtp_moe.py | 156 ++++++++++++++++++ 3 files changed, 339 insertions(+), 18 deletions(-) create mode 100644 aspec/config/qwen3_6_35b_a3b_mtp_draft_config.json create mode 100644 tests/cpu/test_native_mtp_moe.py diff --git a/aspec/config/qwen3_6_35b_a3b_mtp_draft_config.json b/aspec/config/qwen3_6_35b_a3b_mtp_draft_config.json new file mode 100644 index 0000000..a56de6b --- /dev/null +++ b/aspec/config/qwen3_6_35b_a3b_mtp_draft_config.json @@ -0,0 +1,97 @@ +{ + "architectures": [ + "NativeMTPDraftModel" + ], + "model_type": "aspec_native_mtp", + "native_config": { + "attention_bias": false, + "attention_dropout": 0.0, + "attn_output_gate": true, + "bos_token_id": 248044, + "dtype": "bfloat16", + "eos_token_id": 248044, + "full_attention_interval": 4, + "head_dim": 256, + "hidden_act": "silu", + "hidden_size": 2048, + "initializer_range": 0.02, + "layer_types": [ + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention" + ], + "linear_conv_kernel_dim": 4, + "linear_key_head_dim": 128, + "linear_num_key_heads": 16, + "linear_num_value_heads": 32, + "linear_value_head_dim": 128, + "mamba_ssm_dtype": "float32", + "max_position_embeddings": 262144, + "model_type": "qwen3_5_moe_text", + "moe_intermediate_size": 512, + "mtp_num_hidden_layers": 1, + "mtp_use_dedicated_embeddings": false, + "num_attention_heads": 16, + "num_experts": 256, + "num_experts_per_tok": 8, + "num_hidden_layers": 40, + "num_key_value_heads": 2, + "output_router_logits": false, + "pad_token_id": null, + "partial_rotary_factor": 0.25, + "rms_norm_eps": 1e-06, + "rope_parameters": { + "mrope_interleaved": true, + "mrope_section": [ + 11, + 11, + 10 + ], + "partial_rotary_factor": 0.25, + "rope_theta": 10000000, + "rope_type": "default" + }, + "router_aux_loss_coef": 0.001, + "shared_expert_intermediate_size": 512, + "tie_word_embeddings": false, + "use_cache": true, + "vocab_size": 248320 + } +} diff --git a/aspec/models/draft/mtp.py b/aspec/models/draft/mtp.py index 80b8ef9..73e219a 100644 --- a/aspec/models/draft/mtp.py +++ b/aspec/models/draft/mtp.py @@ -14,37 +14,100 @@ # Adapted from Speculators MTP (7ec7aba9450b533334e8f7992baf4e93be3c1a57). # Native decoder, normalization and rotary mathematics use official Transformers. -"""Native Qwen3.5 Dense MTP assets, not an independently initialized EAGLE.""" +"""Native Qwen3.5 Dense/MoE MTP assets, not an independently initialized EAGLE.""" import copy +from collections.abc import Mapping import torch from torch import nn from transformers import PretrainedConfig -from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig -from transformers.models.qwen3_5.modeling_qwen3_5 import ( - Qwen3_5DecoderLayer, - Qwen3_5RMSNorm, - Qwen3_5TextRotaryEmbedding, -) from aspec.models.draft.base import Eagle3DraftModel, load_tensor_from_pretrained +_NATIVE_MODEL_TYPES = ("qwen3_5_text", "qwen3_5_moe_text") + + +def _unwrap_native_config(native_config): + if not isinstance(native_config, Mapping): + raise ValueError("Native MTP requires a native text config mapping") + native = copy.deepcopy(dict(native_config)) + if native.get("model_type") == "qwen3_5_moe": + text = native.get("text_config") + if not isinstance(text, Mapping): + raise ValueError("Native MTP requires the Qwen3.5 MoE text_config") + native = copy.deepcopy(dict(text)) + if native.get("model_type") not in _NATIVE_MODEL_TYPES: + raise ValueError( + "Native MTP currently requires a Qwen3.5 Dense or MoE text config; " + f"got {native.get('model_type')!r}" + ) + return native + + +def _native_classes(model_type): + if model_type == "qwen3_5_text": + from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig + from transformers.models.qwen3_5.modeling_qwen3_5 import ( + Qwen3_5DecoderLayer, + Qwen3_5RMSNorm, + Qwen3_5TextRotaryEmbedding, + ) + + return Qwen3_5TextConfig, Qwen3_5DecoderLayer, Qwen3_5RMSNorm, Qwen3_5TextRotaryEmbedding + if model_type == "qwen3_5_moe_text": + from transformers.models.qwen3_5_moe.configuration_qwen3_5_moe import Qwen3_5MoeTextConfig + from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import ( + Qwen3_5MoeDecoderLayer, + Qwen3_5MoeRMSNorm, + Qwen3_5MoeTextRotaryEmbedding, + ) + + return (Qwen3_5MoeTextConfig, Qwen3_5MoeDecoderLayer, + Qwen3_5MoeRMSNorm, Qwen3_5MoeTextRotaryEmbedding) + raise ValueError(f"Unsupported native MTP model type: {model_type!r}") + + +def _initialize_native_moe(midlayer, native): + """Mirror the official PreTrainedModel init for fused expert/router tensors.""" + from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import ( + Qwen3_5MoeExperts, + Qwen3_5MoeSparseMoeBlock, + ) + + with torch.no_grad(): + for module in midlayer.modules(): + if isinstance(module, Qwen3_5MoeExperts): + if not module.gate_up_proj.is_meta: + nn.init.normal_(module.gate_up_proj, mean=0.0, std=native.initializer_range) + nn.init.normal_(module.down_proj, mean=0.0, std=native.initializer_range) + elif isinstance(module, Qwen3_5MoeSparseMoeBlock): + if not module.gate.weight.is_meta: + nn.init.normal_(module.gate.weight, mean=0.0, std=native.initializer_range) + class NativeMTPConfig(PretrainedConfig): model_type = "aspec_native_mtp" has_no_defaults_at_init = True def __init__(self, native_config=None, **kwargs): - if native_config is None or native_config.get("model_type") != "qwen3_5_text": - raise ValueError("Native MTP currently requires a Qwen3.5 Dense text config") - native = copy.deepcopy(native_config) + native = _unwrap_native_config(native_config) + is_moe = native["model_type"] == "qwen3_5_moe_text" if native.get("mtp_use_dedicated_embeddings", False): raise ValueError("Native MTP dedicated embeddings are not the shared-embedding recipe") - if kwargs.get("ffn_type", "dense") != "dense" or kwargs.get("lm_head_rank_divisor"): - raise ValueError("Native Qwen3.5 Dense MTP cannot replace its native FFN or frozen output head") + expected_ffn = "moe" if is_moe else "dense" + if kwargs.get("ffn_type", expected_ffn) != expected_ffn or kwargs.get("lm_head_rank_divisor"): + raise ValueError("Native MTP cannot replace its native FFN or frozen output head") if native.get("mtp_num_hidden_layers", 1) != 1: raise ValueError("Native Qwen3.5 MTP checkpoint must contain its single native prediction layer") + if is_moe: + for key in ("num_experts", "num_experts_per_tok", "moe_intermediate_size", + "shared_expert_intermediate_size"): + value = native.get(key) + if not isinstance(value, int) or isinstance(value, bool) or value <= 0: + raise ValueError("Native MTP MoE requires a positive native " + key) + if native["num_experts_per_tok"] > native["num_experts"]: + raise ValueError("Native MTP MoE top-k exceeds its routed expert count") # RoPE belongs to the native text config. Accept an identical alias, # but do not duplicate MRoPE fields into generic HF rope validation. if "rope_parameters" in kwargs and kwargs.pop("rope_parameters") != native.get("rope_parameters"): @@ -82,7 +145,10 @@ def __init__(self, config, attention_backend="sdpa"): super().__init__(config) if attention_backend not in {"sdpa", "fa4"}: raise NotImplementedError("Native MTP requires official SDPA or FA4 THD execution") - native = Qwen3_5TextConfig(**config.native_config) + config_cls, decoder_cls, norm_cls, rotary_cls = _native_classes( + config.native_config["model_type"] + ) + native = config_cls(**config.native_config) native._attn_implementation = "sdpa" self.attention_backend = attention_backend if attention_backend == "fa4": @@ -99,12 +165,14 @@ def __init__(self, config, attention_backend="sdpa"): self.target_vocab_size = self.vocab_size = native.vocab_size self.embed_tokens = nn.Embedding(native.vocab_size, native.hidden_size) self.lm_head = nn.Linear(native.hidden_size, native.vocab_size, bias=False) - self.pre_fc_norm_embedding = Qwen3_5RMSNorm(native.hidden_size, native.rms_norm_eps) - self.pre_fc_norm_hidden = Qwen3_5RMSNorm(native.hidden_size, native.rms_norm_eps) + self.pre_fc_norm_embedding = norm_cls(native.hidden_size, native.rms_norm_eps) + self.pre_fc_norm_hidden = norm_cls(native.hidden_size, native.rms_norm_eps) self.fc = nn.Linear(native.hidden_size * 2, native.hidden_size, bias=False) - self.midlayer = Qwen3_5DecoderLayer(native, full_layers[-1]) - self.norm = Qwen3_5RMSNorm(native.hidden_size, native.rms_norm_eps) - self.rotary_emb = Qwen3_5TextRotaryEmbedding(native) + self.midlayer = decoder_cls(native, full_layers[-1]) + if config.native_config["model_type"] == "qwen3_5_moe_text": + _initialize_native_moe(self.midlayer, native) + self.norm = norm_cls(native.hidden_size, native.rms_norm_eps) + self.rotary_emb = rotary_cls(native) self.norm_output = False self.freeze_embedding() self.freeze_lm_head() diff --git a/tests/cpu/test_native_mtp_moe.py b/tests/cpu/test_native_mtp_moe.py new file mode 100644 index 0000000..4253e77 --- /dev/null +++ b/tests/cpu/test_native_mtp_moe.py @@ -0,0 +1,156 @@ +# Copyright 2026 Ant Group Co., Ltd. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Native Qwen3.5-MoE MTP identity, fused-expert layout, parity and fail-closed config.""" + +import copy +import json +from pathlib import Path + +import pytest +import torch +from safetensors.torch import save_file + +from aspec.models.draft import AutoDraftModelConfig, AutoEagle3DraftModel +from aspec.models.draft.mtp import NativeMTPConfig, NativeMTPDraftModel +from aspec.models.mtp import MTPModel, mtp_step_weights + +ROOT = Path(__file__).parents[2] + + +def native_config(): + return { + "model_type": "qwen3_5_moe_text", "hidden_size": 16, "intermediate_size": 32, + "moe_intermediate_size": 8, "shared_expert_intermediate_size": 8, + "num_experts": 4, "num_experts_per_tok": 2, + "num_attention_heads": 2, "num_key_value_heads": 1, "head_dim": 8, + "vocab_size": 32, "num_hidden_layers": 4, + "layer_types": ["linear_attention"] * 3 + ["full_attention"], + "rms_norm_eps": 1e-6, "attention_dropout": 0.0, "attention_bias": False, + "hidden_act": "silu", "max_position_embeddings": 128, "mtp_num_hidden_layers": 1, + "rope_parameters": {"rope_type": "default", "rope_theta": 10000, + "partial_rotary_factor": 1.0, "mrope_section": [1, 1, 2], + "mrope_interleaved": True}, + } + + +def model(): + return NativeMTPDraftModel(NativeMTPConfig(native_config=native_config())) + + +def test_native_moe_dispatch_uses_the_native_moe_predictor(): + config = AutoDraftModelConfig.from_dict({"architectures": ["NativeMTPDraftModel"], + "native_config": native_config()}) + draft = AutoEagle3DraftModel.from_config(config) + assert isinstance(draft, NativeMTPDraftModel) + assert type(draft.midlayer).__name__ == "Qwen3_5MoeDecoderLayer" + state = draft.state_dict() + for key in ("midlayer.mlp.experts.gate_up_proj", "midlayer.mlp.experts.down_proj", + "midlayer.mlp.gate.weight", "midlayer.mlp.shared_expert_gate.weight"): + assert key in state + assert "midlayer.mlp.experts.gate_proj" not in state + assert (draft.native_key("midlayer.mlp.experts.gate_up_proj") + == "mtp.layers.0.mlp.experts.gate_up_proj") + + +def test_native_moe_accepts_the_outer_vlm_config(): + config = NativeMTPConfig(native_config={"model_type": "qwen3_5_moe", + "text_config": native_config(), + "vision_config": {"model_type": "unused"}}) + assert config.native_config["model_type"] == "qwen3_5_moe_text" + assert config.native_config["num_experts"] == 4 + + +@pytest.mark.parametrize("change, match", [ + ({"num_experts": 0}, "num_experts"), + ({"num_experts_per_tok": 5}, "top-k"), + ({"moe_intermediate_size": 0}, "moe_intermediate_size"), + ({"shared_expert_intermediate_size": 0}, "shared_expert_intermediate_size"), + ({"mtp_num_hidden_layers": 2}, "single native prediction layer"), + ({"mtp_use_dedicated_embeddings": True}, "dedicated embeddings"), +]) +def test_native_moe_config_fails_closed(change, match): + native = native_config() + native.update(change) + with pytest.raises(ValueError, match=match): + NativeMTPConfig(native_config=native) + + +def test_native_moe_rejects_replacing_its_native_ffn(): + with pytest.raises(ValueError, match="native FFN"): + NativeMTPConfig(native_config=native_config(), ffn_type="dense") + + +def test_native_moe_ce_and_gradients_match_explicit_teacher_forcing(): + torch.manual_seed(91) + draft = model() + reference = copy.deepcopy(draft) + wrapper = MTPModel(draft, length=3, gradient_checkpointing=True) + ids = torch.randint(0, 32, (1, 13)) + hidden = torch.randn(1, 13, 16) + mask = torch.ones_like(ids) + mask[:, :5] = 0 + result = wrapper(ids, hidden, mask, torch.ones_like(ids)) + state = hidden[:, :9] + positions = torch.arange(9)[None] + expected = [] + for depth in range(3): + embeds = reference.pre_fc_norm_embedding(reference.embed_tokens(ids[:, depth + 1:depth + 10])) + fused = reference.fc(torch.cat((embeds, reference.pre_fc_norm_hidden(state)), -1)) + rotary = reference.rotary_emb(fused, positions[None].expand(3, -1, -1)) + state = reference.norm(reference.midlayer(fused, position_embeddings=rotary, + attention_mask=None, position_ids=positions)) + labels = ids[:, depth + 2:depth + 11].clone() + labels[mask[:, depth + 2:depth + 11] == 0] = -100 + expected.append(torch.nn.functional.cross_entropy( + reference.lm_head(state).flatten(0, 1), labels.flatten(), ignore_index=-100)) + weights = mtp_step_weights(3, 0.6) + sum(weight * value for weight, value in zip(weights, result[0], strict=True)).backward() + sum(weight * value for weight, value in zip(weights, expected, strict=True)).backward() + for actual, target in zip(result[1], expected, strict=True): + torch.testing.assert_close(actual, target) + for (name, actual), (_, target) in zip(draft.named_parameters(), + reference.named_parameters(), strict=True): + if actual.requires_grad: + torch.testing.assert_close(actual.grad, target.grad) + else: + assert actual.grad is target.grad is None, name + + +def test_qwen36_moe_config_builds_the_fused_expert_predictor(): + raw = json.loads((ROOT / "aspec/config/qwen3_6_35b_a3b_mtp_draft_config.json").read_text()) + config = NativeMTPConfig.from_dict(raw) + assert config.native_config["model_type"] == "qwen3_5_moe_text" + assert config.native_config["num_experts"] == 256 + assert config.native_config["num_experts_per_tok"] == 8 + with torch.device("meta"): + draft = NativeMTPDraftModel(config) + state = draft.state_dict() + assert state["midlayer.mlp.experts.gate_up_proj"].shape == (256, 1024, 2048) + assert state["midlayer.mlp.experts.down_proj"].shape == (256, 2048, 512) + assert state["midlayer.mlp.gate.weight"].shape == (256, 2048) + + +def test_native_moe_initialize_native_weights_roundtrip(tmp_path): + torch.manual_seed(93) + source = model() + target = tmp_path / "target" + target.mkdir() + save_file(source.state_dict_for_serving(), str(target / "model.safetensors")) + extracted = model() + extracted.initialize_native_weights(str(target)) + for key, value in source.state_dict().items(): + if key in {"embed_tokens.weight", "lm_head.weight"}: + continue + torch.testing.assert_close(extracted.state_dict()[key], value, rtol=0, atol=0) From 243a23b3da03aab50865ac883956e6e5936f92b2 Mon Sep 17 00:00:00 2001 From: Zijun Li Date: Fri, 4 Dec 2026 19:31:47 +0800 Subject: [PATCH 2/3] fix(mtp): keep RoPE FP32 and validate native MoE checkpoints --- aspec/models/checkpoint.py | 27 ++++++++++++ aspec/models/draft/mtp.py | 58 ++++++++++++++++++++++++- aspec/planning.py | 5 +++ tests/cpu/test_native_mtp_moe.py | 74 +++++++++++++++++++++++++++++++- tests/test_native_mtp.py | 1 + 5 files changed, 162 insertions(+), 3 deletions(-) diff --git a/aspec/models/checkpoint.py b/aspec/models/checkpoint.py index 28c79bf..23fe167 100644 --- a/aspec/models/checkpoint.py +++ b/aspec/models/checkpoint.py @@ -34,6 +34,33 @@ from safetensors import safe_open +def list_tensor_keys_from_pretrained(model_path: str) -> set[str]: + """List tensor keys without loading tensor payloads.""" + if not os.path.exists(model_path): + return list_tensor_keys_from_pretrained(snapshot_download(repo_id=model_path)) + + glob_path = os.path.join(model_path, "*.index.json") + index_json_path = glob.glob(glob_path) + if len(index_json_path) == 1: + with open(index_json_path[0], "r") as f: + return set(json.load(f)["weight_map"]) + if len(index_json_path) > 1: + raise FileNotFoundError(f"Multiple index.json files found in {model_path}") + + safetensors_path = os.path.join(model_path, "model.safetensors") + if os.path.exists(safetensors_path): + with safe_open(safetensors_path, framework="pt") as f: + return set(f.keys()) + + pytorch_model_path = os.path.join(model_path, "pytorch_model.bin") + if os.path.exists(pytorch_model_path): + return set(torch.load(pytorch_model_path, map_location="cpu")) + + raise FileNotFoundError( + f"No index.json, model.safetensors or pytorch_model.bin found in {model_path}" + ) + + def load_tensor_from_pretrained(model_path: str, key: str) -> torch.Tensor: """Read a single tensor by key from an HF checkpoint directory or hub repository id.""" if not os.path.exists(model_path): diff --git a/aspec/models/draft/mtp.py b/aspec/models/draft/mtp.py index 73e219a..6bf7f35 100644 --- a/aspec/models/draft/mtp.py +++ b/aspec/models/draft/mtp.py @@ -23,7 +23,11 @@ from torch import nn from transformers import PretrainedConfig -from aspec.models.draft.base import Eagle3DraftModel, load_tensor_from_pretrained +from aspec.models.checkpoint import ( + list_tensor_keys_from_pretrained, + load_tensor_from_pretrained, +) +from aspec.models.draft.base import Eagle3DraftModel _NATIVE_MODEL_TYPES = ("qwen3_5_text", "qwen3_5_moe_text") @@ -36,6 +40,11 @@ def _unwrap_native_config(native_config): text = native.get("text_config") if not isinstance(text, Mapping): raise ValueError("Native MTP requires the Qwen3.5 MoE text_config") + if text.get("model_type") != "qwen3_5_moe_text": + raise ValueError( + "Outer Qwen3.5 MoE config requires " + "text_config.model_type='qwen3_5_moe_text'" + ) native = copy.deepcopy(dict(text)) if native.get("model_type") not in _NATIVE_MODEL_TYPES: raise ValueError( @@ -172,20 +181,67 @@ def __init__(self, config, attention_backend="sdpa"): if config.native_config["model_type"] == "qwen3_5_moe_text": _initialize_native_moe(self.midlayer, native) self.norm = norm_cls(native.hidden_size, native.rms_norm_eps) + self._rotary_cls = rotary_cls self.rotary_emb = rotary_cls(native) self.norm_output = False self.freeze_embedding() self.freeze_lm_head() + def _apply(self, fn, recurse=True): + result = super()._apply(fn, recurse=recurse) + if hasattr(self, "_rotary_cls"): + # HF rotary buffers are non-persistent but still follow dtype casts. + # Rebuild in FP32 on the final device so BF16 training does not round + # the RoPE frequencies and change routing/token predictions. + with torch.no_grad(): + self.rotary_emb = self._rotary_cls( + self.native, device=self.embed_tokens.weight.device + ) + return result + @staticmethod def native_key(name): if name.startswith("midlayer."): return "mtp.layers.0." + name.removeprefix("midlayer.") return "mtp." + name + def _validate_native_checkpoint(self, target_model_path): + from transformers import AutoConfig + + target = AutoConfig.from_pretrained(target_model_path).to_dict() + text = target.get("text_config", target) + native = self.config.native_config + for key in ( + "model_type", "hidden_size", "num_hidden_layers", "vocab_size", + "num_attention_heads", "num_key_value_heads", "head_dim", + "num_experts", "num_experts_per_tok", "moe_intermediate_size", + "shared_expert_intermediate_size", "mtp_num_hidden_layers", + "mtp_use_dedicated_embeddings", + ): + if key in native and text.get(key) != native[key]: + raise ValueError( + f"Native MTP checkpoint {key} disagrees with its config: " + f"requested={native[key]!r}, checkpoint={text.get(key)!r}" + ) + expected = { + self.native_key(name) for name in self.state_dict() + if name not in {"embed_tokens.weight", "lm_head.weight"} + } + actual = { + key for key in list_tensor_keys_from_pretrained(target_model_path) + if key.startswith("mtp.") + } + if actual != expected: + raise ValueError( + "Native MTP checkpoint must contain exactly one native prediction layer: " + f"missing={sorted(expected - actual)}, " + f"unexpected={sorted(actual - expected)}" + ) + @torch.no_grad() def initialize_native_weights(self, target_model_path): """Load only native MTP tensors, never the full verifier transformer.""" + self._validate_native_checkpoint(target_model_path) state = self.state_dict() for name, destination in state.items(): if name in {"embed_tokens.weight", "lm_head.weight"}: diff --git a/aspec/planning.py b/aspec/planning.py index 22be5c3..20fb883 100644 --- a/aspec/planning.py +++ b/aspec/planning.py @@ -303,6 +303,11 @@ def _load_draft_descriptor(config: DictConfig) -> dict[str, Any]: raw = NativeMTPConfig.from_dict(raw).to_dict() except (ValueError, TypeError) as exc: raise PlanCompileError(str(exc)) from exc + if (raw.get("native_config") or {}).get("model_type") == "qwen3_5_moe_text": + raise PlanCompileError( + "Native MoE MTP planning is not enabled until its routed/shared " + "expert structure is described" + ) steps = _select(config, "training.mtp_steps") beta = _select(config, "training.mtp_step_weight_beta") if type(steps) is not int or steps <= 0: diff --git a/tests/cpu/test_native_mtp_moe.py b/tests/cpu/test_native_mtp_moe.py index 4253e77..053d8b0 100644 --- a/tests/cpu/test_native_mtp_moe.py +++ b/tests/cpu/test_native_mtp_moe.py @@ -22,9 +22,11 @@ import torch from safetensors.torch import save_file +from aspec.config.train_config import load_config from aspec.models.draft import AutoDraftModelConfig, AutoEagle3DraftModel from aspec.models.draft.mtp import NativeMTPConfig, NativeMTPDraftModel from aspec.models.mtp import MTPModel, mtp_step_weights +from aspec.planning import PlanCompileError, compile_execution_plan ROOT = Path(__file__).parents[2] @@ -49,6 +51,12 @@ def model(): return NativeMTPDraftModel(NativeMTPConfig(native_config=native_config())) +def write_target(path, state, config=None): + path.mkdir() + save_file(state, str(path / "model.safetensors")) + (path / "config.json").write_text(json.dumps(config or native_config())) + + def test_native_moe_dispatch_uses_the_native_moe_predictor(): config = AutoDraftModelConfig.from_dict({"architectures": ["NativeMTPDraftModel"], "native_config": native_config()}) @@ -72,6 +80,27 @@ def test_native_moe_accepts_the_outer_vlm_config(): assert config.native_config["num_experts"] == 4 +def test_native_moe_outer_config_requires_a_moe_text_config(): + text = native_config() + text["model_type"] = "qwen3_5_text" + with pytest.raises(ValueError, match="text_config.model_type"): + NativeMTPConfig(native_config={"model_type": "qwen3_5_moe", "text_config": text}) + + +def test_native_moe_rope_frequencies_stay_fp32_after_bfloat16_cast(): + draft = model() + expected = type(draft.rotary_emb)(draft.native).inv_freq.clone() + assert expected.dtype == torch.float32 + cast = copy.deepcopy(draft).to(torch.bfloat16) + assert cast.rotary_emb.inv_freq.dtype == torch.float32 + torch.testing.assert_close(cast.rotary_emb.inv_freq, expected, rtol=0, atol=0) + config = AutoDraftModelConfig.from_dict({"architectures": ["NativeMTPDraftModel"], + "native_config": native_config()}) + auto = AutoEagle3DraftModel.from_config(config, torch_dtype=torch.bfloat16) + assert auto.rotary_emb.inv_freq.dtype == torch.float32 + torch.testing.assert_close(auto.rotary_emb.inv_freq, expected, rtol=0, atol=0) + + @pytest.mark.parametrize("change, match", [ ({"num_experts": 0}, "num_experts"), ({"num_experts_per_tok": 5}, "top-k"), @@ -142,15 +171,56 @@ def test_qwen36_moe_config_builds_the_fused_expert_predictor(): assert state["midlayer.mlp.gate.weight"].shape == (256, 2048) +def test_native_moe_plan_fails_closed_until_its_structure_is_described(tmp_path, monkeypatch): + native = json.loads( + (ROOT / "aspec/config/qwen3_6_35b_a3b_mtp_draft_config.json").read_text() + )["native_config"] + target = tmp_path / "target" + target.mkdir() + (target / "config.json").write_text(json.dumps({ + "model_type": "qwen3_5_moe", + "architectures": ["Qwen3_5MoeForConditionalGeneration"], + "text_config": native, + })) + monkeypatch.setenv("ASPEC_TARGET_MODEL", str(target)) + config = load_config(str(ROOT / "configs/recipes/qwen3_5_9b_mtp.yaml"), + save_snapshot=False) + config.model.target_model_path = str(target) + config.model.draft_model_config = str( + ROOT / "aspec/config/qwen3_6_35b_a3b_mtp_draft_config.json" + ) + with pytest.raises(PlanCompileError, match="Native MoE MTP"): + compile_execution_plan(config) + + def test_native_moe_initialize_native_weights_roundtrip(tmp_path): torch.manual_seed(93) source = model() target = tmp_path / "target" - target.mkdir() - save_file(source.state_dict_for_serving(), str(target / "model.safetensors")) + write_target(target, source.state_dict_for_serving()) extracted = model() extracted.initialize_native_weights(str(target)) for key, value in source.state_dict().items(): if key in {"embed_tokens.weight", "lm_head.weight"}: continue torch.testing.assert_close(extracted.state_dict()[key], value, rtol=0, atol=0) + + +def test_native_moe_loader_rejects_a_different_routing_config(tmp_path): + source = model() + config = native_config() + config["num_experts_per_tok"] = 1 + target = tmp_path / "target" + write_target(target, source.state_dict_for_serving(), config) + with pytest.raises(ValueError, match="num_experts_per_tok"): + model().initialize_native_weights(str(target)) + + +def test_native_moe_loader_rejects_extra_prediction_layers(tmp_path): + source = model() + state = source.state_dict_for_serving() + state["mtp.layers.1.mlp.gate.weight"] = torch.zeros(4, 16) + target = tmp_path / "target" + write_target(target, state) + with pytest.raises(ValueError, match="exactly one native prediction layer"): + model().initialize_native_weights(str(target)) diff --git a/tests/test_native_mtp.py b/tests/test_native_mtp.py index 5346c40..a0d8792 100644 --- a/tests/test_native_mtp.py +++ b/tests/test_native_mtp.py @@ -136,6 +136,7 @@ def test_extract_native_tensors_and_strict_export_roundtrip(tmp_path, monkeypatc target = tmp_path / "target" target.mkdir() save_file(original, str(target / "model.safetensors")) + (target / "config.json").write_text(json.dumps(native_config())) extracted = model() extracted.initialize_native_weights(str(target)) for key, value in source.state_dict().items(): From ab6685816f120c344322f490c45e50cc207c1151 Mon Sep 17 00:00:00 2001 From: Zijun Li Date: Fri, 4 Dec 2026 19:42:27 +0800 Subject: [PATCH 3/3] fix(mtp): validate rotary semantics and avoid bin payload reads --- aspec/models/checkpoint.py | 2 +- aspec/models/draft/mtp.py | 2 +- tests/cpu/test_native_mtp_moe.py | 20 ++++++++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/aspec/models/checkpoint.py b/aspec/models/checkpoint.py index 23fe167..c1fdeb7 100644 --- a/aspec/models/checkpoint.py +++ b/aspec/models/checkpoint.py @@ -54,7 +54,7 @@ def list_tensor_keys_from_pretrained(model_path: str) -> set[str]: pytorch_model_path = os.path.join(model_path, "pytorch_model.bin") if os.path.exists(pytorch_model_path): - return set(torch.load(pytorch_model_path, map_location="cpu")) + return set(torch.load(pytorch_model_path, map_location="meta")) raise FileNotFoundError( f"No index.json, model.safetensors or pytorch_model.bin found in {model_path}" diff --git a/aspec/models/draft/mtp.py b/aspec/models/draft/mtp.py index 6bf7f35..f53e2c3 100644 --- a/aspec/models/draft/mtp.py +++ b/aspec/models/draft/mtp.py @@ -216,7 +216,7 @@ def _validate_native_checkpoint(self, target_model_path): "num_attention_heads", "num_key_value_heads", "head_dim", "num_experts", "num_experts_per_tok", "moe_intermediate_size", "shared_expert_intermediate_size", "mtp_num_hidden_layers", - "mtp_use_dedicated_embeddings", + "mtp_use_dedicated_embeddings", "rope_parameters", ): if key in native and text.get(key) != native[key]: raise ValueError( diff --git a/tests/cpu/test_native_mtp_moe.py b/tests/cpu/test_native_mtp_moe.py index 053d8b0..a10fa63 100644 --- a/tests/cpu/test_native_mtp_moe.py +++ b/tests/cpu/test_native_mtp_moe.py @@ -224,3 +224,23 @@ def test_native_moe_loader_rejects_extra_prediction_layers(tmp_path): write_target(target, state) with pytest.raises(ValueError, match="exactly one native prediction layer"): model().initialize_native_weights(str(target)) + + +def test_native_moe_loader_rejects_a_different_rope_config(tmp_path): + source = model() + config = native_config() + config["rope_parameters"] = { + **config["rope_parameters"], "rope_theta": 17000 + } + target = tmp_path / "target" + write_target(target, source.state_dict_for_serving(), config) + with pytest.raises(ValueError, match="rope_parameters"): + model().initialize_native_weights(str(target)) + + +def test_list_tensor_keys_reads_legacy_bin_metadata(tmp_path): + from aspec.models.checkpoint import list_tensor_keys_from_pretrained + + torch.save({"a": torch.ones(2), "b": torch.zeros(3)}, + str(tmp_path / "pytorch_model.bin")) + assert list_tensor_keys_from_pretrained(str(tmp_path)) == {"a", "b"}