自回归解码与采样
自回归生成先处理 prompt,再逐 token 预测下一个 token;temperature/top-p 决定如何从 logits 取样,KV Cache 避免每一步重复计算整个前缀。
Prefill
Section titled “Prefill”一次处理完整 prompt,产生首个 next-token logits,并把每层 K/V 写入 KV Cache。计算量主要来自 prompt 长度上的矩阵运算与 attention。
Decode
Section titled “Decode”之后每步只输入新 token,读取历史 cache,输出一个新 token 并把其 K/V 追加到缓存。循环直到 EOS、最大长度或其他停止条件。
prompt → prefill → token₁ → decode → token₂ → ... → EOS从 logits 到 token
Section titled “从 logits 到 token”给定 logits :
Temperature
Section titled “Temperature”
使分布更尖锐, 更平; 通常退化为近似 greedy。实现中应避免直接除以 0。
Top-p(nucleus)
Section titled “Top-p(nucleus)”按概率从高到低排序,保留累计概率达到 的最小 token 集合,重新归一化后采样。候选数量随当前分布变化,不等同固定 top-k。
Greedy / sampling
Section titled “Greedy / sampling”- greedy 每步取 argmax,确定性较强;
- sampling 按过滤后的概率抽样,需要显式启用采样并管理随机种子;
- 设置了 temperature/top-p 不代表框架一定会使用,仍要检查
do_sample或实现分支。
Batch 中的结束状态
Section titled “Batch 中的结束状态”不同样本可能在不同步生成 EOS。实现通常维护 finished mask:已结束样本不再产生有效 token,但 batch 循环可能继续服务尚未结束的样本。最终输出需要去掉 prompt padding、无效尾部和特殊 token。
Llama 课程代码链路
Section titled “Llama 课程代码链路”第 15 讲区分 text completion 与 chat completion 输入;第 20 讲解释 cache 的 start_pos;第 22 讲走读完整 generate:
- tokenizer 编码并 padding;
- 按最短 prompt 长度初始化生成位置;
- 前向并读取 logits;
- temperature/top-p 或 argmax 选 token;
- 保留原 prompt token,写入新 token;
- 更新 EOS mask;
- decode 为文本。
可复现性与边界
Section titled “可复现性与边界”- 随机种子只在算法、kernel 和采样调用顺序一致时提供可比结果。
- temperature/top-p 影响多样性,不保证事实性或质量单调变化。
- KV Cache 提高 decode 效率但占随序列长度增长的内存。
- chat template 是 tokenizer/模型配套协议,不应把普通 prompt 列表直接视为通用聊天格式。