自回归采样机制:贪心解码与温度缩放 (Temperature)
Agent 辅助工程分析
前置要求
第 48 日 Decoder-Only 前向传播与第 41 日 Softmax 基础。
学习目标
建立下一词预测分布公式 p_i = softmax(z_i / T),阐明温度 T 如何精确调控输出分布的信息熵。
操作指引
给定 logits z = [2.0, 1.0, 0.0]:(1) 贪心解码取 argmax 为索引 0;(2) T=1.0 时概率为 [0.665, 0.245, 0.090];(3) 计算 T=0.5 下的概率 p = [0.867, 0.117, 0.016];(4) 证明 T->0 退化为贪心 argmax,T->inf 趋于均匀分布。
自主演练与记录
1. 计算 z = [2.0, 1.0, 0.0] 在 T=2.0 时的 Softmax 概率分布。
2. 为什么过低的温度(如 T=0.2)在减少幻觉的同时更容易导致复读机式死循环?
3. 若在代码中直接传入 T=0.0 进行 z / T 计算,会抛出什么运行时异常?
z / 2.0 = [1.0, 0.5, 0.0]。exp([1, 0.5, 0]) = [2.718, 1.649, 1.0],总和为 5.367。
T=2.0 时概率为 [0.506, 0.307, 0.186]。低温将概率质量过度压缩在单一最高 Logit 上,极大降低了探索多样性,遇到局部极大值时陷入重复循环。T=0.0 会直接引发 ZeroDivisionError,工程实现中必须特殊判断并将 T=0 路由至 torch.argmax。
能准确手算温度缩放分布,深入解释创造性与死循环之间的博弈平衡。
权威源资源与权利证明
The Curious Case of Neural Text Degeneration
对应章节 / 时间戳: Section 2.1 Text Generation Decoding Strategies and Section 3.3 Sampling with Temperature
验证版本与日期: ICLR 2020 / arXiv:1904.09751v2 (Verified: 2026-10-30)
Primary source introducing Nucleus (Top-p) sampling and analyzing the failure of greedy decoding (loops, repetition).
Softmax probabilities, cumulative probability distributions from Days 25-27 and 41-42.
Top-p truncation algorithms and worked probability cutoffs are completely explained in the lesson.
对比候选资源与选型分析 (2)
Introduces top-k sampling; Holtzman et al. dynamic nucleus threshold is compared directly against top-k.
Practical library guide; Holtzman provides the foundational mathematical reasoning.
nanoGPT: sample.py autoregressive generation script
对应章节 / 时间戳: sample.py: temperature and top_k settings passed to model.generate (model.py: GPT.generate)
验证版本与日期: Git master (Verified: 2026-10-30)
Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.
PyTorch inference, torch.multinomial, and Day 48 decoder-only forward pass.
The generation loop is implemented in runnable local scripts.
对比候选资源与选型分析 (2)
C++ implementation with high performance; nanoGPT is readable Python matched to our curriculum.
Encoder-decoder model; nanoGPT decoder-only autoregressive loop is the direct fit for modern LLMs.