Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions aspec/config/draft_structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,21 @@ def resolve_draft_structure(raw: Mapping) -> dict:
"router_z_loss_coef", "moe_router_enable_expert_bias")):
raise ValueError("Medusa heads have no FFN or expert routing")
return {"ffn_type": "heads_only"}
if raw.get("architectures") == ["NativeMTPDraftModel"]:
native = raw.get("native_config")
if isinstance(native, Mapping) and native.get("model_type") == "qwen3_5_moe_text":
values = {
"num_experts": native.get("num_experts"),
"num_experts_per_tok": native.get("num_experts_per_tok"),
"moe_intermediate_size": native.get("moe_intermediate_size"),
"shared_expert_intermediate_size": native.get("shared_expert_intermediate_size"),
}
for key, value in values.items():
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
raise ValueError(f"Native MoE MTP {key} must be a positive integer")
if values["num_experts_per_tok"] > values["num_experts"]:
raise ValueError("Native MoE MTP top-k exceeds its routed expert count")
return {"ffn_type": "native_mtp_moe", **values}
ffn_type = raw.get("ffn_type", "dense")
if ffn_type not in {"dense", "qwen3_moe", "ling_moe"}:
raise ValueError(f"Unsupported Draft ffn_type={ffn_type!r}")
Expand Down
17 changes: 12 additions & 5 deletions aspec/planning.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,11 +303,18 @@ 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"
)
try:
mtp_structure = resolve_draft_structure(raw)
except ValueError as exc:
raise PlanCompileError(str(exc)) from exc
native_model_type = (raw.get("native_config") or {}).get("model_type")
if native_model_type == "qwen3_5_moe_text":
if mtp_structure.get("ffn_type") != "native_mtp_moe":
raise PlanCompileError(
"Native MoE MTP requires a native_mtp_moe draft structure"
)
elif mtp_structure.get("ffn_type") != "dense":
raise PlanCompileError("Native MTP requires a dense or native MoE draft structure")
steps = _select(config, "training.mtp_steps")
beta = _select(config, "training.mtp_step_weight_beta")
if type(steps) is not int or steps <= 0:
Expand Down
8 changes: 8 additions & 0 deletions aspec/training/mtp_trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,21 @@
from aspec.models.mtp import MTPModel
from aspec.training import checkpoint
from aspec.training.eagle3_trainer import Eagle3Trainer
from aspec.training.trainer import Trainer


class MTPTrainer(Eagle3Trainer):
def _create_training_model(self, draft_model):
return MTPModel(draft_model, length=self.args.mtp_steps,
gradient_checkpointing=self.args.gradient_checkpointing)

def get_feature_contract_status(self):
# Native MTP has no EAGLE suffix cache or loss checkpoint switch.
status = dict(Trainer.get_feature_contract_status(self))
status["mtp_steps"] = self.args.mtp_steps
status["mtp_gradient_checkpointing"] = bool(self.args.gradient_checkpointing)
return status

def _load_algorithm_weights(self, draft_model, target_model_path):
if not (getattr(self.args, "initial_draft_model_path", None)
or checkpoint.resolve_resume_model_dir(self.args)):
Expand Down
91 changes: 91 additions & 0 deletions configs/recipes/qwen3_6_35b_a3b_mtp.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# Release training starting point: three passes, held-out eval and checkpoints.
# Hyperparameters are not a convergence/quality claim; see docs/user-guide/recipes.md.
# Native Qwen3.5-MoE MTP finetuning: official SDPA decoder, frozen Target embedding/head.
# 16 steps validate function/lifecycle; use domain/Target-generated data for quality training.
model:
target_model_path: ${oc.env:ASPEC_TARGET_MODEL,Qwen/Qwen3.6-35B-A3B}
native_context_length: 262144
trust_remote_code: false
embedding_key: model.language_model.embed_tokens.weight
norm_key: model.language_model.norm.weight
draft_model_config: aspec/config/qwen3_6_35b_a3b_mtp_draft_config.json
dataset:
eval_interval: 100
eval_micro_batch_size: 1
train_data_path: ${oc.env:ASPEC_TRAIN_DATA}
eval_data_path: ${oc.env:ASPEC_EVAL_DATA}
chat_template: qwen
prompt_key: conversations
min_loss_tokens: 1
shuffle_dataset: true
dataset_seed: 42
training:
attention_backend: sdpa
draft_context_parallel_size: 1
micro_batch_size: 1
draft_accumulation_steps: 2
learning_rate: 1e-4
min_lr: 6e-5
weight_decay: 0.0
max_grad_norm: 1.0
max_seq_length: 4096
num_epochs: 3
warmup_ratio: 0.04
seed: 42
continual_training: false
deterministic_anchor_sampling: false
training_num_gpus_per_node: 1
training_num_nodes: 1
placement_strategy: inference_first
fsdp_strategy: REPLICATE
fsdp_reduce_dtype: bfloat16
compile_model: false
max_concurrent_batches: 1
streaming_dispatch_with_training: true
pipeline_dispatch_with_training: true
prefetch_depth: 1
save_interval: 100
save_per_epoch: false
save_final_checkpoint: true
max_checkpoints: 2
dflash_packing: false
mtp_steps: 3
mtp_step_weight_beta: 0.6
gradient_checkpointing: true
inference:
inference_engine_type: sgl
store_last_hidden_states: false
target_prefill_memory_optimized: false
inference_num_gpus: 2
inference_num_gpus_per_engine: 2
inference_num_gpus_per_node: 2
inference_fetch_batch: 4
inference_buffer_threshold: 4
max_sample_pool_size: 8
inference_batch_size: 2
sglang:
tp_size: 2
mem_fraction_static: 0.85
mooncake:
data_plane: transfer_engine
protocol: nvlink_intra
require_nvlink: true
enable_gpu_direct: true
allow_host_fallback: false
enable_hard_pin: true
max_seq_len: 4096
hidden_dim: 2048
global_segment_size: 32GB
local_buffer_size: 8GB
host_buffer_size: 1GB
gpu_ring_slots: 8
source_gpu_ring_slots: 8
destination_gpu_ring_slots: 1
kv_lease_ttl_s: 600
get_retry_max_wait_seconds: 600
logging:
report_to: none
debug:
enable_perf_metrics: true
output_dir: outputs/qwen3.6-35b-a3b-mtp
cache_dir: cache/qwen3.6-35b-a3b-mtp
2 changes: 1 addition & 1 deletion docs/support.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ and tests do not imply CPU training support.
| DFlash2 | Experimental full/causal/SWA training with Flex, cuDNN THD or FA4 packing/CP | Experimental objective; no claim to reproduce an official training recipe |
| JetSpec | Qwen3-style causal parallel Draft head and temperature-scaled forward-KL objective, reused DFlash block machinery; chunked full-vocabulary KL, explicit causal visibility, exact recovery with FlexAttention, CP1, padded/non-packing, SGLang/native export, strict reload and a proposal consumer | No tree builder or long-run convergence claim; CPU causal packing and direct unmasked Draft calls fail closed; see [scope](user-guide/jetspec.md) |
| MTP-conditioned DSpark / DFlash | Target-side frozen native Qwen3.5 features, token/hidden dual-anchor training, exact recovery and strict native assets; legacy Draft-side assets retained | Dense full GQA, CP1, MBS1, REPLICATE, one node, non-packing, decay objective; Target capture PP1/unquantized; no generic serving consumer |
| Native MTP | Qwen3.5-9B native single predictor, same-Target frozen embedding/head, multi-step training, recovery and export/stitch | Text-only Dense MTP; SDPA CP1 or independently validated FA4 packing/CP; no generic multi-layer/MoE MTP |
| Native MTP | Qwen3.5-9B Dense and Qwen3.6-35B-A3B MoE native single predictor, same-Target frozen embedding/head, multi-step training and recovery; Dense export/stitch | SDPA CP1, one node, non-packing; no generic multi-layer MTP, Ling-3.1-flash, or MoE export/stitch yet |
| Dense / Qwen MoE / Ling MoE | Structure-specific FFNs, routing state, checkpointing and strict assets | No promise of every algorithm × structure combination |
| MHA/GQA / materialized MLA | Explicit head geometry and tensor bindings | MLA materializes K/V; no absorbed-MLA claim |
| SWA / CSA / QSA / DSA | Explicit window or staged compressed/indexed structures; native assets where required | DSA uses per-query raw-token selection on DSpark/DFlash GQA/MHA; no CSA2 or arbitrary structure combinations; short contexts may be slower |
Expand Down
11 changes: 7 additions & 4 deletions docs/user-guide/algorithms.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,12 +158,15 @@ consumer and does not certify generic SGLang serving.

## Native Qwen3.5 MTP

`configs/recipes/qwen3_5_9b_mtp.yaml` initializes the actual native predictor and binds frozen embeddings/head
from the same Target. Final post-norm feature at position `t` plus token `t+1` predicts token `t+2`;
later rollout depths reuse normalized predictor state. It is not an independently randomized EAGLE model.
`configs/recipes/qwen3_5_9b_mtp.yaml` initializes the actual native Qwen3.5 Dense predictor and binds
frozen embeddings/head from the same Target. `configs/recipes/qwen3_6_35b_a3b_mtp.yaml` does the same
for the native Qwen3.5-MoE predictor in Qwen3.6-35B-A3B, including its routed and shared experts.
Final post-norm feature at position `t` plus token `t+1` predicts token `t+2`; later rollout depths
reuse normalized predictor state. Neither is an independently randomized EAGLE model.

Use the normal CLI and [recovery workflow](training.md). SDPA is CP1; the FA4 packed path can use CP
with sufficient Draft GPUs and compatible geometry. Export/stitch preserves the shared Target bindings:
with sufficient Draft GPUs and compatible geometry. Dense export/stitch preserves the shared Target
bindings; MoE export/stitch remains a follow-up:

```bash
python -m tools.convert_to_hf --input-dir /path/to/complete/iter_checkpoint \
Expand Down
1 change: 1 addition & 0 deletions docs/user-guide/recipes.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ connections on your hardware before training.
| `eagle4` | Qwen3-8B / EAGLE4 | 1 node, 3 GPUs: 1T + 2D; 4K; sequential stages | Train a Draft, then candidate retrieval projections |
| `dmtp` | Qwen3.5-9B / MTP-conditioned DSpark | 1 node, 8 GPUs: 4T + 4D; 4K, CP1 | Train a Draft conditioned on the frozen native predictor; native assets |
| `native-mtp` | Qwen3.5-9B / native predictor | 1 node, 3 GPUs: 1T + 2D; 4K | Fine-tune the Target's native predictor |
| `native-mtp-moe` | Qwen3.6-35B-A3B / native MoE predictor | 1 node, 3 GPUs: 2T (TP2) + 1D; 4K | Fine-tune the Target's native MoE predictor |
| `ling-tiny` | Ling-3.0-tiny / Dense DSpark | 1 node, 2 GPUs: 1T + 1D; 4K | Train a small Ling Draft |
| `ling-tiny-dflash` | Ling-3.0-tiny / DFlash | 1 node, 3 GPUs: 1T + 2D; 4K | Train a block-parallel DFlash Draft against Ling-3.0-tiny |
| `ling-flash` | Ling-3.0-flash / Dense DSpark | 1 node, 3 GPUs: 2T (TP2) + 1D; 4K | Train against a larger Ling Target |
Expand Down
48 changes: 44 additions & 4 deletions tests/cpu/test_native_mtp_moe.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,12 @@
import torch
from safetensors.torch import save_file

from aspec.config.draft_structure import resolve_draft_structure
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
from aspec.planning import compile_execution_plan

ROOT = Path(__file__).parents[2]

Expand Down Expand Up @@ -157,6 +158,22 @@ def test_native_moe_ce_and_gradients_match_explicit_teacher_forcing():
assert actual.grad is target.grad is None, name


def test_native_moe_feature_status_does_not_require_eagle_fields():
from types import SimpleNamespace

from aspec.training.mtp_trainer import MTPTrainer

trainer = object.__new__(MTPTrainer)
trainer.data_fetcher = None
trainer.args = SimpleNamespace(mtp_steps=3, gradient_checkpointing=True,
attention_backend="sdpa",
draft_context_parallel_size=1)
trainer.dp_rank = trainer.cache_rank = trainer.cp_rank = 0
status = trainer.get_feature_contract_status()
assert status["mtp_steps"] == 3
assert status["mtp_gradient_checkpointing"] is True


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)
Expand All @@ -171,7 +188,23 @@ 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):
def test_native_moe_structure_describes_routed_and_shared_experts():
raw = json.loads((ROOT / "aspec/config/qwen3_6_35b_a3b_mtp_draft_config.json").read_text())
structure = resolve_draft_structure(raw)
assert structure == {
"ffn_type": "native_mtp_moe",
"num_experts": 256,
"num_experts_per_tok": 8,
"moe_intermediate_size": 512,
"shared_expert_intermediate_size": 512,
}
bad = copy.deepcopy(raw)
bad["native_config"]["num_experts_per_tok"] = 999
with pytest.raises(ValueError, match="top-k"):
resolve_draft_structure(bad)


def test_native_moe_plan_accepts_the_structure(tmp_path, monkeypatch):
native = json.loads(
(ROOT / "aspec/config/qwen3_6_35b_a3b_mtp_draft_config.json").read_text()
)["native_config"]
Expand All @@ -189,8 +222,15 @@ def test_native_moe_plan_fails_closed_until_its_structure_is_described(tmp_path,
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)
config.mooncake.hidden_dim = 2048
plan = compile_execution_plan(config).to_dict()
assert plan["workload"]["models"]["draft"]["structure"] == {
"ffn_type": "native_mtp_moe",
"num_experts": 256,
"num_experts_per_tok": 8,
"moe_intermediate_size": 512,
"shared_expert_intermediate_size": 512,
}


def test_native_moe_initialize_native_weights_roundtrip(tmp_path):
Expand Down
2 changes: 1 addition & 1 deletion tests/cpu/test_release_recipes.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def test_qwen8b_recipes_plan_without_target_override(name, monkeypatch):

def test_catalog_exactly_covers_formal_files():
entries = recipes.catalog()
assert len(entries) == 17
assert len(entries) == 18
declared = {p for entry in entries.values() for p in entry["configs"]}
assert declared == {
str(p.relative_to(recipes.ROOT)) for p in (recipes.ROOT / "configs/recipes").glob("*.yaml")
Expand Down
69 changes: 69 additions & 0 deletions tests/test_native_mtp_moe_recipe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# 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.

"""Qwen3.6-35B-A3B native MoE MTP recipe, Plan and model identity."""

import json
from pathlib import Path

import torch

from aspec.config.train_config import load_config
from aspec.models.draft import AutoDraftModelConfig, AutoEagle3DraftModel
from aspec.models.draft.mtp import NativeMTPDraftModel
from aspec.planning import _resolve_target_family, compile_execution_plan
from aspec.training.mtp_trainer import MTPTrainer
from aspec.training.trainer_actor import _trainer_class_for_config
from tools import recipes

ROOT = Path(__file__).parents[1]
RECIPE = "configs/recipes/qwen3_6_35b_a3b_mtp.yaml"
DRAFT = "aspec/config/qwen3_6_35b_a3b_mtp_draft_config.json"


def test_qwen36_moe_mtp_recipe_plan_and_model_contract():
config = load_config(str(ROOT / RECIPE), save_snapshot=False)
plan = compile_execution_plan(config)
assert _resolve_target_family("Qwen/Qwen3.6-35B-A3B") == "qwen3"
assert plan.workload.objective["family"] == "mtp"
assert plan.workload.objective["frozen_shared"] == ["embedding", "lm_head"]
assert set(plan.workload.features["tensors"]) == {"hidden_states", "input_ids"}
assert plan.workload.features["tensors"]["hidden_states"]["value_stage"] == "post_norm"
args = plan.to_runtime_args()
assert args.mtp_steps == 3 and args.freeze_lm_head
assert args.inference_num_gpus == args.inference_num_gpus_per_engine == 2
assert args.target_prefill_memory_optimized is False

raw = json.loads((ROOT / DRAFT).read_text())
cfg = AutoDraftModelConfig.from_dict(raw)
assert cfg.native_config["model_type"] == "qwen3_5_moe_text"
assert cfg.native_config["num_experts"] == 256
assert _trainer_class_for_config(cfg) is MTPTrainer
with torch.device("meta"):
model = AutoEagle3DraftModel.from_config(cfg)
assert isinstance(model, NativeMTPDraftModel)
assert type(model.midlayer).__name__ == "Qwen3_5MoeDecoderLayer"


def test_qwen36_moe_mtp_is_registered_as_a_release_recipe():
entry = recipes.catalog()["native-mtp-moe"]
assert entry == {
"configs": [RECIPE],
"model": "Qwen3.6-35B-A3B",
"nodes": 1,
"gpus": 3,
"target_gpus": 2,
"draft_gpus": 1,
"native_only_export": True,
}
11 changes: 11 additions & 0 deletions tools/recipe_catalog.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,17 @@
"draft_gpus": 2,
"native_only_export": true
},
"native-mtp-moe": {
"configs": [
"configs/recipes/qwen3_6_35b_a3b_mtp.yaml"
],
"model": "Qwen3.6-35B-A3B",
"nodes": 1,
"gpus": 3,
"target_gpus": 2,
"draft_gpus": 1,
"native_only_export": true
},
"ling-tiny": {
"configs": [
"configs/recipes/ling3_tiny_dspark.yaml"
Expand Down