Skip to content
quboliu
⚙

All About Rooflines详解屋顶线模型

第 1 章 · How To Scale Your Model (如何扩展你的模型 | 如何看待 TPU)

When we run algorithms on hardware, we're bounded by three things: how fast our computer can do math (OPs/second), the bandwidth available for moving data around (bytes/second), and the total memory available to store data (bytes). These "roofline" constraints let us upper and lower bound the time of a given computation.

在硬件上运行算法时,运算速度(操作/秒)、数据传输带宽(字节/秒)和可用内存容量(字节)都会限制算法的性能。这些屋顶线约束让我们可以估算给定计算的耗时上限和下限。

Where Does the Time Go?时间都去哪儿了?

Let’s start with an extremely simple question: why does an algorithm take 50ms instead of 50s or 5ms? What is actually happening within the model that takes substantial time and how long should we expect it to take?

让我们从一个极其简单的问题开始:为什么一个算法需要 50 毫秒而不是 50 秒或 5 毫秒? 模型内部到底发生了什么耗费了大量时间,我们应该期望它花费多长时间?

Computation: A deep learning model is effectively a bunch of matrix multiplications, each composed of floating-point multiplication and addition ‘operations’ (FLOPs). Our accelerator speed determines how long these take to compute:

计算: 深度学习模型实际上是一堆矩阵乘法,每个都由浮点乘法和加法“操作” (FLOPs) 组成. 我们的加速器速度决定了这些计算需要多长时间:

Tmath=Computation FLOPsAccelerator FLOPs/s\begin{equation} T_\text{math} = \frac{\text{Computation FLOPs}}{\text{Accelerator FLOPs/s}} \end{equation}

For instance, an NVIDIA H100 can perform about 9.89e14 bfloat161 FLOPs/s while a TPU v6e can perform 9.1e14 FLOPs/s.2 That means doing 1e12 FLOPs on an H100 will take (roughly) 1e12 / 9.89e14 = 1.01ms and 1e12 / 9.1e14 = 1.1ms on a TPU v6e.3

例如,一块 NVIDIA H100 每秒可以执行约 9.89e14 次 bfloat161 FLOPs, 而一个 TPU v6e 每秒可以执行 9.1e14 次 FLOPs.2 这意味着在 H100 上执行 1e12 次 FLOPs 大约需要 1e12 / 9.89e14 = 1.01ms, 在 TPU v6e 上需要 1e12 / 9.1e14 = 1.1ms.3

Communication within a chip: Within an accelerator, tensors need to be transferred between accelerator memory (HBM) and the compute cores. You’ll see the bandwidth of this link referred to as “HBM bandwidth”.4 On an H100, this is about 3.35TB/s and on TPU v6e this is about 1.6TB/s.

芯片内通信: 在加速器内部, 张量需要在片上内存 (HBM) 和计算核心之间传输. 你会看到这条链路的带宽被称为“HBM 带宽”.4 在 H100 上,这大约是 3.35TB/s, 在 TPU v6e 上 这大约是 1.6TB/s.

Communication between chips: When we distribute a model across multiple accelerators, tensors frequently need to be transferred between them. There are often a few options for this on our hardware (ICI, DCN, and PCIe), each with different bandwidths.

芯片间通信: 当我们将模型分布在多个加速器上时,张量经常需要在它们之间传输. 我们的硬件上通常有几种选择 (ICI, DCN 和 PCIe), 每种都有不同的带宽.

Whether the communication is within a chip or between chips, we measure this in bytes/s and estimate the total communication time with:

无论通信是在芯片内部还是芯片之间,我们都以字节/秒为单位进行测量,并用以下公式估算总通信时间:

Tcomms=Communication BytesNetwork/Memory Bandwidth Bytes/s\begin{equation} T_\text{comms} = \frac{\text{Communication Bytes}}{\text{Network/Memory Bandwidth Bytes/s}} \end{equation}

Typically (but not always), computation within a single chip can be overlapped with communication within a chip and between chips. This means we can lower-bound training and inference time by using the maximum of computation and communication time. We can also upper-bound with their sum. In practice, we optimize against the maximum as the algebra is simpler and we can usually come close to this bound by overlapping our communication and computation. If we optimize with the maximum in mind then the lower and upper bounds differ by at most a factor of 2 since Tmath+Tcomms≤2∗max⁡(Tmath,Tcomms)T_\text{math} + T_\text{comms} \leq 2 * \max(T_\text{math}, T_\text{comms}). We then increase accuracy beyond this by modeling ‘overlap regions’ and overheads, which can be informed by profiling your specific model and target system.

通常 (但并非总是), 单个芯片内的计算可以与芯片内和芯片间的通信重叠. 这意味着我们可以通过使用计算和通信时间的最大值来为训练和推理时间设定下限. 我们也可以用它们的和来设定上限. 在实践中,我们针对最大值进行优化,因为代数更简单,而且我们通常可以通过重叠通信和计算来接近这个界限. 如果我们以最大值为目标进行优化,那么下限和上限最多相差 2 倍,因为 Tmath+Tcomms≤2∗max⁡(Tmath,Tcomms)T_\text{math} + T_\text{comms} \leq 2 * \max(T_\text{math}, T_\text{comms}). 然后,我们通过对“重叠区域”和开销进行建模来提高精度,这可以通过分析你的特定模型和目标系统来获得信息.

Tlower=max⁡(Tmath,Tcomms)\begin{equation} T_\text{lower}=\max(T_\text{math}, T_\text{comms}) \end{equation} Tupper=Tmath+Tcomms\begin{equation} T_\text{upper} = T_\text{math} + T_\text{comms} \end{equation}

If we assume we can perfectly overlap communication and computation, when Tmath>TcommsT_\text{math} > T_\text{comms}, we see full utilization from our hardware. We call this being “compute-bound”. When Tcomms>TmathT_\text{comms} > T_\text{math}, we tend to be “communication-bound”5 and at least some fraction of our accelerator FLOPs/s is wasted waiting for data to be passed around. One way to tell if an operation will be compute or communication-bound is to look at its “arithmetic intensity” or “operational intensity”.

如果我们假设可以完美地重叠通信和计算,当 Tmath>TcommsT_\text{math} > T_\text{comms} 时,我们可以看到硬件的完全利用. 我们称之为“受计算限制”. 当 Tcomms>TmathT_\text{comms} > T_\text{math} 时,我们往往是“受通信限制”5,至少有一部分加速器的 FLOPs/s 被浪费在等待数据传输上. 判断一个操作是受计算限制还是受通信限制的一种方法是看它的“算术强度”或“操作强度”.

Definition: the arithmetic intensity of an algorithm is given by the ratio of the total FLOPs it performs to the number of bytes it needs to communicate — either within a chip or between chips.

定义: 算法的算术强度由其执行的总 FLOPs 与其需要通信的字节数之比给出 —— 无论是在芯片内部还是芯片之间.

Arithmetic Intensity=Computation FLOPsCommunication Bytes\begin{equation} \text{Arithmetic Intensity} = \frac{\text{Computation FLOPs}}{\text{Communication Bytes}} \end{equation}

Arithmetic intensity measures the “FLOPs per byte” of a given operation. To a first order, when our arithmetic intensity is high, TmathT_\text{math} is large compared to TcommsT_\text{comms} and we typically use most of the available FLOPs. When the opposite is true, we spend more time on comms and waste FLOPs. The point where this crossover happens is the “peak arithmetic intensity” of our hardware, the ratio of peak accelerator FLOPs/s to accelerator bandwidth.

算术强度衡量给定操作的“每字节 FLOPs”. 初步来看,当我们的算术强度高时,TmathT_\text{math} 相对于 TcommsT_\text{comms} 较大,我们通常会使用大部分可用的 FLOPs. 当情况相反时,我们在通信上花费更多时间并浪费 FLOPs. 这种交叉发生的点是我们硬件的“峰值算术强度”,即峰值加速器 FLOPs/s 与加速器带宽之比.

Tmath>Tcomms⇔Computation FLOPsAccelerator FLOPs/s>Communication BytesBandwidth Bytes/s⇔Computation FLOPsCommunication Bytes>Accelerator FLOPs/sBandwidth Bytes/s⇔Intensity(Computation)>Intensity(Accelerator)\begin{align*} T_\text{math} > T_\text{comms} \Leftrightarrow \frac{\text{Computation FLOPs}} {\text{Accelerator FLOPs/s}} > \frac{\text{Communication Bytes}}{\text{Bandwidth Bytes/s}} & \\[0.5em] \Leftrightarrow \frac{\text{Computation FLOPs}}{\text{Communication Bytes}} > \frac{\text{Accelerator FLOPs/s}}{\text{Bandwidth Bytes/s}} & \\[0.5em] \Leftrightarrow \text{Intensity}(\text{Computation}) > \text{Intensity}(\text{Accelerator}) & \\ \end{align*}

The quantity Intensity(Accelerator)\text{Intensity}(\text{Accelerator}) is the arithmetic intensity at which our accelerator achieves its peak FLOPs/s. For the TPU v5e MXU, this is about 240 FLOPs/byte, since the TPU can perform 1.97e14 FLOPs/s and load 8.2e11 bytes/s from HBM.6 That means if an algorithm has a lower arithmetic intensity than 240 FLOPs/byte, it will be bound by byte loading and thus we won’t make good use of our hardware.7 Let’s look at one such example:

数量 Intensity(Accelerator)\text{Intensity}(\text{Accelerator}) 是我们的加速器达到其峰值 FLOPs/s 时的算术强度. 对于 TPU v5e MXU, 这大约是 240 FLOPs/字节6, 因为 TPU 可以执行 1.97e14 FLOPs/s 并以 8.2e11 字节/秒的速率从 HBM 读取数据。 这意味着如果一个算法的算术强度低于 2407 FLOPs/字节,它将受到字节加载的限制,因此我们无法充分利用我们的硬件. 让我们看一个这样的例子:

Example (dot product): to compute the dot product of two vectors in bfloat16 precision, x • y: bf16[N], bf16[N] → bf16[1], we need to load xx and yy from memory, each of which has 2∗N=2N2 * N = 2N bytes, perform NN multiplications and N−1N-1 additions, and write 22 bytes back into HBM

Intensity(dot product)=Total FLOPsTotal Bytes=N+N−12N+2N+2=2N−14N+2→12\begin{equation} \text{Intensity}(\text{dot product}) = \frac{\text{Total FLOPs}}{\text{Total Bytes}} = \frac{N + N - 1}{2N + 2N + 2} = \frac{2N - 1}{4N + 2} \rightarrow \frac{1}{2} \end{equation}

示例 (点积): 为了计算两个 bfloat16 精度向量的点积,x • y: bf16[N], bf16[N] → bf16[1], 我们需要从内存中加载 xx 和 yy, 每个都有 2∗N=2N2 * N = 2N 字节,执行 NN 次乘法和 N−1N-1 次加法,并将 22 字节写回 HBM

Intensity(dot product)=Total FLOPsTotal Bytes=N+N−12N+2N+2=2N−14N+2→12\begin{equation} \text{Intensity}(\text{dot product}) = \frac{\text{Total FLOPs}}{\text{Total Bytes}} = \frac{N + N - 1}{2N + 2N + 2} = \frac{2N - 1}{4N + 2} \rightarrow \frac{1}{2} \end{equation}

as N→∞N\rightarrow\infty. So the dot product has an arithmetic intensity of 12\frac{1}{2} or, put another way, the dot product does 0.5 floating point operations per byte loaded. This means our arithmetic intensity is lower than that of our hardware and we will be communication-bound.8

当 N→∞N\rightarrow\infty 时. 所以点积的算术强度为 12\frac{1}{2}, 或者换句话说,点积每加载一个字节执行 0.5 次浮点运算. 这意味着我们的算术强度低于我们的硬件,我们将受到通信限制.8

Visualizing rooflines可视化屋顶线

We can visualize the tradeoff between memory and compute using a roofline plot, which plots the peak achievable FLOPs/s (throughput) of an algorithm on our hardware (the y-axis) against the arithmetic intensity of that algorithm (the x-axis). Here’s an example log-log plot:

我们可以使用屋顶线图来可视化内存和计算之间的权衡,该图绘制了算法在我们的硬件上可实现的峰值 FLOPs/s (吞吐量) (y 轴) 与该算法的算术强度 (x 轴) 的关系. 这是一个对数-对数图的例子:

roofline improved

Figure: an example roofline plot showing two algorithms with different arithmetic intensities (Algo 1 and Algo 2) and their corresponding theoretical peak throughput under different bandwidths (BW1 and BW2). In the red area, an algorithm is bandwidth bound at both bandwidths and is wasting some fraction of the hardware’s peak FLOPs/s. The yellow area is bandwidth-bound only at the lower bandwidth (BW1). The green area is compute-bound at all bandwidths. Here, we are using the peak FLOPs/s of the accelerator and increasing bandwidth or improving intensity yield no benefit.

图: 一个屋顶线图示例,显示了两种具有不同算术强度的算法 (算法 1 和算法 2) 及其在不同带宽 (BW1 和 BW2) 下的相应理论峰值吞吐量. 在红色区域,算法在两种带宽下都受到带宽限制,并且浪费了硬件峰值 FLOPs/s 的一部分. 黄色区域仅在较低带宽 (BW1) 下受到带宽限制. 绿色区域在所有带宽下都受到计算限制. 在这里,我们使用的是加速器的峰值 FLOPs/s, 增加带宽或提高强度没有任何好处.

Above, as the intensity increases (moving left to right), we initially see a linear increase in the performance of our algorithm (in FLOPs/s) until we hit the critical arithmetic intensity of the hardware, 240 in the case of the TPU v5e. Any algorithm with a lower intensity will be bandwidth (BW) bound and limited by the peak memory bandwidth (shown in red). Any algorithm to the right will fully utilize our FLOPs (shown in green). Here, Algo 1 is comms-bound and uses only a fraction of the total hardware FLOPs/s. Algo 2 is compute-bound. We can generally improve the performance of an algorithm either by increasing its arithmetic intensity or by increasing the memory bandwidth available (moving from BW1 to BW2).

上面,随着强度的增加 (从左到右移动), 我们最初看到算法性能 (以 FLOPs/s 为单位) 的线性增长,直到我们达到硬件的临界算术强度,在 TPU v5e 的情况下为 240. 任何强度较低的算法都将受到带宽 (BW) 的限制,并受限于峰值内存带宽 (以红色显示). 右侧的任何算法都将充分利用我们的 FLOPs (以绿色显示). 在这里,算法 1 受通信限制,仅使用总硬件 FLOPs/s 的一小部分. 算法 2 受计算限制. 我们通常可以通过增加其算术强度或增加可用内存带宽 (从 BW1 移动到 BW2) 来提高算法的性能.

Matrix multiplication矩阵乘法

Let’s look at our soon-to-be favorite algorithm: matrix multiplication (aka matmul). Given two matrices XX and YY, we can write X∗Y→ZX * Y \rightarrow Z where XX has shape bf16[B,D]\text{bf16}[B, D], YY has shape bf16[D,F]\text{bf16}[D, F], and ZZ has shape bf16[B,F]\text{bf16}[B, F]. To do the matmul we need to load 2DF+2BD2DF + 2BD bytes, perform 2BDF2BDF FLOPs, and write 2BF2BF bytes back.9 10 Thus:

来看本书会反复用到的算法:矩阵乘法(matmul)。对两个矩阵 XX 和 YY,我们写成 X∗Y→ZX * Y \rightarrow Z, 其中 XX 的形状为 bf16[B,D]\text{bf16}[B, D], YY 的形状为 bf16[D,F]\text{bf16}[D, F], ZZ 的形状为 bf16[B,F]\text{bf16}[B, F]. 为了进行矩阵乘法,我们需要加载 2DF+2BD2DF + 2BD 字节,执行 2BDF2BDF FLOPs, 并写回 2BF2BF 字节.9 10 因此:

Intensity(matmul)=2BDF2BD+2DF+2BF=BDFBD+DF+BF\begin{equation} \text{Intensity}(\text{matmul}) = \frac{2BDF}{2BD + 2DF + 2BF} = \frac{BDF}{BD + DF + BF} \end{equation}

We can get a nice simplification if we assume our “batch size” BB is small relative to DD and FF. Then we get

如果我们假设我们的“批次大小” BB 相对于 DD 和 FF 较小,我们可以得到一个很好的简化. 那么我们得到

BDFBD+DF+BF≈BDFDF=B\begin{equation} \frac{BDF}{BD + DF + BF} \approx \frac{BDF}{DF} = B \end{equation} Intensity(matmul)>Intensity(TPU)  ⟹  B>1.97e148.20e11=240\begin{equation} \text{Intensity}(\text{matmul}) > \text{Intensity}(\text{TPU}) \implies B > \frac{1.97e14}{8.20e11} = 240 \end{equation}

This is a reasonable assumption for Transformer matmuls since we typically have a local (per-replica) token batch size B<1024B < 1024 (note, not sequences) but DD and F>8000F > 8000. Thus we generally become compute-bound when our per-replica11 batch size is greater than 240 tokens, a very simple rule!

对于 Transformer 矩阵乘法来说,这是一个合理的假设,因为我们通常有一个本地 (每个副本) 批次大小 B<1024B < 1024 个 token (不是序列), 但 DD 和 F>8000F > 8000. 因此,当我们的每个副本11 批次大小大于 240 个 token 时,我们通常会变得受计算限制,这是一个非常简单的规则!

This comes with a few notable caveats we’ll explore in the problems below, particularly with respect to quantization (e.g., if we quantize our activations but still do full-precision FLOPs), but it’s a good rule to remember. For GPUs, this number is slightly higher (closer to 300), but the same conclusion generally holds. When we decompose a big matmul into smaller matmuls, the tile sizes also matter.13 We’ll discuss the lower-level GPU and TPU details in the next section.

这带有一些我们将在下面的问题中探讨的值得注意的警告,特别是关于量化 (例如,如果我们量化我们的激活但仍然进行全精度 FLOPs), 但这是一个值得记住的好规则. 对于 GPU, 这个数字略高 (接近 300), 但同样的结论通常成立. 当我们将一个大的矩阵乘法分解成更小的矩阵乘法时,分块大小也很重要.13 我们将在下一节中讨论更底层的 GPU 和 TPU 细节.

Network communication rooflines网络通信屋顶线

All the rooflines we’ve discussed so far have been memory-bandwidth rooflines, all within a single chip. This shouldn’t be taken as a rule. In fact, most of the rooflines we’ll care about in this book involve communication between chips: usually matrix multiplications that involve matrices sharded across multiple TPUs.

到目前为止,我们讨论的所有屋顶线都是内存带宽屋顶线,全部在单个芯片内. 这不应被视为规则. 事实上,本书中我们关心的大多数屋顶线都涉及芯片之间的通信:通常是涉及跨多个 TPU 分片的矩阵的矩阵乘法.

To pick a somewhat contrived example, say we want to multiply two big matrices X∼bf16[B,D]X\sim \text{bf16}[B, D] and Y∼bf16[D,F]Y \sim \text{bf16}[D, F] which are split evenly across 2 TPUs/GPUs (along the DD dimension). To do this multiplication (as we’ll see in Section 3), we can multiply half of each matrix on each TPU (Z0 = X[:, :D // 2] @ Y[:D // 2, :] on TPU 0 and Z1 = X[:, D // 2:] @ Y[D // 2:, :] on TPU 1) and then copy the resulting “partial sums” to the other TPU and add them together. Say we can copy 4.5e10 bytes/s in each direction and perform 1.97e14 FLOPs/s on each chip. What are TmathT_\text{math} and TcommsT_\text{comms}?

举一个有点刻意的例子,假设我们想将两个大矩阵 X∼bf16[B,D]X\sim \text{bf16}[B, D] 和 Y∼bf16[D,F]Y \sim \text{bf16}[D, F] 相乘,它们均匀地分布在 2 个 TPU/GPU 上 (沿着 DD 维度). 为了进行这个乘法 (正如我们将在第 3 节中看到的), 我们可以在每个 TPU 上乘以每个矩阵的一半 (Z0 = X[:, :D // 2] @ Y[:D // 2, :] 在 TPU 0 上,Z1 = X[:, D // 2:] @ Y[D // 2:, :] 在 TPU 1 上), 然后将得到的“部分和”复制到另一个 TPU 并将它们相加. 假设我们可以在每个方向上以 4.5e10 字节/秒的速率复制数据,并在每个芯片上执行 1.97e14 FLOPs/s. TmathT_\text{math} 和 TcommsT_\text{comms} 是多少?

TmathT_\text{math} is clearly half of what it was before, since each TPU is doing half the work, i.e.14

TmathT_\text{math} 显然是之前的一半,因为每个 TPU 都在做一半的工作,即14

Tmath=2BDF2⋅Accelerator FLOPs/s=BDF1.97e14T_\text{math} = \frac{2BDF}{2 \cdot \text{Accelerator FLOPs/s}} = \frac{BDF}{1.97e14}

Now what about TcommsT_\text{comms}? This now refers to the communication time between chips! This is just the total bytes sent divided by the network bandwidth, i.e.

那么 TcommsT_\text{comms} 呢?这现在指的是芯片之间的通信时间!这只是发送的总字节数除以网络带宽,即

Tcomms=2BFNetwork Bandwidth=2BF4.5e10T_\text{comms} = \frac{2BF}{\text{Network Bandwidth}} = \frac{2BF}{4.5e10}

Therefore we become compute-bound (now with respect to the inter-chip network) when Intensity(matmul (2-chips))>Intensity(TPU w.r.t. inter-chip network)\text{Intensity}(\text{matmul (2-chips)}) > \text{Intensity}(\text{TPU w.r.t. inter-chip network}) or equivalently when BDF2BF=D2>1.97e144.5e10=4377\frac{BDF}{2BF} = \frac{D}{2} > \frac{1.97e14}{4.5e10} = 4377 or D>8755D > 8755. Note that, unlike before, the critical threshold now depends on DD and not BB! Try to think why that is. This is just one such example, but we highlight that this kind of roofline is critical to knowing when we can parallelize an operation across multiple TPUs.

因此,当 Intensity(matmul (2-chips))>Intensity(TPU w.r.t. inter-chip network)\text{Intensity}(\text{matmul (2-chips)}) > \text{Intensity}(\text{TPU w.r.t. inter-chip network}) 或等效地当 BDF2BF=D2>1.97e144.5e10=4377\frac{BDF}{2BF} = \frac{D}{2} > \frac{1.97e14}{4.5e10} = 4377 或 D>8755D > 8755 时,我们变得受计算限制 (现在是相对于芯片间网络). 请注意,与之前不同,临界阈值现在取决于 DD 而不是 BB! 试着想想为什么会这样. 这只是一个例子,但我们强调这种屋顶线对于了解何时可以在多个 TPU 上并行化操作至关重要.

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

Question 1 [int8 matmul]: Say we want to do the matmul X[B,D]⋅DY[D,F]→Z[B,F]X[B, D] \cdot_D Y[D, F] \rightarrow Z[B, F]15 in int8 precision (1 byte per parameter) instead of bfloat16 (2 bytes per parameter) since TPUs/GPUs can do matmuls faster in lower precision.

问题 1[int8 矩阵乘法]: 假设我们要计算矩阵乘法 X[B,D]⋅DY[D,F]→Z[B,F]X[B, D] \cdot_D Y[D, F] \rightarrow Z[B, F]15。TPU 和 GPU 能更快地执行低精度矩阵乘法,所以我们选用 int8 精度(每个参数 1 字节),而非 bfloat16 精度(每个参数 2 字节)。

  1. How many bytes need to be loaded from memory? How many need to be written back to memory?
  2. How many total OPs are performed?
  3. What is the arithmetic intensity?
  4. What is a roofline estimate for TmathT_\text{math} and TcommsT_\text{comms}? What are reasonable upper and lower bounds for the runtime of the whole operation?
  1. 需要从内存中加载多少字节?需要写回内存多少字节?
  2. 总共执行了多少次操作?
  3. 算术强度是多少?
  4. TmathT_\text{math} 和 TcommsT_\text{comms} 的屋顶线估计是什么?整个操作运行时间的合理上限和下限是什么?

Assume our HBM bandwidth is 8.2e11 bytes/s and our int8 peak OPs/s is 3.94e14 (about 2x bfloat16).

假设我们的 HBM 带宽为 8.2e11 字节/秒,我们的 int8 峰值 OPs/s 为 3.94e14 (大约是 bfloat16 的 2 倍).

Click here for the answer. 点击查看答案
  1. Because we’re storing our parameters in int8, we have 1 byte per parameter, so we have BD+DFBD + DF bytes loaded from HBM and BFBF written back.
  2. This is the same as in bfloat16, but in theory int8 OPs/s should be faster. So this is still 2BDF2BDF OPs.
  3. Arithmetic intensity is 2BDF/(BD+DF+BF)2BDF / (BD + DF + BF). If we make the same assumption as above about B≪DB \ll D and B≪FB \ll F, we get an arithmetic intensity of 2B2B, meaning our rule becomes B>HBM int8 arithmetic intensity/2B > \text{HBM int8 arithmetic intensity} / 2. Using the numbers given, this int8 intensity is 3.94e14 / 8.2e11 = 480, so the rule is B>480/2=240B > 480 / 2 = 240. Note that this is basically unchanged!
  4. Tmath=2BDF/3.94e14T_\text{math} = 2BDF / 3.94e14 and Tcomms=(BD+DF+BF)/8.2e11T_\text{comms} = (BD + DF + BF) / 8.2e11, so a reasonable lower bound is max⁡(Tmath,Tcomms)\max(T_\text{math}, T_\text{comms}) and an upper bound is Tmath+TcommsT_\text{math} + T_\text{comms}.
  1. 因为我们用 int8 存储参数,每个参数有 1 个字节,所以我们从 HBM 加载了 BD+DFBD + DF 字节,并写回了 BFBF 字节.
  2. 这与 bfloat16 中的情况相同,但理论上 int8 OPs/s 应该更快. 所以仍需执行 2BDF2BDF 次操作.
  3. 算术强度是 2BDF/(BD+DF+BF)2BDF / (BD + DF + BF). 如果我们做出与上面相同的假设,即 B≪DB \ll D 和 B≪FB \ll F, 我们得到的算术强度为 2B2B, 这意味着我们的规则变成了 B>HBM int8 arithmetic intensity/2B > \text{HBM int8 arithmetic intensity} / 2. 使用给定的数字,这个 int8 强度是 3.94e14 / 8.2e11 = 480, 所以规则是 B>480/2=240B > 480 / 2 = 240. 请注意,这基本上没有改变!
  4. Tmath=2BDF/3.94e14T_\text{math} = 2BDF / 3.94e14 和 Tcomms=(BD+DF+BF)/8.2e11T_\text{comms} = (BD + DF + BF) / 8.2e11, 所以一个合理的下限是 max⁡(Tmath,Tcomms)\max(T_\text{math}, T_\text{comms}), 一个上限是 Tmath+TcommsT_\text{math} + T_\text{comms}.

Question 2 [int8 + bf16 matmul]: In practice we often do different weight vs. activation quantization, so we might store our weights in very low precision but keep activations (and compute) in a higher precision. Say we want to quantize our weights in int8 but keep activations (and compute) in bfloat16. At what batch size do we become compute bound? Assume 1.97e14 bfloat16 FLOPs/s.

问题 2 [int8 + bf16 matmul]: 在实践中,我们经常进行不同的权重与激活量化,所以我们可能会用非常低的精度存储我们的权重,但保持激活 (和计算) 在更高的精度. 假设我们想用 int8 量化我们的权重,但保持激活 (和计算) 在 bfloat16. 在什么批次大小时我们会变得受计算限制?假设 1.97e14 bfloat16 FLOPs/s.

Hint: this means specifically bf16[B, D] * int8[D, F] -> bf16[B, F] where BB is the “batch size”.

提示: 计算 bf16[B, D] * int8[D, F] -> bf16[B, F],其中 BB 是批次大小。

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

Again assuming B is small, we have 2BDF bfloat16 FLOPs but only DF weights (instead of 2DF in bfloat16). This means we become compute-bound when 2B>2402B > 240 or B>120B > 120. This is a lot lower, meaning if we can do int8 weight quantization (which is fairly easy to do) but still do bfloat16 FLOPs, we get a meaningful win in efficiency (although int8 OPs would be better).

再次假设 B 很小,我们有 2BDF bfloat16 FLOPs, 但权重只占 DF 字节(使用 bfloat16 时则占 2DF 字节). 这意味着当 2B>2402B > 240 或 B>120B > 120 时,我们变得受计算限制. 这个值要低得多,这意味着如果我们能做 int8 权重量化 (这相当容易做到) 但仍然做 bfloat16 FLOPs, 我们在效率上会得到有意义的提升 (尽管 int8 OPs 会更好).

Question 3: Taking the setup from Question 2, make a roofline plot of peak FLOPs/s vs. BB for F=D=4096F = D = 4096 and F=D=1024F = D = 1024. Use the exact number of bytes loaded, not an approximation.

问题 3: 采用问题 2 的设置,为 F=D=4096F = D = 4096 和 F=D=1024F = D = 1024 绘制峰值 FLOPs/s 随 BB 变化的屋顶线图. 使用加载的确切字节数,而不是近似值.

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

Here is the plot in question:

这是所讨论的图:

roofline plot q3

Note that both models eventually achieve the peak hardware FLOPs/s, but the larger D/F achieve it sooner. D=F=1024 almost doubles the critical batch size. The code to generate this figure is here:

请注意,两种模型最终都达到了峰值硬件 FLOPs/s, 但较大的 D/F 更早达到. D=F=1024 几乎使临界批次大小翻了一番. 生成此图的代码在这里:

import matplotlib.pyplot as plt
import numpy as np

bs = np.arange(1, 512)

def roofline(B, D, F):
  total_flops = 2*B*D*F
  flops_time = total_flops / 1.97e14
  comms_time = (2*B*D + D*F + 2*B*F) / 8.2e11
  total_time = np.maximum(flops_time, comms_time)
  return total_flops / total_time

roofline_big = roofline(bs, 4096, 4096)
roofline_small = roofline(bs, 1024, 1024)

plt.figure(figsize=(8, 4))
plt.plot(bs, roofline_big, label='F=D=4096')
plt.plot(bs, roofline_small, label='F=D=1024')
plt.legend()
plt.xlabel('batch size')
plt.ylabel('peak bfloat16 FLOPs/s on TPU v5e')
plt.grid()

Question 4: What if we wanted to perform int8[B,D]⋅Dint8[B,D,F]→int8[B,F]\text{int8}[B, D] \cdot_D \text{int8}[B, D, F] \rightarrow \text{int8}[B, F] where we imagine having a different matrix for each batch element. What is the arithmetic intensity of this operation?

问题 4: 如果我们想执行 int8[B,D]⋅Dint8[B,D,F]→int8[B,F]\text{int8}[B, D] \cdot_D \text{int8}[B, D, F] \rightarrow \text{int8}[B, F], 其中我们想象每个批处理元素都有一个不同的矩阵. 这个操作的算术强度是多少?

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

Let’s start by looking at the total FLOPs and comms.

让我们从查看总 FLOPs 和通信开始.

  1. Total FLOPs: the FLOPs is basically the same, since we’re doing BB independent [D]×[D,F][D] \times [D, F] products, the same total work as a single [B,D]×[D,F][B, D] \times [D, F] matmul (this is discussed more in Section 4). So this is just 2BDF2BDF.
  2. Total comms: we have a lot more comms here: BD+BDF+BFBD + BDF + BF.
  3. Therefore, our arithmetic intensity is now actually 2BDF/(BD+BDF+BF)2BDF / (BD + BDF + BF). Since BDFBDF dominates the denominator, this is roughly 22. So instead of it depending on the batch size, this is essentially constant. This is bad because it means we’ll basically always be comms bound no matter what.
  1. 总 FLOPs: FLOPs 基本相同,因为 BB 次独立的 [D]×[D,F][D] \times [D, F] 乘法与一次 [B,D]×[D,F][B, D] \times [D, F] 矩阵乘法的运算量相同(参见第 4 节)。 所以这只是 2BDF2BDF.
  2. 总通信:我们这里有更多的通信:BD+BDF+BFBD + BDF + BF.
  3. 因此,我们的算术强度现在实际上是 2BDF/(BD+BDF+BF)2BDF / (BD + BDF + BF). 由于 BDFBDF 在分母中占主导地位,这大约是 22. 所以它不再依赖于批次大小,而是基本上是恒定的. 这很糟糕,因为这意味着我们基本上总是会受到通信限制,无论如何.

Question 5 [Memory Rooflines for GPUs]: Using the spec sheet provided by NVIDIA for the H100 SXM, calculate the batch size at which a bfloat16 matrix multiplication will become compute-bound. Note that the Tensor Core FLOPs numbers are twice the true value since they’re only achievable with structured sparsity.

问题 5 [GPU 的内存屋顶线]: 使用 NVIDIA 为 H100 SXM 提供的规格表, 计算 bfloat16 矩阵乘法进入计算受限区所需的批次大小. 请注意,Tensor Core FLOPs 的数字是真实值的两倍,因为它们只能通过结构化稀疏性实现.

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

From the spec sheet, we see that the reported bfloat16 FLOPs value is 1.979e15 FLOPs/s with an asterisk noting “with sparsity”. The true value is half this without sparsity, i.e. 9.89e14 FLOPs/s. The memory bandwidth is 3.35TB/s, or 3.35e12 bytes / second. Thus BcritB_\text{crit} is 9.89e14 / 3.35e12 = 295, rather similar to the TPU.

从规格表中,我们看到报告的 bfloat16 FLOPs 值为 1.979e15 FLOPs/s, 并带有一个星号,注明“带稀疏性”. 没有稀疏性时,真实数值是它的一半,即 9.89e14 FLOPs/s。 内存带宽为 3.35TB/s, 或 3.35e12 字节/秒. 因此 BcritB_\text{crit} 是 9.89e14 / 3.35e12 = 295, 与 TPU 相当相似.

That’s it for Part 1! For Part 2, looking at how real TPUs handle FLOPs and communication, click here.

第一部分到此结束!第二部分,看看真实的 TPU 如何处理 FLOPs 和通信,点击这里.

Footnotes

  1. bf16 is short for bfloat16, a 16-bit floating point format often used in ML.

    bf16 是 bfloat16 的缩写,这是一种常用于机器学习的 16 位浮点格式.

    ↩
  2. H100s and B200s can usually only achieve around 80-85% of the claimed peak FLOPs, while TPUs can get closer to 95% in normal use.

    H100s 和 B200s 通常只能达到声称峰值 FLOPs 的 80-85% 左右,而 TPU 在正常使用中可以接近 95%.

    ↩
  3. Note that these chips are priced differently, and this comparison does not normalize to cost.

    请注意,这些芯片的定价不同,此比较未按成本进行标准化.

    ↩
  4. NVIDIA also calls this “memory bandwidth.”

    NVIDIA 也称之为“内存带宽”.

    ↩
  5. We’ll use “communication-bound”, “comms-bound”, “memory-bound”, and “bandwidth-bound” interchangeably throughout this book.

    本书不区分“受通信限制”(communication-bound 或 comms-bound)、“受内存限制”(memory-bound)与“受带宽限制”(bandwidth-bound)。

    ↩
  6. The MXU is the matrix multiply unit on the TPU. We specify this here because the TPU has other accelerators like the VPU that are responsible for elementwise operations that have a different peak FLOPs/s.

    MXU 是 TPU 上的矩阵乘法单元. 这里特指 MXU,是因为 TPU 上还有 VPU 等其他计算单元。VPU 负责逐元素操作,其峰值 FLOPs/s 与 MXU 不同。

    ↩
  7. This is only true if the algorithm loads its weights from HBM and runs in the MXU. As we’ll discuss in the next section, we can sometimes store parameters in VMEM which has a much higher bandwidth. Many algorithms also run in the VPU, which has different performance characteristics.

    这仅在算法从 HBM 加载其权重并在 MXU 中运行时才成立. 正如我们将在下一节中讨论的,我们有时可以将参数存储在具有更高带宽的 VMEM 中. 许多算法也在 VPU 中运行,VPU 具有不同的性能特征.

    ↩
  8. The 240 number above is not the correct comparison here since, as you will see in the next section, a dot-product is performed on the VPU and not the MXU. The TPU v5p VPU can do roughly 7e12 FLOPs / second per core, so its critical intensity is around 3, which means we are still somewhat comms-bound here. Either way, the fact that our intensity is low and constant means it is difficult to be compute-bound on most hardware.

    上面 240 的数字在这里不是正确的比较,因为正如你将在下一节中看到的,点积是在 VPU 而不是 MXU 上执行的. TPU v5p 的 VPU 每个核心每秒约可执行 7e12 次 FLOPs, 因此其临界强度约为 3, 这意味着我们在这里仍然在某种程度上受通信限制. 无论哪种方式,我们的强度低且恒定的事实意味着在大多数硬件上很难受计算限制.

    ↩
  9. Technically we perform BF×(2D−1)BF \times (2D - 1) FLOPs but this is close enough. This comes from BDFBDF multiplications and BF∗(D−1)BF * (D-1) additions. Section 4 has more details.

    技术上,我们执行 BF×(2D−1)BF \times (2D - 1) FLOPs, 但这已经足够接近了. 这来自 BDFBDF 次乘法和 BF∗(D−1)BF * (D-1) 次加法. 第 4 节有更多细节.

    ↩
  10. Although the output of a matmul is technically float32 we usually cast down to bfloat16 before copying back to HBM.

    虽然 matmul 的输出技术上是 float32, 但我们通常在复制回 HBM 之前将其转换为 bfloat16.

    ↩
  11. We say per-replica because, if we do some kind of model sharding to increase the number of chips used in the matmul, we scale both our available compute and memory bandwidth by the same amount. Thus the critical batch size is true per independent copy of the model weights.

    我们说每个副本,是因为如果我们进行某种模型分片以增加用于矩阵乘法的芯片数量,我们会按相同的数量扩展我们可用的计算和内存带宽. 因此,临界批次大小对于模型权重的每个独立副本都是如此.

    ↩
  12. Note that this is not the batch size in the usual sense, where it means the batch size in sequences. It turns out most rooflines depend purely on the number of tokens, whether they belong to the same or different sequences. For instance if you have a batch size of 512 sequences of 4096 tokens on 2048 GPUs, you have a total batch size of 512 * 4096 = 2M tokens, and a local batch size of 1k tokens.

    请注意,这不是通常意义上的批次大小,通常意义上的批次大小是指序列的批次大小. 事实证明,大多数屋顶线纯粹取决于 token 的数量,无论它们属于相同还是不同的序列. 例如,如果你在 2048 个 GPU 上有一批 512 条序列,每条含 4096 个 token, 那么你的总批次大小为 512 * 4096 = 2M 个 token, 本地批次大小为 1k 个 token.

    ↩
  13. When we do a large matrix multiplication, we need to break it down into smaller tiles which fit into VMEM/SMEM/TMEM, the higher-bandwidth on-chip memory. This causes us to load chunks multiple times, so it’s no longer quite true that we only load O(N2)O(N^2) bytes. Consider an (m,k)⋅(k,n)(m, k) \cdot (k, n) matmul with tile sizes bmbm, bkbk, bnbn. Let tm=m/bmtm = m / bm, etc. Then the total FLOPs is 2⋅tm⋅tn⋅tk⋅bm⋅bn⋅bk2 \cdot tm \cdot tn \cdot tk \cdot bm \cdot bn \cdot bk and the total bytes are 2⋅tm⋅tn⋅(tk⋅(bm⋅bk+bk⋅bn)+bm⋅bn)2 \cdot tm \cdot tn \cdot (tk \cdot (bm \cdot bk + bk \cdot bn) + bm \cdot bn). Ignoring the last term, we have an intensity of bm⋅bn/(bm+bn)bm \cdot bn / (bm + bn), which is similar to the above.

    当我们进行大型矩阵乘法时,我们需要将其分解成更小的块,以适应 VMEM/SMEM/TMEM, 即更高带宽的片上内存. 这导致我们多次加载块,因此我们只加载 O(N2)O(N^2) 字节不再完全正确. 考虑一个 (m,k)⋅(k,n)(m, k) \cdot (k, n) 矩阵乘法,分块大小为 bmbm, bkbk, bnbn. 令 tm=m/bmtm = m / bm, 等等. 那么总 FLOPs 为 2⋅tm⋅tn⋅tk⋅bm⋅bn⋅bk2 \cdot tm \cdot tn \cdot tk \cdot bm \cdot bn \cdot bk, 总字节数为 2⋅tm⋅tn⋅(tk⋅(bm⋅bk+bk⋅bn)+bm⋅bn)2 \cdot tm \cdot tn \cdot (tk \cdot (bm \cdot bk + bk \cdot bn) + bm \cdot bn). 忽略最后一项,我们的强度为 bm⋅bn/(bm+bn)bm \cdot bn / (bm + bn), 这与上面的类似.

    ↩
  14. We’re ignoring the FLOPs required to add the two partial sums together (another BF addition), but this is basically negligible.

    我们忽略了将两个部分和相加所需的 FLOPs (另外 BF 次加法), 但这基本上可以忽略不计.

    ↩
  15. Here and throughout we’ll use the notation A⋅DBA \cdot_D B to indicate that the multiplication is performing a contraction over the D dimension. This is an abuse of einsum notation.

    本书用 A⋅DBA \cdot_D B 表示沿 D 维做张量缩并。这里借用了 einsum 记法。

    ↩

补充说明

*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}
}
原版章节与讨论