Skip to content
quboliu
⚙

All the Transformer Math You Need to Know你需要知道的所有 Transformer 数学

第 4 章 · How To Scale Your Model (分片矩阵及其乘法 | 如何并行训练 Transformer)

Here we'll do a quick review of the Transformer architecture, specifically how to calculate FLOPs, bytes, and other quantities of interest.

在这里, 我们将快速回顾 Transformer 架构, 特别是如何计算 FLOPs, 字节和其他感兴趣的数量.

Counting Dots数点

Let’s start with vectors xx, yy and matrices AA, BB of the following shapes:

让我们从以下形状的向量 xx,yy 和矩阵 AA,BB 开始:

arrayshapex[P]y[P]A[N P]B[P M]\begin{array}{cc} \textrm{array} & \textrm{shape} \\ \hline x & \textrm{[P]} \\ y & \textrm{[P]} \\ A & \textrm{[N P]} \\ B & \textrm{[P M]} \\ \hline \end{array}
  • A dot product of x⋅yx \cdot y requires PP adds and multiplies, or 2P2P floating-point operations total.
  • A matrix-vector product AxAx does NN dot-products along the rows of AA, for 2NP2NP FLOPs.
  • A matrix-matrix product ABAB does a matrix-vector product for each of the MM columns of BB, for 2NPM2NPM FLOPs total.
  • In general, if we have two higher-dimensional arrays CC and DD, where some dimensions are CONTRACTING and some are BATCHING (e.g. C[GHIJKL],D[GHMNKL]C[\textcolor{blue}{GH}IJ\textcolor{red}{KL}], D[\textcolor{blue}{GH}MN\textcolor{red}{KL}]), then the FLOPs cost of this contraction is two times the product of all of the CC and DD dimensions where the batch and contraction dimensions are only counted once (e.g. 2GHIJMNKL2\textcolor{blue}{GH}IJMN\textcolor{red}{KL}). Note that a dimension is only batching if it occurs in both multiplicands. (Note also that the factor of 2 won’t apply if there are no contracting dimensions and this is just an elementwise product.)1
  • x⋅yx \cdot y 的点积需要 PP 次加法和乘法, 或总共 2P2P 次浮点运算.
  • 矩阵向量乘积 AxAx 沿着 AA 的行进行 NN 次点积,共 2NP2NP FLOPs.
  • 矩阵-矩阵乘积 ABAB 对 BB 的 MM 列中的每一列进行一次矩阵-向量乘积,总共 2NPM2NPM FLOPs.
  • 一般来说,如果我们有两个更高维度的数组 CC 和 DD, 其中一些维度是收缩的, 一些是批处理的. (例如 C[GHIJKL],D[GHMNKL]C[\textcolor{blue}{GH}IJ\textcolor{red}{KL}], D[\textcolor{blue}{GH}MN\textcolor{red}{KL}]), 那么这个收缩的 FLOPs 成本是所有 CC 和 DD 维度乘积的两倍,其中批处理和缩并维度只计算一次,(例如 2GHIJMNKL2\textcolor{blue}{GH}IJMN\textcolor{red}{KL}). 请注意,只有当一个维度同时出现在两个乘数中时,它才是批次维度. (另请注意,如果没有缩并维度并且这只是一个逐元素乘积,则 2 的因子将不适用.)1
OperationFLOPsDatax⋅y2P2PAx2NPNP+PAB2NPMNP+PM[c0,...,cN]⋅[d0,...,dN]2∏ci×∏dj∉BATCHdj∉CONTRACTdj∏ci+∏dj\begin{array}{ccc} \textrm{Operation} & \textrm{FLOPs} & \textrm{Data} \\ \hline x \cdot y & 2P & 2P \\ A x & 2NP & NP + P \\ AB & 2NPM & NP + PM \\ [c_0,...,c_N] \cdot [d_0,...,d_N] & 2 \prod c_i \times \prod_{\substack{d_j \notin \textcolor{blue}{BATCH} \\ d_j \notin \textcolor{red}{CONTRACT}}} d_j & \prod c_i + \prod d_j \\ \hline \end{array}

Make note of the fact that for a matrix-matrix multiply, the compute scales cubically O(N3)O(N^3) while the data transfer only scales quadratically O(N2)O(N^2) — this means that as we scale up our matmul size, it becomes easier to hit the compute-saturated limit. This is extremely unusual, and explains in large part why we use architectures dominated by matrix multiplication — they’re amenable to being scaled!

请注意,对于矩阵-矩阵乘法,计算以三次方的速度 O(N3)O(N^3) 扩展,而数据传输仅以二次方的速度 O(N2)O(N^2) 扩展 - 这意味着随着我们扩大矩阵乘法的大小,更容易达到计算饱和的极限. 这是非常不寻常的,并且在很大程度上解释了为什么我们使用以矩阵乘法为主的架构 - 它们易于扩展!

matmul flops

Forward and reverse FLOPs前向和反向 FLOPs

During training, we don’t particularly care about the result of a given matrix multiply; we really care about its derivative. It turns out that calculating that derivative costs about 3x more than just doing the matmul itself.

训练需要对矩阵乘法求导。计算导数所需的运算量大约是直接做矩阵乘法的 3 倍。

If we imagine B is just one matrix in a larger network and A are our input activations with C = A B, the derivative of the loss L with respect to B is given by the chain rule:

如果我们想象 B 只是一个更大网络中的一个矩阵,A 是我们的输入激活,C = A B, 那么损失 L 对 B 的导数由链式法则给出:

∂L∂B=∂L∂C∂C∂B=AT(∂L∂C)\frac{\partial L}{\partial B} = \frac{\partial L}{\partial C}\frac{\partial C}{\partial B} = A^T \left(\frac{\partial L}{\partial C}\right)

which requires 2NPM2NPM FLOPs to compute (since it contracts over the NN dimension). Likewise, the derivative of the loss with respect to A is

这是一个外积,需要 2NPM2NPM FLOPs 来计算 (因为它在 NN 维度上收缩). 同样,损失对 A 的导数是

∂L∂A=∂L∂C∂C∂A=(∂L∂C)BT\frac{\partial L}{\partial A} = \frac{\partial L}{\partial C}\frac{\partial C}{\partial A} = \left(\frac{\partial L}{\partial C}\right) B^T

which is again 2NPM2NPM FLOPs since dL/dC is a matrix of size [N,M][N, M]. While this quantity isn’t the derivative w.r.t. a parameter, it’s used to compute derivatives for previous layers of the network (e.g. just as dL/dC is used to compute dL/dB above).

同样是 2NPM2NPM FLOPs, 因为 dL/dC 是一个大小为 [N,M][N, M] 的 (余) 向量. 虽然这个量不是关于参数的导数,但它用于计算网络前几层的导数 (例如,正如 dL/dC 用于计算上面的 dL/dB).

Adding these up, we see that during training, we have a total of 6NPM FLOPs, compared to 2NPM during inference: 2NPM in the forward pass, 4NPM in the backward pass. Since PM is the number of parameters in the matrix, this is the simplest form of the famous 6∗num parameters∗num tokens6 * \text{num parameters} * \text{num tokens} approximation of Transformer FLOPs during training: each token requires 6∗num parameters6 * \text{num parameters} FLOPs. We’ll show a more correct derivation below.

将这些加起来,我们看到在训练期间,我们总共有 6NPM FLOPs, 而推理期间为 2NPM: 前向传播 2NPM, 后向传播 4NPM. 由于 PM 是矩阵中的参数数量,这是著名的 Transformer 训练期间 FLOPs 的 6∗num parameters∗num tokens6 * \text{num parameters} * \text{num tokens} 近似的简化形式:每个 token 需要 6∗num parameters6 * \text{num parameters} FLOPs. 我们将在下面展示一个更正确的推导.

Transformer AccountingTransformer 核算

Transformers are the future. Well, they’re the present at least. Maybe a few years ago, they were one of many architectures. But today, it’s worth knowing pretty much every detail of the architecture. We won’t reintroduce the architecture, but this blog and the original Transformer paper may be helpful references.

Transformer 是未来. 嗯,至少它们是现在. 也许几年前,它们是众多架构之一. 但今天,几乎值得了解该架构的每一个细节. 我们不会重新介绍该架构,但这篇博客和原始的 Transformer 论文可能会有所帮助.

Here’s a basic diagram of the Transformer decoder architecture:

这是一个 Transformer 解码器架构的基本图:

transformer diagram

Figure: this diagram shows one layer of a standard Transformer and flows from top-to-bottom. We use a single-letter convention to describe the shapes and layouts of arrays in a Transformer, again showing contracting dimensions in red, and batched dimensions in blue. In a given operation, the input shape is given on top-left and the parameter shape is given on the top-right, with the resulting shape below, e.g. BTD is the input shape for the gating einsum and DF is the weight shape.

图: 该图显示了一个标准 Transformer 的一层,从上到下流动. 我们使用单字母约定来描述 Transformer 中数组的形状和布局,再次以红色显示缩并维度,以蓝色显示批次维度. 在给定的操作中,输入形状在左上角给出,参数形状在右上角给出,结果形状在下面,例如 BTD 是门控 einsum 的输入形状,DF 是权重形状.

Note [gating einsum]: The diagram above uses a “gating einsum”[1] where we split the up-projection matrix into two matrices (WIn1W_\text{In1} and WIn2W_\text{In2} above) whose outputs are elementwise multiplied as a kind of “gating function”. Not all LLMs use this, so you will sometimes see a single WInW_\text{In} matrix and a total MLP parameter count of 2DF instead of 3DF. Typically in this case, D and F will be scaled up to keep the parameter count the same as the 3 matrix case. With that said, some form of gating einsum is used by LLaMA, DeepSeek, and many other models.

注意 [门控 einsum]: 上图使用了一个“门控 einsums”[1], 其中我们将上投影矩阵分成两个矩阵 (WIn1W_\text{In1} 和 WIn2W_\text{In2} 上面), 其输出作为一种“门控函数”进行逐元素相乘. 并非所有 LLM 都使用它,因此你有时会看到一个单一的 WInW_\text{In} 矩阵,MLP 参数总数为 2DF 而不是 3DF. 通常在这种情况下,D 和 F 会被放大以保持参数数量与 3 矩阵情况相同. 话虽如此,LLaMA, DeepSeek 和许多其他模型都使用了某种形式的门控 einsum.

Note 2 [MHA attention]: With self-attention, T and S are the same but for cross-attention they may be different. With vanilla Multi-Head Attention (MHA), N and K are the same while for Multi-Query Attention (MQA)[2] K=1 and for Grouped MQA (GMQA)[3], K merely has to divide N.

注意 2 [MHA 注意力]: 对于自注意力,T 和 S 是相同的,但对于交叉注意力,它们可能不同. 对于普通的多头注意力 (MHA), N 和 K 是相同的,而对于多查询注意力 (MQA)[2] K=1, 对于分组 MQA (GMQA)[3] K 只需要整除 N.

Note 3 [pre-norm vs. post-norm]: The above diagram shows what is known as a “pre-norm” architecture in which the norm occurs before the residual connection, usually as x + attn(norm(x)). Models like LLaMA-3 use this today. The original Transformer paper used a “post-norm” architecture in which the layernorm occurs after the residual connection, i.e. norm(x + attn(x)).

注 3[前置归一化与后置归一化]: 上图采用“前置归一化”架构,先归一化再执行残差连接,通常写成 x + attn(norm(x))。LLaMA-3 等模型现在采用这种架构。最初的 Transformer 论文采用“后置归一化”架构,在残差连接后做层归一化,即 norm(x + attn(x))。

Global FLOPs and Params Calculation全局 FLOPs 和参数计算

Let’s calculate the per-layer FLOPs of a Transformer (so we can avoid having to stick factors of L everywhere). Note that the training FLOPs below are almost always 3x the inference FLOPs, so you can divide any total by 3 to get the cost of just the forward pass.

以下按 Transformer 的单层计算 FLOPs,省去反复乘以层数 L。下文的训练 FLOPs 几乎总是推理 FLOPs 的 3 倍,因而把总量除以 3 即可估算单独执行前向传播的开销。

MLPsMLPs

The MLPs of a Transformer typically consist of 2 input matmuls that are element-wise combined and a single output matmul:

Transformer 的 MLP 通常由 2 个输入矩阵乘法组成,它们逐元素组合,以及一个输出矩阵乘法:

operationtrain FLOPsparamsA[B,T,D]⋅Win1[D,F]6BTDFDFA[B,T,D]⋅Win2[D,F]6BTDFDFσ(Ain1)[B,T,F]∗Ain2[B,T,F]O(BTF)A[B,T,F]⋅Wout[F,D]6BTDFDF≈18BTDF3DF\begin{array}{ccc} \textrm{operation} & \textrm{train FLOPs} & \textrm{params} \\ \hline \\ A[B,T,\textcolor{red}{D}] \cdot W_{in1}[\textcolor{red}{D}, F] & 6BTDF & DF \\[10pt] A[B,T,\textcolor{red}{D}] \cdot W_{in2}[\textcolor{red}{D}, F] & 6BTDF & DF \\[10pt] \sigma\left(A_{in1}\right)[B,T, F] * A_{in2}[B,T, F] & \textcolor{gray}{O(BTF)} \\[10pt] A[B,T,\textcolor{red}{F}] \cdot W_{out}[\textcolor{red}{F}, D] & 6BTDF & DF \\[10pt] \hline \\ & \approx 18BTDF & 3DF \end{array}

Attention注意力

For the generic grouped-query attention case with different Q and KV head numbers, let us assume equal head dimension H for Q,K,V projections, and estimate the cost of the QKVO matmuls:

对于具有不同 Q 和 KV 头数的通用分组查询注意力情况,让我们假设 Q,K,V 投影的头维度 H 相等,并估计 QKVO 矩阵乘法的成本:

operationtrain FLOPsparamsA[B,T,D]⋅WQ[D,N,H]6BTDNHDNHA[B,T,D]⋅WK[D,K,H]6BTDKHDKHA[B,T,D]⋅WV[D,K,H]6BTDKHDKHA[B,T,N,H]⋅WO[N,H,D]6BTDNHDNH12BTD(N+K)H2D(N+K)H\begin{array}{ccc} \textrm{operation} & \textrm{train FLOPs} & \textrm{params} \\ \hline \\ A[B,T,\textcolor{red}{D}] \cdot W_{Q}[\textcolor{red}{D}, N, H] & 6BTDNH & DNH \\[10pt] A[B,T,\textcolor{red}{D}] \cdot W_{K}[\textcolor{red}{D}, K, H] & 6BTDKH & DKH \\[10pt] A[B,T,\textcolor{red}{D}] \cdot W_{V}[\textcolor{red}{D}, K, H] & 6BTDKH & DKH \\[10pt] A[B,T,\textcolor{red}{N}, \textcolor{red}{H}] \cdot W_{O}[\textcolor{red}{N}, \textcolor{red}{H}, D] & 6BTDNH & DNH \\[10pt] \hline \\ & 12BTD(N+K)H & 2D(N+K)H \end{array}

The dot-product attention operation is more subtle, effectively being a TH⋅HSTH \cdot HS matmul batched over the BB, KK dimensions, a softmax, and a TS⋅SHTS \cdot SH matmul again batched over the BB, KK dimensions. We highlight the batched dims in blue:

点积注意力操作更微妙,实际上是在 BB, KK 维度上批处理的 TH⋅HSTH \cdot HS 矩阵乘法,一个 softmax, 以及再次在 BB, KK 维度上批处理的 TS⋅SHTS \cdot SH 矩阵乘法. 我们用蓝色突出显示批次维度:

operationtrain FLOPsQ[B,T,K,G,H]⋅K[B,S,K,H]6BTSKGH=6BTSNHsoftmaxS    L[B,T,S,K,G]O(BTSKG)=O(BTSN)S[B,T,S,K,G]⋅V[B,S,K,H]6BTSKGH=6BTSNH≈12BTSNH=12BT2NH\begin{array}{cc} \textrm{operation} & \textrm{train FLOPs} \\ \hline \\[3pt] Q[\textcolor{blue}{B}, T, \textcolor{blue}{K}, G, \textcolor{red}{H}] \cdot K[\textcolor{blue}{B}, S, \textcolor{blue}{K}, \textcolor{red}{H}] & 6BTSKGH = 6BTSNH \\[3pt] \textrm{softmax}_S \;\; L[B, T, S, K, G] & \textcolor{gray}{O(BTSKG) = O(BTSN)} \\[3pt] S[\textcolor{blue}{B}, T, \textcolor{red}{S}, \textcolor{blue}{K}, G] \cdot V[\textcolor{blue}{B}, \textcolor{red}{S}, \textcolor{blue}{K}, H] & 6BTSKGH = 6BTSNH \\[3pt] \hline \\ & \approx 12BTSNH = 12BT^2NH \\ \end{array}

Note [causal masking]: Most recent transformers use a causal mask as opposed to full bidirectional attention. In this case the useful FLOPs of the dot product operations are reduced by half. To achieve this reduction in practice we need to make use of an attention kernel, rather than a naive einsum.

注[因果掩码]: 近来多数 Transformer 使用因果掩码,省去对未来 token 的注意力计算。点积操作实际所需的 FLOPs 因此减半。要在运行中省下这些运算,需要使用专门的注意力核函数。直接调用 einsum 仍会计算这些位置。

Other Operations其他操作

There are several other operations happening in a Transformer. Layernorms are comparatively cheap and can be ignored for first-order cost estimates. Note that each layer typically has two of them (one before attention and one before the MLP). There is also the final enormous (though not per-layer) unembedding matrix multiply.

Transformer 中还有其他运算。层归一化的开销相对较小,粗略估算时可以忽略。每层通常做两次层归一化,一次在注意力前,一次在 MLP 前。整个模型的末尾还有一次很大的反嵌入(unembedding)矩阵乘法。

operationtrain FLOPsparams2×layernormD    A[B,T,D]O(BTD)2DA[B,T,D]⋅Wunembed[D,V]6BTDVDV\begin{array}{ccc} \textsf{operation} & \textsf{train FLOPs} & \textsf{params} \\ \hline \\ 2 \times \textrm{layernorm}_D \;\; A[B,T,\textcolor{red}{D}] & \textcolor{gray}{O\left(BTD\right)} & \textcolor{gray}{2D} \\[10pt] A[B,T,\textcolor{red}{D}] \cdot W_{unembed}[\textcolor{red}{D}, V] & 6BTDV & DV \\ \end{array}

General rule of thumb for Transformer FLOPsTransformer FLOPs 的通用经验法则

If we neglect the cost of dot-product attention (which is reasonable for shorter-context training), then the total FLOPs across all layers is

如果我们忽略短上下文训练的点积注意力成本,那么所有层的总 FLOPs 是

(18BTDF+12BTD(N+K)H)L=6∗BT∗(3DF+2D(N+K)H)L=6∗num tokens∗parameter count\begin{align*} (18BTDF + 12BTD(N+K)H)L = 6 *BT * (3DF + 2D(N+K)H)L \\ = 6 * \textrm{num tokens} * \textrm{parameter count} \end{align*}

This leads to a famous rule of thumb for estimating dense Transformer FLOP count, ignoring the attention FLOPs. (Unembedding is another simple matmul with 6BTDV6BTDV FLOPs and DVDV params, and follows the same rule of thumb.)

这导致了一个著名的经验法则,用于估算密集 Transformer 的 FLOP 数量,忽略了注意力 FLOPs. (Unembedding 是另一个简单的矩阵乘法,有 6BTDV6BTDV FLOPs 和 DVDV 参数,并遵循相同的经验法则.)

Fractional cost of attention with context length注意力与上下文长度的成本分数

If we do account for dot-product attention above and assume F=4DF=4D, D=NHD=NH (as is typical) and N=KN=K, the ratio of dot-product attention FLOPs to all matmul FLOPs (including the attention projections) is:

如果计入上述点积注意力的成本,并按常见配置假设 F=4DF=4D、D=NHD=NH 以及 N=KN=K,点积注意力的 FLOPs 在所有矩阵乘法(包括注意力投影)FLOPs 中的占比如下。

attention FLOPsmatmul FLOPs=12BT2NH18BTDF+24BTDNH=12BT2D4∗18BTD2+24BTD2=12BT2D96BTD2=T8D\small{\frac{\textrm{attention FLOPs}}{\textrm{matmul FLOPs}} = \frac{12BT^2NH}{18BTDF + 24BTDNH} = \frac{12BT^2D}{4*18 BTD^2 + 24 BTD^2} = \frac{12BT^2D}{96 BTD^2} = \frac{T}{8D}}

The upshot is that dot-product attention FLOPs only become dominant during training once T>8D. For D ~ 8k, this would be ~64K tokens. This makes some sense, since it means as the MLP size increases, the attention FLOPs become less critical. For large models, the quadratic cost of attention is not actually a huge obstacle to longer-context training. However, for smaller models, e.g. Gemma-27B with D=4608, attention becomes dominant around 37k sequence lengths.2 Flash Attention also helps alleviate the cost of long-context, which we discuss briefly in Appendix A.

因此,点积注意力的 FLOPs 只有在 T>8D 时才会主导训练的运算量。若 D 约为 8k,阈值约为 64K 个 token。MLP 越大,注意力在计算开销中的占比就越小。对大型模型而言,注意力的二次开销并未严重妨碍较长上下文的训练。但在 D=4608 的 Gemma-27B 等相对较小的模型中,序列长度约为 37k 时,注意力的开销就会占主导。2Flash Attention 也有助于降低长上下文的开销,参见附录 A。

Miscellaneous Math杂项数学

Sparsity and Mixture-of-Experts稀疏性和专家混合

We’d be remiss not to briefly discuss Mixture of Experts (MoE) models[4], which replace the single dense MLP blocks in a standard Transformer with a set of independent MLPs that can be dynamically routed between. To a first approximation, an MoE is just a normal dense model with E MLP blocks per layer, instead of just one. Each token activates kk of these experts, typically k≪Ek \ll E. The ratio E/kE / k is called the sparsity and is usually between 8 and 64 (e.g. DeepSeek v3 has effectively k=8k=8, E=256E=256). This increases the parameter count by O(E)O(E), while multiplying the total number of activated parameters per token by kk, compared with the dense version.

混合专家 (MoE) 模型[4]用一组可以动态路由的独立 MLP 替换标准 Transformer 每层的单个稠密 MLP 块。粗略地说,MoE 可以看成每层有 E 个 MLP 块的普通稠密模型。每个 token 会激活其中的 kk 个专家,通常 k≪Ek \ll E。比值 E/kE / k 称为稀疏度,一般在 8 到 64 之间。例如,DeepSeek v3 实际上采用 k=8k=8、E=256E=256。与稠密模型相比,总参数量增加 O(E)O(E),每个 token 的激活参数总量是原来的 kk 倍。

moe

Figure: an example MoE layer with nn experts. The gating expert routes each token to kk of them, and the output of those kk MLPs get summed. Our parameter count is nn times the size of each expert, but only kk are used for each token. Source.

图: 一个具有 nn 个专家的 MoE 层示例. 门控专家将每个 token 路由到其中的 kk 个,这 kk 个 MLP 的输出被求和. 我们的参数数量是每个专家大小的 nn 倍,但每个 token 只使用 kk 个. 来源.

Compared to a dense model, an MoE introduces new comms, primarily two AllToAlls (one before and one after the MoE block) that route tokens to the correct expert and bring them back to their home device.3 However, as we saw in the previous section, the cost of each AllToAll is only 1/4 that of a comparable AllGather along a single axis (for a bidirectional ring).

与密集模型相比,MoE 引入了新的通信,主要是两个 AllToAll (一个在 MoE 块之前,一个在之后), 将 token 路由到正确的专家,并将它们带回其主设备.3 然而,正如我们在上一节中看到的,每个 AllToAll 的成本仅为沿单个轴的可比 AllGather 的 1/4 (对于双向环).

Gradient checkpointing梯度检查点

Backpropagation as an algorithm trades compute for memory. Instead of a backward pass requiring O(nlayers2)O(n_\text{layers}^2) FLOPs, it requires O(nlayers)O(n_\text{layers}) memory, saving all intermediate activations generated during the forward pass. While this is better than quadratic compute, it’s incredibly expensive memory-wise: a model with B∗T=4MB * T=4M (4M total tokens per batch), L=64, and D=8192 that avoids all unnecessary backward pass compute would have to save roughly 2∗20∗B∗T∗D∗L=84TB2 * 20 * B * T * D * L = 84TB of activations in bfloat16. The 20 comes from (roughly) counting every intermediate node in the Transformer diagram above, since e.g.

反向传播作为一种算法,用内存换取计算. 反向传播不需要 O(nlayers2)O(n_\text{layers}^2) FLOPs, 它需要 O(nlayers)O(n_\text{layers}) 内存, 保存前向传播期间生成的所有中间激活. 虽然这比二次计算要好,但在内存方面却非常昂贵:一个具有 B∗T=4MB * T=4M (每批总共 4M token), L=64 和 D=8192 的模型,如果避免所有不必要的后向传播计算,将不得不保存大约 2∗20∗B∗T∗D∗L=84TB2 * 20 * B * T * D * L = 84TB 的 bfloat16 激活. 20 来自 (粗略地) 计算上面 Transformer 图中的每个中间节点,因为例如

f(x)=exp⁡(g(x))f(x) = \exp(g(x)) dfdx=exp⁡(g(x))⋅dgdx\frac{df}{dx} = \exp(g(x)) \cdot \frac{dg}{dx}

so to avoid recomputing we need to save g(x)g(x) and exp⁡(g(x))\exp(g(x)) from the forward pass. To avoid saving this much memory, we can choose to only save some fraction of the intermediate activations. Here are a few strategies we use.

所以为了避免重新计算,我们需要从前向传播中保存 g(x)g(x) 和 exp⁡(g(x))\exp(g(x)). 为了避免保存这么多内存,我们可以选择只保存一部分中间激活. 以下是我们使用的一些策略.

  • Block remat: only save the input to each layer. This is the most aggressive method we use and only saves 1 checkpoint per layer, meaning we’d only save 4.2TB in the example above. This forces us to repeat essentially all forward pass FLOPs in the backward pass, meaning we increase our FLOPs from 6⋅num params⋅num tokens6 \cdot \text{num params} \cdot \text{num tokens} to roughly 8⋅num params⋅num tokens8 \cdot \text{num params} \cdot \text{num tokens}.
  • Big matmuls only: another simple policy is to only save the outputs of large matmuls. This lets us avoid recomputing any large matmuls during the backward pass, but still makes us recompute other activation functions and parts of attention. This reduces the 20 per layer above to closer to 7 per layer.
  • 块重算: 只保存每层的输入. 这是我们使用的最激进的方法,每层只保存 1 个检查点,这意味着在上面的例子中我们只保存 4.2TB. 这迫使我们在后向传播中重复基本上所有的前向传播 FLOPs, 这意味着我们将 FLOPs 从 6⋅num params⋅num tokens6 \cdot \text{num params} \cdot \text{num tokens} 增加到大约 8⋅num params⋅num tokens8 \cdot \text{num params} \cdot \text{num tokens}.
  • 仅大矩阵乘法: 另一个简单的策略是只保存大矩阵乘法的输出. 这使我们能够避免在后向传播期间重新计算任何大矩阵乘法,但仍然使我们重新计算其他激活函数和部分注意力. 这将每层的 20 个减少到接近 7 个.

This is by no means comprehensive. When using JAX, these are typically controlled by jax.remat/jax.checkpoint (you can read more here).

这绝不是详尽无遗的. 在使用 JAX 时,这些通常由 jax.remat/jax.checkpoint 控制 (你可以在这里阅读更多内容).

Key-Value (KV) caching键值 (KV) 缓存

As we’ll see in Section 7, LLM inference has two key parts, prefill and generation.

正如我们将在第 7 节中看到的,LLM 推理有两个关键部分,预填充和生成.

  • Prefill processes a long prompt and saves its attention activations in a Key-Value Cache (KV Cache) for use in generation, specifically the key-value projections in the attention block.
  • Generation batches several of these KV caches together and samples tokens from each of them.
  • 预填充处理一个长提示,并将其注意力激活保存在一个键值缓存 (KV Cache) 中,以便在生成中使用,特别是注意力块中的键值投影.
  • 生成将其中几个 KV 缓存批处理在一起,并从每个缓存中采样 token.

Each KV cache is then effectively an array of size [2,S,L,K,H][2, S, L, K, H] where the 2 accounts for the keys and values. This is quite large! The total size of the Key-Value cache in int8 is 2SLKH2SLKH. For a moderately sized model with 8k context length, 64 layers, and KH=NH=D=8192KH = NH = D = 8192, this is 2⋅8192⋅64⋅8192=8GiB2 \cdot 8192 \cdot 64 \cdot 8192 = 8\text{GiB}. You can see why we would want to use GMQA with K≪NK \ll N.

每个 KV 缓存实际上是一个大小为 [2,S,L,K,H][2, S, L, K, H] 的数组,其中 2 表示键和值. 这相当大!int8 中键值缓存的总大小为 2SLKH2SLKH. 对于一个中等大小的模型,具有 8k 上下文长度,64 层,以及 KH=NH=D=8192KH = NH = D = 8192, 这是 2⋅8192⋅64⋅8192=8GiB2 \cdot 8192 \cdot 64 \cdot 8192 = 8\text{GiB}. 你可以看到为什么我们想要使用 K≪NK \ll N 的 GMQA.

What Should You Take Away from this Section?你应该从本节中学到什么?

  • The overall parameters and FLOPs of a Transformer are fairly easy to calculate, and are summarized here, assuming MHA (with batch size B, vocab size V, a sequence of length T, D=dmodel, and F=dff):
  • Transformer 的总体参数和 FLOPs 相当容易计算,并在此处进行了总结,假设 MHA (批次大小为 B, 词汇量大小为 V, 序列长度为 T, D=d_model, F=d_ff):
Component
组件
Params per layer
每层参数
Training FLOPs per layer
每层训练 FLOPs
MLP3DF18BTDF
Attention
注意力
4DNH24BTDNH + 12BT2NH
Other
其他
2DBTD
Vocab
词汇表
DV (total, not per-layer)
DV (总计,非每层)
12BTDV
  • The parameter count of the MLP block dominates the total parameter count and the MLP block also dominates the FLOPs budget as long as the sequence length T<8DT < 8D.
  • The total FLOPs budget during training is well approximated by 6⋅num_params⋅num_tokens6 \cdot \text{num\_params} \cdot \text{num\_tokens} for reasonable context lengths.
  • During inference, our KV caches are roughly 2⋅S⋅L⋅K⋅H2 \cdot S \cdot L \cdot K \cdot H per cache (where K is the number of KV heads), although architectural modifications can often reduce this.
  • MLP 块的参数数量在总参数数量中占主导地位,并且只要序列长度 T<8DT < 8D, MLP 块在 FLOPs 预算中也占主导地位.
  • 对于合理的上下文长度,训练期间的总 FLOPs 预算可以很好地近似为 6⋅num_params⋅num_tokens6 \cdot \text{num\_params} \cdot \text{num\_tokens}.
  • 在推理期间,我们的 KV 缓存大约为每个缓存 2⋅S⋅L⋅K⋅H2 \cdot S \cdot L \cdot K \cdot H, 尽管架构修改通常可以减少这个值.

A Few Problems to Work一些待解决的问题

Question 1: How many parameters does a model with D=4096D=4096, F=4⋅DF=4 \cdot D, V=32,000V=32,000, and L=64L=64 have? What fraction of these are attention parameters? How large are our KV caches per token? You can assume N⋅H=DN\cdot H=D and multi-head attention with int8 KVs.

问题 1: 一个具有 D=4096D=4096, F=4⋅DF=4 \cdot D, V=32,000V=32,000 和 L=64L=64 的模型有多少参数?其中有多少是注意力参数?每个 token 的 KV 缓存有多大?你可以假设 N⋅H=DN\cdot H=D 和多头注意力,int8 KVs.

Click here for the answer. 点击查看答案
  1. The total parameters is roughly L⋅(3DF+4DNH+2D)+2DVL \cdot (3DF + 4DNH + 2D) + 2DV (counting the two layernorms per layer). For the given numbers, this is 64⋅(3⋅4e3⋅16e3+4⋅4e3⋅4e3+2⋅4e3)+2⋅4e3⋅32e3=16e964 \cdot (3 \cdot 4e3 \cdot 16e3 + 4 \cdot 4e3 \cdot 4e3 + 2 \cdot 4e3) + 2 \cdot 4e3 \cdot 32e3 = 16e9, or 16B parameters.
  2. The ratio of attention parameters to total parameters in general is 4DNH/(4DNH+3DF)=4D2/(4D2+12D2)=1/44DNH / (4DNH + 3DF) = 4D^2 / (4D^2 + 12D^2) = 1/4. This means roughly 1/4 of the parameters are used in attention.
  3. Per token, our KV caches are 2⋅L⋅N⋅H=2⋅64⋅40962 \cdot L \cdot N \cdot H = 2 \cdot 64 \cdot 4096 in int8, which is 512 KiB / token.
  1. 计入每层的两次层归一化后,总参数量约为 L⋅(3DF+4DNH+2D)+2DVL \cdot (3DF + 4DNH + 2D) + 2DV. 对于给定的数字,这是 64⋅(3⋅4e3⋅16e3+4⋅4e3⋅4e3+2⋅4e3)+2⋅4e3⋅32e3=16e964 \cdot (3 \cdot 4e3 \cdot 16e3 + 4 \cdot 4e3 \cdot 4e3 + 2 \cdot 4e3) + 2 \cdot 4e3 \cdot 32e3 = 16e9, 或 16B 参数.
  2. 注意力参数与总参数之比通常是 4DNH/(4DNH+3DF)=4D2/(4D2+12D2)=1/44DNH / (4DNH + 3DF) = 4D^2 / (4D^2 + 12D^2) = 1/4. 这给了我们大约 1/4 的参数用于注意力.
  3. 每个 token, 我们的 KV 缓存是 2⋅L⋅N⋅H=2⋅64⋅40962 \cdot L \cdot N \cdot H = 2 \cdot 64 \cdot 4096 (int8), 即 512 KiB / token.

Question 2: How many total FLOPs are required to perform A[BX, DY] *D W[DY, F] on {'X': 4, 'Y': 8, 'Z': 4}? How many FLOPs are performed by each TPU?

问题 2: 在 {'X': 4, 'Y': 8, 'Z': 4} 上执行 A[BX, DY] *D W[DY, F] 共需要多少 FLOPs?其中每块 TPU 执行多少 FLOPs?

Click here for the answer. 点击查看答案

The total “theoretical” FLOPs of the operation is 2⋅B⋅D⋅F2 \cdot B \cdot D \cdot F. However, because the computation isn’t sharded across the Z dimension, we’re actually doing Z extra FLOPs, meaning 2⋅B⋅D⋅F⋅Z2 \cdot B \cdot D \cdot F \cdot Z total FLOPs. Since the computation is sharded across the other dimensions, the total per-device is roughly 2⋅B⋅D⋅F/(X⋅Y)2 \cdot B \cdot D \cdot F / (X \cdot Y).

该操作的总“理论” FLOPs 是 2⋅B⋅D⋅F2 \cdot B \cdot D \cdot F. 然而,因为计算没有在 Z 维度上分片,我们实际上多做了 Z 倍的 FLOPs, 这意味着总共有 2⋅B⋅D⋅F⋅Z2 \cdot B \cdot D \cdot F \cdot Z FLOPs. 由于计算在其他维度上是分片的,每个设备的总 FLOPs 大约是 2⋅B⋅D⋅F/(X⋅Y)2 \cdot B \cdot D \cdot F / (X \cdot Y).

Question 3: How many FLOPs are involved in performing A[I,J,K,L]∗B[I,J,M,N,O]→C[K,L,M,N,O]A[I,J,K,L] * B[I,J,M,N,O] \rightarrow C[K,L,M,N,O]?

问题 3: 执行 A[I,J,K,L]∗B[I,J,M,N,O]→C[K,L,M,N,O]A[I,J,K,L] * B[I,J,M,N,O] \rightarrow C[K,L,M,N,O] 涉及多少 FLOPs?

Click here for the answer. 点击查看答案

Following the rule above, we have I and J as contracting dimensions and K, L, M, N, and O as non-contracting dimensions. We have no “batching dimensions”, so this is just 2⋅I⋅J⋅K⋅L⋅M⋅N⋅O2 \cdot I \cdot J \cdot K \cdot L \cdot M \cdot N \cdot O, the product of all the axes. If we had a shared axis, it would only be counted once.

根据上面的规则,我们有 I 和 J 作为缩并维度,K, L, M, N 和 O 作为非缩并维度. 我们没有“批次维度”,所以这只是 2⋅I⋅J⋅K⋅L⋅M⋅N⋅O2 \cdot I \cdot J \cdot K \cdot L \cdot M \cdot N \cdot O, 所有轴的总和. 如果我们有一个共享轴,它只会被计算一次.

Question 4: What is the arithmetic intensity of grouped multi-query attention (ignoring the Q/K/V/O projections)? Give the answer as a function of the Q and KV sequence lengths T and S and the multi-query factor G. At what context length is attention FLOPs-bound? Given the HBM bandwidth of our TPUs, plot the effective relative cost of attention to the FFW block as the context length grows. Hint: assume we’re using an efficient attention implementation that doesn’t do any unnecessary reads/writes. Consider both the limits where T = S and T << S.

问题 4: 自注意力的算术强度是多少 (忽略 Q/K/V/O 投影)? 以 Q 和 KV 长度 T 和 S 的函数形式给出答案. 在什么上下文长度下,注意力是受 FLOPs 限制的?给定我们 TPU 的 HBM 带宽,绘制随着上下文长度的增长,注意力与 FFW 块的有效相对成本.

Click here for the answer. 点击查看答案

Self-attention requires loading the QQ, KK, and VV activations, then computing softmax(Q⋅K)⋅V\text{softmax}(Q \cdot K) \cdot V, then writing the result back to HBM. This will be done with Flash Attention so there are some caveats to this math, but basically in bf16 self-attention performs

自注意力需要加载 QQ, KK 和 VV 激活,然后计算 softmax(Q⋅K)⋅V\text{softmax}(Q \cdot K) \cdot V, 然后将结果写回 HBM. 这将使用 Flash Attention 完成,所以这个数学有一些警告,但基本上在 bf16 自注意力中执行

Q[B,T,N,H]→reshapeQ[B, T, K, G, H]⋅K[B, S, K, H]→O[B, T, S, K, G]\text{Q[B,T,N,H]} \rightarrow_\text{reshape} \text{Q[B, T, K, G, H]} \cdot \text{K[B, S, K, H]} \rightarrow \text{O[B, T, S, K, G]} U=softmaxS(O[B, T, S, K, G])U=\text{softmax}_S(\text{O[B, T, S, K, G]}) U[B, T, S, K, G]⋅V[B, S, K, H]→X[B, T, K, G, H]\text{U[B, T, S, K, G]} \cdot \text{V[B, S, K, H]} \rightarrow \text{X[B, T, K, G, H]}

So our total bytes is 2∗sizeof(Q)+2∗sizeof(K or V)=4BTNH+4BSKH=4BHK∗(TG+S)2 * \text{sizeof}(Q) + 2 * \text{sizeof(K or V)} = 4BTNH + 4BSKH = 4BHK * (TG + S), total FLOPs is 4BTSNH+O(BTSN)4BTSNH + O(BTSN) and the arithmetic intensity is 4BTSKGH/(4BHK∗(TG+S))4BTSKGH / (4BHK * (TG + S)).

所以我们的总字节数是 2∗sizeof(Q)+2∗sizeof(K or V)=4BTNH+4BSKH=4BHK∗(TG+S)2 * \text{sizeof}(Q) + 2 * \text{sizeof(K or V)} = 4BTNH + 4BSKH = 4BHK * (TG + S), 总 FLOPs 是 4BTSNH+O(BTSN)4BTSNH + O(BTSN), 算术强度是 4BTSKGH/(4BHK∗(TG+S))4BTSKGH / (4BHK * (TG + S)).

So basically, during prefill we have S=TS=T so we have an arithmetic intensity of 4BT2KGH/4BHKT⋅(G+1)=TG/(G+1)=O(T)4BT^2KGH / 4BHKT \cdot (G+1) = TG/(G + 1) = O(T). During generation, T=1T=1 so we have 4BSKGH/(4BHK⋅(G+S))=SG/(G+S)→G4BSKGH / (4BHK \cdot (G + S)) = SG / (G + S) \rightarrow G assuming SS is very large. Depending on how you interpret the question, during prefill or training self-attention is compute-bound at S=240 assuming no sequence sharding. During generation, we are never compute-bound because GG is small. Nonetheless, you can see that increasing GG leads to us being closer to compute-bound.

所以基本上,在预填充期间,我们有 S=TS=T, 所以我们的算术强度是 4BT2KGH/4BHKT⋅(G+1)=TG/(G+1)=O(T)4BT^2KGH / 4BHKT \cdot (G+1) = TG/(G + 1) = O(T). 在生成期间,T=1T=1, 所以我们有 4BSKGH/(4BHK⋅(G+S))=SG/(G+S)→G4BSKGH / (4BHK \cdot (G + S)) = SG / (G + S) \rightarrow G, 假设 SS 非常大. 根据你如何解释这个问题,在预填充或训练期间,假设没有序列分片,自注意力在 S=240 时受计算限制. 在生成期间,我们永远不会受计算限制,因为 GG 很小. 然而,无论如何,你可以看到增加 GG 会使我们更接近受计算限制.

Question 5: At what sequence length are self-attention FLOPs equal to the QKVO projection FLOPs?

问题 5: 在什么序列长度下,自注意力 FLOPs 等于 QKVO 投影 FLOPs?

Click here for the answer. 点击查看答案

This is purely a question of when 24BTDNH=12BT2NH24BTDNH = 12BT^2NH. Simplifying we get 2D=T2D = T, so e.g. for D=4096D=4096, this is 81928192. This tells us that for most reasonable context lengths, matmul FLOPs are greater.

这纯粹是一个关于何时 24BTDNH=12BT2NH24BTDNH = 12BT^2NH 的问题. 简化后我们得到 2D=T2D = T, 例如对于 D=4096D=4096, 这是 81928192. 这告诉我们,对于大多数合理的上下文长度,矩阵乘法 FLOPs 更大.

Question 6: Say we only save the output of each of the 7 main matmuls in a Transformer layer during our forward pass (Q, K, V, O + the three FFW matrices). How many extra FLOPs do we need to “rematerialize” during the backward pass?

问题 6: 假设我们在前向传播期间只保存 Transformer 层中 7 个主要矩阵乘法 (Q, K, V, O + 三个 FFW 矩阵) 中每个的输出. 在后向传播期间,我们需要“重新物化”多少额外的 FLOPs?

Click here for the answer. 点击查看答案

Saving only the seven matmul outputs (Q, K, V, O, W₁, W₂, W₃) means the backward pass must recompute the two attention matmuls

只保存七个矩阵乘法输出 (Q, K, V, O, W₁, W₂, W₃) 意味着后向传播必须重新计算两个注意力矩阵乘法

QK⊤andsoftmax⁡(QK⊤)VQK^{\top} \quad\text{and}\quad \operatorname{softmax}(QK^{\top})V

in order to obtain ∂L∂WO\frac{\partial L}{\partial W_\text{O}}.

以求得 ∂L∂WO\frac{\partial L}{\partial W_\text{O}}。

Each is a T×TT \times T matmul batched over BB sequences and NN heads, so the additional FLOPs are

每个都是一个在 BB 个序列和 NN 个头上批处理的 T×TT \times T 矩阵乘法,所以额外的 FLOPs 是

4  B T2 N H.4 \; B \, T^{2} \, N \, H.

Other recomputed operations are:

  1. O(BTD)O(BTD) for ∂L∂WIn1\frac{\partial L}{\partial W_\text{In1}} and ∂L∂WIn2\frac{\partial L}{\partial W_\text{In2}}.
  2. And O(BTF)O(BTF) for ∂L∂WOut\frac{\partial L}{\partial W_\text{Out}}.

另外还需重算:

  1. 求 ∂L∂WIn1\frac{\partial L}{\partial W_\text{In1}} 和 ∂L∂WIn2\frac{\partial L}{\partial W_\text{In2}} 时,需做 O(BTD)O(BTD) 次运算。
  2. 求 ∂L∂WOut\frac{\partial L}{\partial W_\text{Out}} 时,需做 O(BTF)O(BTF) 次运算。

Question 7: DeepSeek v3 says it was trained for 2.79M H800 hours on 14.8T tokens (source). Given that it has 37B activated parameters, roughly what hardware utilization did they achieve? Hint: note that they used FP8 FLOPs without structured sparsity.

问题 7: DeepSeek v3 表示它在 14.8T token 上训练了 279 万 H800 小时 (来源). 鉴于它有 37B 个激活参数,他们大致实现了什么样的硬件利用率?提示:请注意,他们使用了没有结构化稀疏性的 FP8 FLOPs.

Click here for the answer. 点击查看答案

From the spec sheet here, we find 3,026 TFLOPs/s of FP8 performance with sparsity, or typically half this (1.513e15 FLOPs/s) without sparsity. 2.79M H800 hours means 2.79e6 * 1.513e15 * 60 * 60 = 1.52e25 total FLOPs. Given the activated parameter count of 37B, this training run should have used about 6 * 37e9 * 14.8e12 = 3.3e24 FLOPs. That means the FLOPs utilization is about 3.3e24 / 1.52e25 = 21.7%.

从这里的规格表中,我们发现有 3,026 TFLOPs/s 的 FP8 性能 (带稀疏性), 或者通常是这个值的一半 (1.513e15 FLOPs/s) (不带稀疏性). 279 万 H800 小时意味着 2.79e6 * 1.513e15 * 60 * 60 = 1.52e25 总 FLOPs. 鉴于 37B 的激活参数数量,这次训练运行应该使用了大约 6 * 37e9 * 14.8e12 = 3.3e24 FLOPs. 这意味着 FLOPs 利用率大约是 3.3e24 / 1.52e25 = 21.7%.

Question 8: Mixture of Experts (MoE) models have EE copies of a standard dense MLP block, and each token activates kk of these experts. What batch size in tokens is required to be compute-bound for an MoE with weights in int8 on TPU v5e? For DeepSeek, which has 256 (routed) experts and k=8k=8, what is this number?

问题 8: 专家混合 (MoE) 模型有 EE 个标准密集 MLP 块的副本,每个 token 激活这些专家中的 kk 个. 在 TPU v5e 上,对于 int8 权重的 MoE, 需要多大的 token 批次大小才能受计算限制?对于 DeepSeek, 它有 256 个 (路由的) 专家和 k=8k=8, 这个数字是多少?

Click here for the answer. 点击查看答案

Because we have EE copies of each expert, in int8, for each weight matrix we need to load E⋅D⋅FE \cdot D \cdot F bytes. Because each token activates kk experts, for each weight matrix we have 2⋅k⋅B⋅D⋅F2\cdot k \cdot B \cdot D \cdot F FLOPs. To be compute-bound with int8 weights and bfloat16 FLOPs, we need the arithmetic intensity (FLOPs per byte loaded) to exceed the TPU’s ~240 FLOPs/byte, which happens when (2⋅k⋅BDF)/EDF>240(2\cdot k \cdot BDF) / EDF > 240 or k⋅B/E>120k \cdot B / E > 120.

模型共有 EE 个专家,所以对于每个权重矩阵,使用 int8 时需要加载 E⋅D⋅FE \cdot D \cdot F 字节. 每个 token 会激活 kk 个专家,因此每个权重矩阵的运算量为 2⋅k⋅B⋅D⋅F2\cdot k \cdot B \cdot D \cdot F FLOPs. 为了在 bfloat16 FLOPs 下受计算限制,我们需要一个超过 240 的算术强度,这发生在 (2⋅k⋅BDF)/EDF>240(2\cdot k \cdot BDF) / EDF > 240 或 k⋅B/E>120k \cdot B / E > 120 时.

Therefore, we need B>120⋅E/kB > 120 \cdot E / k to be compute-bound. For DeepSeek, this gives us B>120⋅256/8=3840B > 120 \cdot 256 / 8 = 3840. This is a remarkably large batch size at generation time.

因此,我们需要 B>120⋅E/kB > 120 \cdot E / k 才能受计算限制. 对于 DeepSeek, 这给了我们 B>120⋅256/8=3840B > 120 \cdot 256 / 8 = 3840. 这在生成时是一个非常大的批次大小.

That’s it for Part 4! For Part 5 (about scaling Transformer training), click here!

第四部分到此结束!第五部分 (关于扩展 Transformer 训练), 点击这里!

Appendix附录

Appendix A: How does Flash Attention work?附录 A: Flash Attention 是如何工作的?

The traditional objection to scaling Transformers to very long context is that the attention FLOPs and memory usage scale quadratically with context length. While it’s true that the attention QK product has shape [B,T,S,N][B, T, S, N] where B is the batch size, T and S are the Q and K sequence dims, and N is the number of heads, this claim comes with some serious caveats:

把 Transformer 扩展到很长的上下文时,常有人指出注意力的 FLOPs 和内存用量都会随上下文长度呈二次增长。注意力的 QK 乘积形状确实是 [B,T,S,N][B, T, S, N],其中 B 为批次大小,T 和 S 分别是 Q 和 K 的序列维度,N 是注意力头数。但这并不直接等于实际开销,原因有二:

  1. As we noted earlier, even though this is quadratic, the attention FLOPs only dominate when T>8⋅DT > 8 \cdot D, and during training the memory of a single attention matrix is small compared to all of the weights and activation checkpoints living in memory, especially when sharded.
  2. We don’t need to materialize the full attention matrix in order to compute attention! We can compute local sums and maxes and avoid ever materializing more than a small chunk of the array. While the total FLOPs is still quadratic, we drastically reduce memory pressure.
  1. 如前所述,即使这是二次的,注意力 FLOPs 也只在 T>8⋅DT > 8 \cdot D 时占主导地位,特别是在训练期间,单个注意力矩阵的内存与内存中存在的所有权重和激活检查点相比很小,特别是在分片时.
  2. 我们不需要物化完整的注意力矩阵来计算注意力!我们可以计算局部和和最大值,并避免物化超过数组的一小部分. 虽然总 FLOPs 仍然是二次的,但我们大大减少了内存压力.

This second observation was first made by Rabe et al. 2021 and later in the Flash Attention paper (Dao et al. 2022). The basic idea is to compute the attention in chunks of K/V, where we compute the local softmax and some auxiliary statistics, then pass them on to the next chunk which combines them with its local chunk. Specifically, we compute

这一第二个观察首先由 Rabe et al. 2021 提出,后来在 Flash Attention 论文 (Dao et al. 2022) 中提出. 基本思想是将注意力分块计算 K/V, 我们计算局部 softmax 和一些辅助统计数据,然后将它们传递给下一个块,下一个块将它们与自己的局部块组合. 具体来说,我们计算

  1. M: The running max of q⋅kq \cdot k over the sequence dimension
  2. O: The running full attention softmax over the sequence dimension
  3. L: The running denominator ∑iexp⁡(q⋅ki−running max)\sum_i \exp(q \cdot k_i - \text{running max})
  1. M: 沿序列维度累积更新的 q⋅kq \cdot k 最大值。
  2. O: 沿序列维度累积更新的注意力 softmax 结果。
  3. L: 累积更新的分母 ∑iexp⁡(q⋅ki−running max)\sum_i \exp(q \cdot k_i - \text{running max})。

With these, we can compute the new max, the new running sum, and the new output with only a constant amount of memory. To give a sketchy description of how this works, attention is roughly this operation:

有了这些,我们可以用恒定的内存量计算新的最大值,新的运行和,以及新的输出. 为了粗略地描述这是如何工作的,注意力大致是这个操作:

Attn(Q,K,V)=∑iexp⁡(Q⋅Ki−max⁡jQ⋅Kj)Vi∑lexp⁡(Q⋅Kl−max⁡jQ⋅Kj)\text{Attn}(Q, K, V) = \sum_i \frac{\exp(Q \cdot K_i - \max_j Q \cdot K_j) V_i}{\sum_l \exp(Q \cdot K_l - \max_j Q \cdot K_j)}

The max is subtracted for numerical stability and can be subtracted without affecting the outcome since ∑iexp⁡(ai+b)=exp⁡(b)∑exp⁡(a)\sum_i \exp(a_i + b) = \exp(b) \sum \exp(a). Looking just at the denominator above, if we imagine having two contiguous chunks of key vectors, K1K^1 and K2K^2 and we compute the local softmax sums L1L^1 and L2L^2 for each

为了数值稳定性,减去了最大值,并且可以在不影响结果的情况下添加,因为 ∑iexp⁡(ai+b)=exp⁡(b)∑exp⁡(a)\sum_i \exp(a_i + b) = \exp(b) \sum \exp(a). 只看上面的分母,如果我们想象有两个连续的键向量块,K1K^1 和 K2K^2, 我们为每个块计算局部 softmax 和 L1L^1 和 L2L^2

L1=∑iexp⁡(Q⋅Ki1−max⁡jQ⋅Kj1)L^1 = \sum_i \exp(Q \cdot K_i^1 - \max_j Q \cdot K_j^1) L2=∑iexp⁡(Q⋅Ki2−max⁡jQ⋅Kj2)L^2 = \sum_i \exp(Q \cdot K_i^2 - \max_j Q \cdot K_j^2)

Then we can combine these into the full softmax sum for these two chunks together by using

然后我们可以使用以下公式将它们组合成这两个块的完整 softmax 和

Lcombined=exp⁡(M1−max⁡(M1,M2))⋅L1+exp⁡(M2−max⁡(M1,M2))⋅L2L^\text{combined} = \exp(M^1 - \max(M^1, M^2)) \cdot L^1 + \exp(M^2 - \max(M^1, M^2)) \cdot L^2

where

其中

M1=max⁡jQ⋅Kj1 and M2=max⁡jQ⋅Kj2M^1 = \max_j Q \cdot K_j^1 \text{ and } M^2 = \max_j Q \cdot K_j^2

This can be done for the full softmax as well, giving us a way of accumulating arbitrarily large softmax sums. Here’s the full algorithm from the Flash Attention paper.

这也可以对完整的 softmax 进行,给了我们一种累积任意大的 softmax 和的方法. 这是 Flash Attention 论文中的完整算法.

flash algo

From a hardware standpoint, this lets us fit our chunk of Q into VMEM (what the algorithm above calls on-chip SRAM) so we only have to load the KV chunks on each iteration, increasing the arithmetic intensity. We can also keep the running statistics in VMEM.

从硬件的角度来看,这让我们可以将我们的 Q 块放入 VMEM (上面算法称之为片上 SRAM), 所以我们只需要在每次迭代中加载 KV 块,从而降低了算术强度. 我们也可以将运行统计数据保存在 VMEM 中.

One last subtle point worth emphasizing is an attention softmax property that’s used to make the Flash VJP (reverse mode derivative) calculation practical for training. We define an intermediate softmax array:

最后一个值得强调的微妙之处是注意力 softmax 的一个属性,它被用来使 Flash VJP (反向模式导数) 计算在训练中变得实用. 如果我们将一个中间 softmax 数组定义为:

Sij=eτqi⋅kj∑leτqi⋅klS_{ij} = \frac{e^{\tau q_i \cdot k_j}}{\sum_l e^{\tau q_i \cdot k_l}}

In attention, we obtain dS from reverse-mode dO and V arrays:

在注意力中,我们从反向模式 dO 和 V 数组中获得 dS:

dSij=dOid⋅dVjd=∑ddOidVjddS_{ij} = dO_{id} \cdot_d V_{jd} = \sum_d dO_{id} V_{jd}

During the backpropagation of this gradient to Q and K

在将此梯度反向传播到 Q 和 K 期间

d(qi⋅kj)=(dSij−Sij⋅jdSij)Sijd(q_i \cdot k_j) = (dS_{ij} - S_{ij} \cdot_j dS_{ij}) S_{ij}

We exploit an identity that allows us to exchange a contraction along the large key length dimension with a local contraction along the feature depth dimension.

我们利用一个恒等式,允许我们将沿大键长度维度的收缩与沿特征深度维度的局部收缩交换.

Sij⋅jdSij=∑jeτqi⋅kj∑keτqi⋅kk∑ddOidVjd=∑ddOid∑jeτqi⋅kj∑keτqi⋅kkVjd=∑ddOidOid=dOid⋅dOid\begin{align*} S_{ij} \cdot_j dS_{ij} &= \sum_j \frac{e^{\tau q_i \cdot k_j}}{\sum_k e^{\tau q_i \cdot k_k}} \sum_d dO_{id} V_{jd} \\ &= \sum_d dO_{id} \sum_j \frac{e^{\tau q_i \cdot k_j}}{\sum_k e^{\tau q_i \cdot k_k}} V_{jd} \\ &= \sum_d dO_{id} O_{id} \\ &= dO_{id} \cdot_d O_{id} \end{align*}

This replacement is crucial for being able to implement a sequence-block local calculation for the VJP, and enables further clever sharding schemes like ring attention.

这种替换对于能够为 VJP 实现序列块局部计算至关重要,并启用了更巧妙的分片方案,如环形注意力.

References参考文献

  1. GLU Variants Improve Transformer. Shazeer, Noam. 2020.
  2. Fast Transformer decoding: One write-head is all you need. Shazeer, Noam. 2019.
  3. GQA: Training generalized multi-query transformer models from multi-head checkpoints. Ainslie, Joshua and Lee-Thorp, James and de Jong, Michiel and Zemlyanskiy, Yury and Lebrón, Federico and Sanghai, Sumit. 2023.
  4. Outrageously large neural networks: The Sparsely-Gated Mixture-of-experts layer. Shazeer, Noam and Mirhoseini, Azalia and Maziarz, Krzysztof and Davis, Andy and Le, Quoc and Hinton, Geoffrey and Dean, Jeff. 2017.

BibTeX

Footnotes

  1. Contracting dimensions are axes that are summed over during the operation (they appear in both inputs but not in the output), like the inner dimension in a matrix multiply. Batching dimensions are shared axes that appear in both inputs and are carried unchanged to the output; they index independent subproblems and aren’t multiplied together in FLOP counts. In einsum terms: labels present on both inputs and the output are batching; labels present on both inputs but absent from the output are contracting.

    缩并维度是运算中需要沿轴求和的维度。两个输入中都有这条轴,输出中则没有,矩阵乘法的内维度就是一例。批次维度是两个输入共有、且原样保留到输出中的轴。这些轴索引彼此独立的子问题,计算 FLOPs 时只计一次。用 einsum 表示时,批次维度的标签出现在两个输入和输出中,缩并维度的标签只出现在两个输入中。

    ↩
  2. Note that some modern OSS models introduce local attention or other optimizations that reduce the cost of attention and change this roofline.

    一些较新的开源模型采用局部注意力等优化方法,降低了注意力的开销,也改变了这条屋顶线。

    ↩
  3. Technically, this only happens if we are data or sequence sharded along the same axis as our experts.

    技术上,这只在我们在与专家相同的轴上进行数据或序列分片时发生.

    ↩

补充说明

*Work done at Google DeepMind, now at MatX.

*这项工作完成于 Google DeepMind,现任职于 MatX。

引用

For attribution in academic contexts, please cite this work as:

学术写作中请按以下格式引用本书。

Austin et al., "How to Scale Your Model", Google DeepMind, online, 2025.

or as a BibTeX entry:

也可使用以下 BibTeX 条目。

@article{scaling-book,
  title = {How to Scale Your Model},
  author = {Austin, Jacob and Douglas, Sholto and Frostig, Roy and Levskaya, Anselm and Chen, Charlie and Vikram, Sharad
    and Lebron, Federico and Choy, Peter and Ramasesh, Vinay and Webson, Albert and Pope, Reiner},
  publisher = {Google DeepMind},
  howpublished = {Online},
  note = {Retrieved from https://jax-ml.github.io/scaling-book/},
  year = {2025}
}
原版章节与讨论