如何扩展你的模型(10):用 JAX 给 TPU 编程
中英对照第 10 篇:jax.jit / pmap / shard_map、GSPMD、pallas kernel 等并行 API 到底怎么用,配可运行的例子。左栏原文,右栏译文。
本篇属于系列 如何扩展你的模型(How To Scale Your Model) · 第 10 篇
原文: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)》的第 10 篇,共 13 篇。系列目录。
原文以 MIT 许可证发布,版权归 Google LLC;本译文仅作学习交流之用,如有错漏以原文为准。
How Does Parallelism Work in JAX?
JAX 里的并行是怎么工作的?
JAX supports three schools of thought for multi-device programming:
多设备编程在 JAX 里有三大流派:
- Compiler, take the wheel! Let the XLA compiler automatically partition arrays and decide what communication to add to facilitate a given program. This lets you take a program that runs on a single device and automatically run it on thousands without changing anything.
- JAX, take the wheel! Automatic parallelism is great, but sometimes the compiler does something crazy. Explicit sharding lets you write single-device code like usual, but have JAX handle sharding propagation (not the compiler). This means JAX can ask you for clarification when it’s unclear what you want.
- Just let me write what I mean, dammit! While compilers are nice, they sometimes do the wrong thing and add communication you don’t intend. Sometimes we want to be explicit about exactly what communication we intend to run.
- 编译器,你来开车! 让 XLA 编译器自动切分数组,并决定要加入哪些通信来支撑给定的程序。这样你能把一个单设备上跑的程序,原封不动地自动跑在几千台设备上。
- JAX,你来开车! 自动并行很棒,但有时编译器会做出离谱的事。显式分片让你像往常一样写单设备代码,但由 JAX(而不是编译器)来处理分片传播。这意味着当不清楚你想要什么时,JAX 可以向你请求澄清。
- 就让我怎么写就怎么来,行不行! 编译器虽好,但有时会做错事、加入你并不想要的通信。有时我们想明确指定究竟要跑什么通信。
| Mode | View? | Explicit sharding? | Explicit Collectives? |
|---|---|---|---|
| Auto | Global | ❌ | ❌ |
| Explicit | Global | ✅ | ❌ |
| Manual | Per-device | ✅ | ✅ |
| 模式 | 视图? | 显式分片? | 显式集合通信? |
|---|---|---|---|
| Auto | 全局 | ❌ | ❌ |
| Explicit | 全局 | ✅ | ❌ |
| Manual | 每设备 | ✅ | ✅ |
Correspondingly, JAX provides APIs for each of these modes:
相应地,JAX 为每种模式都提供了 API:
jax.jit(withAutomesh axes) lets you take any existing JAX function and call it with sharded inputs. JAX then uses XLA’s Shardy compiler which automatically parallelizes the program. XLA will add communication for you (AllGathers, ReduceScatters, AllReduces, etc.) when needed to facilitate existing operations. While it isn’t perfect, it usually does a decent job at automatically scaling your program to any number of chips without code changes.jax.jitwithExplicitmesh axes looks similar to (1), but lets JAX handle the sharding propagation instead of XLA. That means the sharding of an array is actually part of the JAX type system, and JAX can error out when it detects ambiguous communication and lets the user resolve it.jax.shard_mapis the more manual counterpart. You get a device-local view of the program and have to write any communication you want explicitly. Have a sharded array and want the whole thing on each device? Add ajax.lax.all_gather. Want to sum an array across your devices? Add ajax.lax.psum(an AllReduce). Programming is harder but far less likely to do something you don’t want.
jax.jit(搭配Automesh 轴)让你拿任意已有的 JAX 函数,用分片输入去调用它。JAX 随后使用 XLA 的 Shardy 编译器来自动并行化这个程序。当支撑已有操作需要时,XLA 会替你加入通信(AllGather、ReduceScatter、AllReduce 等)。虽然它并不完美,但通常能很好地自动把程序扩展到任意数量的芯片上,而无需改代码。- 搭配
Explicitmesh 轴的jax.jit看起来和 (1) 类似,但由 JAX 而不是 XLA 来处理分片传播。也就是说,数组的分片实际上成了 JAX 类型系统的一部分,当 JAX 检测到有歧义的通信时它可以报错,让用户来解决。 jax.shard_map是更手动的那一个。你拿到的是程序在设备本地的视图,想做什么通信都得自己显式写。有一个分片数组、想让每台设备都拿到完整数组?加一个jax.lax.all_gather。想跨设备对一个数组求和?加一个jax.lax.pmean(即 AllReduce)。编程更难,但远不容易做出你不想要的事。
Auto sharding mode
自动分片模式(Auto)
jax.jit plays two roles inside JAX. As the name suggests, it “just-in-time” compiles a function from Python into bytecode (via XLA/HLO/LLO) so it runs faster. But if the input is sharded or the user specifies an in_sharding or out_sharding, it also lets XLA distribute the computation across multiple devices and add communication as needed. For example, here’s how you could write a sharded matmul using jax.jit:
jax.jit 在 JAX 里扮演两个角色。顾名思义,它把 Python 函数「即时」编译成字节码(经由 XLA/HLO/LLO)以便跑得更快。但如果输入是分片的,或者用户指定了 in_sharding 或 out_sharding,它也会让 XLA 把计算分布到多个设备上并按需加入通信。例如,下面是用 jax.jit 写一个分片矩阵乘法的方式:
import jax
import jax.numpy as jnp
Auto = jax.sharding.AxisType.Auto
# This creates a fake set of 8 CPU devices so you can run this on a CPU without TPUs.
jax.config.update("jax_num_cpu_devices", 8)
# This creates a 2D 4x2 mesh with axis names X and Y that JAX uses by default.
# We explicitly tell JAX to let the XLA compiler infer sharding along these axes.
mesh = jax.make_mesh(axis_sizes=(4, 2), axis_names=('X', 'Y'), axis_types=(Auto, Auto))
jax.set_mesh(mesh)
# We create a matrix W and input activations In sharded across our devices.
In = jnp.zeros((8, 2048), dtype=jnp.bfloat16, device=jax.NamedSharding(mesh, jax.P('X', 'Y')))
W = jnp.zeros((2048, 8192), dtype=jnp.bfloat16, device=jax.NamedSharding(mesh, jax.P('Y', None)))
def matmul_square(In, W):
return jnp.einsum('bd,df->bf', jnp.square(In), W)
# We can explicitly compile the sharded matmul function here. This adds all the
# necessary comms (e.g. an AllReduce after the matmul).
jit_matmul = jax.jit(matmul_square, out_shardings=jax.P('X', None)).lower(In, W).compile()
out = jit_matmul(In, W)This will run automatically with any sharding and partition the computation across our devices. But what’s actually happening at the hardware level?
它会自动以任意分片运行,把计算切分到我们的设备上。但在硬件层面实际发生了什么?
- First we create In and W sharded across our devices (Notice how we did this. This is one way to create an array with a particular sharding (i.e. by adding the device argument to the creation function). Another one is to create an array normally with
jnp.array(....)and then do e.g.jax.device_put(..., jax.P('X', 'Y')). Yet another is to write a function which creates the array you want, and jit-compile it without_shardingsbeing what you want.). W is sharded 2-way along the contracting dimension, while In is sharded 8-way: 4-way along the input dimension and 2-way along the contracting dimension. This corresponds to a sharding W[DY, F] and In[BX, DY], aka a kind of model and data parallelism. - If we were running this locally (i.e. on one device),
matmul_squarewould simply square the input and perform a simple matmul. But because we specify theout_shardingsasP('X', None), the output will be sharded along the batch but replicated across the model dimension and will require an AllReduce to compute.
- 首先我们创建跨设备分片的 In 和 W(注意我们是怎么做的。这是创建具有特定分片的数组的一种方式,即给创建函数加 device 参数。另一种是用
jnp.array(....)正常创建数组,然后做例如jax.device_put(..., jax.P('X', 'Y'))。还有一种方式是写一个函数来创建你想要的数组,并用你想要的out_shardings去 jit 编译它。)。W 沿收缩维分 2 片,而 In 分 8 片:沿输入维分 4 片、沿收缩维分 2 片。这对应分片 W[DY, F] 和 In[BX, DY],也就是一种模型并行加数据并行。 - 如果我们在本地(即单设备上)运行,
matmul_square就只是把输入平方再做一次简单矩阵乘法。但因为我们把out_shardings指定为P('X', None),输出会沿 batch 分片、沿模型维复制,并且需要一个 AllReduce 来计算。
Using our notation from previous sections, this will likely do something like
沿用前几节的记法,这大概率会做类似这样的事
- Out[BX, F] { UY } = In[BX, DY] *D W[DY, F]
- Out[BX, F] = AllReduce(Out[BX, F] { UY })
jax.jit will add this for us automatically! We can actually print the HLO with jit_matmul.as_text() and see the following HLO (abbreviated dramatically):
jax.jit 会自动替我们加上这个!我们其实可以用 jit_matmul.as_text() 打印 HLO,看到下面这段 HLO(大幅精简):
# This fusion is the actual matmul of the sharded inputs and matrix
%fusion = bf16[2,8192]{1,0:T(4,128)(2,1)S(1)} fusion(bf16[2,1024]{1,0:T(4,128)(2,1)} %param, bf16[8192,1024]{1,0:T(8,128)(2,1)S(1)} %copy-done)
# We reduce the partially summed results across devices
ROOT %AllReduce = bf16[2,8192]{1,0:T(4,128)(2,1)} AllReduce(bf16[2,8192]{1,0:T(4,128)(2,1)S(1)} %fusion)We can see the matmul (the fusion) and the AllReduce above. Pay particular attention to the shapes. bf16[2, 1024] is a local view of the activations, since our batch_size=8 is split across 4 devices and our d_model=2048 is likewise split 2 ways.
我们能在上面看到矩阵乘法(那个 fusion)和 AllReduce。特别注意形状。bf16[2, 1024] 是激活在设备本地的视图,因为我们的 batch_size=8 被切到 4 台设备上,而 d_model=2048 同样被分 2 片。
This is pretty magical! No matter how complicated our program is, Shardy and jit will attempt to find shardings for all the intermediate activations and add communication as needed. With that said, Shardy has its flaws. It can make mistakes. Sometimes you’ll look at a profile and notice something has gone wrong. A giant AllGather takes up 80% of the profile, where it doesn’t need to. When this happens, we can try to correct the compiler by explicitly annotating intermediate tensors with jax.lax.with_sharding_constraint. For instance, with two matmuls I can force the intermediate activations to be sharded along the y dimension (not that this is a good idea) with the following:
这相当神奇! 不管我们的程序多复杂,Shardy 和 jit 都会尝试为所有中间激活找到分片,并按需加入通信。话虽如此,Shardy 也有缺陷,它会犯错。有时你看 profile 会发现哪里出了问题:一个巨大的 AllGather 占了 profile 的 80%,而它本不必如此。遇到这种情况,我们可以试着用 jax.lax.with_sharding_constraint 显式标注中间 tensor 来纠正编译器。例如,用两个矩阵乘法,我可以强行让中间激活沿 y 维分片(并不是说这是个好主意):
import jax
import jax.numpy as jnp
Auto = jax.sharding.AxisType.Auto
mesh = jax.make_mesh((4, 2), ('X', 'Y'), (Auto, Auto))
jax.set_mesh(mesh)
def matmul(x, W_in, W_out):
hidden = jnp.einsum('bd,df->bf', x, W_in)
hidden = jax.lax.with_sharding_constraint(hidden, jax.P('X', 'Y'))
return jnp.einsum('bf,df->bd', hidden, W_out)This makes up about 60% of JAX parallel programming in the automatic partitioning world where you control the intermediate shardings via jax.lax.with_sharding_constraint. But “compiler tickling” is famously not a fun programming model. You could annotate every intermediate variable and still not know if you’ll get the right outcome. Instead, what if JAX itself could handle and control sharding propagation?
在自动分区(你自己通过 jax.lax.with_sharding_constraint 控制中间分片)的世界里,这占了 JAX 并行编程的大约 60%。但「哄编译器」是出了名的不爽的编程模型。你可能标注了每一个中间变量,却仍不知道会不会得到想要的结果。那么,如果让 JAX 自己来处理和控制分片传播呢?
Explicit sharding mode
显式分片模式(Explicit)
Explicit sharding (or “sharding in types”) looks a lot like automatic sharding, but sharding propagation happens at the JAX level! Each JAX operation has a sharding rule that takes the shardings of the op’s arguments and produces a sharding for the op’s result. You can see the resulting sharding using jax.typeof:
显式分片(或「把分片写进类型」)看起来很像自动分片,但分片传播发生在 JAX 层面!每个 JAX 操作都有一条分片规则,它接受该 op 各参数的分片,并为 op 的结果产出一个分片。你可以用 jax.typeof 看到结果分片:
import jax
import jax.numpy as jnp
import numpy as np
Explicit = jax.sharding.AxisType.Explicit
# Running on a TPU v5e 2x2. This assigns names to the two physical axes of the hardware.
mesh = jax.make_mesh(axis_sizes=(2, 2), axis_names=('X', 'Y'), axis_types=(Explicit, Explicit))
# This tells JAX to use this mesh for all operations, so you can just specify the PartitionSpec P.
jax.set_mesh(mesh)
x = jax.device_put(np.arange(16, dtype=np.float32).reshape(8, 2), jax.P('X', 'Y'))
@jax.jit
def f(x):
print(jax.typeof(x)) # float32[8@X,2@Y]
out = x * 2
print(jax.typeof(out)) # float32[8@X,2@Y]
return out
f(x)As you can see, JAX propagated the sharding from input (x) to output (out) which are inspectable at trace-time via jax.typeof. For most operations these rules are simple and obvious because there’s only one reasonable choice (e.g. elementwise ops retain the same sharding). But for some operations it’s ambiguous how to shard the result, in which case JAX throws a trace-time error and asks the programmer to provide an out_sharding argument explicitly (e.g. jnp.einsum, jnp.reshape, etc). Let’s see another example where you have conflicts:
如你所见,JAX 把分片从输入(x)传播到了输出(out),在 trace 时可以通过 jax.typeof 检查。对大多数操作来说这些规则简单明了,因为只有一个合理选择(例如逐元素操作保持相同的分片)。但对某些操作来说,结果该如何分片是有歧义的,这时 JAX 会抛出 trace 时的错误,要求程序员显式提供 out_sharding 参数(例如 jnp.einsum、jnp.reshape 等)。再看一个存在冲突的例子:
# We create a matrix W and input activations In sharded across our devices.
In = jnp.zeros((8, 2048), dtype=jnp.bfloat16, out_sharding=jax.P('X', 'Y'))
W = jnp.zeros((2048, 8192), dtype=jnp.bfloat16, out_sharding=jax.P('Y', None))
@jax.jit
def matmul_square(In, W):
print(jax.typeof(In)) # bfloat16[8@X, 2048@Y]
print(jax.typeof(W)) # bfloat16[2048@Y, 8192]
return jnp.einsum('bd,df->bf', jnp.square(In), W)
matmul_square(In, W) # This will errorThis code errors with:
这段代码报错:
Contracting dimensions are sharded and it is ambiguous how the output should be sharded.
Please specify the output sharding via the `out_sharding` parameter.
Got lhs_contracting_spec=('Y',) and rhs_contracting_spec=('Y',)This is awesome because how the output of einsum should be sharded is ambiguous. The output sharding can be:
这很赞,因为 einsum 的输出该如何分片是有歧义的。输出分片可以是:
- P(‘X’, ‘Y’) which will induce a ReduceScatter or
- P(‘X’, None) which will induce an AllReduce
- P(‘X’, ‘Y’),这会引入一个 ReduceScatter,或者
- P(‘X’, None),这会引入一个 AllReduce
Unlike Auto mode, explicit mode errors out when it detects ambiguous communication and requires the user to resolve it. So here you can do:
和 Auto 模式不同,显式模式在检测到有歧义的通信时会报错,并要求用户来解决。所以这里你可以这么做:
@jax.jit
def matmul_square(In, W):
return jnp.einsum('bd,df->bf', jnp.square(In), W, out_sharding=jax.P('X', 'Y'))
out = matmul_square(In, W)
print(jax.typeof(out)) # bfloat16[8@X,8192@Y]Auto mode and Explicit mode can be composed via jax.sharding.auto_axes and jax.sharding.explicit_axes APIs. This is a great doc to read for more information.
Auto 模式和 Explicit 模式可以通过 jax.sharding.auto_axes 和 jax.sharding.explicit_axes API 组合使用。想了解更多信息,这篇文档很值得一读。
Manual sharding mode via shard_map
用 shard_map 的手动分片模式
While Shardy is the “compiler take the wheel” mode, jax shard_map puts everything in your hands. You specify the sharding of the inputs, like in jax.jit, but then you write all communication explicitly. Whereas jax.jit leaves you with a global cross-device view of the program, shard_map gives you a local per-device view.
如果说 Shardy 是「编译器开车」模式,那么 jax shard_map 就是把一切交到你手里。你像在 jax.jit 里那样指定输入的分片,但之后所有通信都由你显式写出来。jax.jit 给你的是程序的全局跨设备视图,而 shard_map 给你的是每台设备本地的视图。
Here’s an example. Try to reason about what this function does: (If you want to play with this yourself in a colab by emulating a mesh, you can do so using the following cell import jax; jax.config.update('jax_num_cpu_devices', 8))
下面是一个例子。试着推理一下这个函数在做什么:(如果你想自己在 colab 里用一个模拟 mesh 把玩,可以用下面这个 cell:import jax; jax.config.update('jax_num_cpu_devices', 8))
import jax
import jax.numpy as jnp
Explicit = jax.sharding.AxisType.Explicit
mesh = jax.make_mesh((2, 4), ('x', 'y'), (Explicit, Explicit))
jax.set_mesh(mesh)
x = jnp.arange(0, 512, dtype=jnp.int32, out_sharding=jax.P(('x', 'y')))
# This function will operate on 1/8th of the array.
@jax.shard_map(in_specs=jax.P(('x', 'y')), out_specs=jax.P())
def slice_and_average(x):
assert x.shape == (512 // 8,)
return jax.lax.pmean(x[:4], axis_name=('x', 'y'))
out = slice_and_average(x)
assert out.shape == (4,)What does this do? slice_and_average is run on each TPU with 1/8th of the array, from which we slice the first 4 elements and average them across the full mesh. This means we’re effectively doing mean(x[:4], x[64:68], x[128:132], …). This is pretty cool, because that’s not an easy operation to express in JAX otherwise.
它在做什么? slice_and_average 在每颗 TPU 上拿到数组的 1/8 来运行,从中切出前 4 个元素,并在整个 mesh 上对它们求平均。这意味着我们实际上在做 mean(x[:4], x[64:68], x[128:132], …)。这相当酷,因为用 JAX 表达这种操作本来并不容易。
Why do this instead of jax.jit? If we’d used jax.jit, slice_and_average would have seen a global view of the array (the full [512,] array). We’d have had to slice out this non-uniform slice and then perform an average which XLA would have had to interpret correctly. XLA might have added the wrong communication or gotten confused. Here we see the local view and write only the communication we need.
为什么用这个而不是 jax.jit? 如果我们用 jax.jit,slice_and_average 看到的会是数组的全局视图(完整的 [512,] 数组)。我们就得切出这个非均匀的切片,然后做一个 XLA 必须正确解释的平均。XLA 可能加错通信,或者被搞糊涂。而这里我们看到的是设备本地视图,只写我们需要的通信。
Example [Collective Matmul]: To take a more realistic example, say we want to implement model parallelism where the activations are initially model sharded, i.e. A[BX, DY] *D W[D, FY] -> Out[BX, FY]. Naively, we would do this by AllGathering A first followed by a local matrix multiplication:
例子 [集合矩阵乘法]: 举个更现实的例子,假设我们要实现模型并行,其中激活一开始是模型分片的,即 A[BX, DY] *D W[D, FY] -> Out[BX, FY]。朴素做法是先对 A 做 AllGather,再做本地矩阵乘法:
- A[BX, D] = AllGatherY(A[BX, DY])
- Out[BX, FY] = A[BX, D] *D W[D, FY]
Sadly, this is bad because it doesn’t allow us to overlap the communication with the computation. Overlapping them can be done with a “collective matmul”, as described in Wang et al. 2023. The algorithm is basically as follows:
遗憾的是这很糟糕,因为它不允许我们把通信与计算重叠起来。重叠可以用 Wang et al. 2023 中描述的「集合矩阵乘法」(collective matmul)来实现。算法大致如下:
- For each Y shard, perform a matmul of the local chunk of A with the local chunk of W, producing a result of shape
[B / X, F / Y]. Simultaneously, permute A so you get the next chunk locally, perform the matmul, and sum the result.
- 对每个 Y 分片,用 A 的本地块与 W 的本地块做矩阵乘法,得到形状
[B / X, F / Y]的结果。同时,对 A 做置换,让你在本地拿到下一块,再做矩阵乘法并把结果累加进去。
We can implement that quite easily with jax.shard_map:
我们可以用 jax.shard_map 相当容易地实现它:
import functools
import jax
import jax.numpy as jnp
import numpy as np
Explicit = jax.sharding.AxisType.Explicit
# This is intended to run on a TPU v5e-8 runtime. If you can't get this,
# try setting jax.config.update('jax_num_cpu_devices', 8).
#
mesh = jax.make_mesh(axis_sizes=(2, 4), axis_names=('X', 'Y'), axis_types=(Explicit, Explicit))
jax.set_mesh(mesh)
B, D, F = 1024, 2048, 8192
A = jnp.arange(np.prod((B, D))).reshape((B, D))
W = jnp.arange(np.prod((D, F))).reshape((D, F))
A = jax.device_put(A, jax.P('X', 'Y'))
W = jax.device_put(W, jax.P(None, 'Y'))
@functools.partial(jax.jit, out_shardings=jax.P('X', 'Y'))
def matmul(lhs, rhs):
return lhs @ rhs
def collective_matmul_allgather_lhs_contracting(lhs, rhs):
# lhs is the looped operand; rhs is the local operand
axis_size = jax.lax.axis_size('Y') # axis_size = 4 for this example
idx = jax.lax.axis_index('Y')
chunk_size = lhs.shape[1]
assert rhs.shape[0] % chunk_size == 0
def f(i, carrys):
accum, lhs = carrys
rhs_chunk = jax.lax.dynamic_slice_in_dim(rhs, (idx + i) % axis_size * chunk_size, chunk_size)
# Matmul for a chunk
update = lhs @ rhs_chunk
# Circular shift to the left
lhs = jax.lax.ppermute(
lhs,
axis_name='Y',
perm=[(j, (j - 1) % axis_size) for j in range(axis_size)]
)
return accum + update, lhs
accum = jnp.zeros((lhs.shape[0], rhs.shape[1]), dtype=lhs.dtype)
accum = jax.lax.pcast(accum, ('X', 'Y'), to='varying')
accum, lhs = jax.lax.fori_loop(0, axis_size - 1, f, (accum, lhs), unroll=True)
# Compute the last chunk after the final permute to leave lhs in the state we found it
i = axis_size - 1
rhs_chunk = jax.lax.dynamic_slice_in_dim(rhs, (idx + i) % axis_size * chunk_size, chunk_size)
update = lhs @ rhs_chunk
return accum + update
jit_sharded_f = jax.jit(jax.shard_map(
collective_matmul_allgather_lhs_contracting,
in_specs=(jax.P('X', 'Y'), jax.P(None, 'Y')), out_specs=jax.P('X', 'Y')))
shmapped_out = jit_sharded_f(A, W)
expected_out = matmul(A, W)
np.testing.assert_array_equal(shmapped_out, expected_out)This is pretty neat! We can benchmark this and see that it’s also a lot faster! Here’s the profile with the default jit matmul which takes 311us with a big blocking AllGather at the beginning:
这相当漂亮!我们可以对它做 benchmark,看到它也快得多!这里是用默认 jit 矩阵乘法的 profile,花了 311us,开头有一个很大的阻塞式 AllGather:
And here’s the version above that takes 244us. You can see the profile doesn’t have the AllGather. It’s all useful work! Our FLOPs utilization is also a lot higher.
而这里是上面那个版本,花了 244us。你能看到 profile 里没有 AllGather,全是有效工作!我们的 FLOPs 利用率也高得多。
It’s also worth noting that the matmul time with no sharding on the contracting dimension is 224us, so we’re remarkably close to the unsharded baseline here. This is a good example of the kind of performance engineering you might end up doing to improve TPU utilization. For more shard_map examples, this note is great.
Now here are a couple of useful worked problems to try and implement using jax.jit or shard_map!
下面就来做几道有用的动手题,用 jax.jit 或 shard_map 实现它们!
Worked Problems
动手练习
Here are some random JAX-related problems. I’ll add some more later. For all of these, you’ll need some number of TPUs. Colab no longer hands out TPU v2-8 slices, so use Kaggle (which still provides them for free) or an 8-core GCP slice. (If you just want to emulate a mesh 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), though this won’t reflect real performance.) From now on, we’ll assume you have N devices available.
这里是一些随机的 JAX 相关题目。我以后还会再加一些。所有这些题你都需要若干颗 TPU。Colab 不再发放 TPU v2-8 slice 了,所以用 Kaggle(它仍然免费提供)或一个 8 核 GCP slice。(如果你只想在假问题上模拟一个 mesh,也可以用 import jax; jax.config.update('jax_num_cpu_devices', 8)(需要 jax >= 0.4.27 左右)在 CPU 上伪造 8 个设备,不过这不能反映真实性能。)从现在起,我们假设你有 N 台设备可用。
Question 1: Let A be an array of activations of shape float32[SX, DY] with X * Y = N. Do the following:
问题 1: 设 A 是形状为 float32[SX, DY] 的激活数组,其中 X * Y = N。完成以下任务:
- Write a function in JAX that computes the average within each
(X, Y)shard, i.e. it returns an array of size [X, Y] wherearr[i, j]is the average over shard(i, j). Do this with bothjax.jitandshard_map. Profile each and see how long they took. Was there any communication added? Hint: there shouldn’t be, but sometimes XLA adds it anyway.
- 用 JAX 写一个函数,计算每个
(X, Y)分片内的平均值,即返回一个大小为 [X, Y] 的数组,其中arr[i, j]是分片(i, j)上的平均值。分别用jax.jit和shard_map实现。给两者做 profile,看看各花了多久。有没有引入通信?提示:应该没有,但有时 XLA 还是会加上。
- Write a function in JAX that returns
roll(x, shift, axis=0) - xfor some shift within each shard along X. I’m not enough of a masochist to make you do this in jax.jit, so just do this withshard_map.
- 用 JAX 写一个函数,返回
roll(x, shift, axis=0) - x,其中 shift 是在每个沿 X 的分片内部的。我没那么自虐,不会让你用 jax.jit 做这个,所以只用shard_map做。
Click here for the answer.
点击这里看答案。
Part 1: Here is a solution to part 1. Note the fairly complex reshapes we have to do for the jax.jit solution.
第 1 部分: 下面是第 1 部分的一个解法。注意 jax.jit 版本要做相当复杂的 reshape。
import numpy as np
import jax
import jax.numpy as jnp
Auto = jax.sharding.AxisType.Auto
mesh = jax.make_mesh((4, 2), ('X','Y'), (Auto, Auto))
average_shmap = jax.shard_map(
lambda x: x.mean(keepdims=True),
mesh=mesh,
in_specs=jax.P('X','Y'), out_specs=jax.P('X','Y')
)
def average(x):
X, Y = mesh.axis_sizes
return x.reshape(X, x.shape[0] // X, Y, x.shape[1] // Y).mean(axis=(1, 3))
average_jit = jax.jit(average, out_shardings=jax.NamedSharding(mesh, jax.P('X','Y')))
x = jnp.arange(8 * 64 * 8, dtype=jnp.float32).reshape(8 * 64, 8)
x = jax.device_put(x, jax.NamedSharding(mesh, jax.P('X','Y')))
y1 = average_shmap(x)
y2 = average_jit(x)
np.testing.assert_array_equal(y1, y2)Part 2: Here is a similar solution to Part 2. The shard_map version is the one you were asked for, but a jax.jit version is included for comparison.
第 2 部分: 下面是第 2 部分类似的解法。shard_map 版本是你被要求写的,但也附上了一个 jax.jit 版本作对比。
import numpy as np
import jax
import jax.numpy as jnp
import functools
Auto = jax.sharding.AxisType.Auto
mesh = jax.make_mesh((4, 2), ('X','Y'), (Auto, Auto))
def shift_shmap(x, shift: int):
shmapped = jax.shard_map(
lambda x: jnp.roll(x, shift, axis=0) - x,
mesh=mesh,
in_specs=jax.P('X','Y'), out_specs=jax.P('X','Y')
)
return shmapped(x)
@functools.partial(jax.jit, static_argnames=['shift'], out_shardings=jax.NamedSharding(mesh, jax.P('X','Y')))
def shift_jit(x, shift: int):
X, Y = mesh.axis_sizes
reshaped = x.reshape(X, x.shape[0] // X, -1)
return (jnp.roll(reshaped, shift, axis=1) - reshaped).reshape(x.shape[0], x.shape[1])
x = jnp.arange(8 * 64 * 8, dtype=jnp.float32).reshape(8 * 64, 8)
x = jax.device_put(x, jax.NamedSharding(mesh, jax.P('X','Y')))
y1 = shift_shmap(x, 5)
y2 = shift_jit(x, 5)
np.testing.assert_array_equal(y1, y2)Question 2: Here we’ll make a basic “mixture of experts” model together. Let W: float32[EX, D, F] be a set of E “expert” matrices. Let A: float32[SX, D] (our activations) and let B: int32[SX] be a set of “routing assignments” where B[i] is an integer in the range [0, E) telling us which matrix we want to process that activation. We want to write a function in JAX that returns Out[i] = A[i] @ W[B[i]].
问题 2: 这里我们一起做一个基本的「混合专家」(MoE)模型。设 W: float32[EX, D, F] 是一组 E 个「专家」矩阵。设 A: float32[SX, D](我们的激活),并设 B: int32[SX] 是一组「路由分配」,其中 B[i] 是 [0, E) 范围内的整数,告诉我们想用哪个矩阵处理该激活。我们要用 JAX 写一个函数返回 Out[i] = A[i] @ W[B[i]]。
- Let’s start by ignoring sharding altogether. Make all of these tensors small enough so they fit in one device. Write a local implementation of this function. Make sure you don’t materialize an array of shape
[S, D, F]! Hint: there are a few ways to do this. The simplest is to loop over the experts, multiply all of A byW[e], and mask out the tokens not routed to experte. Alternatively, you can sort the tokens by expert into a padded buffer of shape[E, S, D]and do a single batched matmul, masking out the padding (why does the second dimension need to have size S?).jax.lax.ragged_dotdoes the sorted version without the padding.
- 先完全忽略分片。把这些 tensor 都弄得足够小,以便放进单台设备。写一个这个函数的本地实现。确保不要 materialize 形状为
[S, D, F]的数组!提示:有几种做法。最简单的是对专家做循环,把整个 A 乘上W[e],再 mask 掉没路由到专家e的 token。另一种是把 token 按专家排序进一个形状为[E, S, D]的 padded buffer,做一次 batched 矩阵乘法并 mask 掉 padding(为什么第二维需要大小 S?)。jax.lax.ragged_dot做的是排序版且没有 padding。
- If you just
jax.jitthe above method, something will happen. Profile this and see what communication it decided to do. How long does it take?
- 如果你只是把上面的方法
jax.jit,会发生一些事。给它做 profile,看看它决定做哪些通信。要花多久?
- One problem you’ll notice with the above is that it likely gathers the full set of activations A locally, i.e. AllGatherX([SX, D]). Not only is this expensive communication-wise, it’s also incredibly expensive memory-wise if we can’t fit the full set of activations locally. Implement the above using
shard_mapand explicit communication.
- 你会注意到的上面的一个问题是,它很可能把完整的激活集合 A 在本地 gather 起来,即 AllGatherX([SX, D])。这不仅在通信上昂贵,而且如果我们本地装不下完整激活,显存上也极其昂贵。用
shard_map和显式通信实现上面的功能。
1. For a first pass, it might be easiest to use a `jax.lax.all_gather` and reorder as in step 1. 1. 第一遍,最简单的是用 `jax.lax.all_gather` 并像第 1 步那样重排。 2. For a second pass, try to avoid materializing any array of size `[E, S, D]`, i.e. try to perform the computation in a ragged fashion using a `jax.lax.all_to_all` inside a `jax.lax.while_loop`. This way, you can avoid materializing the full activations and wasting compute on padding. How much faster is this than your original implementation? 2. 第二遍,试着避免 materialize 任何大小为 `[E, S, D]` 的数组,即在 `jax.lax.while_loop` 里用 `jax.lax.all_to_all` 以 ragged 的方式做计算。这样你就能避免 materialize 完整激活、也不在 padding 上浪费计算。这比你的原始实现快多少?4. Most MoEs route to multiple (k) experts and then average the result. Refactor the above to implement this. Let B: int32[SX, k] in this case for the k experts to route to.
- 大多数 MoE 会路由到多个(k 个)专家,然后把结果平均。重构上面的实现来支持这一点。这种情况下设 B: int32[SX, k],表示要路由到的 k 个专家。
Click here for the (partial) answer.
点击这里看(部分)答案。
Part 1: You have a lot of choices here. Here’s the simplest option, which just iterates over the experts with masking and never sorts the tokens:
第 1 部分: 这里你有很多选择。下面是最简单的选项,它只是带 mask 地遍历专家、从不对 token 排序:
def moe_local(W: jnp.ndarray, A: jnp.ndarray, B: jnp.ndarray) -> jnp.ndarray:
S, _ = A.shape
E, _, F = W.shape
def expert_forward(carry, e):
output = carry # [S, F]
mask = (B == e)[:, None] # [S, 1]
expert_result = A @ W[e] # [S, F] - this expert's transform of ALL tokens
output = output + expert_result * mask # Only keep results for assigned tokens
return output, None
output = jnp.zeros((S, F))
output, _ = jax.lax.scan(expert_forward, output, jnp.arange(E))
return outputThis wastes compute, since every expert processes every token. A more efficient option is to sort the tokens by expert and then use jax.lax.ragged_dot, which takes the sorted activations along with the number of tokens per expert and does the matmul without any padding or masking.
这会浪费计算,因为每个专家都处理每个 token。更高效的选项是按专家对 token 排序,然后用 jax.lax.ragged_dot,它接受排序后的激活以及每个专家的 token 数,在没有任何 padding 或 masking 的情况下做矩阵乘法。
Part 3: I’m only going to sketch the pseudocode here (if you have a clean solution feel free to add it):
第 3 部分: 这里我只写伪代码(如果你有干净解法欢迎补充):
chunk_size = 128
def matmul(W, x, B):
i = 0
outs = []
x = # sort x according to assignments
while (chunk := x[i:i+chunk_size]).any():
chunk = all_to_all(chunk)
outs.append(matmul_local(W, chunk))
i += chunk_size
return concat(outs)The basic idea is to iterate over chunks of the array, sort them and do an all_to_all, then do the local FLOPs.
基本思路是遍历数组的块,排序后做 all_to_all,然后做本地 FLOPs。
Question 3: The collective matmul example above is actually super relevant for real LLMs. Let’s tweak the example to do the full Transformer stack.
问题 3: 上面那个集合矩阵乘法的例子其实和真实 LLM 极其相关。我们把例子改成完整的 Transformer 栈。
- As an exercise, let’s start by implementing an AllReduce collective matmul, i.e. A[BX, DY] *D W[DY, F] -> Out[BX, F]. Note that the output is sharded only along X, i.e. it is replicated across Y. The naive algorithm is discussed above, basically just a local matmul followed by an AllReduce. Try to make a comms overlapped “collective” version of this operation. Hint: tile over the output dimension and feel free to use
jax.lax.psum(aka AllReduce). Note: due to the way XLA handles this, it may not actually be faster than the baseline.
- 作为练习,先实现一个 AllReduce 集合矩阵乘法,即 A[BX, DY] *D W[DY, F] -> Out[BX, F]。注意输出只沿 X 分片,即在 Y 上复制。朴素算法上面讨论过,基本上就是一个本地矩阵乘法后接一个 AllReduce。试着做一个通信重叠的「集合」版本。提示:沿输出维做 tiling,可以随意使用
jax.lax.psum(即 AllReduce)。 注意:由于 XLA 处理方式的原因,它实际上可能并不比基线快。
- The complement to the AllReduce collective matmul above is a ReduceScatter collective matmul, as in Tmp[BX, FY] *F W2[FY, D] -> Out[BX, DY]. This occurs in the down-projection matrix in a Transformer. Implement a collective, overlapped version of this in JAX. Be careful about passing only the minimal amount of data you need. Hint: try permuting the result as you accumulate it.
- 上面 AllReduce 集合矩阵乘法的补充是 ReduceScatter 集合矩阵乘法,即 Tmp[BX, FY] *F W2[FY, D] -> Out[BX, DY]。它出现在 Transformer 的 down-projection 矩阵里。用 JAX 实现一个集合、重叠的版本。注意只传递你所需的最少数据。提示:试着在累加结果的过程中对它做置换。
- Put the AllGather collective matmul from the main text together with the ReduceScatter collective matmul from (2) into an end-to-end Transformer block that performs In[BX, DY] *D Win[D, FY] *F Wout[FY, D] -> Out[BX, DY] with overlapped communication. (As before, we can’t do $W_{in} \cdot W_{out}$ first because of a non-linearity we’ve omitted here.) How much faster is this than a
jax.jitimplementation?
- 把正文里的 AllGather 集合矩阵乘法与 (2) 里的 ReduceScatter 集合矩阵乘法组合成一个端到端的 Transformer 块,以重叠通信的方式完成 In[BX, DY] *D Win[D, FY] *F Wout[FY, D] -> Out[BX, DY]。(和之前一样,由于这里省略了一个非线性,我们不能先做 $W_{in} \cdot W_{out}$。)这比
jax.jit实现快多少?
Question 4: All of the collective matmuls implemented above are unidirectional: they only permute in one direction. Rewrite the collective AllReduce matmul and the collective ReduceScatter matmuls to use bidirectional communication. How much faster are these?
问题 4: 上面实现的所有集合矩阵乘法都是单向的:它们只朝一个方向做置换。把集合 AllReduce 矩阵乘法和集合 ReduceScatter 矩阵乘法改写成双向通信。它们快多少?
讨论
用 GitHub 账号留言;评论保存在公开仓库chengshu-blog-discussions的 Discussions 里。也可通过 RSS 订阅后续文章。