Repository navigation
feat(mtp): add Qwen3.5-MoE native predictor support #70
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,37 +14,109 @@ | |
|
|
||
| # 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.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") | ||
|
|
||
|
|
||
| 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") | ||
| 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( | ||
| "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, | ||
| ) | ||
|
|
||
| from aspec.models.draft.base import Eagle3DraftModel, load_tensor_from_pretrained | ||
| 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" | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The new config can already reach the existing training planner. When I pointed the native MTP recipe at this draft config and its matching Target, |
||
| 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"]: | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could I’d also compare the full set of |
||
| 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 +154,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,25 +174,74 @@ 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_cls = rotary_cls | ||
| self.rotary_emb = rotary_cls(native) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could we keep Regenerating just |
||
| 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", "rope_parameters", | ||
| ): | ||
|
Comment on lines
+214
to
+220
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Validate rotary semantics before loading Target weights. If the requested MoE config changes only Compare the effective rotary configurations before copying tensors. Reject different frequencies or MRoPE layouts, and retain loading for equivalent configurations. As per path instructions, prioritize “tensor shape/layout/dtype/device contracts” and “numerical stability.”
|
||
| 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"}: | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
One small config guard here would help. An outer
qwen3_5_moeconfig with an innerqwen3_5_textcurrently passes validation and selects the Dense decoder. Could we requiretext_config.model_type == "qwen3_5_moe_text"when unwrapping this outer type, and add a negative test for that pair?