Skip to content
quboliu
⚙

How to Profile TPU Programs如何对 TPU 程序做性能分析

第 9 章 · How To Scale Your Model (在 TPU 上部署 LLaMA 3-70B 推理服务 | 在 JAX 中编程 TPU)

So far this series has been entirely theoretical: back-of-the-envelope calculations based on hardware rooflines. That understanding gets you far but a lot of optimization comes down to practical details: how the XLA compiler works and how to use profiling tools like the JAX/TensorBoard Profiler to figure out what to do when it fails. We discuss this here.

到目前为止,本系列都在讨论理论,用硬件屋顶线做粗略估算。掌握理论能解决不少问题,但很多优化取决于实际细节。本章介绍 XLA 编译器如何工作,以及当编译器无法达到预期性能时,如何用 JAX 和 TensorBoard 的性能分析工具找出下一步怎么做。

A Thousand-Foot View of the TPU Software StackTPU 软件栈概览

Google exposes a bunch of APIs for programming TPUs, from high-level JAX code to low-level Pallas or HLO. Most programmers write JAX code exclusively, which lets you write abstract NumPy-style linear algebra programs that are compiled automatically to run efficiently on TPUs.

Google 为 TPU 编程提供了一系列 API,涵盖高层的 JAX 代码和低层的 Pallas 或 HLO。多数程序员只写 JAX 代码。你可以用 NumPy 风格编写抽象的线性代数程序,编译器会自动生成能在 TPU 上高效运行的代码。

Here’s a simple example, a JAX program that multiplies two matrices together:

这是一个简单的例子,一个将两个矩阵相乘的 JAX 程序:

import jax
import jax.numpy as jnp

def multiply(x, y):
  return jnp.einsum('bf,fd->db', x, y)

y = jax.jit(multiply)(jnp.ones((128, 256)), jnp.ones((256, 16), dtype=jnp.bfloat16))

By calling jax.jit, we tell JAX to trace this function and emit a lower-level IR called StableHLO, a platform-agnostic IR for ML computation, which is in turn lowered to HLO by the XLA compiler. The compiler runs many passes to determine fusions, layouts, and other factors that result in the HLO that is observable in a JAX profile. This HLO represents all the core linear algebra operations in the JAX code (matmuls, pointwise ops, convolutions, etc.) in an LLVM-style graph view. For instance, here is an abridged version of the above program as HLO1:

通过调用 jax.jit,我们告诉 JAX 跟踪这个函数并生成一种名为 StableHLO 的低层中间表示(IR),这是一个用于 ML 计算的平台无关 IR,然后由 XLA 编译器将其转换为 HLO。编译器执行多轮转换,决定算子融合、布局等细节,从而产生在 JAX 性能记录中可观察到的 HLO。这个 HLO 以 LLVM 风格的图视图表示 JAX 代码中的所有核心线性代数操作 (矩阵乘法,逐点操作,卷积等)。例如,这是上面程序的 HLO 删节版1:

ENTRY %main.5 (Arg_0.1: f32[128,256], Arg_1.2: bf16[256,16]) -> f32[16,128] {
  %Arg_1.2 = bf16[256,16]{1,0} parameter(1), metadata={op_name="y"}
  %convert.3 = f32[256,16]{1,0} convert(bf16[256,16]{1,0} %Arg_1.2),
  %Arg_0.1 = f32[128,256]{1,0} parameter(0), metadata={op_name="x"}
  ROOT %dot.4 = f32[16,128]{1,0} dot(f32[256,16]{1,0} %convert.3, f32[128,256]{1,0} %Arg_0.1), lhs_contracting_dims={0}, rhs_contracting_dims={1},
}

We’ll explain the syntax of HLO in just a second, but for now just note that it actually matches the JAX code above fairly well. For instance,

我们稍后会解释 HLO 的语法,但现在只需注意它实际上与上面的 JAX 代码相当匹配。例如,

ROOT %dot.4 = f32[16,128]{1,0} dot(f32[256,16]{1,0} %convert.3, f32[128,256]{1,0} %Arg_0.1), lhs_contracting_dims={0}, rhs_contracting_dims={1}

is the actual matmul above that multiplies two f32 matrices along the 0 and 1 dimensions, respectively.

是上面实际的矩阵乘法,它分别沿 0 和 1 维度乘以两个 f32 矩阵。

To transform this HLO to code that can be executed on the TPU, the XLA compiler first lowers it to LLO (low-level optimizer) IR. LLO programs the TPU directly, scheduling copies between memories, pushing arrays onto the systolic array, etc. LLO code contains primitives that push buffers into the systolic array, pull results off, and schedule DMAs that communicate between different pieces of TPU memory. Once this has been lowered to LLO, it is then compiled to machine code that is loaded into the TPU IMEM and executed.

为了将这个 HLO 转换为可以在 TPU 上执行的代码,XLA 编译器首先将其转换为 LLO (低层优化器) IR。LLO 直接对 TPU 进行编程,调度内存之间的复制,将数组推送到脉动阵列等。LLO 代码包含将缓冲区推送到脉动阵列,取回结果以及调度在不同 TPU 内存片段之间进行通信的 DMA 的原语。转换成 LLO 后,它就会被编译成加载到 TPU IMEM 中并执行的机器代码。

When a program is running slower than we’d like, we primarily work with the JAX level to improve performance. Doing so, however, often requires us to understand some of the semantics of HLO and how the code is actually running on the TPU. When something goes wrong at a lower level, we pull yet another escape hatch and write custom kernels in Pallas. To view the HLO of a program and its runtime statistics, we use the JAX profiler.

当一个程序运行得比我们希望的慢时,我们主要在 JAX 级别上工作以提高性能。然而,这样做通常需要我们理解 HLO 的一些语义以及代码实际上是如何在 TPU 上运行的。当在较低级别出现问题时,我们还可以用 Pallas 编写自定义内核。为了查看程序的 HLO 及其运行时统计信息,我们使用 JAX 分析器。

The JAX Profiler: A Multi-Purpose TPU ProfilerJAX Profiler:多用途 TPU 性能分析器

JAX provides a multi-purpose TPU profiler with a bunch of useful tools for understanding what’s happening on the TPU when a program is run. You can use the jax.profiler module to trace a program as it’s running and record everything from the duration of each subcomponent, the HLO of each program, memory usage, and more. For example, this code will dump a trace to a file in /tmp/tensorboard that can be viewed in TensorBoard (here is a step-by-step guide).

JAX 提供了一个多功能的 TPU 分析器,其中包含一系列有用的工具,用于了解程序运行时 TPU 上发生的情况。你可以使用 jax.profiler 模块来跟踪正在运行的程序,并记录从每个子组件的持续时间,每个程序的 HLO,内存使用情况等等。例如,这段代码会将一个跟踪转储到 /tmp/tensorboard 中的一个文件中,该文件可以在 TensorBoard 中查看 (这里 是一个分步指南)。

import jax
with jax.profiler.trace("/tmp/tensorboard"):
  key = jax.random.key(0)
  x = jax.random.normal(key, (1024, 1024))
  y = x @ x
  y.block_until_ready()

# Now you can load TensorBoard in a Google Colab with
#
# !pip install -U xprof
# !pip install -U protobuf
# %load_ext tensorboard
# %tensorboard --logdir=/tmp/tensorboard
#
# or externally with
#
# > tensorboard --logdir=/tmp/tensorboard
#

Here’s an overview of what you can do in the profiler:

这是你在分析器中可以做的事情的概述:

xprof overview

Once in TensorBoard, the profiler has a few key tabs that help you understand your program:

进入 TensorBoard 后,性能分析器有几个主要选项卡,可以帮助你了解程序的运行情况:

  1. Trace Viewer shows a detailed timeline of what’s actually happening on the TPU.
  2. Graph Viewer shows the HLO graph, letting you see what parts of the program feed into each other and how things are sharded.
  3. Memory Profile and Memory Viewer: these show how much memory your program is using.
  1. Trace Viewer 逐项显示 TPU 所执行操作的时间线。
  2. Graph Viewer 显示了 HLO 图,让你看到程序的各部分之间的数据依赖关系及分片方式。
  3. Memory Profile 和 Memory Viewer 显示程序的内存用量。

While it’s slightly difficult to share profiles, here is a Perfetto link that contains at least the Trace Viewer component for a simple Transformer. This Colab lets you generate the full JAX/TensorBoard trace and play around with it.

虽然共享性能记录有点困难,但这里是一个 Perfetto 链接,至少包含一个简单 Transformer 的 Trace Viewer 组件。这个 Colab 让你生成并查看完整的 JAX/TensorBoard 性能记录。

Trace ViewerTrace Viewer

The Trace Viewer is probably the most useful part of the profiler. The example below shows a simple Transformer with pieces annotated. Names come from labels provided in the code.

Trace Viewer 可能是分析器中最有用的部分. 下面的例子显示了一个简单的 Transformer,其中标注了各个部分。名称来自代码中提供的标签。

trace viewer

The Trace Viewer shows a chronological timeline of all the actions on each TPU core. We’re only looking at TPU:0 here, since typically all TPUs execute the same instructions. A few key notes:

Trace Viewer 按时间顺序显示每个 TPU 核心执行的所有操作。我们在这里只看 TPU:0,因为通常所有 TPU 都执行相同的指令。一些关键说明:

  1. The top row (XLA Ops) shows the actual TPU operations (the names are HLO names). Everything else is an approximate trace based on jax.named_scope, jax.named_call, and the Python stack trace.
  2. Noting the repeated blocks, we can isolate a single layer here. We can also see (from looking at the code/understanding how a Transformer works) what parts are attention and what parts are MLPs.
  3. By clicking on an XLA op, we can view where in the code it comes from (useful for understanding the trace) and see links to the Graph viewer.
  1. 顶行 (XLA Ops) 显示了实际的 TPU 操作 (名称是 HLO 名称)。其他所有内容都是基于 jax.named_scope,jax.named_call 和 Python 堆栈跟踪的近似跟踪。
  2. 注意到重复的块,我们可以在这里辨认出其中一层。我们还可以 (通过查看代码/了解 Transformer 的工作原理) 看到哪些部分是注意力,哪些部分是 MLP。
  3. 通过单击 XLA 操作,我们可以查看它在代码中的来源 (有助于理解跟踪) 并查看指向 Graph viewer 的链接。

How to read an XLA op如何阅读 XLA 操作

HLO isn’t actually very hard to read, and it’s very helpful for understanding what a given part of the trace above corresponds to. Here’s an example op called fusion.3.

HLO 实际上并不难读,它对于理解上面跟踪的给定部分对应的内容非常有帮助。这是一个名为 fusion.3 的示例算子。

%fusion.3 = bf16[32,32,4096]{2,1,0:T(8,128)(2,1)S(1)} fusion(bf16[32,32,8192]{2,1,0:T(8,128)(2,1)S(1)} %fusion.32), kind=kCustom, calls=%all-reduce-scatter.3

Let’s break this down into its pieces.

让我们把它分解成几个部分。

  • Op Name: fusion.3
    • A dot or fusion op is a set of operations containing at most 1 matrix multiplication and possibly a bunch of related pointwise VPU-ops.
  • Shape: bf16[32,32,4096]
    • This is the output shape of the op. We can see the dtype is bf16 (2 bytes per element) and [32,32,4096] is the shape.
  • Layout: {2,1,0:T(8,128)(2,1)}
    • {2,1,0:T(8,128)(2,1)} tells us the order of the axes in memory (column major, row major, etc.) and the array padding. More below.
  • Memory location: S(1)
    • S(1) tells us this array lives in VMEM. S(0) (sometimes omitted) is HBM. S(2) and S(3) are other memory spaces.
  • Arguments: bf16[32,32,8192]{2,1,0:T(8,128)(2,1)S(1)} %fusion.32
    • This op has one input, a bf16 array called fusion.32 with a particular shape. This tells us what function feeds into this one.
  • 操作名称:fusion.3
    • 点或融合操作是一组操作,最多包含 1 个矩阵乘法和可能的一堆相关的逐点 VPU 操作。
  • 形状:bf16[32,32,4096]
    • 这是操作的输出形状。我们可以看到 dtype 是 bf16 (每个元素 2 字节),[32,32,4096] 是形状。
  • 布局: {2,1,0:T(8,128)(2,1)}
    • {2,1,0:T(8,128)(2,1)} 告诉我们内存中轴的顺序 (列主序,行主序等) 和数组填充。更多内容见下文。
  • 内存位置: S(1)
    • S(1) 告诉我们这个数组存在于 VMEM 中。S(0) (有时省略) 是 HBM。S(2) 和 S(3) 是其他内存空间。
  • 参数:bf16[32,32,8192]{2,1,0:T(8,128)(2,1)S(1)} %fusion.32
    • 这个操作有一个输入,一个名为 fusion.32 的 bf16 数组,具有特定的形状。这样就能知道这个算子的输入来自哪个函数。

Let’s try to understand this notation a little more. Let’s take this as a simple example:

让我们试着更多地理解这个符号。让我们以这个简单的例子为例:

f32[3,5]{1,0:T(2,2)}

which again tells us that this Op returns a float32 array of shape [3, 5] with a particular tiling {1,0:T(2,2)}. While tilings don’t matter too much, briefly, tilings tell us how an N-dimensional array is laid out sequentially in memory. Here’s a diagram showing how this array is laid out:

这再次告诉我们,这个 Op 返回一个形状为 [3, 5] 的 float32 数组,具有特定的分块 {1,0:T(2,2)}。虽然分块通常不必深究,但简而言之,分块告诉我们一个 N 维数组在内存中是如何顺序布局的。这是一个显示这个数组如何布局的图:

tiling

Within {1,0:T(2,2)}, the 1,0 part tells us the ordering of array dimensions in physical memory, from most minor to most major. You can read this part from right to left and pick out the corresponding dimensions in f32[3,5] to figure out the physical layout of the array. In this example, the physical layout is [3,5], identical to the logical shape. After that, T(2,2) tells us that the array is tiled in chunks of (2, 2) where within each chunk, the array has rows first (row-major), then columns, i.e. (0, 0) is followed by (0, 1), then (1, 0) and (1, 1). Because of the T(2, 2) tiling, the array is padded to [4, 6], expanding its memory usage by about 1.6x. For the big bf16 array given above, bf16[32,32,8192]{2,1,0:T(8,128)(2,1)S(1)}, we do T(8,128)(2,1) which tells us the array has two levels of tiling, an outer (8, 128) tiling and an inner (2, 1) tiling within that unit (used for bf16 so our loads are always multiples of 4 bytes). For example, here’s bf16[4,8]{1,0:T(2,4)(2,1)} (colors are (2,4) tiles, red boxes are (2,1) tiles):

在 {1,0:T(2,2)} 中,1,0 部分告诉我们物理内存中数组维度的顺序,从最次要到最主要。你可以从右到左阅读这部分,并在 f32[3,5] 中找出相应的维度,以确定数组的物理布局。在这个例子中,物理布局是 [3,5],与逻辑形状相同。 之后,T(2,2) 告诉我们数组以 (2, 2) 的块进行分块,其中在每个块内,数组首先是行 (行主序),然后是列,即 (0, 0) 后面是 (0, 1),然后是 (1, 0) 和 (1,1)。由于 T(2, 2) 分块,数组被填充到 [4, 6],其内存使用量增加了约 1.6 倍。对于上面给出的大的 bf16 数组,bf16[32,32,8192]{2,1,0:T(8,128)(2,1)S(1)},我们做 T(8,128)(2,1),这告诉我们数组有两级分块,一个外部 (8, 128) 分块和一个内部 (2, 1) 分块 (用于 bf16,以便我们的加载总是 4 字节的倍数)。例如,这是 bf16[4,8]{1,0,T(2,4)(2,1)} (颜色是 (2,4) 块,红色框是 (2,1) 块):

tiling2

Tiling can affect how efficiently chunks of tensors can be loaded into VMEM and XLA will sometimes introduce copies that “retile” or “re-layout” a tensor inside a program, sometimes at non-trivial overhead.2

分块会影响张量块加载到 VMEM 的效率,XLA 有时会在程序中引入“重新分块”或“重新布局”张量的复制,有时会产生不小的开销.2

Graph ViewerGraph Viewer

While some of the fusions above can seem complicated, the XLA Graph Viewer makes them easier to parse. For example here’s the view of a fairly complicated fusion:

虽然上面的一些融合看起来很复杂,但 XLA Graph Viewer 使它们更容易解析。例如,这是一个相当复杂的融合的视图:

graph viewer

It’s really helpful to stare at a bunch of HLO graphs and try to map HLO ops onto the code you’re profiling. By hovering over a box you’ll often see the line of code where the function was defined.

盯着一堆 HLO 图,试着将 HLO 操作映射到你正在分析的代码上,这真的很有帮助。将鼠标悬停在一个框上,你通常会看到定义该函数的代码行。

Looking at a real(ish) example profile看一个接近真实的性能分析示例

This Colab has an example profile for a fake Transformer. Here’s a Perfetto link to at least see the Trace Viewer if you’re in a hurry. I’ve gone to more effort than usual to annotate the trace with jax.named_scope calls so you can identify what’s going on.

这个 Colab 有一个模拟 Transformer 的性能记录。这里 是一个 Perfetto 链接,至少可以让你在匆忙中看到 Trace Viewer。我比平时更努力地用 jax.named_scope 调用来注释跟踪,以便你可以识别正在发生的事情。

transformer xprof

Take a look at the profile and try to really understand what each part is doing. Let’s break it down a bit, starting with the FFW block:

看一下性能记录,试着真正理解每个部分在做什么。让我们把它分解一下,从 FFW 块开始:

transformer ffw

Here we’ve zoomed into the FFW block. You’ll see the up-projection Op is a fusion (matmul) with inputs bf16[8, 1024, 8192] and bf16[8192, 16384] and output bf16[8, 1024, 16384]. I know (because I wrote this code) that this is a local view of a 4-way DP, 2-way MP sharded matmul, so we’re actually doing

在这里,我们放大了 FFW 块。你会看到上投影 Op 是一个融合 (矩阵乘法),输入为 bf16[8, 1024, 8192] 和 bf16[8192, 16384],输出为 bf16[8, 1024, 16384]。我知道 (因为我写了这段代码) 这是一个 4 路 DP,2 路 MP 分片矩阵乘法的本地视图,所以我们实际上在做

X: bf16[32, 1024, 8192] * Win: bf16[8192, 32768] -> Tmp: bf16[32, 1024, 32768]

X: bf16[32, 1024, 8192] * Win:bf16[8192, 32768] -> Tmp:bf16[32, 1024, 32768]

How long do we expect this to take? First of all, our batch size per data parallel shard is 8 * 1024 = 8192, so we should be solidly compute-bound. This is on 8 TPU v2 cores, so we expect it to take about 2 * 32 * 1024 * 8192 * 32768 / (23e12 * 8) = 95.6ms which is pretty much exactly how long it takes (96ms). That’s great! That means we’re getting fantastic FLOPs utilization!

我们期望这需要多长时间? 首先,我们每个数据并行分片的批次大小是 8 * 1024 = 8192,所以我们应该完全受计算限制。这里使用 8 个 TPU v2 核心,所以我们期望它大约需要 2 * 32 * 1024 * 8192 * 32768 / (23e12 * 8) = 95.6ms,这几乎与实际花费的时间完全相同 (96ms)。太棒了!这意味着我们获得了极好的 FLOPs 利用率!

Note that Google Colab no longer hands out TPU v2-8 slices. To get a real 8-core slice to follow along, you can use Kaggle, which still provides them for free, or provision an 8-core slice on GCP.3

现在,Google Colab 已不再提供 TPU v2-8 切片。如果你想用真实的 8 核切片跟着做,可以使用仍免费提供这类切片的 Kaggle,也可以在 GCP 上配置一个 8 核切片。3

What about communication? You’ll notice the little fusion hidden at the end of the second matmul. If we click on it, you’ll see

通信呢? 你会注意到第二个矩阵乘法末尾隐藏的小融合。如果我们点击它,你会看到

%fusion.1 = bf16[8,1024,4096]{2,1,0:T(8,128)(2,1)} fusion(bf16[8,1024,8192]{2,1,0:T(8,128)(2,1)} %fusion.31), kind=kCustom, calls=%all-reduce-scatter.1

which is basically a little ReduceScatter (here’s the Graph Viewer);

这基本上是一个小的 ReduceScatter (这是 GraphViewer);

reduce scatter xprof

How long do we expect this to take? Well, we’re doing a ReduceScatter on a TPU v2 4x2, which should require only one hop on 1.2e11 bidirectional bandwidth. The array has size 2*32*1024*8192 with the batch axis sharded 4 ways, so each shard is 2*8*1024*8192=128MB. So this should take roughly 1.1ms. How long does it actually take? 1.13ms reported in the profile. So we’re really close to the roofline!

我们期望这需要多长时间?嗯,我们正在一个 TPU v2 4x2 上进行 ReduceScatter,这应该只需要在双向带宽为 1.2e11 的互连上跳转一跳。数组的大小是 2*32*1024*8192,批处理轴分片 4 路,所以每个分片是 2*8*1024*8192=128MB。所以这大约需要 1.1ms。实际上需要多长时间? 性能记录中报告为 1.13ms。所以我们非常接近屋顶线!

Let’s look at attention too! Here’s a profile of the attention component:

让我们也看看注意力! 这是注意力组件的性能记录:

attn xprof

I’ve clicked on the Q projection op, which uses a matrix WQW_Q of shape [dmodel = 8192, nheads = 32, dqkv = 256]. We’re Megatron sharding along the head dimension. Try to do the same exercise of calculating how long these should take.

我点击了 Q 投影操作,它使用一个形状为 [dmodel = 8192, nheads = 32, dqkv = 256] 的矩阵 WQW_Q。我们正在沿头维度进行 Megatron 分片。试着做同样的练习,计算这些应该需要多长时间。

Memory ProfileMemory Profile

The Memory Profile makes it easy to see the program memory as a function of time. This is helpful for debugging OOMs. You can see here about 7.5GB allocated to model parameters and about 8.5GB free. So we can fit a lot more into memory.

Memory Profile 使查看程序内存随时间的变化变得容易。这对于调试 OOM 很有帮助。你可以在这里看到大约 7.5GB 分配给了模型参数,大约 8.5 GB 空闲。所以我们可以容纳更多的东西到内存中。

memory viewer

Worked Problems例题

Question 1: take a look at this Colab/profile and figure out what looks suspicious and what’s going on here. Can you tell me exactly what computations are happening and what each operation is doing? What are the true shapes of each matrix involved and how are they sharded? Try looking at the profile first without reading the code.

问题 1:看一下这个 Colab/性能记录,找出看起来可疑的地方以及发生了什么。你能准确地告诉我正在进行什么计算以及每个操作在做什么吗?所涉及的每个矩阵的真实形状是什么,它们是如何分片的?先试着只看性能记录,暂时别看代码。

all reduce profile
Click here for the answer. 点击这里查看答案。

This is two matrix multiplications, i.e. specifically this:

这是两个矩阵乘法,即具体如下:

def matmul(w1, w2, x):
  return jnp.einsum('wf,bf->bw', w2, jnp.einsum('fw,bw->bf', w1, x))

You can see a reduce, two big fusions, and an all-reduce. The first big fusion is:

你可以看到一次归约、两个较大的融合算子和一次全归约。第一个大的融合是:

%fusion.1 = bf16[4096]{0:T(1024)(128)(2,1)} fusion(bf16[4096,8192]{1,0:T(8,128)(2,1)} %param.1, bf16[8192]{0:T(1024)(128)(2,1)} %reduce.6), kind=kLoop, calls=%fused_computation.1

which tells us the per-shard shape is bf16[8192] * bf16[4096, 8192] -> bf16[4096] (over the 8192 dimension). By observing the final AllReduce with replica_groups={{0,16,32,48,64,80,96,112}, ...}, we can tell we’re doing 8-way model parallelism, so the true shapes are bf16[8, 8192] * bf16[32768, 8192] -> bf16[8, 32768].

这告诉我们每个分片的形状是 bf16[8192] * bf16[4096, 8192] -> bf16[4096] (在 8192 维度上)。通过观察最终的 AllReduce,replica_groups={{0,16,32,48,64,80,96,112}, ...},我们可以看出我们正在进行 8 路模型并行,所以真实的形状是 bf16[8, 8192] * bf16[32768, 8192] -> bf16[8, 32768]。

Question 2: The Transformer Colab from earlier implements a simple mock Transformer. Since Colab no longer provides TPU v2-8 slices, you’ll want to run this on Kaggle or an 8-core GCP slice to follow along. Follow the instructions in the Colab and get a benchmark of the naive Transformer with GSPMD partitioning. How long does each part take? How long should it take? What sharding is being used? Try fixing the sharding! Hint: use jax.lax.with_sharding_constraint to constrain the behavior. With this fix, what’s the best MFU you can get?

问题 2: 之前的 Transformer Colab 实现了一个简单的模拟 Transformer。Colab 已不再提供 TPU v2-8 切片,你可以用 Kaggle 或 GCP 上的 8 核切片运行它。按照 Colab 中的说明,对使用 GSPMD 分区的朴素 Transformer 进行基准测试。每个部分需要多长时间?应该需要多长时间?正在使用什么分片。尝试修复分片!提示:用 jax.lax.with_sharding_constraint 约束分片方式。修复后,模型 FLOPs 利用率(MFU)最高能达到多少?

For reference, the initial version gets roughly 184ms / layer and the optimized profile gets 67ms / layer. Once you’ve done this, try staring at the profile and see if you can answer these questions purely from the profile:

作为参考,初始版本每层大约需要 184ms,优化后的性能记录每层需要 67ms。完成此操作后,尝试盯着性能记录,看看是否可以仅从性能记录中回答这些问题:

  • What sharding strategy is this?
  • What is the batch size, dmodeld_\text{model}, dffd_\text{ff}?
  • What fraction of time is spent on attention vs. the MLP block?
  • What fraction of time should be spent on each op at the roofline?
  • 这是什么分片策略?
  • 批次大小,dmodeld_\text{model},dffd_\text{ff} 是多少?
  • 注意力与 MLP 块花费的时间比例是多少?
  • 在屋顶线模型下,每个操作应该花费多少时间?

Note: since this problem was written, the XLA compiler has gotten better. The initial version is now at roughly 90ms / layer and the optimized profile is only about 10ms / layer better (80ms / layer). Still, it’s worth playing with and seeing if you can do better.

注意: 自从写下这个问题以来,XLA 编译器已经变得更好了。初始版本现在每层大约需要 90ms,优化后的性能记录只比它好大约 10ms/层 (80ms/层)。尽管如此,还是值得玩一玩,看看你是否能做得更好。

That’s all for Part 9. For Part 10, with a deep dive into JAX parallelism, click here.

第 9 部分到此结束。第 10 部分,深入探讨 JAX 并行,点击 这里.

Footnotes

  1. To get this HLO, you can run jax.jit(f).lower(*args, **kwargs).compile().as_text().

    要获取此 HLO,你可以运行 jax.jit(f).lower(*args, **kwargs).compile().as_text().

    ↩
  2. JAX provides an experimental feature to work around this issue, by allowing XLA to compute its “preferred” layout for inputs to a program. When you “just-in-time” compile a program with jax.jit, you typically pass in “mock” inputs that tell JAX what shape and dtype to expect. These typically also carry tiling information that may not be optimal. Instead, you can specify the input layouts as AUTO, and jax.jit will return a layout that the jitted program prefers. You can then explicitly load the tensor in that layout to avoid inducing copies within the program.

    JAX 提供了一项实验性功能来解决这个问题,即允许 XLA 计算其对程序输入的“首选”布局。当你用 jax.jit“即时”编译一个程序时,你通常会传入“模拟”输入,告诉 JAX 期望的形状和 dtype。这些通常也带有 tiling 信息,可能不是最优的。相反,你可以将输入布局指定为 AUTO,jax.jit 将返回 jitted 程序首选的布局。然后你可以显式地以该布局加载张量,以避免在程序中引起复制.

    ↩
  3. If you only want to play around with sharding on fake problems, you can also fake 8 devices on CPU with import jax; jax.config.update("jax_num_cpu_devices", 8) (requires jax >= 0.4.27ish) and then print(jax.devices()). This only works for toy problems and won’t reflect real performance.

    如果只是想用简单示例试验分片,也可以在 CPU 上模拟 8 个设备:运行 import jax; jax.config.update("jax_num_cpu_devices", 8)(大约需要 JAX ≥ 0.4.27),然后运行 print(jax.devices())。它只适合用来试验简单示例,无法反映实际性能。

    ↩

补充说明

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