Transformer 参数量

🏋️ Transformer Parameter Estimator

Estimate the parameter count of a Transformer from layer count, hidden size and vocabulary, separating body and embedding parameters.

📐 计算公式 / 原理
Transformer 参数量估算(本页代码口径):主体参数≈12·L·d²(L 层数、d 隐藏维度,含注意力与 FFN);嵌入参数≈vocab×d(词表×隐藏维度);两项均按亿展示(÷10⁸)。校验:无强校验,空值按 0 兜底。判据:无固定分级,层数翻倍参数线性增、宽度翻倍参数平方级增。
每层含 Q/K/V/O 四个 d×d 矩阵(4d²)与两层 FFN(通常 4d 宽,共 8d²),合计 12d²,乘层数 L 即得主体规模;词表嵌入另计 vocab×d(若解绑则输出层再加一份)。实际模型还有 LayerNorm 等小量参数,估算值略偏小。

📐 计算公式与说明

参数量判读(与上式互补):12Ld² 的系数 12 对应每层自注意力(Q/K/V/O 四个 d×d 矩阵共 4d²)加 FFN(上/下投影共 8d²);嵌入参数与层数无关、仅随词表线性增长。校验:与上方一致,空值按 0 兜底。判据:无固定分级,d 增大后主体参数远超嵌入参数、占比随之上升。

实际随具体架构大幅浮动。

📚 深度解析:Transformer 参数量

💡 常见使用场景

参数量估算
L=12, d=768, V=50000:每层≈12×768²≈7.08M,12 层≈85M;嵌入 50000×768≈38.4M;合计≈123M(典型 BERT-base 量级)。

❓ 常见问题(FAQ)

为什么 FFN 占参数最多?
标准 FFN 内部维度常 4d,其两层权重约 8d²,而注意力 Q/K/V/O 共 4d²,故 FFN 占每层约 2/3 参数;这也是大模型压缩的重点。
词表越大参数越多吗?
是。嵌入层≈V·d 随词表线性增长;为控参数量常用子词分词限制 V,或用因子分解嵌入降低维度开销。

Formula & Standard References

Item Formula / Note Source / Standard
Attention parameters each layer holds four projection matrices totalling about four times the squared width Vaswani et al. 2017, attention
Feed-forward parameters the feed-forward block uses an expansion ratio of four giving about eight times the squared width Vaswani et al. 2017, attention
Embeddings vocabulary size times width forms the embedding block which may tie weights with the output layer Press & Wolf 2017, weight tying