解码与文本生成

Dive into Deep Learning · §8.6

解码与文本生成
贪心搜索 · 束搜索与长度规范化 · 温度缩放 · top-k、核(top-p)与 min-p 采样 · distinct-n 与复杂度

解码问题:10¹⁵⁰ 条候选续写

动机与组合搜索空间

P(x_1, \ldots, x_T) = \prod_{t=1}^T P(x_t \mid x_{<t})

  • 精确全局最大化不可行:在 1,027 词元 BPE 词表与 50 词元视界上存在 1027^{50} > 10^{150} 种续写——没有任何解码器能穷举搜索树。
  • 最大化与采样的两难:贪心 argmax 迅速将生成器锁入确定性重复循环,而未裁剪采样会抽中低概率尾部词元带偏推演。

两大解码器家族:最大化对比采样

任务驱动的解码器选择

应当搜索高概率序列还是随机采样,根本上取决于目标任务的熵:

  • 最大化解码器(贪心与束搜索):近似 \operatorname*{argmax}_{x_{1:T}} P(x_{1:T})。最适合受限低熵任务(语音识别、机器翻译、OCR),其输入仅容许极窄范围的正确输出。
  • 截断采样解码器(温度、Top-k、Top-p、Min-p):重塑或裁剪 P(x_t \mid x_{<t}) 不可靠的低概率尾部再随机抽取。适合开放式生成(对话、创意写作),校准良好的模型会将概率质量分散在多条合理续写上。

与模型无关的下一词元对数几率接口

统一解码边界

本节每个解码算法仅通过黑盒函数 step_fn(ids) -> logits(返回长度 |\mathcal{V}| = 1{,}027 的一维 NumPy 向量)与已训练 RNN 语言模型(RNNLM,d = 512, h = 128,验证困惑度 \approx 60)交互:

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]
  • 架构与框架无关:由于 step_fn 接收整数词元编号列表并返回 NumPy 对数几率数组,同一套解码代码可在任意框架下驱动 RNN、状态空间模型或 Transformer。

贪心解码与短视陷阱

最大化家族 I:贪心搜索

x_t = \operatorname*{argmax}_{x \in \mathcal{V}} P(x \mid x_{<t})

  • 每词元一次模型调用:确定且快速,但每步不可逆地锁定最高概率词元。
  • 为何局部 argmax 短视:第 1 步选 A(0.50 > 0.40)落入发散的第 2 步(0.50 \times 0.30 = 0.15),剪掉了后续高置信路径 B(0.40 \times 0.90 = 0.36,高 2.4\times)。

神经文本退化:确定性极限环

为何贪心推演会循环

在 'The Time Traveller' 与 'It seemed to me that' 后用贪心解码生成 50 个词元,立刻暴露其更严重的第二个缺陷——重复循环:

"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"
  • 确定性状态空间吸引子:贪心解码下的自回归 RNN 中,\mathbf{H}_t = g(\mathbf{H}_{t-1}, x_t) 与 x_t = \operatorname*{argmax} \mathbf{O}_{t-1} 都是确定性映射。轨迹一旦回到几个词元前访问过的隐藏状态附近,就在数学上永久锁死在周期极限环中。
  • 并非小 RNN 特例:Holtzman 等(2020)在 GPT-2 Large(774M 参数)上同样观察到,对开放式文本做似然最大化必然引发神经文本退化。

束搜索:保留前 w 条部分假设

最大化家族 II:束搜索

束搜索每步维护得分最高的 w 条部分前缀来缓解贪心短视(束宽 w = 1 退化为贪心搜索,w \to \infty 逼近穷举搜索):

  • 展开与剪枝循环(束宽 w = 2,|\mathcal{V}| = 5):
    1. 第 1 步:保留概率最高的 w = 2 个首词元(A 与 C)。
    2. 第 2 步:将每条活跃束沿全部 |\mathcal{V}| 个词元展开(w|\mathcal{V}| = 10 个候选),按累积对数概率 \log P(x_1) + \log P(x_2 \mid x_1) 打分,剪枝回前 w = 2 条(AB 与 CE)。
    3. 第 T 步:总评估数按 O(w|\mathcal{V}|T) 线性增长(5 + 10 + 10 = 25,而非 |\mathcal{V}|^3 = 125)。

面向提前终止束的长度规范化

比较变长假设

\textrm{score}\bigl(x_{t_0+1:t_0+T}\bigr) = \frac{1}{T^\beta}\sum_{t=t_0+1}^{t_0+T} \log P(x_t \mid x_{<t})

  • 为何原始对数似然(\beta = 0)偏袒短句:每项 \log P \le 0 均非正,增加词元会单调拉低累积对数概率,偏向过早输出 <eos>。
  • 插值指数 \beta \in [0, 1](Wu 等,2016):\beta \approx 0.75 在累积似然与逐词元均值(\beta = 1)之间取得平衡。

实现长度规范化束搜索

从零实现与评估

每条束至多有 w 条扩展能存活,因此每条束只需保留前 w 个词元:

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, 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 \to 4 找到更高对数概率得分(负得更少的长度规范化分数)的续写,但开放式散文仍会坍缩为重复从句。

祖先采样与不可靠尾部问题

采样家族:动机

x_t \sim P(x_t \mid x_{<t})

  • 为何纯采样容易跑偏(Holtzman 等,2020):Softmax 给全部 |\mathcal{V}| = 1{,}027 个词元赋正概率。在 'The Time Traveller' 后,前 140–174 个词元占 90\% 质量,其余 \sim 850–890 个离谱尾部词元每步共享高达 10\% 的概率。
  • 50 步复合失效率:按每步 10\% 抽中尾部的概率,50 词元推演全程避开尾部词元的概率仅为 (1 - 0.1)^{50} \approx 0.005。

温度缩放:重塑 Softmax 熵

采样控制 I:温度

温度缩放在施加 softmax 前将对数几率向量 \mathbf{o} \in \mathbb{R}^{|\mathcal{V}|} 除以 \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}

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 \to 0^+ 收敛到确定性贪心 argmax;\tau = 1 恢复原始祖先采样;\tau > 1 将分布拉平趋向均匀(\tau = 2.0 时尾部字节破坏英文甚至合法 UTF-8)。
  • 为何单靠温度是钝器:调低 \tau(如 \tau = 0.5)在压制不可靠尾部的同时,也会碾碎前 3–5 个合理头部词元之间的多样性。

三条尾部截断规则:Top-k、Top-p 与 Min-p

采样控制 II:尾部截断

截断采样器不扭曲头部,而是按概率降序排列词元 P(x_{(1)}) \ge P(x_{(2)}) \ge \cdots \ge P(x_{(|\mathcal{V}|)}),将截断排名 K 之后全部清零,对存活头部重新归一化后再采样:

截断规则 存活支撑集 \mathcal{S} 玩具分布 (0.45, 0.25, 0.15, 0.10, 0.05) 对模型熵的自适应
Top-k(Fan 等,2018) 固定排名数:\{x_{(1)}, \ldots, x_{(k)}\} k = 2 \implies \{0, 1\}(质量 0.70) 无(僵硬):无论熵近 0 还是很高都保留 k 个词元
Top-p / 核采样(Holtzman 等,2020) 满足 \sum_{i=1}^K P(x_{(i)}) \ge p 的最小头部 p = 0.80 \implies \{0, 1, 2\}(累积质量 0.85 \ge 0.80) 累积质量自适应:尖峰时收缩,平坦时放宽
Min-p(Nguyen 等,2025) 相对底线:\{x : P(x) \ge p_{\min}\,P(x_{(1)})\} p_{\min} = 0.50 \implies P(x) \ge 0.225 \implies \{0, 1\} 相对榜首自适应:阈值直接随榜首置信度 P(x_{(1)}) 缩放
greedy: 0
{'k': 2} tokens drawn: [0, 1]
{'p': 0.8} tokens drawn: [0, 1, 2]
{'min_p': 0.5} tokens drawn: [0, 1]

十五行代码实现可组合统一采样器

从零实现

每条规则都归结为决定有多少个排序头部词元 keep 进入重新归一化:

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())])

十五行代码实现可组合统一采样器(续)

从零实现

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

已训练模型上截断的几何视角

双对数轴可视化截断

在双对数坐标轴上绘制已训练 RNN 在 'The Time Traveller' 后的排序下一词元概率,赋予每条截断规则清晰的几何含义:

  • 头部与尾部结构:概率在排名 1\text{--}100 缓降(\approx 0.1 \to 10^{-3}),随后骤跌进 900 词元的噪声尾部。
  • 竖直与水平截断:
    • Top-k(k = 20,品红虚线):固定在排名 20 的竖直墙。
    • Top-p(p = 0.9,绿线):动态置于累积面积达 90\% 处的竖直墙。
    • Min-p(p_{\min} = 0.05,红线):置于排名第 1 峰值 5\% 处的水平底线(0.05\,P(x_{(1)}));线下全部剪除。

自适应截断如何响应模型置信度

尖峰与不确定上下文

将不确定的前缀 'The Time Traveller' 与高度可预测的前缀 'The Time'(小说中 13 次出现有 11 次紧跟 ' Traveller')对比,凸显三条截断规则跨熵区间的表现:

'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',高 P_{\max}):Top-k = 20 盲目放进 19 个低概率词元,而 top-p 与 min-p 均急剧收缩至寥寥数个候选。
  • 模型不确定时('The Time Traveller',头部平坦):为攒够 90\% 概率质量,top-p = 0.9 必须保留约 140–175 个词元,深入尾部;而 min-p = 0.05 只保留榜首 20\times 范围内的词元(约 10 至 30 个合理选择)。

各解码策略正面生成对比

定性推演对比

在 'The Time Traveller' 后用贪心解码、纯采样(\tau = 1)与三种截断采样器各生成 50 词元续写,定性改进立竿见影:

    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"
  • 打破循环且避免尾部胡言:贪心解码锁入确定性循环,纯 \tau = 1 采样偶尔拼出离谱子词,而 top-k=20、top-p=0.9 与 min-p=0.05 均生成多样且不循环的续写。

量化似然与多样性(Distinct-3)

跨 20 条提示的系统基准

为量化模型似然(生成词元平均对数概率)与词汇多样性之间的权衡,我们在 20 次随机 100 词元推演上测量 \textrm{distinct-}3(互异三元语法与总三元语法之比,1.00 表示零重复):

    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
  • 最大化坍缩:贪心与束搜索(w = 4)取得最高逐词元对数概率(\approx -1.5 至 -2.2 奈特,束搜索略高于贪心),但 distinct-3 崩塌至 \approx 0.15\text{--}0.30,超过 70\% 输出由重复三元语法构成。
  • 截断采样的甜蜜点:纯采样(\tau = 1)达 distinct-3 \approx 0.99 但似然偏低(\approx -4.0 奈特);top-k=20 与 min-p=0.05 保持几乎相同的多样性(distinct-3 \approx 0.97\text{--}0.99),同时将逐词元对数概率拉高整整 1 奈特(\approx -2.9 奈特)。

为何困惑度评估的是模型,而非解码器

分离模型质量与解码器选择

语言建模中一个常见陷阱是试图用困惑度(或生成文本的模型对数似然)给解码算法排名:

  • 困惑度在人类文本上为模型打分:\textrm{PPL} = \exp(-\frac{1}{T}\sum_t \log P(x_t \mid x_{<t})) 衡量模型分布给留出真实段落分配了多少概率质量——在调用任何解码器之前就已确定。
  • 为何生成文本的模型似然是同义反复:按 \frac{1}{T}\sum_t \log P(\hat{x}_t \mid \hat{x}_{<t}) 给生成结果打分永远会把贪心或束搜索捧为“赢家”,哪怕产出的是退化循环("and the time traveller and the time traveller...")。
  • 恰当的解码器评估:用表层诊断(distinct-n、重复率)捕捉退化,在受限任务上用参考指标(BLEU、COMET、WER),在开放式生成上采用盲测人类偏好(或校准评审打分)。

推理复杂度:无状态 O(T²) 对比缓存 O(T)

自回归生成的系统开销

  • 无状态前缀重算(step_fn(ids)):在第 t 步在 x_{1:t} 上重跑网络共需 \sum_{t=1}^T t = O(T^2) 次单元更新。
  • 有状态循环延续(predict):前传 \mathbf{H}_{t-1} \in \mathbb{R}^h 只需每词元 1 次单元更新(总计 O(T)),任意序列长度下状态均固定占 512 字节。
  • 下一视界(第 10–12 章):用门控/SSM 升级 \mathbf{H}_t 使梯度在 O(1) 空间内存活(§12),或通过自注意力以 O(T) 显存保留全部历史词元 K/V 向量(§10–11)。

概念自测:束搜索、截断与复杂度

概念自测

检验对解码算法及其计算性质的掌握:

  1. 束搜索函数调用次数:词表大小 |\mathcal{V}| = 1{,}027、生成长度 T = 50、束宽 w = 4(假设不提前出现 <eos>),beam_search 在 50 步内共调用多少次 step_fn?与穷举全部 |\mathcal{V}|^T 条序列相比如何?
  2. 尖峰分布上的 Top-p 对比 Min-p:设第 t 步榜首词元概率 P(x_{(1)}) = 0.95,次选 P(x_{(2)}) = 0.04,其余 1,025 个词元共享 0.01。(a) p = 0.90 的 top-p 与 (b) p_{\min} = 0.05 的 min-p 各自保留哪些精确词元?
  3. 截断的温度不变性:sample_next 在温度缩放 P_\tau(x) \propto P(x)^{1/\tau} 之后施加 top-k、top-p 和 min-p。三条规则中哪一条在任意温度 \tau > 0 下都保留完全相同的词元支撑集?

概念自测:束搜索、截断与复杂度(答案)

概念自测

答案:

  1. beam_search 共调用 step_fn 1 + 49 \times 4 = 197 次(第 1 步对初始提示调用 1 次,第 2, \ldots, 50 步每步调用 w = 4 次,共为 1027 + 49 \times 4 \times 1027 = 202{,}319 条候选扩展打分),对比穷举搜索的 > 10^{150} 条序列。
  2. (a) Top-p(p = 0.90)仅保留 1 个词元(x_{(1)}),因为 0.95 \ge 0.90 已超阈值,退化为纯贪心并排除了 4\% 的次选。(b) Min-p(p_{\min} = 0.05)保留 1 个词元(x_{(1)}),因阈值为 0.05 \times 0.95 = 0.0475 > 0.04(若 P(x_{(2)}) \ge 0.0475 则会一并保留 x_{(2)})。
  3. Top-k 对 \tau > 0 保持不变:由于 p \mapsto p^{1/\tau} 对所有 \tau > 0 严格单调递增,它保持全部词元的排序不变,因此前 k 个词元永不改变(而 top-p 与 min-p 会随 \tau 拉平或锐化分布而改变支撑集大小)。

小结:各类解码策略对比

本节要点

策略 选择 / 截断规则 关键超参数 对分布形状的自适应 每步模型调用 主要场景与失效模式
贪心解码 x_t = \operatorname*{argmax}_{x} P(x \mid x_{<t}) 无(\tau = 0) 确定性单峰 1 快速基线;短视且锁入确定性重复循环
束搜索 按 \frac{1}{T^\beta}\sum \log P 保留前 w 前缀 束宽 w、长度指数 \beta \approx 0.75 并行追踪 w 条路径 w 受限任务标准(机器翻译、语音识别);开放式文本仍会循环
温度采样 按 P_\tau(x) \propto \exp(o_x / \tau) 采样 温度 \tau > 0 全局锐化(\tau < 1)或拉平(\tau > 1) 1 全局重塑熵;压制尾部同时扼杀头部多样性

小结:各类解码策略对比(续)

本节要点

策略 选择 / 截断规则 关键超参数 对分布形状的自适应 每步模型调用 主要场景与失效模式
Top-k 采样 从 P_\tau 前 k 名采样 数量 k \in \{1, \ldots, \lvert\mathcal{V}\rvert\} 固定大小 k,无视模型置信度 1 切除排名 k 之后的尾部;尖峰分布时放进 k-1 个劣质词元
Top-p(核采样) 满足 \sum_{i=1}^K P_\tau(x_{(i)}) \ge p 的最小头部 累积质量 p \in (0, 1)(如 0.9) 质量自适应(尖峰收缩、平坦放宽) 1 随熵自适应;高 \tau 平坦分布时可能深入尾部数百词元
Min-p 采样 保留 \{x : P_\tau(x) \ge p_{\min} P_\tau(x_{(1)})\} 相对底线 p_{\min}(如 0.05) 置信度自适应(直接随榜首 P_{\max} 缩放) 1 跨温度稳健;防止平坦分布卷入噪声尾部