CS336.wiki
CS336 中文实验手册/训练与生成
反馈与讨论
ASSIGNMENT 01 / 6

文本生成与采样

2026 春季 · v26.0.3原文 p. 37–38对照 PDF ↗

6 生成文本#

具备训练能力后,最后一块是让模型生成文本。语言模型接收长度为 sequence_length 的整数序列,可带批次维,并产生 (sequence_length, vocab_size) 的输出;每个位置描述其后下一 token 的预测。

现在要把这些输出变成新序列的采样过程。

Softmax#

按惯例,模型输出是最后一个线性层的 logits,因此需要用公式 10 的 softmax 把它转成归一化概率。

解码#

向模型提供一个 token 前缀,即 prompt,让模型预测下一 token 的词表分布,然后从中采样。一步解码接收 x1…tx_{1\ldots t},返回 xt+1x_{t+1}:

P(xt+1=i∣x1…t)=exp⁡(vi)∑jexp⁡(vj)(21) P(x_{t+1}=i\mid x_{1\ldots t})= \frac{\exp(v_i)}{\sum_j\exp(v_j)} \tag{21}
v=TransformerLM⁡(x1…t)t∈Rvocab_size(22) v=\operatorname{TransformerLM}(x_{1\ldots t})_t \in\mathbb{R}^{\mathrm{vocab\_size}} \tag{22}

取模型输出矩阵最后一个位置,因为要预测的是第 tt 个位置之后的 token。

反复从单步条件分布采样,并把已生成 token 接到下一步输入后,就得到基本解码器;直到生成 <|endoftext|>,或达到用户指定的最大生成数量。

解码技巧:温度缩放#

小模型有时会生成质量很差的文本。两个简单技巧可以改善。首先是给 softmax 引入温度 τ\tau:

softmax⁡(v,τ)i=exp⁡(vi/τ)∑j=1vocab_sizeexp⁡(vj/τ)(23) \operatorname{softmax}(v,\tau)_i= \frac{\exp(v_i/\tau)} {\sum_{j=1}^{\mathrm{vocab\_size}}\exp(v_j/\tau)} \tag{23}

当 τ→0\tau\to0,最大分数项逐渐主导,分布趋向集中在该项上的独热向量。

解码技巧:核采样(top-p)#

第二个技巧是 nucleus sampling,也称 top-p 采样,通过截去低概率 token 调整采样分布。

令 qq 为温度缩放后、大小为词表长度的概率分布。给定阈值 pp:

P(xt+1=i∣q)={qi∑j∈V(p)qj,i∈V(p)0,其他情况(24) P(x_{t+1}=i\mid q)= \begin{cases} \dfrac{q_i}{\sum_{j\in V(p)}q_j}, & i\in V(p)\\ 0, & \text{其他情况} \end{cases} \tag{24}

V(p)V(p) 为概率总和至少达到 pp 的最小索引集合。可先按概率从大到小排序,再依次选取最大的词表项,直到达到阈值。

练习 decoding3 分

解码

交付物: 实现从语言模型解码的函数,建议支持:

  • 接收用户 prompt,采样补全,直到遇到 <|endoftext|>。
  • 允许用户控制最大生成 token 数。
  • 采样之前按用户给定温度缩放下一 token 分布。
  • 按用户给定阈值进行 top-p/核采样 [27]。

一起把这一章读得更好

发现翻译、公式或排版错误?欢迎反馈。概念疑问和学习心得,也可以在本章讨论中交流。

直接选中正文,点击旁边的「反馈这处错误」,即可在页内填写并提交,无需登录。
English original 展开本章英文原文 PDF 文本提取

下列文本提取自本地原版 PDF。图表和公式的准确布局请对照 PDF。

6 Generating text
Now that we can train models, the last piece we need is the ability to generate text from our model.
Recall that a language model takes in a (possibly batched) integer sequence of length sequence_length
and produces a matrix of size (sequence_length, vocab_size), where each element of the sequence is a
probability distribution predicting the next token after that position. We will now write a few functions
to turn this into a sampling scheme for new sequences.

Softmax
By standard convention, the language model output is the output of the final linear layer (the “logits”)
and so we have to turn this into a normalized probability via the softmax operation, which we saw earlier
in Equation 10.

Decoding
To generate text (decode) from our model, we will provide the model with a sequence of prefix tokens
(the “prompt”), and ask it to produce a probability distribution over the vocabulary that predicts the
next token in the sequence. Then, we will sample from this distribution over the vocabulary items to
determine the next output token.
Concretely, one step of the decoding process should take in a sequence 𝑥1…𝑡 and return a token 𝑥𝑡+1 via
the following equation,
                                                     exp(𝑣𝑖 )
                           𝑃 (𝑥𝑡+1 = 𝑖 | 𝑥1…𝑡 ) =                                                        (21)
                                                    ∑𝑗 exp(𝑣𝑗 )

                                             𝑣 = TransformerLM(𝑥1…𝑡 )𝑡 ∈ ℝvocab_size                     (22)

where TransformerLM is our model which takes as input a sequence of length sequence_length and
produces a matrix of size (sequence_length, vocab_size), and we take the last element of this matrix, as
we are looking for the next token prediction at the 𝑡-th position.
This gives us a basic decoder by repeatedly sampling from these one-step conditionals (appending our
previously-generated output token to the input of the next decoding timestep) until we generate the end-
of-sequence token <|endoftext|> (or a user-specified maximum number of tokens to generate).

Decoder tricks
We will be experimenting with small models, and small models can sometimes generate very low-quality
texts. Two simple decoder tricks can help fix these issues. First, in temperature scaling we modify our
softmax with a temperature parameter 𝜏 , where the new softmax is
                                                             exp(𝑣𝑖 /𝜏 )
                                    softmax(𝑣, 𝜏 )𝑖 =    vocab_size
                                                                                .                        (23)
                                                        ∑𝑗=1        exp(𝑣𝑗 /𝜏 )

Note how setting 𝜏 → 0 makes it so that the largest element of 𝑣 dominates, and the output of the
softmax becomes a one-hot vector concentrated at this maximal element.



 9
     wandb.ai

Second, another trick is nucleus or top-p sampling, where we modify the sampling distribution by
truncating low-probability tokens. Let 𝑞 be a probability distribution that we get from a (temperature-
scaled) softmax of size vocab_size. Nucleus sampling with hyperparameter 𝑝 produces the next token
according to the equation
                                                         𝑞𝑖
                                                      ∑𝑗∈𝑉 (𝑝) 𝑞𝑗 if 𝑖 ∈ 𝑉 (𝑝)
                                 𝑃 (𝑥𝑡+1 = 𝑖 | 𝑞) = {                                                   (24)
                                                     0           otherwise

where 𝑉 (𝑝) is the smallest set of indices such that ∑𝑗∈𝑉 (𝑝) 𝑞𝑗 ≥ 𝑝. You can compute this quantity easily
by first sorting the probability distribution 𝑞 by magnitude, and selecting the largest vocabulary elements
until you reach the target level of 𝑝.


 Problem (decoding): Decoding (3 points)


   Deliverable: Implement a function to decode from your language model. We recommend that
   you support the following features:
   • Generate completions for a user-provided prompt (i.e., take in some 𝑥1…𝑡 and sample a
     completion until you hit an <|endoftext|> token).
   • Allow the user to control the maximum number of generated tokens.
   • Given a desired temperature value, apply softmax temperature scaling to the predicted next-
     token distributions before sampling.
   • Top-𝑝 sampling ([A. Holtzman et al., 2020] also referred to as nucleus sampling), given a user-
     specified threshold value.

关于这一章的疑问、理解与心得,都可以在这里交流。阅读无需登录;发表评论或回复时使用 GitHub 账号。

正在加载本章讨论…

欢迎交流概念与阅读疑问,请勿发布作业完整实现或题目答案。

输入中文、英文术语或题号,例如 RoPE、检查点、train_bpe。