LLM 参数量分解
把词表、attention、MLP 与层数的张量 shape 相乘,可以解释“7B/8B 从哪里来”,也能看出 GQA、大词表和 SwiGLU 如何重新分配参数预算。
- :词表大小;
- :hidden size;
- :Transformer 层数;
- :Q 头数;
- :K/V 头数;
- :单头维度;
- :MLP 中间维度。
Embedding 与输出头
Section titled “Embedding 与输出头”输入 embedding:
若 LM head 与 embedding 不共享权重,再加约 ;共享则不会再增加同规模独立矩阵。词表扩张会直接增加这一部分。
Attention
Section titled “Attention”Q 投影与输出投影通常各约 。GQA 下 K/V 输出维度为 :
MHA 中 ,约为 ;GQA 让 K/V 投影和 KV Cache 按 缩小,但 Q/O 不变。
SwiGLU MLP
Section titled “SwiGLU MLP”Llama 风格 SwiGLU 有三组主要矩阵:
因此每层主要参数可估为:
总 block 参数约 。RMSNorm 等向量参数是 ,相对较小,但计算图中仍重要。
Llama 2 7B 与 Llama 3 8B 课程算例
Section titled “Llama 2 7B 与 Llama 3 8B 课程算例”| 项目 | Llama 2 7B | Llama 3 8B | 参数预算影响 |
|---|---|---|---|
| hidden size | 4096 | 4096 | 主维度相同 |
| layers | 32 | 32 | 深度相同 |
| vocab | 32,000 | 128,256 | Llama 3 embedding/head 更大 |
| Q heads | 32 | 32 | Q/O 接近 |
| KV heads | 32 | 8 | Llama 3 用 GQA 节省 K/V 与 cache |
| MLP intermediate | 11,008 | 14,336 | Llama 3 MLP 更大 |
这说明“8B 比 7B 多在哪里”不能只看层数:Llama 3 用 GQA 节省 attention/KV 预算,同时把预算放到更大词表和 MLP。
从参数到显存
Section titled “从参数到显存”仅权重内存的粗略估计:
训练还要加梯度、优化器状态、激活、临时 workspace 和通信 buffer;推理还要加随 batch/序列增长的 KV Cache。因此“参数量 × dtype 字节”不是训练峰值显存。
- 模型名的 B 是精确逐项总和:公开名称常四舍五入,且是否计 embedding/head、tie 权重需看实现。
- GQA 把 attention 全部缩小 倍:它主要缩小 K/V;Q 与 O 仍在。
- 词表更大只影响 tokenizer 文件:embedding/LM head 参数也会增大。
- 参数多就一定更慢同样比例:吞吐还受序列长度、kernel、带宽与 cache 影响。