使用 Hugging Face Transformers 的 Gemma 4 多令牌预测 (MTP)

在 ai.google.dev 上查看 在 Google Colab 中运行 在 Kaggle 中运行 在 Vertex AI 中打开 在 GitHub 上查看源代码

为了提高 Gemma 4 模型的推理速度,我们发布了一系列新的自回归“起草”模型,与主要产品阵容一同推出。草稿模型不会仅依赖于主要的 Gemma 4 模型(称为“目标”模型),而是以目标模型处理一个 token 所需的时间,自回归地预测多个 token。这种技术也称为推测性解码。

起草模型预测多个草稿 token 后,目标模型现在只需验证这些建议的草稿 token。验证是并行完成的,从而大幅加快了推理速度。这样可以减少目标模型必须为每个 token 执行的前向传递次数。由于我们的起草器会生成一系列用于验证的令牌,因此我们将其称为“多令牌预测 (MTP) 头”。

png

为 Gemma 4 系列发布的草稿模型体积较小,并引入了多项增强功能,以提高草稿令牌的质量并进一步加快推理速度,例如使用目标模型激活和 KV 缓存来获得更好的预测结果。

这些增强功能可显著提高解码速度,同时保证相似的质量,使这些检查点非常适合低延迟和设备端应用。

安装 Python 软件包

安装运行 Gemma 4 和 Gemma 4 助理模型所需的 Hugging Face 库。

# Install PyTorch & other libraries
pip install torch accelerate

# Install the transformers library
pip install transformers

加载模型

对于每个目标模型(Gemma 4 模型中的主要模型之一),都有一个助理来帮助加快推理速度。因此,您将加载两个模型:

  • 目标(例如 google/gemma-4-E2B-it):完整的 Gemma 4 目标模型
  • Drafter(例如 google/gemma-4-E2B-it-assistant):轻量级 4 层 MTP drafter,用于提出候选 token

请注意,起草者通常被称为助理,因为该模型可帮助更大的模型选择要预测哪些 token。

使用 transformers 库,通过 AutoProcessor 和 AutoModelForCausalLM 类创建 processor 和 model 的实例,如以下代码示例所示:

TARGET_MODEL_ID = "google/gemma-4-E2B-it" # @param ["google/gemma-4-E2B-it", "google/gemma-4-E4B-it", "google/gemma-4-12B-it", "google/gemma-4-31B-it", "google/gemma-4-26B-A4B-it"]
ASSISTANT_MODEL_ID = TARGET_MODEL_ID + "-assistant"
import torch
from transformers import AutoProcessor, AutoModelForCausalLM

# Target Model
processor = AutoProcessor.from_pretrained(TARGET_MODEL_ID)
target_model = AutoModelForCausalLM.from_pretrained(
    TARGET_MODEL_ID,
    torch_dtype=torch.bfloat16,
    device_map="auto",
)

# Assistant Model (the drafter)
assistant_model = AutoModelForCausalLM.from_pretrained(
    ASSISTANT_MODEL_ID,
    torch_dtype=torch.bfloat16,
    device_map="auto",
)
[transformers] `torch_dtype` is deprecated! Use `dtype` instead!
Loading weights:   0%|          | 0/1951 [00:00<?, ?it/s]
Loading weights:   0%|          | 0/50 [00:00<?, ?it/s]

搭配 Google 助理的 Gemma 4

幸运的是,在 transformers 中使用助理非常简单,只需将助理模型传递给 model.generate 函数即可:

# Process inputs with the `target_model`
messages = [
    {
        "role": "user",
        "content": "Explain the concepts of speculative decoding and MTP in 3 sentences."
    }
]
input_text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = processor(text=input_text, return_tensors="pt").to(target_model.device)

# `assistant_model=assistant_model` is all you need to enable MTP!
outputs = target_model.generate(
    **inputs,
    assistant_model=assistant_model,
    max_new_tokens=256,
    do_sample=False,
)

# Decode the response into text
response = processor.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
print(response)
**Speculative decoding** is a technique where a smaller, faster language model (the "draft model") generates several candidate tokens, which are then quickly verified by a larger, more accurate model to produce a final, high-quality output much faster than decoding the large model alone. **MTP (Multi-Task Prediction)** involves training a single model to perform multiple related tasks simultaneously, allowing it to leverage shared knowledge across different objectives. Together, these methods aim to significantly accelerate the inference speed of large language models while maintaining or improving output quality.

在后台,该流程如下所示:

  • 起草器提出以自回归方式生成的 N 个 token
  • 目标模型可在一次正向传递中验证所有 N 个令牌
  • 接受概率较高的草稿词元
  • 拒绝概率较低的草稿令牌
  • 由于目标模型会进行前向传递,因此无论接受或拒绝了多少草稿令牌,它始终会自行生成 1 个令牌

草稿令牌

起草者可以生成任意数量的 token 以供目标模型验证。不过,目标模型仍然可以选择拒绝某些令牌。如果遇到,则忽略之后的所有令牌。

png

因此,在为草稿令牌数量使用各种值时,了解权衡取舍非常重要。

更多草稿 token

如果您生成了许多令牌(例如 15 个),那么很可能并非所有令牌都会被接受。因此,浪费计算资源的风险更高。相比之下,当接受率较高时,它确实有加快推理的趋势。

png

更少的草稿 token

当您起草的 token 数量较少时,接受率往往会更高,因为位置更接近初始提示的 token 会更准确。不过,由于仅起草了少量 token,因此更快的起草模型带来的速度提升会减少。

png

幸运的是,您无需在 transformers 中尝试最适合您应用场景的值,因为您可以将 num_assistant_tokens_schedule 设置为“启发式”,这样系统会在运行时自动调整草稿 token 的数量:

  • 接受所有 token - 将用于起草的 token 数量增加 2,因为起草器对提示的理解非常准确。如果草稿中的 token 也被接受,增加草稿中的 token 数量可能会加快速度。
  • 有任何 token 被拒绝 - 如果有任何 token 被拒绝,则将要生成草稿的 token 数量减少 1。减少令牌数量可避免在目标模型继续拒绝大多数令牌的情况下浪费过多草稿。

同样,您可以通过更新 drafter 中的 num_assistant_tokens 来更新草稿令牌的数量,如下所示:

# Update how many draft tokens are generated at the start of inference
assistant_model.generation_config.num_assistant_tokens = 4

# Update how the number of draft tokens are updated ("heuristic" for a dynamic schedule and "constant" for a constant schedule)
assistant_model.generation_config.num_assistant_tokens_schedule = "heuristic"

# Run with MTP
outputs = target_model.generate(
    **inputs,
    assistant_model=assistant_model,
    max_new_tokens=256,
    do_sample=False,
)

# Decode the response into text
response = processor.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
print(response)
**Speculative decoding** is a technique where a smaller, faster language model (the "draft model") generates several candidate tokens, which are then verified by a larger, more accurate model to quickly produce a high-quality output. **MTP (Multi-Task Prediction)** involves training a single model to perform multiple related tasks simultaneously, allowing it to leverage shared knowledge across different objectives. Together, these methods aim to significantly speed up the inference process of large language models while maintaining or improving output quality.