Skip to content

35. Multi Token Decoding | Native Multi-Token Prediction|原生多 Token 预测 ​

难度: Hard | 环境: CPU + GPU | 标签: 推理优化, 投机解码, MTP

🚀 云端运行环境

本章节的实战代码可以点击以下链接在免费 GPU 算力平台上直接运行:

Open In ColabOpen In Studio (国内推荐:魔搭社区免费实例)

本节导读 ​

原生多 Token 预测(MTP)把未来位置的预测模块放在目标模型内部,用共享状态形成多个候选,不再依赖独立草稿模型。本节关注内置候选如何产生、怎样与目标模型结果逐位置验证,以及连续接受长度如何决定单轮有效推进量。

前置阅读 ​

Step 1:内置预测模块如何形成候选 ​

原生 MTP 的候选来自目标模型检查点内部。多个预测深度复用主模型状态,分别面向更远的未来位置给出词表分数;每个深度选择一个候选后,按位置组成有序候选块。模型检查点没有相应模块时,运行参数不能凭空启用这条路径。

对象作用必须成立的条件
主模型状态提供当前上下文表示与本轮目标验证共享同一模型语义
MTP 预测深度面向不同未来位置给出词表分数检查点包含对应数量的内置模块
有序候选块按预测深度排列候选 Token顺序与待验证位置一一对应

原生 MTP 与投机解码机制链

Step 2:候选怎样与目标结果逐位置验证 ​

目标模型为候选位置给出验证结果。贪心路径下,第 i 个 MTP 候选与目标模型在同一位置的首选 Token 比较:相同则进入连续接受前缀;首次不同则关闭后缀,并使用目标模型在该位置的结果修正本轮输出。

验证状态条件状态变化
当前位置匹配MTP 候选等于目标首选 Token接受长度加一,继续检查
首次不匹配两者在当前位置不同提交已接受前缀和目标修正 Token
全部匹配所有候选均通过提交候选块和额外目标 Token

Step 3:连续接受长度如何转化为有效推进 ​

候选数量只表示最多尝试多少位置,连续接受长度才决定本轮能复用多少候选。更长的候选块扩大潜在推进量,也会增加候选计算和验证成本;首次不匹配越早,后部候选越难转化为实际收益。

观察量表示的机制不能单独推出的结论
候选长度本轮最大尝试范围不等于实际推进量
连续接受长度可直接提交的候选数量不等于端到端加速比
每轮输出长度接受前缀加修正或追加 Token仍需结合候选和验证成本

多 Token 解码的接受长度与收益

Step 4:实现原生 MTP 候选与贪心验证 ​

TODO / 函数学习者完成的机制必须满足的约束测试证据
TODO 1 · select_mtp_candidates从各预测深度形成有序候选块每个深度独立选择;候选数不超过预算正常候选、预算截断、空输入与维度错误
TODO 2 · continuous_match_length计算候选与目标结果的连续匹配长度首次不匹配立即停止首位置失败、中途失败与全部匹配
TODO 3 · build_mtp_round根据匹配边界提交修正或追加 Token后缀不得越过首次不匹配位置修正路径、全部匹配路径与统一状态记录
python
from typing import List, Sequence
import torch
python
def _validate_depth_logits(depth_logits: torch.Tensor) -> torch.Tensor:
    """校验 MTP 预测深度与词表维度。"""
    scores = torch.as_tensor(depth_logits)
    if scores.ndim != 2 or scores.shape[0] == 0 or scores.shape[1] == 0:
        raise ValueError("depth_logits 必须是非空二维张量 [depth, vocab]")
    if not torch.isfinite(scores).all():
        raise ValueError("词表分数不能包含 NaN 或 Inf")
    return scores


def select_mtp_candidates(depth_logits: torch.Tensor, max_candidates: int) -> List[int]:
    """按预测深度形成受预算约束的有序候选块。"""
    scores = _validate_depth_logits(depth_logits)
    if not isinstance(max_candidates, int) or isinstance(max_candidates, bool) or max_candidates < 1:
        raise ValueError("max_candidates 必须是正整数")
    # ==========================================
    # TODO 1:从各预测深度形成有序候选块。
    # ==========================================
    # candidates = ???  # 各深度最高分 Token,长度不超过 max_candidates。
    raise NotImplementedError("TODO 1:请形成 MTP 候选块")
    return candidates


def continuous_match_length(
    candidates: Sequence[int],
    target_tokens: Sequence[int],
) -> int:
    """返回候选与目标结果从首位置开始连续匹配的长度。"""
    if len(target_tokens) < len(candidates):
        raise ValueError("目标结果必须覆盖所有候选位置")
    accepted_length = 0
    for candidate, target in zip(candidates, target_tokens):
        # ==========================================
        # TODO 2:在首次不匹配位置停止连续接受。
        # ==========================================
        # matches = ???  # 当前 MTP 候选与目标首选 Token 相同时为 True。
        raise NotImplementedError("TODO 2:请比较当前位置")
        if not matches:
            break
        accepted_length += 1
    return accepted_length


def build_mtp_round(candidates: Sequence[int], target_tokens: Sequence[int]) -> dict:
    """根据连续匹配边界形成本轮输出和下一轮状态。"""
    if len(target_tokens) != len(candidates) + 1:
        raise ValueError("目标结果必须包含候选位置和一个额外位置")
    accepted_length = continuous_match_length(candidates, target_tokens)
    # ==========================================
    # TODO 3:提交接受前缀,并追加修正或额外目标 Token。
    # ==========================================
    # emitted_tokens = ???  # 接受前缀后追加 target_tokens[accepted_length]。
    # all_candidates_accepted = ???  # 接受长度等于候选长度时为 True。
    raise NotImplementedError("TODO 3:请形成本轮输出")
    return {
        "candidate_count": len(candidates),
        "accepted_length": accepted_length,
        "emitted_tokens": emitted_tokens,
        "all_candidates_accepted": all_candidates_accepted,
        "first_mismatch": None if all_candidates_accepted else accepted_length,
    }

测试 ​

测试分别检查内置候选形成、连续匹配边界以及修正和追加两条状态路径。

python
def test_select_mtp_candidates():
    """候选应按预测深度排列,并受最大候选数限制。"""
    logits = torch.tensor([[0.1, 0.9, 0.0], [0.8, 0.1, 0.1], [0.2, 0.3, 0.5]])
    assert select_mtp_candidates(logits, 2) == [1, 0]
    assert select_mtp_candidates(logits, 8) == [1, 0, 2]
    for invalid in (torch.empty(0, 3), torch.tensor([0.1, 0.9])):
        try:
            select_mtp_candidates(invalid, 2)
        except ValueError:
            pass
        else:
            raise AssertionError("空输入或非二维输入应失败")


def test_continuous_match_length():
    """连续匹配必须在首个不同位置停止。"""
    assert continuous_match_length([4, 5, 6], [4, 5, 9, 8]) == 2
    assert continuous_match_length([4, 5], [9, 5, 8]) == 0
    assert continuous_match_length([4, 5], [4, 5, 8]) == 2


def test_build_mtp_round():
    """中途不匹配使用目标修正,全部匹配使用额外目标 Token。"""
    rejected = build_mtp_round([4, 5, 6], [4, 5, 9, 8])
    assert rejected == {
        "candidate_count": 3,
        "accepted_length": 2,
        "emitted_tokens": [4, 5, 9],
        "all_candidates_accepted": False,
        "first_mismatch": 2,
    }
    accepted = build_mtp_round([4, 5], [4, 5, 8])
    assert accepted["emitted_tokens"] == [4, 5, 8]
    assert accepted["all_candidates_accepted"] is True
    assert accepted["first_mismatch"] is None


test_select_mtp_candidates()
test_continuous_match_length()
test_build_mtp_round()
print("✅ 原生 MTP 候选与贪心验证测试通过")

🛑 STOP HERE 🛑









请先尝试自己完成代码并跑通测试。
如果遇到困难,再向下查看参考代码与解析。










参考代码与解析 ​

代码 ​

python
def _validate_depth_logits(depth_logits: torch.Tensor) -> torch.Tensor:
    """校验 MTP 预测深度与词表维度。"""
    scores = torch.as_tensor(depth_logits)
    if scores.ndim != 2 or scores.shape[0] == 0 or scores.shape[1] == 0:
        raise ValueError("depth_logits 必须是非空二维张量 [depth, vocab]")
    if not torch.isfinite(scores).all():
        raise ValueError("词表分数不能包含 NaN 或 Inf")
    return scores


# ==========================================
# TODO 1:从各预测深度形成有序候选块。
# ==========================================
def select_mtp_candidates(depth_logits: torch.Tensor, max_candidates: int) -> List[int]:
    """按预测深度形成受预算约束的有序候选块。"""
    scores = _validate_depth_logits(depth_logits)
    if not isinstance(max_candidates, int) or isinstance(max_candidates, bool) or max_candidates < 1:
        raise ValueError("max_candidates 必须是正整数")
    candidates = scores.argmax(dim=-1)[:max_candidates].tolist()
    return candidates


# ==========================================
# TODO 2:在首次不匹配位置停止连续接受。
# ==========================================
def continuous_match_length(
    candidates: Sequence[int],
    target_tokens: Sequence[int],
) -> int:
    """返回候选与目标结果从首位置开始连续匹配的长度。"""
    if len(target_tokens) < len(candidates):
        raise ValueError("目标结果必须覆盖所有候选位置")
    accepted_length = 0
    for candidate, target in zip(candidates, target_tokens):
        matches = int(candidate) == int(target)
        if not matches:
            break
        accepted_length += 1
    return accepted_length


# ==========================================
# TODO 3:提交接受前缀,并追加修正或额外目标 Token。
# ==========================================
def build_mtp_round(candidates: Sequence[int], target_tokens: Sequence[int]) -> dict:
    """根据连续匹配边界形成本轮输出和下一轮状态。"""
    if len(target_tokens) != len(candidates) + 1:
        raise ValueError("目标结果必须包含候选位置和一个额外位置")
    accepted_length = continuous_match_length(candidates, target_tokens)
    emitted_tokens = list(candidates[:accepted_length]) + [int(target_tokens[accepted_length])]
    all_candidates_accepted = accepted_length == len(candidates)
    return {
        "candidate_count": len(candidates),
        "accepted_length": accepted_length,
        "emitted_tokens": emitted_tokens,
        "all_candidates_accepted": all_candidates_accepted,
        "first_mismatch": None if all_candidates_accepted else accepted_length,
    }

解析 ​

TODO 1:形成 MTP 候选块 ​

  • 机制: 每个内置预测深度为一个未来位置提供词表分数,按深度顺序选择候选后形成候选块。
  • 不变量: 候选顺序不能重排,数量不得超过预测深度和本轮预算。
  • 测试证据: 测试覆盖正常候选、预算截断、预算大于深度数、空输入和维度错误。

TODO 2:计算连续匹配长度 ​

  • 机制: 从首位置逐个比较 MTP 候选与目标首选 Token,首次不匹配即结束接受前缀。
  • 不变量: 接受结果始终是候选块的连续前缀,后部匹配不能越过前面的不匹配位置。
  • 测试证据: 测试覆盖首位置失败、中途失败和全部匹配。

TODO 3:形成本轮输出 ​

  • 机制: 提交连续接受前缀,再加入目标模型在首个不匹配位置的修正 Token;全部匹配时加入额外目标 Token。
  • 不变量: 每轮只在接受前缀之后加入一个目标 Token,未验证的候选后缀不得进入输出。
  • 测试证据: 测试核对修正路径、全部匹配路径、首个不匹配位置和统一状态字段。

Step 5:GPU 机制实验——原生 MTP 路径 ​

CPU 题目确认内置候选、连续匹配和修正/追加状态;GPU 实验进一步检查模型检查点是否包含原生 MTP 层、后端是否命中对应路径,以及真实模型上的正确性、有效推进、延迟和显存。

学习问题CPU 已确认GPU 要确认
原生 MTP 能否增加每次目标模型调用的有效推进量候选形成、连续匹配和首个不匹配处理同一模型检查点的仅目标模型/MTP-1 是否成功配对,以及输出、接受长度、Median/P95、吞吐和峰值显存

5.1 环境与固定工作负载 ​

本实验使用隔离的 INF-VLLM-MTP 环境。首次运行先完成推理优化实验 Quickstart;已有环境先通过同名 Profile 预检。只有仅目标模型路径完成模型加载、内核初始化、预热和固定输入生成后,才启用 MTP-1。

配置层本节固定口径修改规则
运行环境INF-VLLM-MTP;隔离的 vLLM、PyTorch、CUDA wheel 与 Triton 组合更换驱动、wheel 或 Triton 后使用新运行标签,并先重跑仅目标模型路径
12 GB 配置Qwen/Qwen3.5-0.8B;MTP-1;BF16;批量 1;max_model_len=2048;显存利用率 0.75模型检查点必须包含原生 MTP 层;候选深度不得超过可用层数
24 GB 配置先复用 0.8B 配对,再扩大上下文、并发或重复次数9B BF16 不作为默认配置;更换模型后单独登记工作负载版本
配对变量同一模型检查点的仅目标模型 → MTP-1两条路径共用输入、数据类型、生成长度、随机种子和执行模式
测量方法输出一致性、接受长度、Median/P95、吞吐、峰值显存和失败阶段初始化和下载不计入正式延迟;两条路径分别预热
结果资产benchmarks/results/inf_mtp_<run_label>.json正式复测使用唯一标签;失败结果不得覆盖
python
RUN_MODE = 'real_backend'  # 默认 real_backend;只做配置检查时改为 dry_run。
RUN_LABEL = 'rtx5070ti_qwen35_08b_mtp1_v4'  # 默认不覆盖实测结果;真实复测改为唯一标签。
PROFILE_ID = 'INF-VLLM-MTP'  # 原生 MTP 使用独立 vLLM 环境。
SEMANTIC_ID = 'INF-MTP'  # 稳定机制身份。
WORKLOAD_ID = 'inf-native-mtp-qwen35-08b'  # 稳定工作负载身份。
WORKLOAD_VERSION = 'v2'  # v2 固定原生 MTP-1 与隔离 worker 配对协议。
MODEL_ID = 'Qwen/Qwen3.5-0.8B'  # 默认原生 MTP 小模型。
MODEL_REVISION = 'main'  # 运行时自动解析并记录不可变 commit。
DTYPE = 'bfloat16'  # baseline 与 candidate 共用 BF16。
MAX_NEW_TOKENS = 64  # 每条提示固定生成 64 Token。
MAX_MODEL_LEN = 2048  # 单卡机制实验只保留短上下文容量。
GPU_MEMORY_UTILIZATION = 0.75  # 为 Notebook 与 backend 保留显存余量。
ENFORCE_EAGER = False  # 两条路径共用 vLLM 默认编译/CUDA Graph 路径。
WARMUP_STEPS = 2  # 每条路径独立预热 2 次。
REPEAT_STEPS = 5  # 每条路径正式重复 5 次。
SPECULATIVE_TOKENS = 1  # checkpoint 只有一个原生 MTP 层。
SEED = 42  # 固定贪心生成与 backend 随机状态。
PROMPTS = [
    'Explain why speculative decoding can reduce latency in two concise paragraphs.',
    'Write a Python function that checks whether a string is a palindrome, then explain its complexity.',
    'A shop applies a 20 percent discount and then a 10 percent tax. Explain the final price for an item costing 100 dollars.',
]
OUTPUT_RELATIVE_PATH = f'benchmarks/results/inf_mtp_{RUN_LABEL}.json'

5.2 执行真实后端配对并保存 JSON ​

本单元先检查模型配置中的原生 MTP 层,再用两个独立子进程顺序执行 target-only 与 MTP-1。初始化和模型下载不计入正式延迟;两条路径分别预热后才采集结果。

python
import importlib
from tools.project_runtime import resolve_project_root
import tools.mtp_mechanism_runtime as mtp_runtime

mtp_runtime = importlib.reload(mtp_runtime)
RESULT_PATH = resolve_project_root() / OUTPUT_RELATIVE_PATH
GPU_REPORT = mtp_runtime.run_native_mtp_benchmark(
    semantic_id=SEMANTIC_ID, profile_id=PROFILE_ID, run_mode=RUN_MODE, run_label=RUN_LABEL,
    workload_id=WORKLOAD_ID, workload_version=WORKLOAD_VERSION,
    model_id=MODEL_ID, model_revision=MODEL_REVISION, dtype=DTYPE, prompts=PROMPTS,
    max_new_tokens=MAX_NEW_TOKENS, max_model_len=MAX_MODEL_LEN,
    gpu_memory_utilization=GPU_MEMORY_UTILIZATION, enforce_eager=ENFORCE_EAGER,
    warmup_steps=WARMUP_STEPS, repeat_steps=REPEAT_STEPS,
    speculative_tokens=SPECULATIVE_TOKENS, seed=SEED, output_path=RESULT_PATH,
)
GPU_REPORT

5.3 读取结果 ​

读取固定身份、模型契约、两条路径和配对比较。failure 非空时先处理环境、模型或执行后端,不解释性能字段。

python
import json
from pathlib import Path

report = json.loads(Path(RESULT_PATH).read_text(encoding='utf-8'))
{
    'semantic_id': report.get('semantic_id'),
    'workload': report.get('workload'),
    'model_contract': report.get('model_contract'),
    'comparison': report.get('comparison'),
    'failure': report.get('failure'),
    'evidence_level': report.get('evidence_level'),
    'decision': report.get('decision'),
}

5.4 解释结果并作出决策 ​

当前默认标签 rtx5070ti_qwen35_08b_mtp1_v4 的原始报告在专用后端构建检查阶段停止:运行环境未满足要求的 vLLM 0.31.0 CUDA 12.9 构建。本次尚未完成模型契约检查,也没有生成 target-only / MTP-1 配对结果。

使用 INF-VLLM-MTP 通过预检后,以新标签先运行 target-only,确认模型加载、初始化、预热和固定输出生成均成功,再比较 MTP-1。不同标签的失败阶段与历史记录分别保留。

观察项读取字段当前结果解释与动作
后端构建failure专用 vLLM CUDA 构建门禁失败核对解释器与 Profile,不用其他构建替代
模型契约model_contract本次为 null环境通过后重新读取模型配置与不可变版本
正确性与推进comparison、接受统计未产生target-only 完成后生成配对证据
性能与资源Median/P95、吞吐、峰值显存未产生启动门禁失败不能用于推断性能或显存容量
证据与决策evidence_level、decisionfailed_real_backend_attempt;reject_until_fixed修复环境后新标签复测

相关阅读 ​

Released under the MIT License.