data = d2l.TimeMachine(batch_size=1024, num_steps=32)8.6 解码与文本生成
本章迄今为止仅按语言模型为下一个词元分配概率的准确程度来评判它。然而要生成文本,模型还必须在每一步从预测分布中选出一个具体词元——这一选择的重要性远超直觉,因为不同的选择规则会让完全相同的模型写出截然不同的文本。在 8.4.2 节 中我们已经看到最简单规则的短板:每步贪心挑选概率最高的单个词元会迅速把生成器困在重复循环里。那么,究竟该如何把下一词元分布转化为流畅文本?
将一连串下一词元分布转化为输出词元的算法称为解码(decoding)(Graves 2013年; Holtzman 等 2020年),解码策略大致分为两大流派:最大化算法搜索在模型下联合概率高的输出序列;采样算法则先重塑或裁剪分布中不可靠的尾部,再随机抽取每个词元。下文将依次展开并对比两大流派。关键在于,每条解码规则仅通过下一词元分布与语言模型交互,因此本节构建的算法无需修改即可适用于任何自回归语言模型——无论是 RNN、状态空间模型还是 Transformer。
8.6.1 解码问题
训练好的语言模型提供下一词元条件分布:给定任意前缀 \(x_{<t} = x_1, \ldots, x_{t-1}\),它输出 \(P(x_t \mid x_{<t})\);由概率链式法则(8.1 节),这些条件分布通过 \(P(x_1, \ldots, x_T) = \prod_{t=1}^{T} P(x_t \mid x_{<t})\) 定义了任意完整序列的联合概率。
解码提出的是逆问题:给定这些条件分布,我们应输出哪条序列?乍看之下,找出最可能的序列似乎是显而易见的目标,但精确最大化完全不可行。在词表 \(\mathcal{V}\) 与视界 \(T\) 上共有 \(|\mathcal{V}|^T\) 种可能续写——对 1,027 词表与 50 词元续写而言,候选数高达 \(1027^{50} > 10^{150}\),远远超出任何穷举能力。因此,每个实用解码器都只能探索搜索树中的极小切片,每步决定保留哪些前缀。
即便精确搜索可行,概率最高的单条序列也往往并非我们想要的。当任务只允许极窄范围的正确答案(如语音转写或技术文档翻译)时,寻找高概率序列非常有效。相反,当许多续写都同样合理时(如对话或创意写作),校准良好的模型会把概率质量分散在许多可行轨迹上,单条续写本身必然只占极小概率。强迫模型走概率最高的唯一路径会扼杀这种自然多样性,而采样通过直接从学得的分布抽取,保留了这种多样性。
图 8.6.1 沿这一分界线梳理了各类解码策略。最大化方法(贪心解码与束搜索)仍是输出空间受限任务的标准选择,而结合温度缩放或截断的采样方法则是开放式生成的默认选择。
8.6.1.1 用于解码的模型
本节实验采用 8.4.6 节 中的简洁 RNN 语言模型:512 维嵌入、128 个隐藏单元、嵌入与隐藏状态均加暂退法,输出层覆盖《时间机器》的 1,027 个 BPE 词元。先从 d2l.TimeMachine 加载 32 词元训练与验证窗口。
接着以 \(d = 512\)、\(h = 128\)、暂退法及学习率 lr=4 构建简洁循环单元 d2l.RNN 与语言模型 d2l.RNNLM。
rnn = d2l.RNN(num_inputs=512, num_hiddens=128)
model = d2l.RNNLM(rnn, vocab_size=len(data.vocab), lr=4, dropout=0.5,
emb_dropout=0.1)with d2l.try_gpu():
rnn = d2l.RNN(num_inputs=512, num_hiddens=128)
model = d2l.RNNLM(rnn, vocab_size=len(data.vocab), lr=4, dropout=0.5,
emb_dropout=0.1)rnn = d2l.RNN(num_inputs=512, num_hiddens=128)
model = d2l.RNNLM(rnn, vocab_size=len(data.vocab), lr=4, dropout=0.5,
emb_dropout=0.1)rnn = d2l.RNN(num_inputs=512, num_hiddens=128)
model = d2l.RNNLM(rnn, vocab_size=len(data.vocab), lr=4, dropout=0.5,
emb_dropout=0.1)在 gradient_clip_val=1 的梯度裁剪下训练 model 10 轮,在《时间机器》上复现约 60 的验证困惑度。
trainer = d2l.Trainer(max_epochs=10, gradient_clip_val=1, num_gpus=1)
trainer.fit(model, data)
print(f'validation perplexity {math.exp(trainer.history["val_loss"][-1]):.1f}')validation perplexity 58.7
validation perplexity 58.6
validation perplexity 59.7
validation perplexity 59.1
本节的每个解码算法都通过同一个与模型无关的接口 step_fn(ids) 访问语言模型:传入迄今的前缀词元编号,返回一个一维 NumPy 向量表示下一词元对数几率。返回普通 NumPy 数组让我们能在四个框架上只写一套解码代码,且刻意省略显式隐藏状态:任何自回归模型(循环网络或 Transformer)都满足这一签名。
model.eval() # Dropout off
def seq_logits(ids): # Token ids in, NumPy logits at every position out
with torch.inference_mode():
logits = model(d2l.tensor([ids], device=d2l.try_gpu()))
return d2l.numpy(logits)[0]
def step_fn(ids): # Token ids in, NumPy logits for the next token out
return seq_logits(ids)[-1]forward = tf.function(lambda X: model(X, training=False), jit_compile=True)
def seq_logits(ids): # Token ids in, NumPy logits at every position out
padded = ids + [0] * (-len(ids) % 32) # Few distinct lengths to compile
logits = forward(tf.constant([padded], dtype=tf.int32))
return d2l.numpy(logits)[0, :len(ids)]
def step_fn(ids): # Token ids in, NumPy logits for the next token out
return seq_logits(ids)[-1]@nnx.jit
def forward(model, X):
return model(X)
model_eval = nnx.view(model, deterministic=True, raise_if_not_found=False)
def seq_logits(ids): # Token ids in, NumPy logits at every position out
padded = ids + [0] * (-len(ids) % 32) # Few distinct lengths to compile
logits = forward(model_eval, d2l.tensor([padded])) # Dropout off
return d2l.numpy(logits)[0, :len(ids)]
def step_fn(ids): # Token ids in, NumPy logits for the next token out
return seq_logits(ids)[-1]def seq_logits(ids): # Token ids in, NumPy logits at every position out
return d2l.numpy(model(d2l.tensor([ids], ctx=d2l.try_gpu())))[0]
def step_fn(ids): # Token ids in, NumPy logits for the next token out
return seq_logits(ids)[-1]带 jit_compile=True 的 tf.function 会用 XLA 按输入形状分别编译前向传播,因此我们将每个前缀补零至 32 的倍数,只需编译寥寥几种形状。网络从左到右读取序列,补零不会改变最后一个真实位置(即我们读取的位置)的对数几率。
nnx.jit 按输入形状分别编译前向传播,因此我们将每个前缀补零至 32 的倍数,只需编译寥寥几种形状。网络从左到右读取序列,补零不会改变最后一个真实位置(即我们读取的位置)的对数几率。
这一设计的代价是效率:每次调用都为提取单个对数几率向量而重跑整个前缀。对 RNN 而言这笔额外开销本可避免,我们在本节末尾将回到计算成本问题。
8.6.2 贪心解码
最简单的解码器在每一步都锁定条件概率最高的单个词元:
\[x_t = \operatorname*{argmax}_{x \in \mathcal{V}} P(x \mid x_{<t}). \tag{8.6.1}\]
为前缀打分、取 argmax、追加到末尾、不断重复。贪心解码每生成一个词元只需一次模型评估,且完全确定——相同前缀总是产出完全相同的续写。下面的辅助函数 show 将词元编号解码为带引号字符串,把换行显示为 \n,并将不可打印字节替换为 U+FFFD。
def show(ids): # Decoded text as a literal; control characters -> U+FFFD
text = data.tokenizer.decode(ids)
return repr(''.join(c if c.isprintable() or c == '\n' else '\ufffd'
for c in text))
def decode_greedy(text, num_tokens=50):
ids = data.tokenizer.encode(text)
for _ in range(num_tokens):
ids.append(int(step_fn(ids).argmax()))
return ids
for text in ('The Time Traveller', 'It seemed to me that'):
d2l.print_wrapped(show(decode_greedy(text)))"The Time Traveller.\n\n'I had\nfrom the\nsidea.\n\n'I had\nfrom
the\nsidea.\n\n'I had\nfrom the\nsidea.\n\n'I had\nf"
"It seemed to me that\ntheir.\n\n'I had\nfrom the\nsidea.\n\n'I had\nfrom
the\nsidea.\n\n'I had\nfrom the\nsidea.\n\n'I"
'The Time Traveller, and the silent. I had a\ndimension. I was a faintness
of the\nshamination. I was a faintness of the\nshamination. I was a f'
'It seemed to me that the Time Traveller. I was a faintness of
the\nshamination. I was a faintness of the\nshamination. I was a
faintness of the\nshamination. I'
'The Time Traveller. I was a vastly. I was a vastly. I was a vastly. I was a
vastly. I was a vastly. I was a vastly. I was a vastly.'
"It seemed to me that the Time Traveller. 'I'I think I was a champ.
The\nday. The\nday. The\nday. The\nday. The\nday. The\nday. The\nd"
'The Time Traveller, and the\nday. I was a little\ndoors, and the\nday. I
was a little\ndoors, and the\nday. I was a little\ndoors, and'
'It seemed to me that the pathy, and the\nday. I was a little\ndoors, and
the\nday. I was a little\ndoors, and the\nday. I was a little\nd'
与 8.4.2 节 如出一辙,两条续写都迅速坍缩进重复循环。贪心解码内建了两大结构弱点。其一是短视(myopia):串联局部最优选择未必得到全局最优序列。设模型赋予首词元概率 \(P(A) = 0.5\)、\(P(B) = 0.4\),接着 \(A\) 之后的第二步很不确定(最高续写概率 \(0.3\)),而 \(B\) 之后的第二步高度确定(最高概率 \(0.9\))。贪心解码立刻锁定 \(A\),最终仅得联合概率 \(0.5 \times 0.3 = 0.15\),错过了以 \(B\) 开头、概率高达 \(0.4 \times 0.9 = 0.36\) 的序列(图 8.6.2)。
第二个弱点正是重复本身。由于贪心解码每步都将确定性 argmax 回馈到递推中,下一隐藏状态是当前状态的确定性函数;一旦轨迹落入吸引环,就没有任何随机性将其推离。这绝非小型 RNN 的特例:Holtzman 等 (2020年) 在规模大一千倍的语言模型上同样观察到了这种神经文本退化(neural text degeneration),表明在开放式文本上最大化似然总是产出单调重复、与人类写作迥异的文字。
8.6.3 束搜索
贪心解码立刻锁定单一路径,穷举搜索保留所有可能路径,而束搜索(beam search)通过单个超参数——束宽 \(w\)——在两者之间取得可控折中。每一步,束搜索保留得分最高的 \(w\) 条前缀。从概率最高的 \(w\) 个首词元出发,随后每步将每条存活前缀沿整个词表展开,按累积对数概率给全部 \(w \cdot |\mathcal{V}|\) 条候选扩展打分,再剪枝回前 \(w\) 条序列。取 \(w = 1\) 即退化为贪心解码;当 \(w\) 大到不再剪除任何候选时,则退化为穷举搜索。
图 8.6.3 展示了五词元词表 \(\mathcal{V} = \{A, B, C, D, E\}\) 上束宽 \(w = 2\) 的三步束搜索(记号中省略共享提示)。设 \(A\) 与 \(C\) 为概率最高的两个首词元。在第 2 步,我们为全部十条扩展 \(x' \in \mathcal{V}\) 打分:
\[ \begin{aligned} P(A, x') &= P(A)\, P(x' \mid A),\\ P(C, x') &= P(C)\, P(x' \mid C), \end{aligned} \]
保留得分最高的两条(比如 \(AB\) 与 \(CE\)),在第 3 步重复同样展开,保留 \(ABD\) 与 \(CED\)。束搜索无需评估全部 \(5^3 = 125\) 条序列,而只评估 \(5 + 10 + 10 = 25\) 条。一般而言,生成 \(T\) 个词元的开销为 \(O(w |\mathcal{V}| T)\)——仅为贪心解码的 \(w\) 倍,比穷举搜索呈指数级低廉。
当序列允许通过输出序列结束词元提前终止时,比较不同长度的候选需要长度校正。由于每个词元的对数概率均非正,原始累积对数概率随序列变长单调递减,不公平地偏袒较短假设。标准修正是长度规范化(length normalization)(Wu 等 2016年):对在长度 \(t_0\) 的前缀后追加 \(T\) 个词元的候选,按以下公式打分
\[\frac{1}{T^\beta} \sum_{t=t_0+1}^{t_0+T} \log P(x_t \mid x_{<t}), \tag{8.6.2}\]
其中指数 \(\beta\)(通常取约 \(0.75\))在未规范化对数概率(\(\beta = 0\))与逐词元平均对数概率(\(\beta = 1\))之间插值;下文代码沿用 Wu 等 (2016年) 将该参数命名为 alpha。
下面的 beam_search 实现原样保留已完成假设(以 eos_id 结尾),仅展开活跃束。注意一处简洁优化:总排名前 \(w\) 的候选至多包含同一前缀的 \(w\) 条扩展,因此每条活跃束只需取前 \(w\) 个下一词元,无需对全部 \(|\mathcal{V}|\) 条扩展排序。
def beam_search(step_fn, prefix, num_tokens, beam_size=4,
alpha=0.75, eos_id=None):
"""Length-normalized beam search (score = log P / len^alpha).
Returns candidates sorted best-first; [0][1] is the argmax sequence."""
def log_softmax(logits):
logits = [float(l) for l in logits]
m = max(logits)
lse = m + math.log(sum(math.exp(l - m) for l in logits))
return [l - lse for l in logits]
score = lambda logp, ids: logp / max(1, len(ids) - len(prefix))**alpha
beams = [(0.0, list(prefix), False)] # (log-prob, sequence, finished)
for _ in range(num_tokens):
if all(done for _, _, done in beams):
break
candidates = [b for b in beams if b[2]] # Finished pass through
for logp, ids, _ in (b for b in beams if not b[2]):
logprobs = log_softmax(step_fn(ids))
best = sorted(range(len(logprobs)),
key=lambda i: -logprobs[i])[:beam_size]
candidates += [(logp + logprobs[i], ids + [i], i == eos_id)
for i in best]
beams = sorted(candidates, key=lambda b: score(b[0], b[1]),
reverse=True)[:beam_size]
return sorted([(score(logp, ids), ids) for logp, ids, _ in beams],
reverse=True)下面分别取 \(w = 1\)(复现贪心解码)和 \(w = 4\) 解码相同的两条提示,打印榜首假设的长度规范化得分 式 8.6.2。由于本语料不含序列结束词元,所有候选长度均为 30,常数分母 \(30^{0.75} \approx 12.8\) 不改变它们的相对排序。
for text in ('The Time Traveller', 'It seemed to me that'):
prefix = data.tokenizer.encode(text)
for w in (1, 4):
score, ids = beam_search(step_fn, prefix, 30, beam_size=w)[0]
d2l.print_wrapped(f'w={w}, score {score:.2f}: {show(ids)}')w=1, score -4.13: "The Time Traveller.\n\n'I had\nfrom the\nsidea.\n\n'I
had\nfrom the\nsidea.\n"
w=4, score -3.43: "The Time Traveller.\n\n'Then I had\ndeliculture.\n\n'Then
I had\ndeliculture.\n"
w=1, score -4.21: "It seemed to me that\ntheir.\n\n'I had\nfrom
the\nsidea.\n\n'I had\nfrom the\nside"
w=4, score -3.60: "It seemed to me that it was a\npossibly.\n\n'As I saw
a\npossibly.\n\n'As"
w=1, score -4.75: 'The Time Traveller, and the silent. I had a\ndimension. I
was a faintness of the\nshamination'
w=4, score -4.08: 'The Time Traveller, and I could see no doubt, and I could
see no doubt, and I could see no signs of the'
w=1, score -4.79: 'It seemed to me that the Time Traveller. I was a
faintness of the\nshamination. I was a faintness of the\nsha'
w=4, score -4.01: 'It seemed to me that the Time Traveller, and I could see
no doubt, and I could see no doubt, and I could see no doubt'
w=1, score -5.46: 'The Time Traveller. I was a vastly. I was a vastly. I was
a vastly. I was a vastly. I'
w=4, score -4.19: "The Time Traveller.\n\n'What is the slopes of the
preason. I felt assured to me.\n\n'"
w=1, score -5.09: "It seemed to me that the Time Traveller. 'I'I think I was
a champ. The\nday. The\nday. The\nd"
w=4, score -4.22: "It seemed to me that the Time Traveller.\n\n'What is the
slopes of the preason. I felt assured to me."
w=1, score -5.06: 'The Time Traveller, and the\nday. I was a little\ndoors,
and the\nday. I was a little\ndo'
w=4, score -3.94: 'The Time Traveller, and the little people, and the little
people, and the little people, and the little people, and the little
people, and the little people'
w=1, score -4.85: 'It seemed to me that the pathy, and the\nday. I was a
little\ndoors, and the\nday. I was'
w=4, score -4.03: 'It seemed to me that the patient, and the little people,
and the little people, and the little people, and the little people, and
the little people'
拓宽束宽通常能找到比贪心解码概率更高的续写——但并非必然,因为近似剪枝仍可能扔掉后来居上的前缀。然而更高概率并不自动等同于更好的文字:在开放式生成上,大语言模型的束搜索产出的文本比人类写作明显更具重复性 (Holtzman 等 2020年),下文将量化这一反差。相反,在语音识别和机器翻译等强约束任务上,中等束宽(通常 4 至 10)的束搜索仍是标准解码器 (Sutskever 等 2014年; Wu 等 2016年)。
8.6.4 采样
如果模型已经学到了合理的续写分布,替代最大化的最自然选择就是直接祖先采样:按 \(x_t \sim P(x_t \mid x_{<t})\) 抽取词元、追加到末尾并重复。采样恢复了最大化所扼杀的丰富多样性,但原始采样直接撞上了尾部问题。由于 softmax 会给词表中的每个词元都分配非零概率(此处上千个词元,现代 LLM 超过十万个),数千个离谱词元上的微小概率合起来在每一步都占据可观的总质量。于是纯采样经常抽中极其荒谬的词元,而将其回馈作为上下文会带偏整段后续文本——正是 8.1 节 讨论的推演误差滚雪球效应。Holtzman 等 (2020年) 称之为不可靠尾部(unreliable tail):语言模型的概率在分布头部校准良好,但在遥远尾部充满噪声。实用对策是在采样前重塑或截断分布,四种广泛使用的控制手段以不同方式实现这一目标。
温度缩放(temperature scaling)在 softmax 之前将每个对数几率 \(o_x\) 除以正标量 \(\tau > 0\):
\[P_\tau(x \mid x_{<t}) = \frac{\exp(o_x / \tau)}{\sum_{x' \in \mathcal{V}} \exp(o_{x'} / \tau)} \propto P(x \mid x_{<t})^{1/\tau}. \tag{8.6.3}\]
将 \(\tau\) 降至 1 以下会锐化分布(\(\tau \to 0\) 时收敛到贪心解码),将 \(\tau\) 升至 1 以上则将其拉平趋向均匀分布。不过,温度对整个分布做统一重缩放,属于钝器:把 softmax 降温到足以压制不可靠尾部时,往往也同时压扁了合理头部词元之间的正常多样性。
Top-\(k\) 采样按排名截断,仅保留概率最高的 \(k\) 个词元,重新归一化后采样 (Fan 等 2018年; Radford 等 2019年)。Top-\(p\)(或核,nucleus)采样改为按累积概率质量截断,保留概率之和至少达到 \(p\)(通常 \(p = 0.9\))的最小头部词元集合 (Holtzman 等 2020年)。这一区别至关重要,因为模型的熵在词元间剧烈波动:当下一个词几乎确定时,固定 \(k = 20\) 会放进十九个糟糕候选;而当数十个词同样自然时,\(k = 20\) 又可能砍掉真正的多样性。Top-\(p\) 动态自适应:在尖峰分布上收紧候选集,在平坦分布上放宽候选集;但当单个榜首词元概率超过 \(p\) 时(例如 \(p = 0.9\) 下榜首概率 \(0.95\),排除了稳健的次选),它仍可能过于贪心。
Min-\(p\) 采样相对于模型的最高概率设定阈值 (Nguyen 等 2025年),保留所有概率至少为最可能词元概率 \(p_{\min}\) 倍的词元(例如 \(p_{\min} = 0.05\))。模型自信时阈值自动抬高,只放行强力竞争者;模型不确定时阈值降低,允许更广探索。Nguyen 等 (2025年) 表明,在较高温度下这种相对阈值的退化远比 top-\(p\) 平缓——绝对累积质量阈值在分布拉平时会把大片尾部一并扫入。
8.6.4.1 统一采样器
由于温度、top-\(k\)、top-\(p\) 与 min-\(p\) 均作用于同一个下一词元分布,一个紧凑函数就能处理任意组合。下面的 sample_next 在 temperature == 0 时返回贪心 argmax,否则按 式 8.6.3 构造 \(P_\tau\)、按概率降序排列词元、计算每个启用截断允许保留的前缀词元数、取最紧界、重新归一化,再用 NumPy 随机数生成器 rng 抽取一个词元。
def sample_next(logits, temperature=1.0, k=None, p=None, min_p=None,
rng=None):
"""Draw a token id from 1-D NumPy logits; temperature 0 is greedy.
Top-k, top-p, and min-p truncate the temperature-scaled distribution."""
logits = np.asarray(logits, dtype=np.float64)
if temperature == 0:
return int(logits.argmax())
probs = np.exp((logits - logits.max()) / temperature)
order = np.argsort(-probs) # token ids, most probable first
probs = probs[order] / probs.sum()
keep = len(probs)
if k is not None: # top-k: a fixed count
keep = min(keep, k)
if p is not None: # top-p: smallest head of mass p
keep = min(keep, int(np.searchsorted(probs.cumsum(), p)) + 1)
if min_p is not None: # min-p: a fraction of the top
keep = min(keep, int((probs >= min_p * probs[0]).sum()))
rng = np.random.default_rng() if rng is None else rng
return int(order[rng.choice(keep, p=probs[:keep] / probs[:keep].sum())])封装函数 generate 打包自回归解码循环:调用 step_fn、用 sample_next 抽取下一词元(转发任意策略关键字参数)、追加结果,若输出 eos_id 则提前终止。由于《时间机器》开放式散文不含序列结束词元,下文示例均生成固定词元数。
def generate(step_fn, prefix, num_tokens, eos_id=None, **strategy):
"""Extend prefix by up to num_tokens ids, each chosen by sample_next
from step_fn(ids), the next-token logits; stop early at eos_id."""
ids = list(prefix)
for _ in range(num_tokens):
ids.append(sample_next(step_fn(ids), **strategy))
if eos_id is not None and ids[-1] == eos_id:
break
return ids一个概率为 \(0.45, 0.25, 0.15, 0.10\) 和 \(0.05\) 的五词元玩具分布便于直接验证每种截断:\(k = 2\) 的 top-\(k\) 仅保留词元 0 和 1;\(p = 0.8\) 的 top-\(p\) 保留词元 0、1 和 2(累积质量达 \(0.85\));\(p_{\min} = 0.5\) 的 min-\(p\) 保留概率至少为 \(0.5 \times 0.45 = 0.225\) 的词元,同样是 0 和 1。在每种规则下抽取 1,000 个样本即可确认精确支撑集。
logits = np.log([0.45, 0.25, 0.15, 0.10, 0.05])
print('greedy:', sample_next(logits, temperature=0))
for cutoff in (dict(k=2), dict(p=0.8), dict(min_p=0.5)):
drawn = {sample_next(logits, **cutoff) for _ in range(1000)}
print(cutoff, 'tokens drawn:', sorted(drawn))greedy: 0
{'k': 2} tokens drawn: [0, 1]
{'p': 0.8} tokens drawn: [0, 1, 2]
{'min_p': 0.5} tokens drawn: [0, 1]
不出所料,每种规则都严格在各自存活支撑集内采样:top-\(k\) 与 min-\(p\) 仅出词元 0 和 1,top-\(p\) 仅出词元 0 至 2。
8.6.4.2 已训练模型上的截断行为
为了观察三条规则在真实语言模型上的表现,我们在双对数坐标轴上绘制 RNN 在 "The Time Traveller" 后排序的下一词元分布。这样看,每条截断规则都有清晰的几何解释:top-\(k\) 无视曲线形状,在排名 \(k\) 处画一条固定竖线;top-\(p\) 在累积质量达到 \(p\) 的排名处画竖线;min-\(p\) 则在最高概率的 \(p_{\min}\) 倍处画一条横线,随模型置信度上下浮动。竖线右侧或横线下方的所有词元全部被剪除。
def next_probs(text): # Next-token probabilities after text, sorted
logits = step_fn(data.tokenizer.encode(text))
probs = np.exp(logits - logits.max())
return np.sort(probs / probs.sum())[::-1]
def cutoffs(probs, p=0.9, min_p=0.05): # Tokens kept by top-p and min-p
return (int(np.searchsorted(probs.cumsum(), p)) + 1,
int((probs >= min_p * probs[0]).sum()))
probs = next_probs('The Time Traveller')
n_p, n_m = cutoffs(probs)
lo, hi = probs[-1], probs[0]
d2l.plot([np.arange(1, len(probs) + 1), [20, 20], [n_p, n_p],
[1, len(probs)]], [probs, [lo, hi], [lo, hi], [0.05 * hi] * 2],
xlabel='token rank', ylabel='probability', xscale='log',
yscale='log', figsize=(5.5, 3),
legend=['model', 'top-k, k=20', f'top-p=0.9: keep {n_p}',
f'min-p=0.05: keep {n_m}'])在双对数坐标轴上,排序概率从排名 1 的 \(0.1\) 至 \(0.25\) 稳步降至排名 100 附近的约 \(10^{-3}\),随后在其余数百个词元上陡然下坠——这正是截断要切除的庞大低概率尾部。为观察各规则如何随模型置信度自适应,我们将 "The Time Traveller" 与更短的前缀 "The Time" 对比:小说中该前缀出现 13 次有 11 次紧跟 " Traveller",因此给出尖锐的分布。
for text in ('The Time Traveller', 'The Time'):
probs = next_probs(text)
n_p, n_m = cutoffs(probs)
print(f'{text!r}: top probability {probs[0]:.2f}; kept: top-k 20, '
f'top-p {n_p}, min-p {n_m}')'The Time Traveller': top probability 0.10; kept: top-k 20, top-p 140, min-p 31
'The Time': top probability 0.69; kept: top-k 20, top-p 6, min-p 2
'The Time Traveller': top probability 0.13; kept: top-k 20, top-p 148, min-p 26
'The Time': top probability 0.70; kept: top-k 20, top-p 7, min-p 2
'The Time Traveller': top probability 0.11; kept: top-k 20, top-p 174, min-p 29
'The Time': top probability 0.80; kept: top-k 20, top-p 2, min-p 2
'The Time Traveller': top probability 0.25; kept: top-k 20, top-p 145, min-p 9
'The Time': top probability 0.55; kept: top-k 20, top-p 21, min-p 4
top-\(k\) 无论上下文如何都僵硬地保留 20 个词元,而两种自适应规则在模型自信时都急剧收缩:在榜首占绝对优势的 "The Time" 之后,两者都激进剪枝,min-\(p\) 仅留寥寥数个候选。然而在模型不确定的 "The Time Traveller" 之后,两者分道扬镳:top-\(p\) 必须深入尾部才能攒够 90% 质量——放进远超一百个词元,绝大多数个体概率低于 1%——而 min-\(p\) 只锚定榜首候选,至多保留几十个概率不低于榜首二十分之一的词元。
8.6.4.3 单一前缀上的策略对比
下面检视各策略实际生成的续写,先从 \(\tau = 0.5\)、\(1.0\) 和 \(2.0\) 的纯温度缩放开始。
prefix = data.tokenizer.encode('The Time Traveller')
for tau in (0.5, 1.0, 2.0):
out = generate(step_fn, prefix, 50, temperature=tau)
d2l.print_wrapped(f'tau={tau}: {show(out)}')tau=0.5: "The Time Traveller pale of the\ndelight of\nthe lamp and\npresent
bushes.\n\n'I had\npresently\nmetinessed\nof a time. I felt\nwhich\n"
tau=1.0: "The Time Traveller.'\n\n'From the powersing solack, and silent it
would by vanished! I came gave me to me.\n\n'I took with me up of
them?ly dancing ru"
tau=2.0: 'The Time Traveller went co tsprockated d�ir can� stoelt-lice slow
against\nich�ined to hished theirsentantworld in dararact disItvesj�
perllow\nWild5ise?3 seemed'
tau=0.5: 'The Time Traveller\nthe lever. I saw the future. In the barted. I
had not felt like the\ntheir conditions, and the\nfecessity. I were the
glass of the oddly of the'
tau=1.0: "The Time Traveller end.' As. There is that the time. But I have to
as if it might as they 'uesthens and pe\nsonky cur from what went
parceally at the thing was drear of the "
tau=2.0: "The Time Traveller diffting be about comeon The Thegedific thing
it isation ag lau ownateles abouteed thought under[ound I d dark that m
goilesol� se� ar went. tableith over 'agap did man might lab"
tau=0.5: "The Time Traveller regued that the old faint\ndelight of the
beautifulation. I suppose I had seen in the despient, I had don't know
how I remember of the"
tau=1.0: 'The Time Traveller looked now, part is a\ntheena� of the burned to
going to myself. The sky of an,\nmewight my necies. I tried rising dist
or soistibly norbe, who'
tau=2.0: 'The Time Traveller a gheautite laroterllow For NayN Andest perhaps
Cor none round my poper indungual toofround towardsigapf found Thereles
creatical face, was at�ve oldmekes�'
tau=0.5: 'The Time Traveller smiled, and the Time Traveller, and the lamp,
and, and in a tempoor of the violence of the little people were others.
I had a faint charange, and'
tau=1.0: "The Time Traveller, amount, and and larghten set on my eyes, and
there is no glass. 'Now the Editor ob to myself to you-turned that the
eyek quundered oddcountry,' said"
tau=2.0: "The Time TravellerE�ree on wit.' And duridelo handes� For cyway
thely are under be perway betered theth an f*le come if, des travelled
day came how too cate� breadning"
\(\tau = 0.5\) 时采样器保守地紧贴高概率词元;\(\tau = 1.0\) 时输出明显更富变化,偶尔滑入乱码词;\(\tau = 2.0\) 时被拉平的分布让尾部词元淹没输出流,跳出英文甚至吐出无法组成合法 UTF-8 字符的字节序列。接下来在同一提示上按标准参数正面对比主要解码策略。
strategies = {'greedy': dict(temperature=0), 'tau=1': dict(),
'top-k=20': dict(k=20), 'top-p=0.9': dict(p=0.9),
'min-p=0.05': dict(min_p=0.05)}
for name, strategy in strategies.items():
out = generate(step_fn, prefix, 50, **strategy)
d2l.print_wrapped(f'{name:>10}: {show(out)}') greedy: "The Time Traveller.\n\n'I had\nfrom the\nsidea.\n\n'I had\nfrom
the\nsidea.\n\n'I had\nfrom the\nsidea.\n\n'I had\nf"
tau=1: 'The Time Traveller, and sgat; so like a sttyj dayshindting,
posserent and buth on that Gecting it leve against\nbut7 Sa crying\ndark
weight at first'
top-k=20: "The Time Traveller looked round in these gone. His animals
had\nsoon.\n\n'I wood to see some\nthe Psychologist in\nmank, and I
directive, and my hand. I was in"
top-p=0.9: 'The Time Traveller rarements. Then I thought "As of trift his
ownisterse of the Palace of Gallen Proburned this white.\n\n\'Chen my an
exton.\n'
min-p=0.05: "The Time Traveller came to pates of\nbit\nmels. Then\n'Then.
As\nbefore a bigroud of these chambuge steading\ninsmination. I"
greedy: 'The Time Traveller, and the silent. I had a\ndimension. I was a
faintness of the\nshamination. I was a faintness of the\nshamination. I
was a f'
tau=1: 'The Time Traveller, for think name by\nree Traveller certain
glass shinking in my gaturther. I felt through Crack and popated to
E�icive mused. So something in such eight ac'
top-k=20: 'The Time Traveller, and the Vorner of the sensation--which I
was at the botterrorning. So\nshandition. Then Filway. At first as I was
lacle that the m'
top-p=0.9: 'The Time Traveller smil that night was a fallos, and it was
never made to me already, and reverrew hers. Then I followed a qulen
Panes of the intelligence. It was at'
min-p=0.05: 'The Time Traveller, and my the Upper and oddcror. I could not
felt the thought. His I must have been at last, and\nthe proper. And I
thought of it seemed to me, but\npresently'
greedy: 'The Time Traveller. I was a vastly. I was a vastly. I was a
vastly. I was a vastly. I was a vastly. I was a vastly. I was a vastly.'
tau=1: 'The Time Traveller\ncove about the hail going. And the I had
been nunningaryhinguntively. It seemed metmey of the tinught and leave
me to overhas that put mees.'
top-k=20: 'The Time Traveller I had the softs and the sphinx, and the
fruit of his paintrieve, to the\nfeltighing\nof the pallications of the
sight of that I will sh'
top-p=0.9: "The Time Traveller remained it, and I was determist\nwemed of
the stotst of the little people were a little tural?\nAnd for any
kind.'\n\n'I sat, the machine was n"
min-p=0.05: 'The Time Traveller\nsume of a miles of the gradual story of the
simply draat of the low. Thing had a next. The Editor came upon the ran,
and the\nlighter'
greedy: 'The Time Traveller, and the\nday. I was a little\ndoors, and
the\nday. I was a little\ndoors, and the\nday. I was a little\ndoors,
and'
tau=1: 'The Time Traveller,\nwere upon the like haib anepingar, had
rait cassing. The moonstar I never\nbleme placeted to us, and wrong you.
You went by\nbe left it seemed'
top-k=20: "The Time Traveller the bars of the line. 'Don't lat of a little
lamp, perhaps, for it I could imagicke to be out the end. And crivit and
three, and\nsub"
top-p=0.9: 'The Time Traveller still more\nhadilled on the Palact, and then
now windows\nand this well as it apparady into the vatis to\nof the
..lighting\nlittle\nmetent of'
min-p=0.05: 'The Time Traveller, but the numbably enough--to fruits of the
question of the wallen as I could sumake a decay. It, I was noisease and
the ballery and r'
当然,在单部中篇小说上训练的小型单层 RNN 在任何解码器下都无法产出完美散文,单次采样也充满噪声。即便如此,定性反差仍一目了然:贪心解码确定且迅速落入循环,而每种采样器每次调用都产出新鲜不循环的文本。实践中,中等温度配合 top-\(p\) 或 min-\(p\) 截断能很好平衡流畅度与多样性,是开放式生成的默认配置。
8.6.5 评估与开销
8.6.5.1 生成文本的质量
除了肉眼审视零星段落,如何系统比较各解码策略?困惑度无法回答这个问题:困惑度评估的是模型在留出人类文本上的表现,而非具体解码规则;而用模型自身似然为生成样本打分会同义反复地把冠军颁给最大化方法,尽管采样本就是刻意以峰值似然换取多样性。
不过,自动化诊断仍能精准捕捉特定失效模式。为量化重复程度,我们使用 distinct-3——生成续写中互异三元语法数与总三元语法数之比:没有任何三词元片段重复时等于 1,文本陷入循环时趋向 0。下面我们在 20 条随机抽取的六词元验证前缀上,用贪心解码、束搜索(\(w = 4\))及各采样器分别生成 100 词元续写,同时报告模型下的平均逐词元对数概率与平均 distinct-3。
def log_prob(ids, start): # Mean log-probability of ids[start:] in one pass
logits = seq_logits(ids[:-1])[start - 1:]
lse = logits.max(1) + np.log(np.exp(logits - logits.max(1, keepdims=True)).sum(1))
return float(np.mean(logits[np.arange(len(logits)), ids[start:]] - lse))
def distinct(ids, n=3): # Fraction of distinct n-grams in ids
grams = [tuple(ids[i:i + n]) for i in range(len(ids) - n + 1)]
return len(set(grams)) / len(grams)
val = d2l.numpy(data.X[data.num_train:data.num_train + data.num_val])
rows = np.random.default_rng().choice(len(val), 20, replace=False)
prefixes = [[int(i) for i in val[r, :6]] for r in rows]
decoders = {
'greedy': lambda pre: generate(step_fn, pre, 100, temperature=0),
'beam, w=4': lambda pre: beam_search(step_fn, pre, 100, beam_size=4)[0][1],
'tau=1': lambda pre: generate(step_fn, pre, 100),
'top-k=20': lambda pre: generate(step_fn, pre, 100, k=20),
'top-p=0.9': lambda pre: generate(step_fn, pre, 100, p=0.9),
'min-p=0.05': lambda pre: generate(step_fn, pre, 100, min_p=0.05)}
for name, decode in decoders.items():
outs = [decode(pre) for pre in prefixes]
print(f'{name:>10}: log-prob per token '
f'{np.mean([log_prob(o, 6) for o in outs]):.2f}, distinct-3 '
f'{np.mean([distinct(o[6:]) for o in outs]):.2f}') greedy: log-prob per token -1.89, distinct-3 0.15
beam, w=4: log-prob per token -1.46, distinct-3 0.19
tau=1: log-prob per token -3.93, distinct-3 0.99
top-k=20: log-prob per token -2.83, distinct-3 0.99
top-p=0.9: log-prob per token -3.38, distinct-3 0.99
min-p=0.05: log-prob per token -2.78, distinct-3 0.98
greedy: log-prob per token -2.08, distinct-3 0.23
beam, w=4: log-prob per token -1.76, distinct-3 0.18
tau=1: log-prob per token -3.96, distinct-3 1.00
top-k=20: log-prob per token -2.88, distinct-3 0.99
top-p=0.9: log-prob per token -3.41, distinct-3 1.00
min-p=0.05: log-prob per token -2.87, distinct-3 0.99
greedy: log-prob per token -2.17, distinct-3 0.09
beam, w=4: log-prob per token -1.82, distinct-3 0.35
tau=1: log-prob per token -4.05, distinct-3 1.00
top-k=20: log-prob per token -2.82, distinct-3 0.99
top-p=0.9: log-prob per token -3.51, distinct-3 1.00
min-p=0.05: log-prob per token -2.80, distinct-3 0.99
greedy: log-prob per token -2.14, distinct-3 0.19
beam, w=4: log-prob per token -1.69, distinct-3 0.10
tau=1: log-prob per token -3.96, distinct-3 1.00
top-k=20: log-prob per token -2.79, distinct-3 0.99
top-p=0.9: log-prob per token -3.41, distinct-3 1.00
min-p=0.05: log-prob per token -2.77, distinct-3 0.98
两项指标径直拉向相反方向。两种最大化策略的逐词元对数概率都显著高于任何采样器(束搜索通常略胜贪心解码),但它们的 distinct-3 断崖下跌,因为大部分三元语法都在重复。四种采样器的 distinct-3 全都接近 1,在微型尺度上精准复现了 Holtzman 等 (2020年) 记录的似然与多样性权衡。
在采样家族内部,四种规则的多样性几乎全部饱和,而逐词元对数概率将它们清晰拉开。纯祖先采样(\(\tau = 1\))平均对数概率最低(每词元约 \(-4\) 奈特),而三种截断采样器在不牺牲 distinct-3 的前提下大幅抬升似然。与前文截断保留数一致,top-\(p\)(\(0.9\))因保留最宽支撑集而最接近纯采样,top-\(k\)(\(20\))与 min-\(p\)(\(0.05\))剪枝更果断,将逐词元对数概率拉高约整整 1 奈特——直接印证了尾部截断的有效性。
distinct-3 这类自动指标善于捕捉具体失效模式,却无法衡量连贯性、事实准确性或文风。归根结底,开放式文本生成由人类读者(或经校准的代理评审)评判,而翻译等带参考真值的受限任务则可对照参考输出度量。简而言之,困惑度指导模型选择,而人类偏好或任务专属基准指导解码器选择。
8.6.5.2 生成开销
为了使 step_fn 无状态以适配任意自回归模型,每生成一个新词元都要在整个前缀上重跑一遍 RNN,导致生成 \(T\) 个词元耗费 \(O(T^2)\) 次单元更新。自回归生成还天然是顺序的:不同于预先已知全部位置的教师强制训练,在选定第 \(t\) 个词元之前无法为第 \(t + 1\) 个词元打分。尽管顺序依赖是本质的,二次方重复计算对 RNN 而言却完全多余:既然隐藏状态已概括前缀,像 8.4.2 节 的 predict 那样将状态逐步前传,开销立刻降至与序列长度无关的每词元恰好一次单元更新。没有循环状态的模型则通过缓存每个历史词元的中间计算避免重复计算,代价是显存随前缀长度增长(第 10 章)。
每生成词元恒定计算与恒定显存,是循环语言模型标志性的效率优势。然而同一个固定尺寸状态也是本模型的瓶颈,迫使记住的全部前缀信息挤进区区 128 个浮点数(8.4.1.1 节)。如果模型本身的下一词元分布抓不住长程结构,再精巧的解码技巧也无力回天——不过正因我们的解码器把模型视作纯黑盒,本节构建的所有算法都能原封不动迁移到强大得多的模型上。
至此,“基础篇”告一段落——而且恰好落在一道鲜明的架构分界线上。我们的 RNN 以恒定开销逐词元预测文本,实际上却只利用了最近两三个词元的历史(8.4.2 节),加之梯度在短短几步内消失(8.5 节),几乎无望学到更长依赖。前路由此一分为二:第一条路保留固定尺寸状态,重新设计递推使梯度能跨越长视界存活(第 12 章);第二条路干脆放弃固定尺寸压缩,保留每个历史词元的表征并直接跨其计算关联(代价随序列长度增长)——即现代大语言模型核心的注意力机制(第 10 章)。无论底层选用哪种架构,本章的子词词元化器、每字节比特数评估与解码算法都将直接延续。
8.6.6 小结
解码将语言模型的下一词元分布转化为具体词元序列。最大化方法追求高概率输出:贪心解码每步局部锁定,既短视又易陷入重复循环;束搜索以 \(w\) 倍开销追踪前 \(w\) 条假设(允许提前终止时配合长度规范化),在输出空间窄小的受限任务上表现出色。对开放式生成而言,采样保留自然多样性,而温度缩放(式 8.6.3)配合 top-\(k\)、top-\(p\) 或 min-\(p\) 尾部截断可防止低概率尾部词元带偏推演——在保持与纯采样相当的 distinct-3 多样性的同时大幅提升似然。最后,困惑度评估的是模型而非解码器,而延续循环隐藏状态可消除朴素无状态解码的 \(O(T^2)\) 重复计算。
8.6.7 练习
束搜索性质。
- 取束宽 2、图 8.6.3 的五词元词表与三步。构造一组条件概率,使束搜索未能返回概率最高的三词元序列,并计算两条序列的概率。你的构造说明束搜索为何可能错过最优序列?
- 为保证 \(T\) 步束搜索对任意模型都一定返回全部 \(|\mathcal{V}|^T\) 条序列中概率最高的一条,最小束宽是多少?
- 设 \(w \leq |\mathcal{V}|\) 且假设不出现序列结束词元。计算
beam_search在 \(T\) 步内调用step_fn的次数,并计算穷举搜索对每个前缀只评估一次时的调用次数。代入 \(|\mathcal{V}| = 1{,}027\)、\(T = 50\) 和 \(w = 4\) 求出两者数值。
[code] 长度规范化。在
'The Time Traveller'与'It seemed to me that'后以 \(w = 4\) 运行beam_search最多 40 个词元。将换行符编号data.tokenizer.encode('\n')[0]传入eos_id,令 \(\beta\)(参数alpha)取遍 \(\{0, 0.75, 1.5\}\)。比较胜出候选的长度与总对数概率,并用 式 8.6.2 解释趋势。温度缩放下的截断。
sample_next将所有截断施加在 式 8.6.3 的温度缩放分布 \(P_\tau\) 上。将 min-\(p\) 条件 \(P_\tau(x \mid x_{<t}) \geq p_{\min} \max_{x'} P_\tau(x' \mid x_{<t})\) 改写为关于未缩放概率的条件。对五词元分布 0.45、0.25、0.15、0.10、0.05,计算 \(\tau = 2\) 时 \(k = 2\) 的 top-\(k\)、\(p = 0.85\) 的 top-\(p\) 与 \(p_{\min} = 0.5\) 的 min-\(p\) 各自保留的集合。三条规则中哪一条在任意温度下都保留完全相同的集合?[code] Top-\(p\) 对比 min-\(p\)。● 在 \(\tau = 1.5\) 下,在一组网格值上分别扫描 top-\(p\) 的 \(p\) 与 min-\(p\) 的 \(p_{\min}\)。对每个设置,为自选五条前缀生成 50 词元续写,并记录生成词元上的两项均值:规则保留的词元数,以及所抽词元在未缩放模型下的对数概率。以第一项为横轴、第二项为纵轴绘制两条曲线(每条规则一条)。在相同平均保留词元数下,哪条规则抽出的词元概率更高?将你的发现与 Nguyen 等 (2025年) 对比。
[code] 每词元恒定开销。●
step_fn每生成一个词元都在整个前缀上重跑网络,因此 \(T\) 词元续写耗费 \(O(T^2)\) 次单元更新(8.6.5.2 节)。- 为
step_fn编写有状态替代版:保存model.rnn的隐藏状态且每次仅消费最新词元,使每次调用只执行一次单元更新。验证两个版本下generate产出完全相同的贪心续写。 - 分别用两个版本对生成 50、200 和 800 个词元的
generate计时。根据时间比值估计两者耗时如何随词元数增长,并解释与单元更新次数所预测的二次方及线性增长之间的任何偏差。 - 为何同一个替代方案不能直接套用到
beam_search上?需要补充什么状态管理才能使其工作?
- 为