Basic Math

1. Basic statistics

1.1 Operations

类型Formula大白话定义LLM Use Case(带公式)
Arithmetic Mean 算术平均\(\mu=\frac1N\sum_i x_i\)全部加起来,平均分SFT Loss:对有效 token positions 的 CE 求平均(\(N\) 仅计入有效 target positions),\(L=-\frac1N\sum_t\log p_t\)。Mean log probability:\(\bar\ell=\frac1N\sum_t\log p_t=-L\),是每个 token 的平均 log probability。
Weighted Mean 加权平均\(\mu_w=\frac{\sum_iw_ix_i}{\sum_iw_i}\)重要的数据占更大权重Attention:用 attention probabilities 加权 Values,\(o_t=\sum_j a_{tj}V_j\),其中 \(\sum_j a_{tj}=1\)。
Geometric Mean 几何平均\(GM=(\prod_i x_i)^{1/N}\);\(GM=e^{\frac1N\sum_i\log x_i}\)连乘后开 N 次方,适合平均倍率(\(x_i>0\))Perplexity:\(PPL=(\prod_t p_t)^{-1/N}=e^{-\bar\ell}\)。Geometric mean token probability:\(GM(p)=P(y\mid x)^{1/N}=e^{\bar\ell}\),因此 \(PPL=1/GM(p)\)。GM 是长度归一化后的典型 token probability,不是整条 sequence 的概率。
Harmonic Mean 调和平均\(HM=\frac{N}{\sum_i1/x_i}\)先取倒数再平均,特别受较小值影响(\(x_i>0\))F1 Score:Precision 和 Recall 的调和平均,\(F_1=\frac{2PR}{P+R}\)。
RMS 均方根\(RMS(x)=\sqrt{\frac1N\sum_i x_i^2}\)先平方再平均开根号,衡量整体数值大小RMSNorm:\(y=\frac{x}{\sqrt{\operatorname{mean}(x^2)+\epsilon}}\odot\gamma\),稳定 hidden-state scale。
Expectation 期望\(\mathbb E[X]=\sum_i p_ix_i\)考虑每种结果发生的概率,算平均收益RL Objective:最大化 policy 的 expected reward,\(J(\theta)=\mathbb E_{y\sim\pi_\theta(\cdot\mid x)}[R(x,y)]\)。
Sum 求和\(S=\sum_i x_i\)把所有数字加起来Sequence Log Probability:整条回答的 log probability 是各 token 的 log probabilities 之和,\(\log P(y\mid x)=\sum_t\log p_t\)。
Product 连乘\(P=\prod_i x_i\)把所有数字乘起来Autoregressive LM / sequence probability:整条回答的概率是条件概率连乘(\(p_t\) 是给定 prompt 和已有回答后,实际 token 的条件概率;\(N\) 是计入的 token 数,完整终止序列需包含 EOS 等结束事件),\(P(y_{1:N}\mid x)=\prod_{t=1}^{N}p_t\),其中 \(p_t=P(y_t\mid x,y_{\lt t})\)。
Log 对数\(\log(ab)=\log a+\log b\)把连乘变成连加,方便计算很小的概率(\(\log\) 默认是自然对数)NLL:\(L=-\log P(y\mid x)=-\sum_t\log p_t\),用于 SFT training;这里是 sequence NLL,除以有效 token 数后得到平均 token loss。
Exp 指数\(e^{a+b}=e^ae^b\)Log 的反向操作,把 log-space 的差或和还原PPO/GRPO:用同一 token、同一 context 下 log probabilities 的差计算 ratio,\(r_t=e^{\log\pi_\theta(y_t)-\log\pi_{\rm old}(y_t)}\)。
Variance 方差\(\sigma^2=\frac1N\sum_i(x_i-\mu)^2\)衡量数字围绕平均值分散得有多厉害GRPO:Group reward variance 为 \(\sigma_r^2=\frac1G\sum_i(r_i-\bar r)^2\),用于衡量 rollout rewards 的差异。
Standard Deviation 标准差\(\sigma=\sqrt{\sigma^2}\)方差开根号,得到和原数据相同单位的波动大小GRPO Advantage:常见形式 \(A_i=\frac{r_i-\bar r}{\sigma_r+\epsilon}\),衡量 rollout 相对 group 的表现。
LogSumExp\(LSE(z)=\log\sum_i e^{z_i}\)先 exp、求和、再 log;常用于稳定地归一化 logitsLogSoftmax:Softmax 是 \(p_i=\frac{e^{z_i}}{\sum_j e^{z_j}}\);取 log 得到 \(\log p_i=z_i-\log\sum_j e^{z_j}\),所以 \(\boxed{\log p_i=z_i-\operatorname{LSE}(z)}\)。CE:\(\boxed{L=-\log p_{\mathrm{correct}}}\),所以 \(\boxed{L=\operatorname{LSE}(z)-z_{\mathrm{target}}}\)。
EMA 指数移动平均\(m_t=\beta m_{t-1}+(1-\beta)x_t\)最近的数据权重大,旧数据逐渐淡化Adam Optimizer:Gradient 一阶动量使用 EMA,\(m_t=\beta_1m_{t-1}+(1-\beta_1)g_t\)。
Min / Max 极值\(m=\max_i x_i\)找到最小或最大的数字Stable Softmax:先减最大 logit,\(p_i=\frac{e^{z_i-m}}{\sum_je^{z_j-m}}\),防止 overflow。
Median 中位数\(P_{50}(X)\)排序后处于中间的数,不容易被极端值带偏Inference:P50 latency 表示约一半请求的延迟不超过该值,\(P50=Q_{0.5}(T_{\rm latency})\)。
Quantile 分位数\(Q_q(X)\)排序后某个百分位对应的值Serving:P99 latency,\(Q_{0.99}(T_{\rm latency})\),衡量慢请求的尾部延迟。
Power Mean 幂平均\(M_p=(\frac1N\sum_ix_i^p)^{1/p}\)一个通用公式,通过改变 p 得到不同的平均数(\(x_i>0\))RMSNorm:\(p=2\) 时 \(M_2=RMS\);\(p\to0\) 得到 GM(正数输入),\(p=-1\) 得到 HM。

1.2 Expectation、Variance 与 Monte Carlo

类型Formula大白话定义LLM Use Case(带公式)
Expectation 期望\(\mu=\mathbb E[X]=\sum_xp(x)x\)可能结果按概率加权的平均(例如正确概率 0.7、reward 为 1,错误 reward 为 0,期望 reward 就是 0.7)。Policy reward:\(J(\theta)=\mathbb E_{y\sim\pi_\theta}[R(x,y)]\),衡量当前策略的平均表现。
Population variance 总体方差\(\operatorname{Var}(X)=\mathbb E[(X-\mu)^2]\);\(\sigma_N^2=\frac1N\sum_i(x_i-\bar x)^2\)偏离均值的平方的平均;描述当前这批数时分母用 \(N\)。Rollout spread:衡量 rollout rewards 的离散程度;PyTorch 用 rewards.var(correction=0)。
Standard deviation 标准差\(\sigma=\sqrt{\operatorname{Var}(X)}\)方差开根号,单位与原数据一致;Std 大只表示样本波动大,不等于均值估计一定差。GRPO:用组内 reward 标准差归一化相对表现,\(A_i=\frac{r_i-\bar r}{\sigma_r+\epsilon}\)。
Sample variance 样本方差\(s^2=\frac1{N-1}\sum_i(X_i-\widehat\mu)^2\)用独立样本估计总体方差,通常分母用 \(N-1\)(\(N>1\))。Reward estimation:估计策略 reward 的总体波动;PyTorch 用 rewards.var(correction=1)。
Monte Carlo mean 采样均值\(\widehat\mu=\frac1N\sum_iX_i\)从目标分布独立采样,用样本均值近似无法穷举的期望。Rollout evaluation:\(\widehat J=\frac1N\sum_iR(x,y_i)\),其中 \(y_i\sim\pi_\theta\);有限次 rollout 的均值只是估计,不是策略的固定得分。
Standard error 均值标准误\(\operatorname{SE}(\widehat\mu)\approx s/\sqrt N\)衡量均值估计的不确定性;独立采样时通常按 \(1/\sqrt N\) 缩小。Evaluation confidence:独立 rollout 的 \(\operatorname{SE}(\widehat J)\approx s_R/\sqrt N\);相关样本会降低有效样本量,不能直接套用独立采样误差。
PyTorch implementation
import torch
rewards = torch.tensor([1., 0., 1., 1., 0.])
mean = rewards.mean()
population_var = rewards.var(correction=0)
sample_var = rewards.var(correction=1)
se = rewards.std(correction=1) / rewards.numel() ** 0.5
print([round(x.item(), 4) for x in [mean, population_var, sample_var, se]])
# [0.6, 0.24, 0.3, 0.2449]
# 5 次 rollout 只是很粗的估计;单次平均值不是策略的固定得分。
Statistics
类型Formula大白话定义LLM Use Case(带公式)
p-value\(p=\Pr_{H_0}(T(X)\text{ 至少与观测一样极端})\)在 null hypothesis \(H_0\) 与检验假设成立时,出现至少这么极端统计量的概率;不是 \(P(H_0\text{ 为真})\)。Model comparison:判断差异是否与 \(H_0\) 相容;\(p\ge0.05\) 不代表两个模型完全相同,显著也不等于收益足够大。
KS test\(D_{\mathrm{KS}}=\sup_x\lvert\widehat F_A(x)-\widehat F_B(x)\rvert\)比较两组连续观测的整体分布,找两个 empirical CDF 的最大距离。Response lengths:比较两个模型生成长度的分布,\(\widehat F_A(t)=\frac1{N_A}\sum_i\mathbf1[T_{A,i}\le t]\)。
Chi-squared test\(\chi^2=\sum_k\frac{(O_k-E_k)^2}{E_k}\)比较类别计数的分布或关联;近似检验要求期望频数足够大。Error types:比较两个模型的错误类型占比(\(O_k\) 为观测计数,\(E_k\) 为期望计数);不能把同题成对 correctness 当独立计数。
T-test\(t_{\mathrm{paired}}=\frac{\bar d}{s_d/\sqrt N}\)比较均值:one-sample 对固定值;Welch two-sample 对独立两组;paired T-test 对同一批样本的差值。小样本要考虑差值分布与异常值。Same-question scores:\(d_i=\mathrm{score}_{A,i}-\mathrm{score}_{B,i}\),对连续评分的成对差值做检验。
ANOVA / F-test\(F=\frac{MS_{\mathrm{between}}}{MS_{\mathrm{within}}}\)比较三个或更多组的均值;经典 ANOVA 需要相应的独立性、残差正态性与等方差条件,显著只说明至少一组不同。Multiple models:检验多个模型的平均评分,\(H_0:\mu_1=\mu_2=\cdots=\mu_K\)。
McNemar’s test\(X\sim\operatorname{Binomial}(b+c,1/2)\)比较同一批题上的二元 correctness,只关注 A 对 B 错的 \(b\) 题与 A 错 B 对的 \(c\) 题;通常比 paired T-test 更直接。Paired correctness:exact test 在 \(H_0\) 下,两种不一致方向各占一半;例如 \(b=8,\ c=2\) 时双侧 \(p\approx0.1094\),差 6 题仍未显著。
Reporting 报告结果\(\widehat\Delta\pm1.96\operatorname{SE}(\widehat\Delta)\)(大样本正态近似的 95% CI)同时报告样本量、差值、置信区间和检验设置;统计显著不代表产品收益足够大。Evaluation protocol:展示模型分数差 \(\widehat\Delta\) 及不确定性;反复挑题或挑 checkpoint 后,需要考虑选择与多重检验,不能把未校正的 p-value 当独立证据。
Pearson r\(r=\frac{\operatorname{Cov}(X,Y)}{\sigma_X\sigma_Y}\)衡量线性关系;强非线性依赖也可能得到接近 0 的相关系数,例如对称采样的 \(Y=X^2\)。Reward vs human score:用 \(r(R,H)\) 看 reward 与人工评分是否线性一致。
Spearman\(\rho_s=\operatorname{Corr}(\operatorname{rank}(X),\operatorname{rank}(Y))\)先转 rank 再算 Pearson,衡量单调关系;并列值使用平均 rank,比 Pearson 更少受数值异常点影响,但并非完全免疫。Ranking agreement:用 \(\rho_s(R,H)\) 看 reward 是否保留人工排序;非线性但单调时,Spearman 可很高而 Pearson 较低。
Mutual Information 互信息\(I(X;Y)=\sum_{x,y}p(x,y)\log\frac{p(x,y)}{p(x)p(y)}\)联合分布与边缘分布乘积之间的 KL,衡量一般依赖;离散情形独立时为 0。本身不是有显著性阈值的假设检验,也不说明因果关系。Token / context dependence:\(I(Y;C)\) 衡量 token 与 context 的依赖,能够捕捉不局限于线性的关系。
Statistical tests · Python code
from scipy import stats
# 同一批题的连续评分用 paired test;独立两组才用 Welch test。
a = [0.7, 0.8, 0.6, 0.9, 0.8, 0.7]
b = [0.6, 0.8, 0.5, 0.7, 0.7, 0.6]
print(round(stats.ttest_rel(a, b).pvalue, 4))  # 0.0117
# McNemar exact:100 道同题中,A独对8题、B独对2题;其余90题一致。
# H0 下,不一致的10题落在两种方向的概率都是 1/2。
mcnemar_p = stats.binomtest(k=8, n=10, p=0.5).pvalue
print(round(mcnemar_p, 4))                    # 0.1094:差6题仍不显著
# 以下只演示 API,不把这些小样本的 p-value 当稳定结论。
ks = stats.ks_2samp([20, 30, 40, 50], [25, 35, 45, 80])
chi2 = stats.chi2_contingency([[30, 20], [20, 30]])
anova = stats.f_oneway([1, 2, 3], [2, 3, 4], [5, 6, 7])
assert 0 <= ks.pvalue <= 1
assert 0 <= chi2.pvalue <= 1
assert 0 <= anova.pvalue <= 1
Correlation · Python code
from scipy import stats
x = [-2., -1., 0., 1., 2.]
y = [4., 1., 0., 1., 4.]                    # y=x²:强依赖但非单调
print(round(stats.pearsonr(x, y).statistic, 4))  # 0.0
monotonic = [v ** 3 for v in x]
print(round(stats.spearmanr(x, monotonic).statistic, 4))  # 1.0

2. Derivatives and gradient

  • Gradient(梯度)本质上就是多个 Derivatives(导数)组成的向量。

    区别是:

    • Derivative(导数):一个变量变化时,函数值变化有多快。例如,若 \(f'(x)=3\),输入增加 \(\Delta x\) 时,函数值约增加 \(3\Delta x\)。
    • Partial Derivative(偏导数):多个变量中,只改变其中一个,其他保持不变。例如 \(f(x,y)=x^2+y^3\),固定 \(y=5\) 时 \(\partial f/\partial x=2x\)(因为 \(y^3=125\) 为常数)。
    • Gradient(梯度):把所有变量的偏导数放在一起,告诉你函数在哪个方向上升最快。例如 \(f(x,y)=x^2+y^3\) 在 \((x,y)=(2,5)\) 处的梯度是 \(\nabla f(2,5)=[4,75]^T\)。

2.1 基本导数

  • \(\frac{d}{dx}x=1\)。
  • \(\frac{d}{dx}x^2=2x\)。
  • \(\frac{d}{dx}\frac1x=-\frac1{x^2}\)(\(x\ne0\))。
  • \(\frac{d}{dx}e^x=e^x\)。
  • \(\frac{d}{dx}\log x=\frac1x\)(\(x>0\),自然对数)。
  • \(\frac{d}{dx}\sigma(x)=\sigma(x)(1-\sigma(x))\),导数最大为 \(1/4\)。
  • \(\frac{d}{dx}\tanh(x)=1-\tanh^2(x)\)。

2.2 Formula 的导数

  • 乘法:\(\frac{d}{dx}[f(x)g(x)]=f'(x)g(x)+f(x)g'(x)\)(不能直接把两个导数相乘)。
  • 除法:\(\frac{d}{dx}\frac{f(x)}{g(x)}=\frac{f'(x)g(x)-f(x)g'(x)}{g(x)^2}\)(\(g(x)\ne0\))。

2.3 Basic rules

  • Chain rule
    • 单变量:复合函数把沿途导数相乘;\(z=3y,\ y=x^2\),所以 \(\frac{dz}{dx}=\frac{dz}{dy}\frac{dy}{dx}=3\cdot2x=6x\)。
    • 多变量:复合函数把 Jacobians 相乘;\(\mathbf z=\mathbf W\mathbf x+\mathbf b,\ \mathbf h=f(\mathbf z)\),所以 \(\frac{\partial\mathbf h}{\partial\mathbf x}=\frac{\partial\mathbf h}{\partial\mathbf z}\frac{\partial\mathbf z}{\partial\mathbf x}=J_f(\mathbf z)\mathbf W\)。
  • 多路径必须相加:同一个变量通过多条路径影响 loss 时,要把每条路径的贡献加起来,\(\frac{\partial L}{\partial z_i}=\sum_j\frac{\partial L}{\partial p_j}\frac{\partial p_j}{\partial z_i}\)。
    • 例如 \(u=x^2,\ v=3x,\ L=u+v\),两条路径给出 \(\frac{dL}{dx}=\frac{\partial L}{\partial u}\frac{du}{dx}+\frac{\partial L}{\partial v}\frac{dv}{dx}=1\cdot2x+1\cdot3=2x+3\)。

2.4 Gradient matrix

  • Jacobian:对 \(f:\mathbb R^n\to\mathbb R^m\),将所有一阶偏导排成 \([m,n]\) 矩阵;第 \((i,j)\) 项 \((J_f)_{ij}=\frac{\partial f_i}{\partial x_j}\) 表示第 \(j\) 个输入对第 \(i\) 个输出的影响。
    • 例如 \(f(x,y)=\begin{bmatrix}x^2+y\\3x\end{bmatrix}\),则 \(J_f(x,y)=\begin{bmatrix}2x&1\\3&0\end{bmatrix}\),在 \((2,5)\) 处为 \(\begin{bmatrix}4&1\\3&0\end{bmatrix}\)。
  • Hessian:对 \(n\) 个输入、一个标量输出的函数,将二阶偏导排成 \([n,n]\) 矩阵,\((H_f)_{ij}=\frac{\partial^2f}{\partial x_i\partial x_j}\),描述局部曲率;完整 LLM Hessian 太大,通常不显式构造。
    • 例如 \(f(x,y)=x^2+y^3\),\(H_f(x,y)=\begin{bmatrix}2&0\\0&6y\end{bmatrix}\),在 \((2,5)\) 处为 \(\begin{bmatrix}2&0\\0&30\end{bmatrix}\)。

2.5 Common gradient derivative

  • Sigmoid:\(\sigma(x)=(1+e^{-x})^{-1}\),用 chain rule 推导:
    \[\begin{align*} \frac{d}{dx}\sigma(x) &= \frac{d}{dx}(1+e^{-x})^{-1} \\ &=(1+e^{-x})^{-2}\cdot e^{-x}&\text{chain rule}\\ &= \frac{e^{-x}}{(1+e^{-x})^2}\\ &= \frac{1}{1+e^{-x}}\cdot\frac{e^{-x}}{1+e^{-x}}\\ &=\sigma(x)\cdot(1-\sigma(x)) \end{align*}\]
  • Swish:\(\operatorname{Swish}(x)=x\sigma(x)\),用 product rule 和 Sigmoid 的导数:
    \[\begin{align*} \frac{\partial}{\partial x}\text{Swish}(x)&=\frac{\partial}{\partial x}x\cdot\sigma(x)\\ &=\sigma(x)+x\cdot\sigma'(x)&\text{product rule}\\ &=\sigma(x)+x\cdot\sigma(x)(1-\sigma(x))&\text{derivative of sigmoid}\\ &=\sigma(x)+x\sigma(x)-x\sigma(x)^2\\ &=\sigma(x)+\text{Swish}(x)(1-\sigma(x)) \end{align*}\]
  • Linear layer:
    • Affine projection:令 \(\mathbf z=\mathbf W\mathbf x+\mathbf b\),其中 \(\mathbf x\in\mathbb R^d,\ \mathbf W\in\mathbb R^{k\times d},\ \mathbf b\in\mathbb R^k\);因此 \(\frac{\partial\mathbf z}{\partial\mathbf x}=\mathbf W\),\(\frac{\partial\mathbf z}{\partial\mathbf b}=\mathbf I_k\)。
    • Element-wise activation:\(\mathbf h=f(\mathbf z)\) 的每个输出只依赖同位置输入,因此 Jacobian 是对角矩阵:
      \[\left(\frac{\partial\mathbf h}{\partial\mathbf z}\right)_{ij}=\begin{cases}f'(z_i),&i=j\\0,&i\ne j\end{cases},\qquad\frac{\partial\mathbf h}{\partial\mathbf z}=\operatorname{diag}(f'(\mathbf z))\]
    • Scalar projection:\(s=\mathbf u^\top\mathbf h\),则 \(\frac{\partial s}{\partial\mathbf u}=\mathbf h^\top\),\(\frac{\partial s}{\partial\mathbf h}=\mathbf u^\top\)(列向量输入、row-vector Jacobian 约定)。
  • Softmax + CE loss

    以下针对一个 token position,\(V\) 是词表大小,\(t\) 是正确 token 的索引。

    Softmax: \(p_i=\frac{e^{z_i}}{\sum_{k=1}^{V}e^{z_k}}\)

    Cross-Entropy: \(L=-\sum_{i=1}^{V}y_i\log p_i\)

    One-hot label: \(y_i=\begin{cases}1,&i=t\\0,&i\ne t\end{cases}\)

    所以: \(L=-\log p_t\)

    代入 Softmax: \(L=-\log\left(\frac{e^{z_t}}{\sum_{k=1}^{V}e^{z_k}}\right)\)

    展开: \(\boxed{L=-z_t+\log\left(\sum_{k=1}^{V}e^{z_k}\right)}\)

    对任意 logit \(z_j\) 求偏导: \(\frac{\partial L}{\partial z_j}=-\frac{\partial z_t}{\partial z_j}+\frac{\partial}{\partial z_j}\log\left(\sum_{k=1}^{V}e^{z_k}\right)\)

    第一项: \(\frac{\partial z_t}{\partial z_j}=\begin{cases}1,&j=t\\0,&j\ne t\end{cases}=y_j\)

    第二项(Chain Rule): \(\frac{\partial}{\partial z_j}\log\left(\sum_{k=1}^{V}e^{z_k}\right)=\frac{1}{\sum_{k=1}^{V}e^{z_k}}\cdot\frac{\partial}{\partial z_j}\left(\sum_{k=1}^{V}e^{z_k}\right)=\frac{e^{z_j}}{\sum_{k=1}^{V}e^{z_k}}=p_j\)

    其中求和对 \(z_j\) 求导时,只有 \(k=j\) 的项不为零,因为其他 \(z_k\) 都视为独立变量。

    合并得到 Gradient: \(\boxed{\frac{\partial L}{\partial z_j}=p_j-y_j}\)

    向量形式: \(\boxed{\nabla_zL=\mathbf p-\mathbf y}\)

    Intuition:

    情况GradientGradient Descent 对 logit 的局部影响
    \(j=t\)(正确 token)\(p_j-1\)倾向提高 logit
    \(j\ne t\)(错误 token)\(p_j\)倾向降低 logit

    其实就是: \(\underbrace{\nabla_zL}_{\text{Gradient}}=\underbrace{\mathbf p}_{\text{Predicted probabilities}}-\underbrace{\mathbf y}_{\text{Ground-truth distribution}}\);三个向量的 shape 都是 [V],对应一个 token position。

3. Information theory

本节的 \(\log\) 默认以 \(e\) 为底,信息量的单位是 nat。用 bit 表示时,写作 \(\log_2\)。

3.1 Entropy, cross-entropy and KL divergence

类型Intuition(大白话)公式LLM Use Case
Entropy \(H(P)\)P 自己有多难预测?\(\displaystyle H(P)=-\sum_iP(i)\log P(i)\)RL Entropy Bonus:鼓励 exploration,\(J=J_{\mathrm{RL}}+\beta H(\pi_\theta)\)(最大化目标)。
Cross-Entropy \(H(P,Q)\)用 Q 预测 P 有多难?\(\displaystyle H(P,Q)=-\sum_iP(i)\log Q(i)\)SFT Loss:对 one-hot ground truth 计算 CE,\(L=-\log Q(y_{\mathrm{target}})\)。
KL Divergence \(D_{\mathrm{KL}}(P\Vert Q)\)用 Q 预测 P,比使用真正的 P 多难了多少?\(\displaystyle D_{\mathrm{KL}}(P\Vert Q)=\sum_iP(i)\log\frac{P(i)}{Q(i)}\)RLHF / PPO / GRPO:约束 policy 偏离 reference,例如 \(L_{\mathrm{KL}}=\beta D_{\mathrm{KL}}(\pi_\theta\Vert\pi_{\mathrm{ref}})\)。
Forward KL按目标分布 \(P\) 加权,目标常见的 token 若被模型低估,惩罚就大。\(D_{\mathrm{KL}}(P\Vert Q)=\sum_i P(i)\log\frac{P(i)}{Q(i)}\)知识蒸馏里让学生分布覆盖老师认为可能的 token。
Reverse KL按模型分布 \(Q\) 加权,模型常选但目标认为不太可能的 token 会受到更大惩罚。\(D_{\mathrm{KL}}(Q\Vert P)=\sum_i Q(i)\log\frac{Q(i)}{P(i)}\)RLHF 用 \(D_{\mathrm{KL}}(\pi_\theta\Vert\pi_{\mathrm{ref}})\) 约束当前 policy 偏离 reference。
Negative log-likelihood (NLL)正确 token 的预测概率越小,loss 就越大。\(L_{\mathrm{NLL}}=-\log Q(y)\)\(y\) 是正确 token。One-hot label 下,单个 token 的 NLL 就是 cross-entropy。
  • 三者的核心关系: \(\boxed{\underbrace{H(P,Q)}_{\text{Cross-Entropy}}=\underbrace{H(P)}_{\text{Entropy}}+\underbrace{D_{\mathrm{KL}}(P\Vert Q)}_{\text{额外预测代价}}}\)

    其中 \(P\) 是 ground truth/真实分布,\(Q\) 是用于预测的分布。

    • Proof:\(D_{\mathrm{KL}}(P\Vert Q)=\sum_iP(i)(\log P(i)-\log Q(i))=\sum_iP(i)\log P(i)-\sum_iP(i)\log Q(i)=-H(P)+H(P,Q)\)。
  • Entropy intuition:one-hot distribution 的 entropy 最小,为 0,结果完全确定,没有 uncertainty。对同一组可能结果,uniform distribution 给每个结果相同的概率,uncertainty 最大。
  • Cross-Entropy Loss:就是把 Cross-Entropy 当作 Training Loss 来最小化。
    • SFT 用 Cross-Entropy Loss;Ground Truth 是 one-hot 时,Cross-Entropy Loss 和 KL Divergence 相等:\(L_{\mathrm{CE}}=H(P,Q)=D_{\mathrm{KL}}(P\Vert Q)\)。

      Example:假设一个 token position 的正确 token 是 cats:\(P=[1,0,0],\quad Q=[0.7,0.2,0.1]\)(使用自然对数,并按连续极限约定 \(0\log0=0\))。

      Concept计算过程结果
      Entropy\(H(P)=-(1\log1+0\log0+0\log0)\)0
      Cross-Entropy Loss\(H(P,Q)=-(1\log0.7+0\log0.2+0\log0.1)\)0.357
      KL Divergence\(D_{\mathrm{KL}}(P\Vert Q)=1\log\frac1{0.7}\)0.357

      为什么 Entropy 为 0?因为 \(P=[1,0,0]\) 意味着正确答案确定是 cats,没有任何不确定性。

      所以 \(H(P,Q)=H(P)+D_{\mathrm{KL}}(P\Vert Q)=0+D_{\mathrm{KL}}(P\Vert Q)\)。

      得到 \(\boxed{L_{\mathrm{CE}}=D_{\mathrm{KL}}(P\Vert Q)=-\log Q(t)}\),其中 \(t\) 是正确 token 的 index。

3.2 Evaluation metrics · NLL, perplexity and bits per byte

在同一份评估文本上,只统计参与打分的 \(N\) 个真实 token。\(p_t\) 是模型给定前文后分给第 \(t\) 个真实 token 的概率,\(B\) 是这些 token 所对应原文的 UTF-8 总字节数。

  • NLL loss 总 NLL 为 \(-\sum_{t=1}^{N}\log p_t\)。除以 token 数得到平均 loss \(L=-\frac{1}{N}\sum_{t=1}^{N}\log p_t\),单位是 nats/token。
  • Perplexity(PPL) \(\mathrm{PPL}=e^L\),即真实 token 概率几何平均数的倒数。
  • Bits per byte(BPB) \(\mathrm{BPB}=\frac{-\sum_{t=1}^{N}\log_2 p_t}{B}\)。它表示按模型给出的概率编码原文时,平均每个原始字节需要多少个 bit。
    • 一个概率为 \(p\) 的事件发生时,信息量是 \(I(p)=-\log_2 p\) bit。概率每减半,信息量就增加 1 bit。
    • \(p=1\) 对应 0 bit(结果已确定),\(p=0.5\) 对应 1 bit,\(p=0.25\) 对应 2 bits。
    • 同一段原文即使用不同 tokenizer 切分,UTF-8 字节数也相同,因此可以用 BPB 比较模型。BPB 越低,模型为这段文本分配的总概率越高。
  • 从 perplexity 推导 BPB
    • 先算每个 token 的平均信息量。对 \(\mathrm{PPL}=e^L\) 取以 2 为底的对数,得到 \(\log_2(\mathrm{PPL})=\frac{L}{\log 2}\) bits/token。
    • 再换成每个 byte 的平均信息量。乘以 \(N\) 得到总 bits,再除以 \(B\),所以 \(\mathrm{BPB}=\frac{N}{B}\log_2(\mathrm{PPL})\)。
    • 例如,假设原文 “go!” 切成 “go” 和 “!”,真实 token 的概率分别为 \(1/2\) 和 \(1/8\)。共 \(1+3=4\) bits,平均 2 bits/token,所以 \(\mathrm{PPL}=2^2=4\)。原文有 3 bytes,所以 \(\mathrm{BPB}=\frac{2}{3}\log_2 4=\frac{4}{3}\)。

4. RL

类型公式Notation 解释Intuition(大白话)
Distillation · Temperature softmax\(p_i^{(\tau)}=\frac{\exp(z_i/\tau)}{\sum_j\exp(z_j/\tau)}\)\(\tau\) 是温度,\(z_i\) 是 token \(i\) 的 logit。升高温度会让概率分布更平缓,看得到老师对其他候选 token 的偏好。
Distillation · Mixed KD loss\(\mathcal L=(1-\alpha_{\mathrm{KD}})\mathrm{CE}(y,p^{(1)})\)
\(+\alpha_{\mathrm{KD}}\tau^2 D_{\mathrm{KL}}(q^{(\tau)}\Vert p^{(\tau)})\)
\(y\) 是正确 token,\(\alpha_{\mathrm{KD}}\) 是蒸馏项的权重。一部分学正确答案,一部分学老师对整个词表的概率分配。
PPO / GAE · TD residual\(\delta_t=r_t+\gamma V_\psi(s_{t+1})-V_\psi(s_t)\)\(s_t\) 是当前 token 前缀,\(r_t\) 是当步奖励,\(V_\psi\) 是 critic 的估值,\(\gamma\) 是折扣因子。比较这一步拿到的奖励加上下一步估值,和行动前的预期差多少。
PPO / GAE · Advantage\(A_t=\delta_t+\gamma\lambda A_{t+1}\)\(A_t\) 是优势估计,\(\lambda\) 控制后续 TD residual 的权重。把之后的好坏算回这一步,越远的影响越小。
PPO · Probability ratio\(\rho_t(\theta)=\exp(\ell_t-\ell_t^{\mathrm{old}})\)
\(\ell_t=\log\pi_\theta(y_t\mid s_t)\)
\(\ell_t^{\mathrm{old}}=\log\pi_{\mathrm{old}}(y_t\mid s_t)\)
\(y_t\) 是采样 token,\(\pi_\theta\) 是当前 policy,\(\pi_{\mathrm{old}}\) 是生成 rollout 的快照。同一个 token,新 policy 愿意选它的程度是旧 policy 的多少倍?
DPO · Preference loss\(\Delta_\pi(y)=\log\frac{\pi_\theta(y\mid x)}{\pi_{\mathrm{ref}}(y\mid x)}\)
\(\mathcal L_{\mathrm{DPO}}=-\log\sigma\!\bigl(\beta_{\mathrm{DPO}}[\Delta_\pi(y_w)-\Delta_\pi(y_l)]\bigr)\)
\(x\) 是 prompt,\(y_w,y_l\) 是 preferred / rejected 回答,\(\pi_{\mathrm{ref}}\) 是冻结的 reference,\(\beta_{\mathrm{DPO}}\) 缩放差值,\(\sigma\) 是 sigmoid。看新 policy 相对 reference 的变化,让好回答比差回答更受偏好。
GRPO · Group advantage\(\bar r_i=\frac1G\sum_{j=1}^{G}r^{(i,j)}\)
\(\widehat A^{(i,j)}=\frac{r^{(i,j)}-\bar r_i}{\sigma_i+\varepsilon}\)
\(G\) 是每个 prompt 的回答数,\(r^{(i,j)}\) 是第 \(i\) 题第 \(j\) 个回答的奖励,\(\bar r_i,\sigma_i\) 是组内均值和标准差,\(\varepsilon\) 防止除零。只跟同一道题的其他答案比。高于组内平均的回答获得正优势。
  • Distillation notation
    • \(\pi_T\) 是冻结的老师,\(\pi_\theta\) 是可训练的学生。\(q_t(v)=\pi_T(v\mid s_t)\)、\(p_{\theta,t}(v)=\pi_\theta(v\mid s_t)\) 是同一前缀下对 token \(v\) 的概率。
    • \(q^{(\tau)},p^{(\tau)}\) 是用同一温度软化后的老师和学生分布。\(p^{(1)}\) 是学生原始分布,\(\tau^2\) 用于补偿温度对软目标梯度尺度的影响。
    • \(\mathcal D\) 是固定的 prompt–response 数据集,\(k\) 是 top-\(k\) 蒸馏保留的老师候选数。

5. Softmax stability tricks

  • Instabilities come from:
    • Large exponentials: \(e^x\) can overflow to \(\infty\) for large \(x\) (around \(x>88.7\) in FP32).
    • Log inputs near zero: tiny probabilities may underflow to zero before taking the log, giving \(\log(0)=-\infty\).
    • Log inputs near one: rounding can erase a small difference from one; \(\log(1)=0\) is exact, but use log1p(u) to compute \(\log(1+u)\) accurately for small \(u\).
  • Stable softmax:
    • Unstable because: directly computing \(p_i=e^{x_i}/\sum_j e^{x_j}\) can overflow the exponentials, producing \(\infty/\infty\) and NaN.
    • Subtracting a constant changes nothing: divide the numerator and denominator by the same \(e^c\): \(\frac{e^{x_i}}{\sum_j e^{x_j}}=\frac{e^{x_i}/e^c}{(\sum_j e^{x_j})/e^c}=\frac{e^{x_i-c}}{\sum_j e^{x_j-c}}\).
    • Subtract the maximum: set \(m=\max_j x_j\) and compute \(p_i=\frac{e^{x_i-m}}{\sum_j e^{x_j-m}}\). For finite logits, every exponent is nonpositive, the largest exponential is \(e^0=1\), and the denominator is at least one.
  • Compute LSE — log(sum(exp(x))):
    • Stable implementation: logsumexp(x) subtracts the maximum inside the exponential and adds it back outside the log: \(\operatorname{LSE}(x)=\log\!\left(e^m\sum_i e^{x_i-m}\right)=m+\log\sum_i e^{x_i-m}\), where \(m=\max_i x_i\). The largest term is one and the sum is at least one, avoiding exponential overflow and a zero sum from underflow.
    • Log-softmax: compute \(\log p_i=x_i-\operatorname{LSE}(x)\) directly instead of log(softmax(x)), so a tiny probability is never rounded to zero before taking its log.
  • Online softmax:
    • Idea: ordinary stable softmax first scans for the maximum, then scans for the denominator. Online softmax computes both in one pass by tracking the maximum so far and rescaling earlier contributions whenever that maximum increases.
    • Process:
      • Maintain: after \(k\) logits, keep \(m_k=\max_{1\le j\le k}x_j\) and \(d_k=\sum_{j=1}^k e^{x_j-m_k}\). Initialize with \(m_1=x_1\) and \(d_1=1\).
      • Update rule: for the next logit \(x_{k+1}\), set \(m_{k+1}=\max(m_k,x_{k+1})\), then \(d_{k+1}=d_k e^{m_k-m_{k+1}}+e^{x_{k+1}-m_{k+1}}\). If the maximum is unchanged, the rescaling factor is one.
      • Return probabilities: after all \(S\) logits, one additional pass returns each \(p_i=e^{x_i-m_S}/d_S\).
      • Weighted sum / FlashAttention: the same trick computes \(o=\sum_i p_i v_i=\frac{\sum_i e^{x_i-m_S}v_i}{\sum_i e^{x_i-m_S}}\) without storing all attention probabilities. For a query \(q\), the logits are scaled query–key scores \(x_i=q^\top k_i/\sqrt H\), and each value vector \(v_i\in\mathbb R^H\) has head dimension \(H\).
      • Maintain a numerator too: keep \(u_k=\sum_{i=1}^k e^{x_i-m_k}v_i\), initialized with \(u_1=v_1\). Update \(u_{k+1}=u_k e^{m_k-m_{k+1}}+e^{x_{k+1}-m_{k+1}}v_{k+1}\), then return the attention output \(o=u_S/d_S\).
    • Proof:
      • Split off the new term: \(d_{k+1}=\sum_{j=1}^{k+1}e^{x_j-m_{k+1}}=\sum_{j=1}^k e^{x_j-m_{k+1}}+e^{x_{k+1}-m_{k+1}}\).
      • Rescale the earlier terms: \(\sum_{j=1}^k e^{x_j-m_{k+1}}=e^{m_k-m_{k+1}}\sum_{j=1}^k e^{x_j-m_k}=e^{m_k-m_{k+1}}d_k\), which gives the denominator update. Applying the same factorization with each \(v_j\) gives the numerator update.
      • General trick: multiply both numerator and denominator by the same \(e^{-m}\), usually with \(m=\max_i x_i\), to keep exponentials bounded without changing the ratio.