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 每个设备 | ✅ | ✅ |
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(带有Auto网格轴) 让你能够获取任何现有的 JAX 函数,并用分片输入调用它。然后 JAX 使用 XLA 的 Shardy 编译器,该编译器会自动并行化程序。XLA 会在需要时为你添加通信 (AllGathers,ReduceScatters,AllReduces 等) 以促进现有操作。虽然它并不完美,但它通常在自动将你的程序扩展到任意数量的芯片而无需更改代码方面做得很好。- 带有
Explicit网格轴的jax.jit看起来与 (1) 类似,但让 JAX 处理分片传播而不是 XLA。这意味着数组的分片实际上是 JAX 类型系统的一部分,当 JAX 检测到不明确的通信时可以报错,并让用户解决它。 jax.shard_map是更手动的对应物。你会得到一个程序的设备本地视图,并且必须显式地编写你想要的任何通信。有一个分片数组,并希望在每个设备上都有完整的东西?添加一个jax.lax.all_gather。想要在你的设备上对一个数组求和?添加一个jax.lax.psum(一个 AllReduce)。编程更难,但不太可能做一些你不想做的事情。
Auto sharding mode自动分片模式
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 devices1. 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 和 W1。W 沿收缩维度进行了 2 路分片,而 In 则分成 8 片(沿输入维度分成 4 片,沿收缩维度分成 2 片)。这对应于分片 W[DY, F] 和 In[BX, DY],又名一种模型和数据并行。
- 如果我们要在本地运行这个 (即,在一个设备上),
matmul_square将简单地对输入进行平方并执行一个简单的矩阵乘法。但是因为我们将out_shardings指定为P('X', None),输出将沿批次维分片,但在模型维度上进行复制,并且需要一个 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.
我们可以看到上面的矩阵乘法 (融合) 和 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 也有其缺陷。它可能会犯错。有时你会看一个性能记录,注意到出了问题。一个巨大的 AllGather 占用了 80% 的性能记录,而它本不需要。当这种情况发生时,我们可以尝试通过用 jax.lax.with_sharding_constraint 显式地注释中间张量来纠正编译器。例如,对于两个矩阵乘法,我可以强制中间激活沿 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 并行编程中自动分区世界的 60%,你可以通过 jax.lax.with_sharding_constraint 控制中间分片。但“编译器挠痒痒”是出了名的不好玩的编程模型。你可以注释每个中间变量,但仍然不知道是否会得到正确的结果。相反,如果 JAX 本身可以处理和控制分片传播呢?
Explicit sharding mode显式分片模式
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 操作都有一个分片规则,该规则接受操作参数的分片并为操作的结果生成一个分片。你可以使用 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) 传播到输出 (x),这些分片可以在跟踪时通过 jax.typeof 进行检查。对于大多数操作,这些规则简单明了,因为只有一个合理的选择 (例如,逐元素操作保留相同的分片)。但对于某些操作,如何对结果进行分片是不明确的,在这种情况下,JAX 会在跟踪时抛出一个错误,我们要求程序员显式地提供一个 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 error
This 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:
- P(‘X’, ‘Y’) which will induce a ReduceScatter or
- P(‘X’, None) which will induce an AllReduce
这很棒,因为 einsum 的输出应该如何分片是不明确的。输出分片可以是:
- P(‘X’,‘Y’) 这将引起一个 reduce-scatter 或
- P(‘X’,None) 这将引起一个 all-reduce
Unlike Auto mode, explicit mode errors out when it detects ambiguous communication and requires the user to resolve it. So here you can do:
与自动模式不同,显式模式在检测到不明确的通信时会报错,并要求用户解决它。所以在这里你可以这样做:
@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.
自动模式和显式模式可以通过 jax.sharding.auto_axes 和 jax.sharding.explicit_axes API 进行组合。这是一篇很好的文档以获取更多信息。
Manual sharding mode via shard_mapshard_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 给你一个本地的每个设备的视图。
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 个元素,并在整个网格上对它们进行平均。这意味着我们实际上在做 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 所述。算法基本上如下:
- 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:
我们可以用 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:
这很酷!我们可以对它进行基准测试,发现它也快得多!这里 是默认 jit 矩阵乘法的性能记录,它需要 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.
这里 是上面的版本,需要 244 us。你可以看到性能记录没有 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例题
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都做一遍。对每个进行分析,看看它们花了多长时间。是否添加了任何通信?提示:应该没有,但有时 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,在沿 X 轴分片的每个分片内部执行指定的 shift。我不是一个受虐狂,不会让你用 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 解决方案,我们必须进行相当复杂的重塑。
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 部分:**解法与前一小题相似。请用 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) 内的整数,指定由哪个专家矩阵处理对应的激活。请编写一个返回 Out[i] = A[i] @ W[B[i]] 的 JAX 函数。
- 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.
- 先忽略分片。让这些张量都能放进一台设备,并编写函数的本地实现。**不要实际生成形状为
[S, D, F]的数组!提示:**解法有几种。最简单的办法是遍历专家,让每个专家e用W[e]乘以整个 A,再掩蔽未路由给该专家的 token。你也可以按专家对 token 排序,放入补齐到形状[E, S, D]的缓冲区中,做一次批量矩阵乘法,并掩蔽填充的位置(为什么第二维需要长度 S?)。jax.lax.ragged_dot可以在不填充的情况下完成排序后的计算。
- 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,会发生一些事情。对此进行分析,看看它决定进行什么通信。需要多长时间?
- 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,即 AllGatherX([SX, D])。这不仅在通信方面成本高昂,而且如果我们无法在本地容纳完整的激活集,在内存方面也极其昂贵。使用
shard_map和显式通信来实现上述功能。
- For a first pass, it might be easiest to use a
jax.lax.all_gatherand reorder as in step 1.
- 对于第一次尝试,使用
jax.lax.all_gather并像第 1 小题那样重新排序可能最简单。
- 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 ajax.lax.all_to_allinside ajax.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?
- 对于第二次尝试,尽量避免物化任何大小为
[E, S, D]的数组,即尝试使用jax.lax.while_loop内的jax.lax.all_to_all以不规则的方式执行计算。这样,你可以避免物化完整的激活并浪费计算在填充上。这比你最初的实现快多少?
- 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],记录每个 token 路由到的 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 部分:**有多种解法。最简单的是遍历专家并使用掩码,全程无需对 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 output
This 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 数量,然后直接执行矩阵乘法,无需填充或掩蔽。
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 通信,再在本地计算。
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。尝试制作这个操作的通信重叠的“集合”版本。提示:在输出维度上进行分块,并随意使用
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 的下投影矩阵中。在 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.4 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] -> Out[BX, DY],让通信与计算重叠。4 这比
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 矩阵乘法以使用双向通信。这些快多少?
That’s all for Part 10. That’s basically it! For final conclusions and further reading, click here.第 10 部分到此结束。基本上就是这样了!有关最终结论和进一步阅读,请点击 这里。
Footnotes
-
↩
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.注意我们是如何做到这一点的。这是创建具有特定分片的数组的一种方法 (即,通过向创建函数添加 device 参数)。另一种方法是正常地用
jnp.array(....)创建一个数组,然后执行例如jax.device_put(..., jax.P('X', 'Y'))。还有一种方法是编写一个创建你想要的数组的函数,并用你想要的out_shardings对其进行 jit 编译。 -
↩
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 中通过模拟一个网格来自己玩这个,你可以用以下单元格来做
import jax; jax.config.update('jax_num_cpu_devices', 8) -
↩
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.如果只想用简单示例模拟设备网格,也可以在 CPU 上运行
import jax; jax.config.update('jax_num_cpu_devices', 8)来模拟 8 个设备(大约需要 JAX ≥ 0.4.27)。这种方式无法反映实际性能。 -
↩
As before, we can’t do first because of a non-linearity we’ve omitted here.
和以前一样,由于我们在这里省略了一个非线性,我们不能先做 。