跳到主要内容

附录 A 数学符号与公式速查

本附录汇总 LLM 大纲各章常用 符号、损失与复杂度,便于跨章节对照。详细推导见对应正文。

通用符号

符号含义
LL序列长度(token 数)
BBbatch size
d,dmodeld, d_\text{model}隐藏维度
HH注意力头数
dhd_h每头维度,常 dh=d/Hd_h = d/H
N,NlN, N_lTransformer 层数
VV词表大小
θ\theta模型参数

语言建模

下一 token 负对数似然(因果 LM):

LLM=t=1Llogpθ(xtx<t)\mathcal{L}_\text{LM} = -\sum_{t=1}^{L} \log p_\theta(x_t \mid x_{<t})

交叉熵与 perplexity:

PPL=exp(1Ltlogp(xtx<t))\text{PPL} = \exp\left(-\frac{1}{L}\sum_t \log p(x_t \mid x_{<t})\right)

注意力

Scaled dot-product:

Attention(Q,K,V)=softmax(QKdh)V\text{Attention}(Q,K,V) = \text{softmax}\left(\frac{QK^\top}{\sqrt{d_h}}\right) V

多头:

headi=Attention(QWiQ,KWiK,VWiV),MHA=Concat(head1,)WO\text{head}_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V),\quad \text{MHA} = \text{Concat}(\text{head}_1,\ldots) W^O

复杂度(稠密): 每层约 O(L2d)O(L^2 d) FLOPs,KV 存储 O(Ld)O(L d) per layer。

位置编码(RoPE 直觉)

对二维子空间应用旋转矩阵 Rθ,mR_{\theta,m}θ\theta 与维度、位置 mm 相关;外推时调整 base 或插值(见 9.1.2)。

归一化

LayerNorm:

LN(x)=γxμσ+ϵ+β\text{LN}(x) = \gamma \odot \frac{x - \mu}{\sigma + \epsilon} + \beta

RMSNorm: 省略均值项,只 RMS 缩放。

优化

AdamW 更新:

θt+1=θtη(m^v^+ϵ+λθt)\theta_{t+1} = \theta_t - \eta \left( \frac{\hat{m}}{\sqrt{\hat{v}}+\epsilon} + \lambda \theta_t \right)

梯度裁剪:g2>τ\|g\|_2 > \tau,则 ggτ/g2g \leftarrow g \cdot \tau / \|g\|_2

对齐损失

DPO(示意):

LDPO=E[logσ(βlogπθ(ywx)πref(ywx)βlogπθ(ylx)πref(ylx))]\mathcal{L}_\text{DPO} = -\mathbb{E}\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]

RLHF 奖励目标: maxθE[r(x,y)βKL(πθπref)]\max_\theta \mathbb{E}[r(x,y) - \beta \text{KL}(\pi_\theta \| \pi_\text{ref})]

MoE

路由: top-kk 专家选择,负载均衡 aux loss 或动态 bias(DeepSeek 无 aux)。

激活参数量: 每 token 仅计 kk 个专家 FFN + 共享部分。

推理与 KV

KV cache 体积(每层、每序列,量级):

MemKV2×L×H×dh×bytes\text{Mem}_\text{KV} \approx 2 \times L \times H \times d_h \times \text{bytes}

(MLA 等压缩结构见 5.2.1。)

Scaling(Chinchilla 直觉)

最优 token 数 DD 与参数量 NN 近似 DN0.74D \propto N^{0.74}(以 Hoffmann 等为准,具体指数随设定略变)。

相关章节