Chengshu@skadai · 2026.11.18
RSS
2,789 字 · 3,808 词 · 约 17 分钟

如何扩展你的模型(9):如何给 TPU 代码做性能剖析

中英对照第 9 篇:真实模型永远比理论复杂——JAX + XLA 栈、TensorBoard profiler、trace viewer,以及怎么定位真实的性能问题。左栏原文,右栏译文。

本篇属于系列 如何扩展你的模型(How To Scale Your Model) · 第 9 篇

原文 · English中文译文

原文:How To Scale Your Model(Google DeepMind,作者 Jacob Austin、Sholto Douglas、Roy Frostig、Anselm Levskaya、Charlie Chen、Sharad Vikram、Federico Lebron、Peter Choy、Vinay Ramasesh、Albert Webson、Reiner Pope)。

本站是中英对照排版:左栏是英文原文,右栏是对应的中文译文。不好直译的术语(roofline、strong scaling、ICI、MXU、KV cache、FSDP、TP 等)保留英文写法;原文配图全部保留。

本文是系列《如何扩展你的模型(How To Scale Your Model)》的第 9 篇,共 13 篇。系列目录。

原文以 MIT 许可证发布,版权归 Google LLC;本译文仅作学习交流之用,如有错漏以原文为准。

A Thousand-Foot View of the TPU Software Stack

俯瞰 TPU 软件栈

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 HLO (To get this HLO, you can run jax.jit(f).lower(*args, **kwargs).compile().as_text().):

通过调用 jax.jit,我们告诉 JAX 追踪这个函数,并生成一种更底层的 IR,叫做 StableHLO——一种平台无关的 ML 计算 IR,它又会被 XLA 编译器 lowering 成 HLO。编译器会跑很多趟(pass)来决定 fusion、layout 以及其他因素,最终得到你在 JAX profile 里能观察到的 HLO。这份 HLO 以 LLVM 风格的图视图,表示 JAX 代码里所有核心的线性代数运算(矩阵乘法、逐元素运算、卷积等)。例如,下面是上面这段程序压缩后的 HLO(要得到这份 HLO,可以运行 jax.jit(f).lower(*args, **kwargs).compile().as_text()):

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 编译器首先把它 lowering 成 LLO(low-level optimizer)IR。LLO 直接对 TPU 编程:调度显存之间的拷贝、把数组推上脉动阵列(systolic array)等等。LLO 代码里包含把 buffer 推进脉动阵列、把结果取出来的原语,以及调度 TPU 不同显存之间通信的 DMA。一旦 lowering 到 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 写自定义 kernel。要查看一个程序的 HLO 及其运行时统计,我们用 JAX profiler。

The JAX Profiler: A Multi-Purpose TPU Profiler

JAX 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 profiler,里面有很多有用的工具,帮你理解程序运行时 TPU 上发生了什么。你可以用 jax.profiler 模块在程序运行时追踪它,记录从每个子组件的耗时、每个程序的 HLO、显存占用等等。例如,下面这段代码会把一份 trace 导出到 /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:

下面是你能在 profiler 里做的事情的概览:

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

进入 TensorBoard 后,profiler 有几个关键的标签页帮你理解程序:

  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.

虽然分享 profile 稍微有点麻烦,但这里有一个 Perfetto 链接,至少包含一个简单 Transformer 的 Trace Viewer 部分。这个 Colab 让你能生成完整的 JAX/TensorBoard trace 并自己把玩。

Trace Viewer

Trace 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 大概是 profiler 里最有用的部分。 下面的例子展示了一个简单的 Transformer,各个部分都做了标注。名字来自代码里提供的标签。

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

Trace Viewer 展示每颗 TPU core 上所有动作的按时序排列的时间线。这里我们只看 TPU,因为通常所有 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 调用栈的近似 trace。
  2. 注意那些重复的块,我们可以从中隔离出单独一层。我们还能看出(通过看代码/理解 Transformer 如何工作)哪些部分是 attention、哪些是 MLP。
  3. 点击一个 XLA op,就能看到它来自代码的哪一行(对理解 trace 很有用),并看到通向 Graph viewer 的链接。

Tip: you can navigate the Trace Viewer using “video game” style controls, with A/D panning left and right, and W/S zooming in and out. These controls make navigating a lot easier.

提示: 你可以用「电子游戏」式的控制来浏览 Trace Viewer:A/D 左右平移,W/S 缩放。这些控制让浏览方便很多。

How to read an XLA op

如何阅读一个 XLA op

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 其实并不难读,而且对理解上面 trace 的某个部分对应什么非常有帮助。下面是一个叫 fusion.3 的示例 op。

%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.
  • Op 名字:fusion.3
    • dot 或 fusion op 是一组操作,包含至多 1 个矩阵乘法,还可能有一堆相关的逐元素 VPU 操作。
  • 形状:bf16[32,32,4096]
    • 这是该 op 的输出形状。可以看到 dtype 是 bf16(每元素 2 字节),[32,32,4096] 是形状。
  • 布局: {2,1,0:T(8,128)(2,1)}
    • {2,1,0:T(8,128)(2,1)} 告诉我们轴在显存中的顺序(列主序、行主序等)以及数组的 padding。下面细说。
  • 显存位置: 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
    • 这个 op 有一个输入,一个叫 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 数组,具有特定的 tiling {1,0:T(2,2)}。虽然 tiling 没那么重要,但简单说,tiling 告诉我们一个 N 维数组在显存中是如何顺序排布的。下面这张图展示了这个数组是如何排布的:

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 部分告诉我们数组各维在物理显存中的顺序,从最 minor 到最 major。你可以从右往左读这一部分,并在 f32[3,5] 里挑出对应的维度,来弄清数组的物理布局。在这个例子里,物理布局是 [3,5],与逻辑形状相同。 之后,T(2,2) 告诉我们数组按 (2, 2) 的块做 tiling,每个块内数组先按行(row-major)再按列,即 (0, 0) 后面是 (0, 1),然后是 (1, 0) 和 (1, 1)。由于有 T(2, 2) tiling,数组被 padding 到 [4, 6],显存占用扩大约 1.6 倍。对于上面那个大 bf16 数组 bf16[32,32,8192]{2,1,0:T(8,128)(2,1)S(1)},我们做的是 T(8,128)(2,1),它告诉我们数组有两级 tiling:外层 (8, 128) tiling,以及该单元内层 (2, 1) tiling(用于 bf16,这样我们的加载总是 4 字节的倍数)。例如,下面是 bf16[4,8]{1,0:T(2,4)(2,1)}(颜色是 (2,4) tile,红框是 (2,1) tile):

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. (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.)

Tiling 会影响一块块 tensor 加载进 VMEM 的效率,XLA 有时会引入拷贝,在一个程序内部「重新 tiling」或「重新布局」一个 tensor,有时开销还不小。(JAX 提供了一个实验性特性来绕过这个问题,它允许 XLA 为程序的输入计算它「偏好的」布局。当你用 jax.jit「即时」编译一个程序时,你通常传入「mock」输入,告诉 JAX 期望什么形状和 dtype。这些输入通常也带有可能并非最优的 tiling 信息。反之,你可以把输入布局指定为 AUTO,jax.jit 会返回 jitted 程序偏好的布局。然后你就可以显式地按那个布局加载 tensor,避免在程序内引入拷贝。)

Graph Viewer

Graph 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:

虽然上面一些 fusion 看起来可能很复杂,但 XLA Graph Viewer 让它们更容易解析。例如,下面是一个相当复杂的 fusion 的视图:

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 op 对应到你正在剖析的代码上,是非常有帮助的。把鼠标悬停在一个框上,你常常能看到定义该函数的代码行。

Looking at a real(ish) example profile

看一个真实(-ish)的示例 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 的示例 profile。这里有一个 Perfetto 链接,如果你赶时间,至少能看 Trace Viewer。我比平时多花了不少功夫,用 jax.named_scope 调用给 trace 做标注,好让你能辨认发生了什么。

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:

看看这个 profile,试着真正理解每一部分在做什么。我们稍微拆解一下,从 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 块。你会看到 up-projection Op 是一个 fusion(矩阵乘法),输入是 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]

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!

我们预期这要花多久? 首先,我们每个数据并行分片的 batch size 是 8 * 1024 = 8192,所以应该稳稳是计算受限的。这是在 8 颗 TPU v2 core 上,所以我们预期它花大约 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. (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.)

注意 Google Colab 不再发放 TPU v2-8 slice 了。要拿一个真实的 8 核 slice 跟着做,你可以用 Kaggle,它仍然免费提供,或者在 GCP 上开一个 8 核 slice。(如果你只想在假问题上玩分片,也可以用 import jax; jax.config.update("jax_num_cpu_devices", 8)(需要 jax >= 0.4.27 左右)在 CPU 上伪造 8 个设备,然后 print(jax.devices())。这只对玩具问题有效,不能反映真实性能。)

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。如果我们点它,会看到

%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(这里是 Graph Viewer);

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,batch 轴分了 4 片,所以每个分片是 2*8*1024*8192=128MB。所以这大约需要 1.1ms。实际花了多久? profile 里报的是 1.13ms。所以我们真的非常接近 roofline!

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

也来看看 attention! 下面是 attention 部分的 profile:

I’ve clicked on the Q projection op, which uses a matrix $$W_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 projection op,它用一个形状为 [dmodel = 8192, nheads = 32, dqkv = 256] 的矩阵 $$W_Q$$。我们沿 head 维度做 Megatron 分片。你也试着做同样的练习,算算这些应该花多久。

Memory Profile

显存剖析(Memory 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.5GB 空闲。所以我们还能往显存里塞很多东西。

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/profile,找出哪里可疑、这里发生了什么。你能确切说出正在进行什么计算、每个操作在做什么吗?涉及的每个矩阵的真实形状是什么、它们是如何分片的?先只看 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:

你能看到一个 reduce、两个大的 fusion 和一个 all-reduce。第一个大 fusion 是:

%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 那一维)。通过观察最后那个带 replica_groups={{0,16,32,48,64,80,96,112}, ...} 的 AllReduce,我们能看出我们在做 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 实现了一个简单的 mock Transformer。由于 Colab 不再提供 TPU v2-8 slice,你会想在 Kaggle 或一个 8 核 GCP slice 上跑它来跟着做。按 Colab 里的说明,用 GSPMD 分区给这个朴素 Transformer 做一个 benchmark。每一部分花多久?应该花多久?用的是什么分片?试着修好分片!提示:用 jax.lax.with_sharding_constraint 来约束行为。修好之后,你能拿到的最佳 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,优化后的 profile 是每层 67ms。做完之后,试着盯着 profile,看看能否纯粹从 profile 回答这些问题:

  • What sharding strategy is this?
  • What is the batch size, $$d_\text{model}$$, $$d_\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?
  • 这是什么分片策略?
  • batch size、$$d_\text{model}$$、$$d_\text{ff}$$ 分别是多少?
  • 花在 attention 与 MLP 块上的时间各占多少比例?
  • 在 roofline 下,每个 op 应该各占多少时间比例?

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,优化后的 profile 只好了大约 10ms(每层 80ms)。不过,玩玩它、看看你能不能做得更好,仍然值得。

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

第 9 部分就到这里。第 10 部分深入讲 JAX 并行,点这里。

讨论

用 GitHub 账号留言;评论保存在公开仓库chengshu-blog-discussions的 Discussions 里。也可通过 RSS 订阅后续文章。