跳到内容

后缀解码

以下代码配置 vLLM 使用投机采样(Speculative Decoding),其中草稿由“后缀解码”(技术报告)生成。

与 n-gram 类似,后缀解码可以通过匹配最后 n 个生成的 token 来生成草稿 token。但与 n-gram 不同的是,后缀解码 (1) 可以针对提示词(prompt)和之前的生成内容进行模式匹配;(2) 利用频率计数来提出最可能的后续内容;(3) 在每次迭代中为每个请求推测自适应数量的 token,从而获得更高的接受率。

对于具有高度重复性的任务,例如代码编辑、智能体循环(如自我反思、自我一致性)和强化学习(RL)展开,后缀解码可以实现更好的性能。

安装 Arctic Inference

后缀解码需要 Arctic Inference。你可以通过 pip install arctic-inference 进行安装。

后缀解码投机 token

后缀解码会在每个解码步骤中为每个请求推测动态数量的 token,因此 num_speculative_tokens 配置指定的是投机 token 的最大数量。建议使用较大的数值,例如 1632(默认值)。

from vllm import LLM, SamplingParams

prompts = ["The future of AI is"]
sampling_params = SamplingParams(temperature=0.8, top_p=0.95)

llm = LLM(
    model="Qwen/Qwen3-8B",
    tensor_parallel_size=1,
    speculative_config={
        "method": "suffix",
        "num_speculative_tokens": 32,
    },
)
outputs = llm.generate(prompts, sampling_params)

for output in outputs:
    prompt = output.prompt
    generated_text = output.outputs[0].text
    print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")