破晓之刻:Transformer的诞生与自然语言处理前沿

Transformer decoder and GPT

Apply attention mask to forbid the attention from future timesteps to train AR-LM.

A transformer model for AR-LM is also referred to as a transformer decoder.

1
2
3
4
5
6
7
8
9
10
def attention(query, key, value, mask=None, dropout=None):
"Compute 'Scaled Dot Product Attention'"
d_k = query.size(-1)
scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9) #在mask为0的地方加一个很小的负数,保证exp之后趋于0,形状为(L_Q,L_k)
p_attn = scores.softmax(dim=-1)
# 对key维度做softmax
output = torch.matmul(p_attn, value)
return output, p_attn

GPT2

apply the learned model zero-shot to some downstream language generation task (translation, summarization, QA, etc.).

zero-shot:完全不微调

设计一些很好的prompt来实现,比如;

“Translate the following text to French. Text: [ENG TEXT] French:” “Given the document, answer the question. Document: [DOC] Question: [Q] Answer:”

open-ended generation: tasks that has big freedom and diversity, like story or news generation.The model needs to rely its own (memory, consistency or creativity)

topk sampling

We will represent \(P(\cdot | W_{1..i})\) by \(p = (p_1, p_2, \dots, p_{|V|})\) (where the elements are sorted so that \(p_1 \geq p_2 \geq p_3 \dots \geq p_{|V|}\)).

Top-K sampling transforms \(p\) to \(\hat{p}\) by: \[\hat{p}_i = \frac{p_i \cdot \mathbb{1}\{i \leq K\}}{Z}\] \(Z\) 是归一化常数 (normalization constant)。 \[Z = \sum_{i=1}^{|V|} p_i \cdot \mathbb{1}\{i \leq K\} = \sum_{i=1}^{K} p_i\] 保留概率最大的k个,并重新归一化总概率为1。如果k=1,那就变成了greedy decoding了。

quality-diversity trade-off

Rethink MLE(最大似然估计)

MLE 目标函数 (The MLE objective): \[\log P(W) = \sum \log P(W_i | W_{1:i-1})\] * \(P(W_i | W_{1:i-1})\) 是在给定历史上下文 \(W_{1:i-1}\) 的情况下,下一个词是 \(W_i\) 的概率。

  • “Researchers thinks the teacher forcing in MLE training is to blame.” 在训练过程中,当模型预测下一个词 \(W_i\) 时,它使用的历史上下文 \(W_{1:i-1}\) 总是来自于真实的训练数据,而不是模型自己之前预测的词。

The exposure bias hypothesis: Due to the exposure to ground-truth prefix, the model is biased to only perform well during training, but not generation. (训练的时候前文是完美的所以表现好)

Importantly, the error is assumed to accumulate during generation, and the generation will be incrementally distorted(扭曲). 自回归中错误累加

we cannot directly use GAN

GAN 的目标是让生成器 \(G\) 和判别器 \(D\) 互相竞争: \[\min_{G} \max_{D} V(D, G) = \mathbb{E}_{\mathbf{x} \sim p_{\text{data}}(\mathbf{x})}[\log D(\mathbf{x})] + \mathbb{E}_{\mathbf{z} \sim p_{\mathbf{z}}(\mathbf{z})}[\log(1 - D(G(\mathbf{z})))]\] * 判别器 \(D\) 的目标 (最大化 \(\max_{D}\)): * 最大化 \(\log D(\mathbf{x})\) (真实数据 \(\mathbf{x}\) 被判别为真的概率)。 * 最大化 \(\log(1 - D(G(\mathbf{z})))\) (生成数据 \(G(\mathbf{z})\) 被判别为假的概率)。 * 生成器 \(G\) 的目标 (最小化 \(\min_{G}\)): * 最小化 \(\log(1 - D(G(\mathbf{z})))\) (即让生成数据 \(G(\mathbf{z})\) 被判别为真的概率 \(D(G(\mathbf{z}))\) 尽量高)。

  • \(G\) (生成器) 输出的是词汇表上概率分布。
    • 为了得到一个具体的词序列(文本),需要从这个分布中进行采样(例如,选择概率最高的词或用 Top-K 采样)。
    • 语言模型中的词是离散的(例如,"猫"、"狗"、"跑"),而不是像图像像素值那样的连续值。 gradient cannot flow back through discrete sampling!

The gumbel-softmax reparameterization

Gumbel-Max:离散采样的过程:argmax非连续不可微 \[z = \text{one\_hot}(\arg \max_i [\log \pi_i + g_i])\]

Gumbel-Softmax用 Softmax 函数替换了 \(\arg \max\) 操作

\[y_i = \frac{\exp((\log \pi_i + g_i) / \tau)}{\sum_{j=1}^{k} \exp((\log \pi_j + g_j) / \tau)}\]

温度的作用: * \(\tau\) 较大:\(y\) 的分布会更平滑,更接近均匀分布,但近似误差较大。 * \(\tau\) 较小:\(y\) 的分布会更尖锐 (sharper),更接近 One-Hot 向量,从而更好地近似离散的采样,并且更接近 Gumbel-Max 的结果。

对于温度也有diversity-quality trade-off

However, it is shown that language GANs are actually worse than the MLE baseline.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def gumbel_softmax(logits, tau=1.0, hard=False, dim=-1):
"""
实现了 Gumbel-Softmax 重参数化技巧。

参数说明:
logits (Tensor): 未标准化的对数概率(来自生成器 G 的输出)。
tau (float): 温度参数 (τ),控制 Softmax 近似的平滑程度。
hard (bool): 如果为 True,则应用 Straight-Through(直通)技巧:
在前向传播中使用 One-Hot 向量,而在反向传播中使用连续梯度。
dim (int): 应用 Softmax 的维度(通常是词汇表维度)。
"""

# --- 1. Gumbel 噪声注入 ---

# 1a. 生成 Gumbel 噪声 g_i ~ Gumbel(0, 1)。
# 这是通过逆变换采样方法实现的:g_i = -log(-log(U)),其中 U ~ Uniform(0, 1)。
gumbels = -torch.empty_like(logits).exponential_().log()

# 1b. 将 Gumbel 噪声添加到 logits 并除以温度 (tau)。
# 这对应于 Gumbel-Softmax 公式中的分子部分:(log(pi_i) + g_i) / tau
gumbels = (logits + gumbels) / tau

# --- 2. 连续 Softmax 输出 (y_soft) ---

# 计算连续的、可微分的 Softmax 输出。
# 这个 y_soft 值用于在反向传播中计算梯度。
y_soft = gumbels.softmax(dim)

# --- 3. Straight-Through(直通)技巧实现 ---

if hard:
# A. 前向传播(使用硬性 One-Hot 向量)

# 找到 y_soft 中最大概率值对应的索引。
# [1] 从 .max() 返回的元组中提取索引(max_indices)。
# 这模拟了 Gumbel-Max 技巧中的 arg max 操作。
index = y_soft.max(dim, keepdim=True)[1]

# 基于最大索引,创建一个硬性(离散)的 One-Hot 向量 y_hard。
# 在前向计算中(例如作为判别器 D 的输入),使用的是 y_hard。
y_hard = torch.zeros_like(logits).scatter_(dim, index, 1.0)

# B. 反向传播(使用柔性连续梯度)

# Straight-Through 表达式:ret = y_hard - y_soft.detach() + y_soft
# 梯度分析(链式法则):
# 1. d(y_hard)/d(logits) ≈ 0 (由于离散/arg max 操作,梯度被忽略)。
# 2. d(y_soft.detach())/d(logits) = 0 (梯度被 .detach() 显式切断)。
# 3. d(y_soft)/d(logits) 是唯一有效的、平滑的梯度。
# 最终梯度:d(ret)/d(logits) ≈ d(y_soft)/d(logits)
ret = y_hard - y_soft.detach() + y_soft

else:
# 标准重参数化技巧(不使用 ST 技巧)。
# 连续的 y_soft 向量用于前向和反向传播。
ret = y_soft

return ret

policy gradient

避免了采样导致的不可微分

公式右侧的梯度 \(\nabla_{\theta}\) 只作用于对数概率 \(\log P_{\theta}(\mathbf{y}|\mathbf{x})\)。 * \(\log P_{\theta}(\mathbf{y}|\mathbf{x})\) 是一个连续且可微分的函数,它是模型输出概率的对数,与模型参数 \(\theta\) 之间有明确的、可微分的计算图。 * 回报 \(r(\mathbf{x}, \mathbf{y})\) 只是一个在采样完成后计算出来的标量权重(它不依赖于 \(\theta\),因此求梯度时被视为常量)。 * 采样过程 \(\mathbf{y} \sim P_{\theta}\) 被移到了期望 \(\mathbb{E}\) 的外部,通过蒙特卡洛(Monte Carlo)方法近似实现。

MLE 希望更多的diversity

最大似然估计 - MLE: \[\arg \min_{\theta} \underset{W \sim P_D}{\mathbb{E}} \left[ -\frac{1}{L} \sum_{l=0}^{L-1} \log P_M(W_{l+1}|W_{1:l}) \right]\]

根据链式法则,\(P_M(W) = P_M(W_1) \cdot P_M(W_2|W_1) \cdots P_M(W_L|W_{1:L-1})\),因此负对数似然可以简化为对整个序列 \(W\) 的负对数似然的期望。

\[\arg \min_{\theta} \underset{W \sim P_D}{\mathbb{E}} \left[ -\log P_M(W) \right]\]

\[D_{KL}(P_D || P_M) = \underset{W \sim P_D}{\mathbb{E}} [\log P_D(W)] - \underset{W \sim P_D}{\mathbb{E}} [\log P_M(W)]\]

前一项就是真实分布的entropy的负数,所以我们可以看出MLE是希望model的分布非常接近真实的分布

exposure bias 不是大问题——The Prefix Switching Experiment

第一组,给真实的句子

第二组,自回归

第三组,随机token前缀

Did the error accumulate ? 模型在前缀中接收到了严重的错误或干扰(打乱的或随机的 Token),但它并没有导致整个后续序列的生成质量灾难性地下降。

Mysteriously, the model self-recovers from the errors in the prefix.

For the shuffled data prefix, the model still generates something related to the air force.

EB-M, quantifies the quality ratio between generations from data prefix and a given (imperfect) prefix.

The combination of MLE training and sampling algorithm is very strong and is the default choice.

sampling

topk

\[\hat{p}_i = \frac{p_i \cdot \mathbf{1}\{i \leq K\}}{Z}\]

topp

\[\hat{p}_i = \frac{p_i \cdot \mathbf{1}\{\sum_{j=1}^{i-1} p_j < P\}}{Z}\]

Temperature Sampling

\[\hat{p}_i = \frac{\exp(\log(p_i)/T)}{Z} = \frac{(p_i)^{1/T}}{Z}\]

🤔 它们有什么共同点?

Entropy Reduction Order Preservation Slope Preservation

1. 元素顺序得以保留

\(p_i \ge p_j \implies \hat{p}_i \ge \hat{p}_j\)

2. 分布的熵被降低

\(\mathcal{H}(\hat{p}) \le \mathcal{H}(p)\)

3. 分布的斜率得以保留

\[\frac{\log p_i - \log p_j}{\log p_l - \log p_k} = \frac{\log \hat{p}_i - \log \hat{p}_j}{\log \hat{p}_l - \log \hat{p}_k}\]

Correcting bad behavior of NLG models

repeat

这种基于点积的匹配机制,尤其是在解码 (Decoding) 阶段与贪婪搜索 (Greedy Search) 或波束搜索 (Beam Search) 结合时,特别容易导致重复:

  • 语义惯性:Transformer 本质上是擅长捕捉局部依赖和语义一致性的。当一个序列在短时间内重复出现时,模型会认为“保持这种模式”是最安全、最一致的选择,从而在众多可能的下一个词中,倾向于选择与当前历史相似度最高的词(即点积分数最高的词)。
  • 缺乏全局抑制:标准的 Transformer 架构在设计上缺乏一个内置的机制来惩罚或抑制刚刚生成过的内容。它只是在寻找局部最佳匹配,而点积正是找到这个局部最佳匹配(相似度)的有效工具。

Biased decoding

\[p_i = \frac{\exp(x_i / (T \cdot I(i \in g)))}{\sum_{j} \exp(x_j / (T \cdot I(j \in g)))}\]

  • \(I(c)\):这是一个指示函数 (Indicator Function) 或惩罚因子,定义如下: \[I(c) = \begin{cases} \theta & \text{if } c \text{ is True} \\ 1 & \text{else} \end{cases}\]

  • \(\theta\) (Theta):设定为 \(1.2\),对重复 token 的惩罚/偏差因子。

  • 对于新的、未重复的 Token \(i\): 指示函数 \(I(i \in g)\) 的值为 \(1\)

  • 对于已生成的、重复的 Token \(j\): 指示函数 \(I(j \in g)\) 的值为 \(\theta = 1.2\),导致整个分数 \(x_j / (T \cdot \theta)\) 变小,降低重复的概率

Unlikelihood training for repetition

\[\mathcal{L}^t_{\text{UL-token}} \left( p_\theta(\cdot|x_{<t}), c^t \right) = - \alpha \sum_{c \in c^t} \log(1 - p_\theta(c|x_{<t})) - \log p_\theta(x_t|x_{<t})\]

最大化似然(后一项),最小化预测出重复token的概率(前一项)

Generic Response Problem

模型给出的generic的回复,而不是有针对性的信息量大的回复

Combined with MLE training, when the model is not sure about what to say, it degrades to some simple and “safe” pattern in data.

Maximum Mutual Information (MMI)

\[\text{MMI}(S; T) = \log \frac{P(S, T)}{P(S)P(T)}\]

\[\hat{T} = \arg \max_T \left\{ \log P(T|S) - \log P(T) \right\}\]

在有前文的条件下后文出现的概率-后文单独出现的概率,惩罚和前文关系不大的通用回答。

negative training

用负样本告诉大模型不应该去说什么

\[\text{Loss}_{\text{new}} = \underbrace{- \log P_\theta(y_{\text{pos}}|x_{\text{pos}})}_{\text{最大似然项 (正样本)}} + \underbrace{\log P_\theta(y_{\text{neg}}|x_{\text{neg}})}_{\text{负样本惩罚项}}\]

Transformer encoder-decoder

Each decoder layer is a selfattention followed by a crossattention.

The query vector for a transformer decoder’s cross-attention head is from the output of the previous decoder layer. However, the key and value vectors are from the encoders’ outputs.

Why decoder-only LM is more convenient (less design choiceto consider) or efficient (for both training or application)?

Pretraining (left) and chatbot generation (right) are highly consistent.

• Naturally handles variable-length text generation during pretraining!

• During application, we just do natural concatenation (always causal attention). No computation is wasted (assuming we save hidden states of the history).

In pretraining, we need to build text of variable length, and the training signal is only from the decoder side.

• During application, we need to re-encode (especially when the encoder is bi-directional) the whole history for each dialogue turn.

rope

We want the dot product between query (position \(m\)) and key (position \(n\)) to directly be a function of (\(m-n\)).

\[ \langle \boldsymbol{f}_{\boldsymbol{q}}(\boldsymbol{x}_m, m), \boldsymbol{f}_{\boldsymbol{k}}(\boldsymbol{x}_n, n) \rangle = \boldsymbol{g}(\boldsymbol{x}_m, \boldsymbol{x}_n, m-n) \]

GPT3 and in-context learning

上下文学习(ICL)是指 大型语言模型通过分析其输入提示(Prompt)中嵌入的少数示例或演示(Demonstrations),来快速理解并执行特定下游任务的能力,而无需进行传统的模型参数更新(即无需微调或梯度下降)。

few shot before GPT3

Before GPT3, few-shot learning still refers to how a model can quickly adapt to a new task demonstrated with only a few examples via gradient update.

We have a meta-learning phase on a wide set of tasks. In effect, the meta-learning problem treats entire tasks as training examples.(把一个任务看作一个样本,想要学习到一个比较好的初始配置)

chain of thought (cot)

idea:reasoning is more consuming than computation,give llm more time to think

cot 的效果在模型大的时候更加明显

few-shot: 给几个例子——add manually written reasoning before giving answer in prompt.

zero-shot: chaining of 2 prompts. 第一步明确说要一步一步推理,获得推理的过程。第二步接着这个告诉它输出的格式,获得正确的输出。

research

CoT with self-consistency

For CoT, we could sample multiple reasoning path from the LLM with temperature sampling. 温度越高越随机,越有diversity

And then take a majority voting over the answers!

Tree of Thoughts

Maintain and expand a thought-tree.

• For each existing step, we prompt the LLM to propose multiple next steps, and also to judge which path (by giving a value) is more promising (pls refer to paper for how the prompts are designed).

• The nodes that are judged to be unlikely will be discarded

bias in icl

Majority and recency bias

多数偏差是指在少样本学习的提示中,如果提供的训练示例的类别分布是不平衡的,模型就会倾向于预测出现次数最多的那个类别。即使一个新的测试样本客观上属于少数类别,模型也更倾向于输出多数类别,从而牺牲了少数类别的召回率和整体准确性。

近因偏差是指在少样本学习的提示中,模型会倾向于预测在提示末尾(或最近)出现的类别。即使提示中的类别分布是平衡的,仅仅改变示例的顺序,也会显著改变模型的预测结果,导致预测的高方差(不稳定)。

Calibration (修正)of few-shot prediction

\[\mathbf{\hat{q}} = \text{softmax}(\mathbf{W}\mathbf{\hat{p}} + \mathbf{b})\] * \(\mathbf{\hat{p}}\):模型(如大型语言模型 LLM)原始预测的类别概率分布向量。 * \(\mathbf{W}\):权重矩阵。 * \(\mathbf{b}\):偏置向量 (bias)。 * \(\mathbf{\hat{q}}\):校准后的类别概率分布向量。

利用模型对“空输入”的预测 \(\text{prediction}_{\text{null}}\) 来抵消其固有的偏差。 * 设置 \(\mathbf{b}\): 将偏置向量 \(\mathbf{b}\) 设为 \(\mathbf{0}\)。 * 设置 \(\mathbf{W}\): 将权重矩阵 \(\mathbf{W}\) 设为一个对角矩阵,其对角线元素是空输入预测概率的倒数。 \[\mathbf{W} = \text{diag}(\text{prediction}_{\text{null}})^{-1}\] 这是希望最后空输入的输出分布是均匀的

Induction attention head: for repetition

“归纳注意力头”不是 Transformer 架构中预设的组件,而是模型在训练过程中自发学习到的、由一个或多个注意力头(通常是两个头在不同层中协作)组成的功能性电路(Circuit)。

假设输入序列是:...[A][B]...[A]

当模型处理第二个 [A] 时,归纳头会执行以下操作:

匹配(Match): 它会回顾序列,找到上一次出现 [A] 的位置。

复制/预测(Copy/Predict): 它会查看上一次 [A] 后面紧跟着的标记 [B],并利用这个信息来预测当前第二个 [A] 后面也应该跟着 [B]。

简单来说,它能发现并应用序列中重复出现的 [A] → [B] 模式。

Instruction tuning

motivation: we are lazy, 希望zero-shot prompting(不给例子)

FLAN (Finetuned Language Net)

Simple idea: After pretraining, we finetune the language model on a good amount of “instruction following” data.

Each training samples contains the task description, an input, and the target output.

During evaluation, we hope the model can generalize to unseen task type.

FLAN data construction: Collected data from 62 existing NLP tasks. For each task, manually compose ten unique templates (for diversity) that use natural language instructions to describe the task.

Alignment with reinforcement learning human feed back (RLHF)

We collect samples from the model, and ask labelers to rank them. These ranks are used to train the reward model

This reward model is used for RL.

Why is it practical?

• It’s also easier for the human labeler to rank the responses, than coming up with a better response.

• From pretraining, the LLM might be strong enough to give a good sample when you sample enough times.

what could be its advantage

(comparing to, say, more supervised finetuning on high-quality data)?

• It’s usually easier to train a good discriminator than a good generator (especially now that we can use base the reward model on an existing LLM).

• By giving low reward, we are teaching the model “what not to say” by sampling from it.

让机器生成更符合我们需求的回答

Trivial method: Prompting(Directly prompt the LM to align)

Pros: Training-free;

Cons: No guarantee that the model will precisely follow, and requires careful prompt design

Best-of-N

  1. Samples multiple solutions;
  2. Chooses the one with the highest score given by a reward model.

Pros: Do not need to train the policy model, simple and powerful;

Cons: not efficient and you might need a large N

objective

\[\max_{\pi_{\theta}} \mathbb{E}_{x \sim \mathcal{D}, y \sim \pi_{\theta}(\cdot|x)} \left[ r_{\phi}(x, y) \right] - \beta \mathbb{D}_{\text{KL}} \left[ \pi_{\theta}(\cdot | x) \parallel \pi_{\text{ref}}(\cdot | x) \right]\]

\[\mathbb{E}_{x \sim \mathcal{D}, y \sim \pi_{\theta}(\cdot|x)} \left[ r_{\phi}(x, y) - \beta (\log \pi_{\theta}(y|x) - \log \pi_{\text{ref}}(y|x)) \right]\]

奖励模型 \(\phi\) , 前一项是为了提高奖励

后一项防止优化后的模型 \(\pi_{\theta}\) 偏离太远(deviating too far)于初始参考模型 \(\pi_{\text{ref}}\) (Reward over-optimization issue) The reward model is an imperfect proxy, optimizing its value too much can hinder ground truth performance (first increase, then decrease).

\(\pi_{\theta}(\cdot | x)\)\(\pi_{\text{ref}}(\cdot | x)\)含义: 它们代表在给定输入 \(x\) 的条件下,所有可能的输出 \(y\) 上的完整概率分布。

\(\pi_{\theta}(y|x)\)\(\pi_{\text{ref}}(y|x)\)含义: 它们代表在给定输入 \(x\) 的条件下,模型生成特定回复 \(y\) 的概率。

synthetic(人造的) setting for the Gold model:实际上并没有真的用人类标记,而是使用大模型标记

PPO

算法 对应行为 结果
策略梯度 (PG) 司机非常激进,一脚油门到底或一脚刹车踩死。 方差太大 (Variances are too high),容易导致训练不稳定甚至崩溃。
TRPO 司机知道要温和驾驶,但每次启动前都要用复杂的数学公式精确计算方向盘转角和油门深度。 安全稳定,但实现极其复杂,计算成本高。
PPO-Clip 司机学了一个简单的“安全规则”:如果当前操作被认为很好,就鼓励他继续,但不能超过一个固定的限度。如果操作不好,就限制他别做得太差。 安全且高效。 它用一个简单的“截断”机制,达到了与 TRPO 相似的稳定效果,但避免了复杂的计算。

PPO 的直觉就体现在它的 CLIP 目标函数中:

\[L^{CLIP}(\theta) = \mathbb{E}_t \left[ \min\left( p_t(\theta) \hat{A}_t, \text{clip}(p_t(\theta), 1-\epsilon, 1+\epsilon) \hat{A}_t \right) \right]\]

  1. \(p_t(\theta)\) (新旧策略的比率):代表新策略 \(\pi_\theta\) 相对于旧策略 \(\pi_{\theta_{old}}\) “变动了多少”。
  2. 优势函数 \(\hat{A}_t\):代表当前动作 \(a_t\) 的好坏程度。
  3. 核心直觉(最小化和截断):
    • \(\hat{A}_t\) 为正(动作好):PPO 想要提高这个动作的概率(增大 \(p_t(\theta)\)),但 \(\min\) 函数会确保这个比率不会超过 \(1+\epsilon\)。这就好像在说:“你做得很好,但我只奖励你到这个程度,防止你太得意忘形,把策略改得面目全非。”
    • \(\hat{A}_t\) 为负(动作差):PPO 想要降低这个动作的概率(减小 \(p_t(\theta)\)),但 \(\min\) 函数会确保这个比率不会低于 \(1-\epsilon\)。这就好像在说:“你做得很差,我惩罚你,但惩罚不能太重,防止你一次性把策略改错。”

PPO的问题: too much hyper parameters

DPO

Advantage: We no longer need a reward model or a value model.

\[\mathcal{L}_{\text{DPO}}(\pi_{\theta}; \pi_{\text{ref}}) = -\mathbb{E}_{(x, y_w, y_l) \sim \mathcal{D}} \left[ \log \sigma \left( \beta \log \frac{\pi_{\theta}(y_w | x)}{\pi_{\text{ref}}(y_w | x)} - \beta \log \frac{\pi_{\theta}(y_l | x)}{\pi_{\text{ref}}(y_l | x)} \right) \right].\] \(y_w\):模型对 \(x\) 生成的被选择/偏好 (winner) 的回复。\(y_l\):模型对 \(x\) 生成的被拒绝/不偏好 (loser) 的回复。

\[\nabla_{\theta}\mathcal{L}_{\text{DPO}}(\pi_{\theta}; \pi_{\text{ref}}) = -\beta \mathbb{E}_{(x, y_w, y_l) \sim \mathcal{D}} \left[ \sigma(\hat{r}_{\theta}(x, y_l) - \hat{r}_{\theta}(x, y_w)) \left[ \nabla_{\theta} \log \pi_{\theta}(y_w | x) - \nabla_{\theta} \log \pi_{\theta}(y_l | x) \right] \right].\]

A. 策略更新方向 (Action Term)

\[\left[ \nabla_{\theta} \log \pi_{\theta}(y_w | x) - \nabla_{\theta} \log \pi_{\theta}(y_l | x) \right]\] * 这是梯度上升方向

B. 奖励估计 (Estimated Reward)

\[\hat{r}_{\theta}(x, y) = \beta \log \frac{\pi_{\theta}(y | x)}{\pi_{\text{ref}}(y | x)}\] * DPO 的关键在于,它隐含地将奖励模型 \(r(x, y)\) 替换成了策略模型 \(\pi_{\theta}\) 相对于参考模型 \(\pi_{\text{ref}}\) 的对数概率比,再乘以 \(\beta\)。这个 \(\hat{r}_{\theta}(x, y)\) 被称为经验奖励 (empirical reward),它是策略 \(\pi_{\theta}\) 在当前参数下对 \(y\) 的奖励估计。

C. 权重项 (Weight Term)

\[\sigma(\hat{r}_{\theta}(x, y_l) - \hat{r}_{\theta}(x, y_w))\] * 如果当前策略 \(\pi_{\theta}\) 已经正确地捕捉了偏好(即 \(\hat{r}_{\theta}(x, y_w) > \hat{r}_{\theta}(x, y_l)\)),那么这个奖励差异 \((\hat{r}_{\theta}(x, y_l) - \hat{r}_{\theta}(x, y_w))\) 是一个较大的负数。Sigmoid 函数 \(\sigma(\text{大负数})\) 接近 0,因此权重很小。 * 如果当前策略 \(\pi_{\theta}\) 错误地捕捉了偏好(即 \(\hat{r}_{\theta}(x, y_w) < \hat{r}_{\theta}(x, y_l)\)),那么这个奖励差异是一个正数。Sigmoid 函数 \(\sigma(\text{正数})\) 接近 1 或 0.5 以上,因此权重很大。

✨ 进一步的直觉:正则化 (Regularization Intuition)

\(\beta [\log \pi_{\theta}(y_l|x) - \log \pi_{\theta}(y_w|x)] - \beta [\log \pi_{\text{ref}}(y_l|x) - \log \pi_{\text{ref}}(y_w|x)]\)

这个表达式实际上是: \[\underbrace{\beta (\log \frac{\pi_{\theta}(y_l|x)}{\pi_{\theta}(y_w|x)})}_{\text{策略 } \pi_{\theta} \text{的 log-prob 差异}} - \underbrace{\beta (\log \frac{\pi_{\text{ref}}(y_l|x)}{\pi_{\text{ref}}(y_w|x)})}_{\text{参考 } \pi_{\text{ref}} \text{的 log-prob 差异}}\]

  • DPO 目标: DPO 损失的目标是让策略 \(\pi_{\theta}\)\(y_w\)\(y_l\) 的对数概率差异 (\(\log \pi_{\theta}(y_w|x) - \log \pi_{\theta}(y_l|x)\)) 增大(即让 \(y_w\)\(y_l\) 更可能出现)。
  • 正则化作用: DPO 损失要求 \(\pi_{\theta}\) 的这个差异不仅要大,而且要相对于参考模型 \(\pi_{\text{ref}}\) 的原始差异进行调整。
  • 结论: DPO 实际上是在正则化策略 \(\pi_{\theta}\) 的对数概率差异,使其在拟合人类偏好的同时,不会过度偏离基础模型 \(\pi_{\text{ref}}\) 的行为。这与 RLHF-PPO 中使用 KL 散度进行正则化有相似的目的,但 DPO 将这个正则化直接嵌入到了损失函数的定义中。

DPO 通过绕过 奖励模型 (Reward Model) 和 强化学习 (RL) 步骤,使得训练过程更简单、更稳定。 RLHF-PPO 由于引入了复杂的强化学习和奖励模型,被认为有更大的潜力(可能在复杂的对齐任务上表现更好)。

Mixture of Experts Model

Idea of conditional computation: We still build a super big model, but we only selectively activate a relevant portion for each training sample.

MoE is natural for model parallel

\[ G(x) = \text{Softmax}(\text{KeepTopK}(H(x), k)) \]

\[ \text{KeepTopK}(v, k)_i = \begin{cases} v_i & \text{if } v_i \text{ is in the top } k \text{ elements of } v \\ -\infty & \text{otherwise} \end{cases} \]

\[ H(x)_i = (x \cdot W_{g})_i + \text{StandardNormal}() \cdot \text{Softplus}((x \cdot W_{\text{noise}})_i) \]

  • 核心线性变换: \((x \cdot W_{g})_i\) 是对输入 \(x\) 应用权重矩阵 \(W_{g}\) 后的第 \(i\) 个元素。这是计算专家 \(i\) 初始得分的基础。
  • 噪声项: 防止专家过度专业化 (Over-Specialization) 或坍塌 (Collapse):门控网络 \(G(x)\) 倾向于将相似的输入持续路由到得分最高的少数专家。这会导致这些少数专家被过度使用 (over-utilized),而其他大多数专家则利用不足 (under-utilized),参数更新少,形同虚设。这种不平衡也被称为“路由坍塌” (Routing Collapse)。

Balancing loads between experts

\[\text{Importance}(X) = \sum_{x \in X} G(x) \quad \text{(6)}\]

  • \(G(x)\) 是指门控值(gate value)。在MoE模型中,门控网络会为每个输入 \(x\) 输出一个分布,决定将该输入分配给哪个专家。
  • \(\text{Importance}(X)\) 是该专家在整个批次 \(X\) 中所有样本门控值(使用概率)的总和。这个值衡量了该专家在当前批次中被激活和使用的程度。

负载均衡损失 \(\mathcal{L}_{\text{importance}}\) 是根据所有专家的重要性值集合计算得出的:

\[\mathcal{L}_{\text{importance}}(X) = w_{\text{importance}} \cdot \text{CV}(\text{Importance}(X))^2 \quad \text{(7)}\]

  • \(\text{Importance}(X)\) 此时是一个向量,包含了所有专家各自的 \(\text{Importance}\) 值。
  • \(\text{CV}(\cdot)\) 是变异系数(Coefficient of Variation),其定义如下: \[\text{CV} = \text{std}/\text{mean}\] 即:\(\text{CV} = \text{标准差} / \text{均值}\)
  • \(w_{\text{importance}}\) 是一个手动调整的缩放因子(scaling factor),用于控制此损失在总损失中的权重和影响力。

最小化 \(\mathcal{L}_{\text{importance}}\) 意味着最小化 \(\text{CV}(\text{Importance}(X))\)。由于 \(CV\) 越小表示数据越集中,因此这鼓励所有专家具有近似相等的“重要性”,从而实现了专家间的均衡负载。

更简单的负载均衡损失”解析

\[\text{loss} = \alpha \cdot \sum_{i=1}^{N} f_i \cdot P_i \quad \text{(4)}\]

在这里,\(p\) 指的是 路由器概率(Router Probability),也称为 门控概率(Gate Probability)。

  • \(p_i(x)\): 是指门控网络(Router)对输入 \(x\) 计算得到的、将其分派给第 \(i\) 个专家的概率。
    • 在MoE模型中,门控网络通常会输出一个 \(N\) 维的概率向量 \(p(x)\),其中 \(N\) 是专家数量,\(\sum_{i=1}^{N} p_i(x) = 1\)
  • \(P_i\) (公式 6): 是指在整个批次 \(B\) 中,分配给第 \(i\) 个专家的概率的平均值。 \[P_i = \frac{1}{T} \sum_{x \in B} p_i(x) \quad \]

\(f_i\) 表示在当前批次 \(B\) 中实际被分派(hard-routed)给专家 \(i\) 的 tokens 的比例(Actual Usage):

\[f_i = \frac{1}{T} \sum_{x \in B} \mathbb{I}\{\operatorname{argmax} p(x) = i\} \quad \]

  • \(\operatorname{argmax} p(x) = i\) 表示 \(p_i(x)\) 是所有专家中概率最大的,即样本 \(x\) 最终被确定分派给了专家 \(i\)
  • \(f_i\) 衡量的是专家 \(i\) 在当前批次中 “硬性”处理的实际工作量。

惩罚少数专家被过度使用

特性 \(f_i\)(实际使用率 - Actual Usage) \(P_i\)(概率分配率 - Allocated Probability)
公式 \[f_i = \frac{1}{T} \sum_{x \in B} \mathbb{I}\{\operatorname{argmax} p(x) = i\}\] \[P_i = \frac{1}{T} \sum_{x \in B} p_i(x)\]
含义 硬性选择结果。实际被分派给专家 \(i\) 的 tokens 占总 tokens 数 \(T\) 的比例。 软性概率均值。门控网络分配给专家 \(i\) 的概率 \(p_i(x)\) 在整个批次 \(B\) 中的平均值。
计算基准 基于 \(\operatorname{argmax}\) 运算:只关心哪个专家获得了最高的概率,结果是 0 或 1(指示函数 \(\mathbb{I}\))。 基于 软概率 \(p_i(x)\) 的求和:考虑了门控网络对所有专家的概率分配大小。
代表性 衡量专家 \(i\) 实际处理的工作量。 衡量专家 \(i\) 预期被使用的平均概率权重。

Fine-Grained Expert Segmentation

while maintaining the number of parameters constant, we segment the experts into a finer grain by splitting the FFN intermediate hidden dimension.

Shared Expert Isolation

we isolate certain experts to serve as shared experts that are always activated, aiming at capturing and consolidating common knowledge across varying contexts. (一部分是专家for通用知识,一直被激活)


破晓之刻:Transformer的诞生与自然语言处理前沿
http://example.com/2025/12/12/nlp3/
作者
瑾瑜當年
发布于
2025年12月12日
许可协议