Skip to content
quboliu
⚙

Sharded Matrices and How to Multiply Them分片矩阵及其乘法

第 3 章 · How To Scale Your Model (如何看待 TPU | 你需要知道的所有 Transformer 数学)

When we train large ML models, we have to split (or "shard") their parameters or inputs across many accelerators. Since LLMs are mostly made up of matrix multiplications, understanding this boils down to understanding how to multiply matrices when they're split across devices. We develop a simple theory of sharded matrix multiplication based on the cost of TPU communication primitives.

训练大型机器学习模型时,需要将参数或输入分片到多个加速器上。由于 LLM 的计算主要是矩阵乘法,本章讨论如何让分布在不同设备上的矩阵相乘,并根据 TPU 通信原语的成本建立一个简单的分析模型。

Partitioning Notation and Collective Operations分区符号和集合通信

When we train an LLM on ten thousand TPUs or GPUs, we’re still doing abstractly the same computation as when we’re training on one. The difference is that our arrays don’t fit in the HBM of a single TPU/GPU, so we have to split them.1 We call this “sharding” or “partitioning” our arrays. The art of scaling is figuring out how to shard our models so computation remains efficient.

当我们在成千上万的 TPU 或 GPU 上训练一个 LLM 时,我们抽象地做的计算与在单个设备上训练时是相同的。不同之处在于我们的数组无法容纳在单个 TPU/GPU 的 HBM 中,所以我们必须将它们拆分。1 我们称之为“分片”或“分区”我们的数组。扩展的艺术在于弄清楚如何对我们的模型进行分片,以便计算保持高效。

Here’s an example 2D array A sharded across 4 TPUs:

这是一个在 4 个 TPU 上分片的 2D 数组 A 的例子:

sharding example

Figure: an example array of shape A[I, J] gets sharded across 4 devices. Both dimensions are evenly sharded across 2 devices with a sharding A[IX, JY]. Each TPU holds 1/4 of the total memory.

图: 一个形状为 A[I, J] 的示例数组在 4 个设备上进行分片. 两个维度都在 2 个设备上均匀分片, 分片方式为 A[IX, JY]. 每个 TPU 持有总内存的 1/4.

Note how the sharded array still has the same global or logical shape as the unsharded array, say (4, 128), but it also has a device local shape, like (2, 64), which gives us the actual size in bytes that each TPU is holding (in the figure above, each TPU holds ¼ of the total array). Now we’ll generalize this to arbitrary arrays.

请注意,分片数组仍然具有与未分片数组相同的全局或逻辑形状,例如 (4, 128),但它也有一个设备本地形状,例如 (2, 64),这给了我们每个 TPU 持有的实际字节大小 (在上图中,每个 TPU 持有总数组的 ¼)。现在我们将 这一结论推广到任意数组。

A unified notation for sharding分片的统一符号

We use a variant of named-axis notation to describe how the tensor is sharded in blocks across the devices: we assume the existence of a 2D or 3D grid of devices called the device mesh where each axis has been given mesh axis names e.g. X, Y, and Z. We can then specify how the matrix data is laid out across the device mesh by describing how each named dimension of the array is partitioned across the physical mesh axes. We call this assignment a sharding.

我们使用命名轴表示法的一种变体来描述张量如何以块的形式在设备上分片:我们假设存在一个 2D 或 3D 的设备网格,称为设备网格,其中每个轴都被赋予了网格轴名称, 例如 X, Y 和 Z. 然后,我们可以通过描述数组的每个命名维度如何跨物理网格轴进行分区来指定矩阵数据在设备网格上的布局。我们称这个分配为分片.

Example (the diagram above): For the above diagram, we have:

  • Mesh: the device mesh above Mesh(devices=((0, 1), (2, 3)), axis_names=('X', 'Y')), which tells us we have 4 TPUs in a 2x2 grid, with axis names XX and YY.
  • Sharding: A[IX,JY]A[I_X, J_Y], which tells us to shard the first axis, II, along the mesh axis XX, and the second axis, JJ, along the mesh axis YY. This sharding tells us that each shard holds 1/(∣X∣⋅∣Y∣)1 / (\lvert X\rvert \cdot \lvert Y\rvert) of the array.

示例 (上图):对于上图,我们有:

  • 网格: 上面的设备网格 Mesh(devices=((0, 1), (2, 3)), axis_names=('X', 'Y')),这告诉我们我们有 4 个 TPU,排列成一个 2x2 的网格,轴名称为 XX 和 YY.
  • 分片: A[IX,JY]A[I_X, J_Y],这告诉我们将第一个轴 II 沿网格轴 XX 分片,将第二个轴 JJ 沿网格轴 YY 分片。这个分片告诉我们每个分片持有数组的 1/(∣X∣⋅∣Y∣)1 / (\lvert X\rvert \cdot \lvert Y\rvert).

Taken together, we know that the local shape of the array (the size of the shard that an individual device holds) is (∣I∣/2,∣J∣/2)(\lvert I\rvert / 2, \lvert J\rvert / 2), where ∣I∣\lvert I\rvert is the size of A’s first dimension and ∣J∣\lvert J\rvert is the size of A’s second dimension.

综上所述,我们知道数组的本地形状 (单个设备持有的分片的大小) 是 (∣I∣/2,∣J∣/2)(\lvert I\rvert / 2, \lvert J\rvert / 2),其中 ∣I∣\lvert I\rvert 是 A 的第一个维度的大小,∣J∣\lvert J\rvert 是 A 的第二个维度的大小。

Pop Quiz [2D sharding across 1 axis]: Consider an array fp32[1024, 4096] with sharding A[IXY,J]A[I_{XY}, J] and mesh {'X': 8, 'Y': 2}. How much data is held by each device? How much time would it take to load this array from HBM on H100s (assuming 3.4e12 memory bandwidth per chip)?

小测验 [沿 1 个轴的 2D 分片]: 考虑一个数组 fp32[1024, 4096],分片为 A[IXY,J]A[I_{XY}, J],网格为 {'X': 8, 'Y': 2}。每个设备持有多少数据?在 H100s 上从 HBM 加载这个数组需要多长时间 (假设每个芯片的内存带宽为 3.4e12)?

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

A[IXY,J]A[I_{XY}, J] shards the first dimension (I) along both the X and Y hardware axes. In this example, the local shape is (∣I∣/(∣X∣⋅∣Y∣),∣J∣)(\lvert I\rvert /(\lvert X\rvert \cdot \lvert Y\rvert), \lvert J\rvert). For the given example, the global shape is fp32[1024, 4096], so the local shape is fp32[64, 4096].

A[IXY,J]A[I_{XY}, J] 将第一个维度 (I) 沿 X 和 Y 硬件轴进行分片。在这个例子中,本地形状是 (∣I∣/(∣X∣⋅∣Y∣),∣J∣)(\lvert I\rvert /(\lvert X\rvert \cdot \lvert Y\rvert), \lvert J\rvert)。对于给定的例子,全局形状是 fp32[1024, 4096],所以本地形状是 fp32[64, 4096].

Since each GPU has 4 * 64 * 4096 = 1MiB bytes, this would take about 1e6 / 3.4e12 = 294ns, although likely significantly more due to various overheads since this is so small.

由于每个 GPU 有 4 * 64 * 4096 = 1MiB 字节,这大约需要 1e6 / 3.4e12 = 294ns,尽管由于各种开销,实际时间可能要长得多,因为这个数组很小。

Visualizing these shardings: Let’s try to visualize these shardings by looking at a 2D array of data split over 4 devices:

可视化这些分片: 让我们尝试通过查看一个分布在 4 个设备上的 2D 数据数组来可视化这些分片:

sharding colored1

We write the fully-replicated form of the matrix simply as A[I,J]A[I, J] with no sharding assignment. This means that each device contains a full copy of the entire matrix.

我们将矩阵的完全复制形式简单地写为 A[I,J]A[I, J],没有分片分配。这意味着每个设备都包含整个矩阵的完整副本。

sharding colored2

We can indicate that one of these dimensions has been partitioned across a mesh axis with a subscript mesh axis. For instance A[IX,J]A[I_X, J] would mean that the I logical axis has been partitioned across the X mesh dimension, but that the J dimension is not partitioned, and the blocks remain partially-replicated across the Y mesh axis.

我们可以用一个下标网格轴来表示其中一个维度已经跨一个网格轴进行了分区。例如,A[IX,J]A[I_X, J] 意味着 I 逻辑轴已经跨 X 网格维度进行了分区,但 J 维度没有分区,并且这些块在 Y 网格轴上保持部分复制.

sharding colored3

A[IX,JY]A[I_X, J_Y] means that the I logical axis has been partitioned across the X mesh axis, and that the J dimension has been partitioned across the Y mesh axis.

A[IX,JY]A[I_X, J_Y] 意味着 I 逻辑轴已经跨 X 网格轴进行了分区,并且 J 维度已经跨 Y 网格轴进行了分区。

sharding colored4

We illustrate the other possibilities in the figure below:

我们在下图中说明了其他可能性:

sharding colored5

Here A[IXY,J]A[I_{XY}, J] means that we treat the X and Y mesh axes as a larger flattened dimension and partition the I named axis across all the devices. The order of the multiple mesh-axis subscripts matters, as it specifies the traversal order of the partitioning across the grid.

这里 A[IXY,J]A[I_{XY}, J] 意味着我们将 X 和 Y 网格轴视为一个更大的扁平化维度,并将 I 命名轴跨所有设备进行分区。多个网格轴下标的顺序很重要,因为它指定了分区跨网格的遍历顺序。

sharding colored6

Lastly, note that we cannot have multiple named axes sharded along the same mesh dimension. e.g. A[IX,JX]A[I_X, J_X] is a nonsensical, forbidden sharding. Once a mesh dimension has been used to shard one dimension of an array, it is in a sense “spent”.

最后,请注意,我们不能将多个命名轴沿相同的网格维度进行分片。例如,A[IX,JX]A[I_X, J_X] 是一个无意义的,禁止的分片。一旦一个网格维度被用于分片数组的一个维度,它在某种意义上就被“用掉了”。

Pop Quiz: Let A be an array with shape int8[128, 2048], sharding A[IXY,J]A[I_{XY}, J], and mesh Mesh({'X': 2, 'Y': 8, 'Z': 2}) (so 32 devices total). How much memory does A use per device? How much total memory does A use across all devices?

小测验: 设 A 是一个形状为 int8[128, 2048] 的数组,分片为 A[IXY,J]A[I_{XY}, J],网格为 Mesh({'X': 2, 'Y': 8, 'Z': 2}) (总共 32 个设备). A 每个设备使用多少内存?A 在所有设备上总共使用多少内存?

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

Answer: Our array A is sharded over X and Y and replicated over Z, so per device it has shape int8[128 / (2 * 8), 2048] = int8[8, 2048], with size 8 * 2048 = 16,384 bytes. Because it’s replicated over Z, while within a Z-plane it’s fully sharded over X and Y, there are 2 complete copies of the original array (one per Z-plane). So the total size across all devices is: original array size × Z replicas = 128 * 2048 * 2 = 512 KiB total. Alternatively, we can verify this as: 32 devices × 16,384 bytes per device = 512 KiB total.

答案: 数组 A 沿 X、Y 轴分片,沿 Z 轴复制。每台设备持有的分片形状为 int8[128 / (2 * 8), 2048] = int8[8, 2048],大小为 8 * 2048 = 16,384 字节。由于阵列沿 Z 轴复制,而在每个 Z 平面内沿 X、Y 轴完整分片,原数组共有两个完整副本,每个 Z 平面一个。所有设备合计占用原数组大小 × Z 轴副本数,即 128 * 2048 * 2 = 512 KiB。也可以按 32 台设备 × 每台 16,384 字节 = 512 KiB 来核算。

How do we describe this in code?我们如何在代码中描述它?

So far we’ve avoided talking about code, but now is a good chance for a sneak peek. JAX uses a named sharding syntax that very closely matches the abstract syntax we describe above. We’ll talk more about this in Section 10, but here’s a quick preview. You can play with this in a Google Colab here and profile the result to see how JAX handles different shardings. This snippet does 3 things:

到目前为止,我们一直避免谈论代码,但现在是时候先睹为快了。JAX 使用一种与我们上面描述的抽象语法非常匹配的命名分片语法。我们将在第 10 节中更多地讨论这一点,但这里有一个快速预览。你可以在 Google Colab 这里中玩这个,并分析结果以查看 JAX 如何处理不同的分片。这个代码片段做了 3 件事:

  1. Creates a jax.Mesh that maps our 8 TPUs into a 4x2 grid with names ‘X’ and ‘Y’ assigned to the two axes.
  2. Creates matrices A and B where A is sharded along both its dimensions and B is sharded along the output dimension.
  3. Compiles and performs a simple matrix multiplication that returns a sharded array.
  1. 创建一个 jax.Mesh,将我们的 8 个 TPU 映射到一个 4x2 的网格中,并将名称‘X’和‘Y’分配给两个轴。
  2. 创建矩阵 A 和 B,其中 A 在其两个维度上都进行了分片,B 在输出维度上进行了分片。
  3. 编译并执行一个简单的矩阵乘法,返回一个分片数组。
import jax
import jax.numpy as jnp

# Create our mesh! We're running on a TPU v2-8 4x2 slice with names 'X' and 'Y'.
# The Auto axis type tells JAX to let the XLA compiler infer intermediate shardings.
assert len(jax.devices()) == 8
Auto = jax.sharding.AxisType.Auto
mesh = jax.make_mesh(axis_sizes=(4, 2), axis_names=('X', 'Y'), axis_types=(Auto, Auto))

# A little utility function to help define our sharding. A PartitionSpec is our
# sharding (a mapping from axes to names).
def P(*args):
  return jax.NamedSharding(mesh, jax.sharding.PartitionSpec(*args))

# We shard both A and B over the non-contracting dimension and A over the contracting dim.
A = jnp.zeros((8, 2048), dtype=jnp.bfloat16, device=P('X', 'Y'))
B = jnp.zeros((2048, 8192), dtype=jnp.bfloat16, device=P(None, 'Y'))

# We can perform a matmul on these sharded arrays! out_shardings tells us how we want
# the output to be sharded. JAX/XLA handles the rest of the sharding for us.
y = jax.jit(lambda A, B: jnp.einsum('BD,DF->BF', A, B), out_shardings=P('X', 'Y'))(A, B)

The cool thing about JAX is that these arrays behave as if they’re unsharded! B.shape will tell us the global or logical shape (2048, 8192). We have to actually look at B.addressable_shards to see how it’s locally sharded. We can perform operations on these arrays and JAX will attempt to figure out how to broadcast or reshape them to perform the operations. For instance, in the above example, the local shape of A is [2, 1024] and for B is [2048, 4096]. JAX/XLA will automatically add communication across these arrays as necessary to perform the final multiplication.

JAX 的酷之处在于这些数组的行为就像它们没有被分片一样!B.shape 会告诉我们全局或逻辑形状 (2048, 8192)。我们必须实际查看 B.addressable_shards 才能看到它是如何本地分片的。我们可以对这些数组执行操作,JAX 会尝试找出如何广播或重塑它们以执行操作。例如,在上面的例子中,A 的本地形状是 [2, 1024], B 的本地形状是 [2048, 4096]. JAX/XLA 会自动在这些数组之间添加必要的通信以执行最终的乘法。

Computation With Sharded Arrays使用分片数组进行计算

If you have an array of data that’s distributed across many devices and wish to perform mathematical operations on it, what are the overheads associated with sharding both the data and the computation?

如果你有一个分布在许多设备上的数据数组,并希望对其执行数学运算,那么对数据和计算进行分片会带来哪些开销?

Obviously, this depends on the computation involved.

显然,这取决于所涉及的计算。

  • For elementwise operations, there is no overhead for operating on a distributed array.
  • When we wish to perform operations across elements resident on many devices, things get complicated. Thankfully, for most machine learning nearly all computation takes place in the form of matrix multiplications, and they are relatively simple to analyze.
  • 对于逐元素操作,对分布式数组进行操作没有开销.
  • 当我们希望对驻留在许多设备上的元素执行操作时,事情就变得复杂了。值得庆幸的是,对于大多数机器学习来说,几乎所有的计算都以矩阵乘法的形式进行,而且它们相对容易分析。

The rest of this section will deal with how to multiply sharded matrices. To a first approximation, this involves moving chunks of a matrix around so you can fully multiply or sum each chunk. Each sharding will involve different communication. For example, A[IX,J]⋅B[J,KY]→C[IX,KY]A[I_X, J] \cdot B[J, K_Y] \to C[I_X, K_Y] can be multiplied without any communication because the contracting dimension (J, the one we’re actually summing over) is unsharded. However, if we wanted the output unsharded (i.e. A[IX,J]⋅B[J,KY]→C[I,K]A[I_X, J] \cdot B[J, K_Y] \to C[I, K]), we would either need to copy AA and BB or CC to every device (using an AllGather). These two choices have different communication costs, so we need to calculate this cost and pick the lowest one.

本节的其余部分将讨论如何乘以分片矩阵。初步来看,这涉及到移动矩阵的块,以便你可以完全乘以或求和每个块。每个分片都会涉及不同的通信。 例如,A[IX,J]⋅B[J,KY]→C[IX,KY]A[I_X, J] \cdot B[J, K_Y] \to C[I_X, K_Y] 可以在没有任何通信的情况下进行乘法,因为收缩维度 (J,我们实际求和的维度) 是未分片的。然而,如果我们希望输出是未分片的 (即 A[IX,J]⋅B[J,KY]→C[I,K]A[I_X, J] \cdot B[J, K_Y] \to C[I, K]),我们就需要将 AA 和 BB 一起复制到每台设备,或者将 CC 复制到每台设备 (使用 AllGather)。这两种选择有不同的通信成本,所以我们需要计算这个成本并选择最低的一个。

You can think of this in terms of "block matrix multiplication". 你可以从“块矩阵乘法”的角度来思考这个问题.

To understand this, it can be helpful to recall the concept of a “block matrix”, or a nested matrix of matrices:

为了理解这一点,回忆一下“块矩阵”的概念可能会有所帮助,即一个嵌套的矩阵的矩阵:

(a00a01a02a03a10a11a12a13a20a21a22a23a30a31a32a33)=([a00a01a10a11][a20a21a30a31][a02a03a12a13][a22a23a32a33])=(A00A01A10A11)\begin{equation} \begin{pmatrix} a_{00} & a_{01} & a_{02} & a_{03} \\ a_{10} & a_{11} & a_{12} & a_{13} \\ a_{20} & a_{21} & a_{22} & a_{23} \\ a_{30} & a_{31} & a_{32} & a_{33} \end{pmatrix} = \left( \begin{matrix} \begin{bmatrix} a_{00} & a_{01} \\ a_{10} & a_{11} \end{bmatrix} \\ \begin{bmatrix} a_{20} & a_{21} \\ a_{30} & a_{31} \end{bmatrix} \end{matrix} \begin{matrix} \begin{bmatrix} a_{02} & a_{03} \\ a_{12} & a_{13} \end{bmatrix} \\ \begin{bmatrix} a_{22} & a_{23} \\ a_{32} & a_{33} \end{bmatrix} \end{matrix} \right) = \begin{pmatrix} \mathbf{A_{00}} & \mathbf{A_{01}} \\ \mathbf{A_{10}} & \mathbf{A_{11}} \end{pmatrix} \end{equation}

Matrix multiplication has the nice property that when the matrix multiplicands are written in terms of blocks, the product can be written in terms of block matmuls following the standard rule:

矩阵乘法有一个很好的性质,即当矩阵乘数用块来表示时,乘积可以用块矩阵乘法来表示,遵循标准规则:

(A00A01A10A11)⋅(B00B01B10B11)=(A00B00+A01B10A00B01+A01B11A10B00+A11B10A10B01+A11B11)\begin{equation} \begin{pmatrix} A_{00} & A_{01} \\ A_{10} & A_{11} \end{pmatrix} \cdot \begin{pmatrix} B_{00} & B_{01} \\ B_{10} & B_{11} \end{pmatrix} = \begin{pmatrix} A_{00}B_{00} + A_{01}B_{10} & A_{00}B_{01} + A_{01}B_{11} \\ A_{10}B_{00} + A_{11}B_{10} & A_{10}B_{01} + A_{11}B_{11} \end{pmatrix} \end{equation}

What this means is that implementing distributed matrix multiplications reduces down to moving these sharded blocks over the network, performing local matrix multiplications on the blocks, and summing their results. The question then is what communication to add, and how expensive it is.

这意味着实现分布式矩阵乘法归结为在网络上移动这些分片块,对这些块执行本地矩阵乘法,并对它们的结果求和。那么问题是添加什么通信,以及它的成本是多少。

Conveniently, we can boil down all possible shardings into roughly 4 cases we need to consider, each of which has a rule for what communication we need to add

  1. Case 1: neither input is sharded along the contracting dimension. We can multiply local shards without any communication.
  2. Case 2: one input has a sharded contracting dimension. We typically “AllGather” the sharded input along the contracting dimension.
  3. Case 3: both inputs are sharded along the contracting dimension. We can multiply the local shards, then “AllReduce” the result.
  4. Case 4: both inputs have a non-contracting dimension sharded along the same axis. We cannot proceed without AllGathering one of the two inputs first.

方便的是,我们可以将所有可能的分片归结为大约 4 种需要考虑的情况,每种情况都有一个规则,说明我们需要添加什么通信

  1. 情况 1: 两个输入都没有在收缩维度上进行分片。我们可以对本地分片进行乘法,无需任何通信。
  2. 情况 2: 一个输入在收缩维度上进行了分片。我们通常对收缩维度上的分片输入进行“AllGather”。
  3. 情况 3: 两个输入都在收缩维度上进行了分片。我们可以对本地分片进行乘法,然后对结果进行“AllReduce”。
  4. 情况 4: 两个输入都在同一轴上对非收缩维度进行了分片。我们无法在不先对其中一个输入进行 AllGather 的情况下继续。

You can think of these as rules that simply need to be followed, but it’s also valuable to understand why these rules hold and how expensive they are. We’ll go through each one of these in detail now.

你可以将这些视为只需要遵循的规则,但理解这些规则为什么成立以及它们的成本是多少也很有价值。我们现在将详细介绍每一个。

Case 1: neither multiplicand has a sharded contracting dimension情况 1:两个乘数都没有分片的收缩维度

Lemma: when multiplying sharded matrices, the computation is valid and the output follows the sharding of the inputs unless the contracting dimension is sharded or both matrices are sharded along the same axis. For example, this works fine

引理: 当乘以分片矩阵时,计算是有效的,并且输出遵循输入的分片,除非收缩维度被分片或两个矩阵都沿同一轴分片。例如,这可以正常工作

A[IX,J]⋅B[J,KY]→C[IX,KY]\begin{equation*} \mathbf{A}[I_X, J] \cdot \mathbf{B}[J, K_Y] \rightarrow \mathbf{C}[I_X, K_Y] \end{equation*}

with no communication whatsoever, and results in a tensor sharded across both the X and Y hardware dimensions. Try to think about why this is. Basically, the computation is independent of the sharding, since each batch entry has some local chunk of the axis being contracted that it can multiply and reduce. Any of these cases work fine and follow this rule:

没有任何通信,并且得到一个跨 X 和 Y 硬件维度分片的张量。试着想想为什么会这样。基本上,计算与分片无关,因为每个批处理条目都有一些本地的收缩轴块,它可以乘以和归约。任何这些情况都可以正常工作,并遵循这个规则:

A[I,J]⋅B[J,K]→ C[I,K]A[IX,J]⋅B[J,K]→ C[IX,K]A[I,J]⋅B[J,KY]→ C[I,KY]A[IX,J]⋅B[J,KY]→ C[IX,KY]\begin{align*} \mathbf{A}[I, J] \cdot \mathbf{B}[J, K] \rightarrow &\ \mathbf{C}[I, K] \\ \mathbf{A}[I_X, J] \cdot \mathbf{B}[J, K] \rightarrow &\ \mathbf{C}[I_X, K]\\ \mathbf{A}[I, J] \cdot \mathbf{B}[J, K_Y] \rightarrow &\ \mathbf{C}[I, K_Y]\\ \mathbf{A}[I_X, J] \cdot \mathbf{B}[J, K_Y] \rightarrow &\ \mathbf{C}[I_X, K_Y] \end{align*}

Because neither A nor B has a sharded contracting dimension J, we can simply perform the local block matrix multiplies of the inputs and the results will already be sharded according to the desired output shardings. When both multiplicands have non-contracting dimensions sharded along the same axis, this is no longer true (see the invalid shardings section for details).

因为 A 和 B 都没有分片的收缩维度 J,我们可以简单地执行输入的本地块矩阵乘法,结果将已经根据所需的输出分片进行了分片。当两个乘数都有沿同一轴分片的非收缩维度时,这不再成立 (有关详细信息,请参见无效分片部分).

Case 2: one multiplicand has a sharded contracting dimension情况 2:一个乘数有分片的收缩维度

Let’s consider what to do when one input A is sharded along the contracting J dimension and B is fully replicated:

让我们考虑当一个输入 A 沿收缩 J 维度分片,而 B 完全复制时该怎么做:

A[I,JX]⋅B[J,K]→C[I,K]\mathbf{A}[I, J_X] \cdot \mathbf{B}[J, K] \rightarrow \mathbf{C}[I, K]

We cannot simply multiply the local chunks of A and B because we need to sum over the full contracting dimension of A, which is split across the X axis. Typically, we first “AllGather” the shards of A so every device has a full copy, and only then multiply against B:

我们不能简单地将 A 和 B 的本地块相乘,因为我们需要对 A 的完整收缩维度求和,该维度分布在 X 轴上。通常,我们首先“AllGather” A 的分片,以便每个设备都有一个完整的副本,然后才与 B 相乘:

AllGatherX[I,JX]→A[I,J]\textbf{AllGather}_X[I, J_X] \rightarrow \mathbf{A}[I, J] A[I,J]⋅B[J,K]→C[I,K]\mathbf{A}[I, J] \cdot \mathbf{B}[J, K] \rightarrow \mathbf{C}[I, K]

This way the actual multiplication can be done fully on each device.

这样,实际的乘法就可以在每个设备上完全完成。

Note that when B is not also sharded along X, we could also do the local partial matmul and then sum (or AllReduce) the sharded partial sums, which lets us shard the compute but usually has a higher communication cost. This can be faster in some cases, although it’s usually true in practice that B will be sharded. Question 4 below works through when this is better.

如果 B 沿 X 轴未分片,还可以先在本地计算部分矩阵乘积,再对各分片的部分和做求和(AllReduce)。这样可以将计算分片,但通信成本通常更高。某些情况下更快,但实际通常也会对 B 分片。下方的问题 4分析了这一方案在什么条件下更有利。

What is an AllGather? An AllGather is the first core MPI communication primitive we will discuss. An AllGather removes the sharding along an axis and reassembles the shards spread across devices onto each device along that axis. Using the notation above, an AllGather removes a subscript from a set of axes, e.g.

什么是 AllGather? AllGather 是我们将要讨论的第一个核心 MPI 通信原语。AllGather 移除沿一个轴的分片,并将分布在设备上的分片重新组装到该轴上的每个设备上。使用上面的符号,AllGather 从一组轴中移除一个下标,例如

AllGatherXY(A[IXY,J])→A[I,J]\textbf{AllGather}_{XY}(A[I_{XY}, J]) \rightarrow A[I, J]

We don’t have to remove all subscripts for a given dimension, e.g. A[IXY,J]→A[IY,J]A[I_{XY}, J] \rightarrow A[I_Y, J] is also an AllGather, just over only a single axis. Also note that we may also wish to use an AllGather to remove non-contracting dimension sharding, for instance in the matrix multiply:

我们不必移除给定维度的所有下标,例如 A[IXY,J]→A[IY,J]A[I_{XY}, J] \rightarrow A[I_Y, J] 也是一个 AllGather,只是只在一个轴上进行。另请注意,我们也可能希望使用 AllGather 来移除非收缩维度分片,例如在矩阵乘法中:

A[IX,J]⋅B[J,K]→C[I,K]A[I_X, J] \cdot B[J, K] \rightarrow C[I, K]

We could either AllGather A initially to remove the input sharding, or we can do the sharded matmul and then AllGather the result C.

我们可以先对 A 进行 AllGather 以移除输入分片,或者我们可以进行分片矩阵乘法,然后对结果 C 进行 AllGather.

How is an AllGather actually performed? To perform a 1-dimensional AllGather around a single TPU axis (a ring), we basically have each TPU pass its shard around a ring until every device has a copy.2 Here is an animation:

AllGather 实际上是如何执行的? 为了在一个 TPU 轴 (一个环) 周围执行一维 AllGather,我们基本上让每个 TPU 将其分片在一个环周围传递,直到每个设备都有一个副本。2 这是一个动画:

all gather

Figure: An animation showing how to perform an AllGather around a set of 8 TPU or GPU devices. Each device starts with 1 / 8th of the array and ends up with a full copy.

图: 一个动画, 显示了如何在一组 8 个 TPU 或 GPU 设备周围执行 AllGather. 每个设备开始时拥有数组的 1/8, 结束时拥有一个完整的副本.

We can either do an AllGather in one direction or both directions (two directions are shown above). If we do one direction, each TPU sends chunks of size bytes/N\text{bytes} / N over N−1N - 1 hops around the ring. If we do two directions, we have ⌊N2⌋\lfloor \frac{N}{2} \rfloor hops of size 2⋅bytes/N2 \cdot \text{bytes} / N.

我们可以单向或双向进行 AllGather (上图显示了双向)。如果我们单向进行,每个 TPU 会在环周围发送大小为 bytes/N\text{bytes} / N 的块,共 N−1N - 1 次跳跃。如果我们双向进行,我们有 ⌊N2⌋\lfloor \frac{N}{2} \rfloor 次跳跃,大小为 2⋅bytes/N2 \cdot \text{bytes} / N.

How long does this take? Let’s take the bidirectional AllGather and calculate how long it takes. Let VV be the number of bytes in the array, and XX be the number of shards on the contracting dimension. Then from the above diagram, each hop sends V/∣X∣V / \lvert X\rvert bytes in each direction, so each hop takes

这需要多长时间? 让我们以双向 AllGather 为例,计算它需要多长时间。设 VV 为数组中的字节数,XX 为收缩维度上的分片数。那么从上图中,每个跳跃在每个方向上发送 V/∣X∣V / \lvert X\rvert 字节,所以每个跳跃需要

Thop=2⋅V∣X∣⋅WiciT_{hop} = \frac{2 \cdot V}{\lvert X \rvert \cdot W_\text{ici}}

where WiciW_\text{ici} is the bidirectional ICI bandwidth.3 We need to send a total of ∣X∣/2\lvert X\rvert / 2 hops to reach every TPU4, so the total reduction takes

其中 WiciW_\text{ici} 是双向 ICI 带宽。3 我们需要发送总共 ∣X∣/2\lvert X\rvert / 2 次跳跃才能到达每个 TPU4,所以总的归约需要

Ttotal=2⋅V⋅X2⋅X⋅WiciT_{total} = \frac{2 \cdot V \cdot X}{2 \cdot X \cdot W_\text{ici}} Ttotal=VWiciT_{total} = \frac{V}{W_\text{ici}}

Note that this doesn’t depend on XX! That’s kind of striking, because it means even though our TPUs are only locally connected, the locality of the connections doesn’t matter. We’re just bottlenecked by the speed of each link.

请注意,这不依赖于 XX! 这有点惊人,因为这意味着即使我们的 TPU 只是本地连接的,连接的局部性也不重要。我们只是受每个链接速度的瓶颈。

A note on ICI latency: Each hop over an ICI link has some intrinsic overhead regardless of the data volume. This is typically around 1us. This means when our array AA is very small and each hop takes less than 1us, we can enter a “latency-bound” regime where the calculation does depend on XX.

关于 ICI 延迟的说明: 无论数据量大小,每个 ICI 链接上的每次跳跃都有一些固有的开销。这通常在 1us 左右。这意味着当我们的数组 AA 非常小并且每次跳跃的时间少于 1us 时,我们可以进入一个“受延迟限制”的状态,此时计算确实依赖于 XX.

For the full details, click here. 有关完整详细信息, 请单击此处.

Let TminT_\text{min} be the minimum time for a single hop. Then

设 TminT_\text{min} 为单次跳跃的最小时间。那么

Thop=max⁡[Tmin,2⋅VX⋅Wici]T_{hop} = \max \left[ T_{min}, \frac{2 \cdot V}{X \cdot W_\text{ici}} \right] Ttotal=max⁡[Tmin⋅X2,VWici]T_{total} = \max \left[ \frac{T_{min} \cdot X}{2}, \frac{V}{W_\text{ici}} \right]

since we perform X/2X / 2 hops. For large reductions or gathers, we’re solidly bandwidth bound. We’re sending so much data that the overhead of each hop is essentially negligible. But for small arrays (e.g. when sampling from a model), this isn’t negligible, and the ICI bandwidth isn’t relevant. We’re bound purely by latency. Another way to put this is that given a particular TPU, e.g. TPU v5e with 4.5e10 unidirectional ICI bandwidth, sending any buffer under 4.5e10 * 1e-6 = 45kB will be latency bound.

因为我们执行 X/2X / 2 次跳跃。对于大型归约或收集,我们完全受带宽限制。我们发送的数据量如此之大,以至于每次跳跃的开销基本上可以忽略不计。但对于小数组 (例如,从模型中采样时),这不可忽略,ICI 带宽也不相关。我们完全受延迟限制。另一种说法是,给定一个特定的 TPU,例如具有 4.5e10 单向 ICI 带宽的 TPU v5e,发送任何小于 4.5e10 * 1e-6 = 45kB 的缓冲区都将受延迟限制。

Here is an empirical measurement of AllGather bandwidth on a TPU v5e 8x16 slice. The array is sharded across the 16 axis so it has a full bidirectional ring.

这是一个在 TPU v5e 8x16 切片上 AllGather 带宽的实证测量。数组在 16 轴上分片,因此它有一个完整的双向环。

all gather bandwidth

Figure: empirical bandwidth and estimated link bandwidth for TPU v5e during an AllGather. BW in orange is the actual bytes per second AllGathered, while the blue curve shows the empirical unidirectional link bandwidth calculated according to the known cost of the collective.

图: 在 AllGather 期间, TPU v5e 的实证带宽和估计链接带宽. 橙色的 BW 是每秒实际 AllGather 的字节数, 而蓝色曲线显示了根据集合的已知成本计算的实证单向链接带宽.

Note that we not only achieve about 95% of the peak claimed bandwidth (4.5e10) but also that we achieve this peak at about 10MB, which when 16-way sharded gives us about 625kB per device (aside: this is much better than GPUs).

请注意,我们达到了标称峰值带宽 (4.5e10) 的约 95%,并且我们在约 10MB 时达到了这个峰值,当 16 路分片时,每个设备约 625kB (旁注:这比 GPU 好得多).

What happens when we AllGather over multiple axes? When we gather over multiple axes, we have multiple dimensions of ICI over which to perform the gather. For instance, AllGatherXY([B, DXY]) operates over two hardware mesh axes. This increases the available bandwidth by a factor of NaxesN_\text{axes}.

当我们跨多个轴进行 AllGather 时会发生什么? 当我们跨多个轴进行收集时,我们有多个 ICI 维度可以进行收集。例如,AllGatherXY([B, DXY]) 在两个硬件网格轴上操作。这将可用带宽增加了 NaxesN_\text{axes} 倍。

When considering latency, we end up with the general rule:

计入延迟后,可得通用公式:

Ttotal=max⁡[Tmin⋅∑i∣Xi∣2,VWici⋅Naxes]T_{total} = \max \left[ \frac{T_{min} \cdot \sum_{i} |X_i|}{2}, \frac{V}{W_\text{ici} \cdot N_\text{axes}} \right]

where ∑i∣Xi∣/2\sum_i \lvert X_i \rvert / 2 is the length of the longest path in the TPU mesh.

其中 ∑i∣Xi∣/2\sum_i \lvert X_i \rvert / 2 是 TPU 网格中最长路径的长度。

Pop Quiz 2 [AllGather time]: Using the numbers from Part 2, how long does it take to perform the AllGatherY([EY, F]) → [E, F] on a TPU v5e with a 2D mesh {'X': 8, 'Y': 4}, E=2048E = 2048, F=8192F = 8192 in bfloat16? What about with E=256,F=256E=256, F=256?

小测验 2 [AllGather 时间]: 使用第 2 部分中的数字,在具有 2D 网格 {'X': 8, 'Y': 4} 的 TPU v5e 上执行 AllGatherY([EY, F]) → [E, F] 需要多长时间,其中 E=2048E = 2048, F=8192F = 8192 (bfloat16)?如果 E=256,F=256E=256, F=256 呢?

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

Answer: Let’s start by calculating some basic quantities:

答案: 让我们从计算一些基本量开始:

  1. TPU v5e has 4.5e10 bytes/s of unidirectional ICI bandwidth for each of its 2 axes.
  2. In bfloat16 for (a), we have A[EY,F]A[E_Y, F] so each device holds an array of shape bf16[512, 8192] which has 512 * 8192 * 2 = 8.4MB. The total array has size 2048 * 8192 * 2 = 34MB.
  1. TPU v5e 的每个轴都有 4.5e10 字节/秒的单向 ICI 带宽。
  2. 在 bfloat16 中,对于 (a),我们有 A[EY,F]A[E_Y, F],所以每个设备持有一个形状为 bf16[512, 8192] 的数组,大小为 512 * 8192 * 2 = 8.4MB。总数组大小为 2048 * 8192 * 2 = 34MB.

For part (1), we can use the formula above. Since we’re performing the AllGather over one axis, we have Tcomms=34e6/9e10=377usT_{\text{comms}} = \text{34e6} / \text{9e10} = \text{377us}. To check that we’re not latency-bound, we know over an axis of size 4, we’ll have at most 3 hops, so our latency bound is something like 3us, so we’re not close. However, TPU v5e only has a wraparound connection when one axis has size 16, so here we actually can’t do a fully bidirectional AllGather. We have to do 3 hops for data from the edges to reach the other edge, so in theory we have more like Tcomms=3∗8.4e6/4.5e10=560μsT_{\text{comms}} = 3 * \text{8.4e6} / \text{4.5e10} = 560\mu s. Here’s an actual profile from this Colab, which shows 680μs680 \mu s, which is reasonable since we’re likely not getting 100% of the theoretical bandwidth! For part (2) each shard has size 64 * 256 * 2 = 32kB. 32e3 / 4.5e10 = 0.7us, so we’re latency bound. Since we have 3 hops, this will take roughly 3 * 1us = 3us. In practice, it’s closer to 8us.

对于第 (1) 部分,我们可以使用上面的公式。由于我们是在一个轴上执行 AllGather,我们有 Tcomms=34e6/9e10=377usT_{\text{comms}} = \text{34e6} / \text{9e10} = \text{377us}。为了检查我们是否不受延迟限制,我们知道在一个大小为 4 的轴上,我们最多有 3 次跳跃,所以我们的延迟限制大约是 3us,所以我们离得不近。然而,TPU v5e 只有在一个轴的大小为 16 时才有环绕连接,所以在这里我们实际上无法进行完全双向的 AllGather。我们需要 3 次跳跃才能让数据从边缘到达另一边,所以理论上我们更像是 Tcomms=3∗8.4e6/4.5e10=560μsT_{\text{comms}} = 3 * \text{8.4e6} / \text{4.5e10} = 560\mu s. 这里 是来自这个 Colab 的实际性能剖析结果,显示为 680μs680 \mu s,这是合理的,因为我们可能没有获得 100% 的理论带宽!对于第 (2) 部分,每个分片的大小为 64 * 256 * 2 = 32kB. 32e3 / 4.5e10 = 0.7us,所以我们受延迟限制。由于我们有 3 次跳跃,这大约需要 3 * 1us = 3us. 在实践中,它更接近 8us.

Case 3: both multiplicands have sharded contracting dimensions情况 3:两个乘数都有分片的收缩维度

The third fundamental case is when both multiplicands are sharded on their contracting dimensions, along the same mesh axis:

第三种基本情况是当两个乘数都在它们的收缩维度上分片,并且沿同一网格轴:

A[I,JX]⋅B[JX,K]→C[I,K]\textbf{A}[I, J_X] \cdot \textbf{B}[J_X, K] \rightarrow C[I, K]

In this case the local sharded block matrix multiplies are at least possible to perform, since they will share the same sets of contracting indices. But each product will only represent a partial sum of the full desired product, and each device along the X dimension will be left with different partial sums of this final desired product. This is so common that we extend our notation to explicitly mark this condition:

在这种情况下,本地分片块矩阵乘法至少是可能执行的,因为它们将共享相同的收缩索引集。但是每个乘积只代表最终期望乘积的部分和,并且沿 X 维度的每个设备将剩下这个最终期望乘积的不同部分和。这种情况非常普遍,以至于我们扩展了我们的符号来明确标记这种情况:

A[I,JX]⋅LOCALB[JX,K]→C[I,K]{ UX}\textbf{A}[I, J_X] \cdot_\text{LOCAL} \textbf{B}[J_X, K] \rightarrow C[I, K] \{\ U_X \}

The notation { UX } reads “unreduced along X mesh axis” and refers to this status of the operation being “incomplete” in a sense, in that it will only be finished pending a final sum. The ⋅LOCAL\cdot_\text{LOCAL} syntax means we perform the local sum but leave the result unreduced.

符号 { UX } 读作“沿 X 网格轴未归约”,指的是该操作在某种意义上是“未完成”的状态,因为它只有在最终求和后才算完成。⋅LOCAL\cdot_\text{LOCAL} 语法意味着我们执行本地求和,但将结果保持未归约状态。

This can be seen as the following result about matrix multiplications and outer products:

这可以看作是关于矩阵乘法和外积的以下结果:

A⋅B=∑i=1PA:,i⊗Bi,:⏟∈Rn×mA \cdot B = \sum_{i=1}^{P} \underbrace{A_{:,i} \otimes B_{i,:}}_{\in \mathbb{R}^{n \times m}}

where ⊗ is the outer product. Thus, if TPU i on axis X has the ith column of A, and the ith row of B, we can do a local matrix multiplication to obtain A:,i⊗Bi,:∈Rn×mA_{:,i} \otimes B_{i,:} \in \mathbb{R}_{n\times m}. This matrix has, in each entry, the ith term of the sum that A • B has at that entry. We still need to perform that sum over P, which we sharded over mesh axis X, to obtain the full A • B. This works the same way if we write A and B by blocks (i.e. shards), and then sum over each resulting shard of the result.

其中 ⊗ 是外积。因此,如果轴 X 上的 TPU i 具有 A 的第 i 列和 B 的第 i 行,我们可以进行本地矩阵乘法以获得 A:,i⊗Bi,:∈Rn×mA_{:,i} \otimes B_{i,:} \in \mathbb{R}_{n\times m}。这个矩阵的每个条目都包含 A • B 在该条目处的和的第 i 项。我们仍然需要对 P 进行求和,我们在网格轴 X 上对其进行了分片,以获得完整的 A • B。如果我们按块 (即分片) 写出 A 和 B,然后对结果的每个分片求和,这种方式同样有效。

We can perform this summation using a full AllReduce across the X axis to remedy this:

我们可以使用跨 X 轴的完整 AllReduce 来解决这个问题:

A[I,JX]⋅LOCALB[JX,K]→ C[I,K]{UX}AllReduceXC[I,K]{UX}→ C[I,K]\begin{align*} A[I, J_X] \cdot_\text{LOCAL} B[J_X, K] \rightarrow &\ C[I, K] \{ U_X \} \\ \textbf{AllReduce}_X C[I, K] \{ U_X \} \rightarrow &\ C[I, K] \end{align*}

AllReduce removes partial sums, resulting in each device along the axis having the same fully-summed value. AllReduce is the second of several key communications we’ll discuss in this section, the first being the AllGather, and the others being ReduceScatter and AllToAll. An AllReduce takes an array with an unreduced (partially summed) axis and performs the sum by passing those shards around the unreduced axis and accumulating the result. The signature is

AllReduce 移除部分和,导致沿该轴的每个设备都具有相同的完全求和的值。AllReduce 是我们将在本节中讨论的几个关键通信中的第二个,第一个是 AllGather,其他是 ReduceScatter 和 AllToAll. AllReduce 接受一个具有未归约 (部分求和) 轴的数组,并通过在该未归约轴周围传递这些分片并累积结果来执行求和。签名为

AllReduceYA[IX,J]{UY}→A[IX,J]\textbf{AllReduce}_Y A[I_X, J] \{U_Y\} \rightarrow A[I_X, J]

This means it simply removes the {UY}\{U_Y\} suffix but otherwise leaves the result unchanged.

这意味着它只是移除了 {UY}\{U_Y\} 后缀,但在其他方面保持结果不变。

How expensive is an AllReduce? One mental model for how an AllReduce is performed is that every device sends its shard to its neighbors, and sums up all the shards that it receives. Clearly, this is more expensive than an AllGather because each “shard” has the same shape as the full array. Generally, an AllReduce is twice as expensive as an AllGather. One way to see this is to note that an AllReduce can be expressed as a composition of two other primitives: a ReduceScatter and an AllGather. Like an AllReduce, a ReduceScatter resolves partial sums on an array but results in an output ‘scattered’ or partitioned along a given dimension. AllGather collects all those pieces and ‘unpartitions/unshards/replicates’ the logical axis along that physical axis.

AllReduce 的成本是多少? 一个关于 AllReduce 如何执行的心智模型是,每个设备都将其分片发送给其邻居,并将接收到的所有分片相加。显然,这比 AllGather 更昂贵,因为每个“分片”都与完整数组具有相同的形状。通常,AllReduce 的成本是 AllGather 的两倍。 一种看待这个问题的方式是注意到 AllReduce 可以表示为另外两个原语的组合:一个 ReduceScatter 和一个 AllGather。与 AllReduce 一样,ReduceScatter 解析数组上的部分和,但结果是沿给定维度“分散”或分区的输出。AllGather 收集所有这些片段,并沿该物理轴“取消分区/取消分片/复制”逻辑轴。

ReduceScatterY,J:A[IX,J]{UY}→ A[IX,JY]AllGatherY:A[IX,JY]→ A[IX,J]\begin{align*} \textbf{ReduceScatter}_{Y,J} : A[I_X,J] \{U_Y\} \rightarrow &\ A[I_X, J_Y] \\ \textbf{AllGather}_Y : A[I_X, J_Y] \rightarrow &\ A[I_X, J] \end{align*}

What about a ReduceScatter? Just as the AllGather reassembles a sharded array (removing a subscript), a ReduceScatter sums an unreduced/partially summed array and then scatters (shards) a different logical axis along the same mesh axis. X[F]{UY}→X[FY]X[F]\{U_Y\} \to X[F_Y]. The animation shows how this is done: note that it’s very similar to an AllGather but instead of retaining each shard, we sum them together. Thus, its latency is roughly the same, excluding the time taken to perform the reduction.

ReduceScatter 呢? AllGather 会把分片数组重新组装起来(移除一个下标),而 ReduceScatter 则对未归约的部分和求和,再沿同一网格轴对另一个逻辑轴进行分片:X[F]{UY}→X[FY]X[F]\{U_Y\} \to X[F_Y]。下方动画展示了这一过程。它和 AllGather 很接近,但收到的分片会相加,而不是分别保留。除去归约运算本身的耗时,两者的延迟大致相同。

reduce scatter

The communication time for each hop is simply the per-shard bytes V/YV / Y divided by the bandwidth WiciW_\text{ici}, as it was for an AllGather, so we have

每个跳跃的通信时间就是每个分片的字节数 V/YV / Y 除以带宽 WiciW_\text{ici},就像 AllGather 一样,所以我们有

Tcomms per AllGather or ReduceScatter=VWiciT_{\text{comms per AllGather or ReduceScatter}} = \frac{V}{W_\text{ici}} Tcomms per AllReduce=2⋅VWiciT_{\text{comms per AllReduce}} = 2 \cdot \frac{V}{W_\text{ici}}

where WiciW_\text{ici} is the bidirectional bandwidth, so long as we have a full ring to reduce over.

其中 WiciW_\text{ici} 是双向带宽,只要我们有一个完整的环可以进行归约。

Case 4: both multiplicands have a non-contracting dimension sharded along the same axis情况 4:两个乘数都有一个非收缩维度沿同一轴分片

Each mesh dimension can appear at most once when sharding a tensor. Performing the above rules can sometimes lead to a situation where this rule is violated, such as:

每个网格维度在对张量进行分片时最多只能出现一次。执行上述规则有时会导致违反此规则的情况,例如:

A[IX,J]⋅B[J,KX]→C[IX,KX]A[I_X, J] \cdot B[J, K_X] \rightarrow C[I_X, K_X]

This is invalid because a given shard, say i, along dimension X, would have the **(i, i)**th shard of C, that is, a diagonal entry. There is not enough information among all shards, then, to recover anything but the diagonal entries of the result, so we cannot allow this sharding.

这是无效的,因为沿维度 X 的给定分片,比如说 i,将具有 C 的 (i, i) 分片,即一个对角线条目。那么,在所有分片中没有足够的信息来恢复除对角线条目之外的任何内容,所以我们不能允许这种分片。

The way to resolve this is to AllGather some of the dimensions. Here we have two choices:

解决这个问题的方法是对某些维度进行 AllGather。在这里我们有两个选择:

AllGatherXA[IX,J]→ A[I,J]A[I,J]⋅B[J,KX]→ C[I,KX]\begin{align*} \textbf{AllGather}_X A[I_X, J] \rightarrow &\ A[I, J] \\ A[I, J] \cdot B[J, K_X] \rightarrow &\ C[I, K_X] \end{align*}

or

或

AllGatherXB[J,KX]→ B[J,K]A[IX,J]⋅B[J,K]→ C[IX,K]\begin{align*} \textbf{AllGather}_X B[J, K_X] \rightarrow &\ B[J, K] \\ A[I_X, J] \cdot B[J, K] \rightarrow &\ C[I_X, K] \end{align*}

In either case, the result will only mention X once in its shape. Which one we pick will be based on what sharding the following operations need.

在任何一种情况下,结果在其形状中只会提到 X 一次。我们选择哪一个将取决于后续操作需要什么样的分片。

A Deeper Dive into TPU Communication Primitives深入了解 TPU 通信原语

The previous 4 cases have introduced several “core communication primitives” used to perform sharded matrix multiplications:

前面的 4 种情况介绍了几种用于执行分片矩阵乘法的“核心通信原语”:

  1. AllGather: removes a subscript from a sharding, gathering the shards.
  2. ReduceScatter: removes an “un-reduced” suffix from an array by summing shards over that axis, leaving the array sharded over a second axis.
  3. AllReduce: removes an “un-reduced” suffix, leaving the array unsharded along that axis.
  1. AllGather: 从分片中移除一个下标,收集分片。
  2. ReduceScatter: 通过在该轴上对分片求和来移除数组的“未归约”后缀,使数组在第二个轴上分片。
  3. AllReduce: 移除一个“未归约”后缀,使数组在该轴上未分片。

There’s one more core communication primitive to mention that arises in the case of Mixture of Experts (MoE) models and other computations: the AllToAll.

还有一种核心通信原语需要提及,它出现在专家混合 (MoE) 模型和其他计算中:AllToAll.

Our final communication primitive: the AllToAll我们最后的通信原语:AllToAll

A final fundamental collective which does not occur naturally when considering sharded matrix multiplies, but which comes up constantly in practice, is the AllToAll collective, or more precisely the special case of a sharded transposition or resharding operation. e.g.

最后一个基本的集合通信,在考虑分片矩阵乘法时不会自然出现,但在实践中经常出现,是 AllToAll 集合,或者更准确地说,是分片转置或重分片操作的特殊情况。例如

AllToAllX,JA[IX,J]→A[I,JX]\textbf{AllToAll}_{X, J} A[I_X, J] \rightarrow A[I, J_X]

AllToAlls are typically required to rearrange sharded layouts between different regions of a sharded computation that don’t have compatible layout schemes. They arise naturally when considering sharded mixture-of-experts models. You can think of an AllToAll as moving a subscript from one axis to another. Because an all to all doesn’t need to replicate all of the data of each shard across the ring, it’s actually cheaper than an AllGather (by a factor of ¼)5.

AllToAll 通常需要重新排列分片计算的不同区域之间的分片布局,这些区域没有兼容的布局方案。在考虑分片专家混合模型时,它们会自然出现。你可以将 AllToAll 视为将一个下标从一个轴移动到另一个轴。因为 all to all 不需要复制每个分片的所有数据到环上,它实际上成本只有 AllGather 的四分之一5.

all to all

If we generalize to an ND AllToAll, the overall cost for an array of VV total bytes (summed across all devices) on an AxBxC mesh is

如果将 AllToAll 推广到 N 维网格,那么在 A×B×C 网上,对各设备合计占用 VV 字节的数组执行 AllToAll,总成本为

Tcomms per AllToAll=V⋅max⁡(A,B,C,...)4⋅N⋅WiciT_\text{comms per AllToAll} = \frac{V \cdot \max(A, B, C, ...)}{4 \cdot N \cdot W_\text{ici}}

where as usual WiciW_\text{ici} is the bidirectional ICI bandwidth and N=A⋅B⋅C⋅…N = A \cdot B \cdot C \cdot \ldots is the total number of devices. Equivalently, in terms of the per-device bytes V/NV / N, the cost is (V/N)⋅max⁡(A,B,C,...)/(4⋅Wici)(V / N) \cdot \max(A, B, C, ...) / (4 \cdot W_\text{ici}). For a 1D mesh, this reduces to V/(4⋅Wici)V / (4 \cdot W_\text{ici}), which is 1 / 4 the cost of an AllGather. In 2D, the cost actually scales down with the size of the smallest axis.

与前文一样,WiciW_\text{ici} 是双向 ICI 带宽,N=A⋅B⋅C⋅…N = A \cdot B \cdot C \cdot \ldots 是设备总数。换用每台设备上的字节数 V/NV / N,成本为 (V/N)⋅max⁡(A,B,C,...)/(4⋅Wici)(V / N) \cdot \max(A, B, C, ...) / (4 \cdot W_\text{ici})。对于一维网格,公式化简为 V/(4⋅Wici)V / (4 \cdot W_\text{ici}),即 AllGather 成本的四分之一。在二维网格上,最短轴越长,成本越低。

Aside: If you want a hand-wavy derivation of this fact, start with a 1D torus Z/NZ\mathbb{Z} / N\mathbb{Z}. If we pick a source and target node at random, they are on average N / 4 hops from each other, giving us a cost of (V⋅N)/(4∗N)(V \cdot N) / (4 * N). Now if we consider an ND torus, each axis is basically independent. Each node has 1/N1 / N bytes and on average has to hop its data max⁡(A,B,C,…)/4\max(A, B, C, …) / 4 hops. You can also derive this from bisection bandwidth: in an AllToAll, each half of the mesh sends half its data (V/4V / 4 bytes) to the other half. The narrowest bisection cuts perpendicular to the longest axis, crossing 2⋅N/max⁡(A,B,…)2 \cdot N / \max(A, B, …) links (two cut planes, counting wraparound), for a one-directional bandwidth of N⋅Wici/max⁡(A,B,…)N \cdot W_\text{ici} / \max(A, B, …). Dividing gives the formula above.

旁注:可以从一维环面 Z/NZ\mathbb{Z} / N\mathbb{Z} 出发粗略推导这一结论。随机选取一个源节点和一个目标节点,平均距离是 N / 4 跳,因此成本为 (V⋅N)/(4∗N)(V \cdot N) / (4 * N)。推广到 N 维环面,各轴基本相互独立。每个节点持有 1/N1 / N 的字节,数据平均需传输 max⁡(A,B,C,…)/4\max(A, B, C, …) / 4 跳。也可以通过二分带宽来推导。执行 AllToAll 时,网格每半边都要把自己的一半数据(V/4V / 4 字节)发给另一边。二分带宽最小时,切面垂直于最长轴,切断 2⋅N/max⁡(A,B,…)2 \cdot N / \max(A, B, …) 条链路(计入回绕连接,共有两个切面),单向带宽为 N⋅Wici/max⁡(A,B,…)N \cdot W_\text{ici} / \max(A, B, …)。将数据量除以带宽,就得到上面的公式。

More about the ReduceScatter关于 ReduceScatter 的更多信息

ReduceScatter is a more fundamental operation than it first appears, as it is actually the derivative of an AllGather, and vice versa. i.e. if in the forward pass we have:

ReduceScatter 是一个比它最初看起来更基本的操作,因为它实际上是 AllGather 的导数,反之亦然。即,如果在前向传播中我们有:

AllGatherXA[IX]→A[I]\textbf{AllGather}_X A[I_X] \rightarrow A[I]

Then we ReduceScatter the reverse-mode derivatives A’ (which will in general be different on each shard) to derive the sharded A’:

然后我们对反向模式导数 A’ (通常在每个分片上都不同) 进行 ReduceScatter,以推导出分片的 A’:

ReduceScatterXA′[I]{UX}→A′[IX]\textbf{ReduceScatter}_X A'[I] \{ U_X \} \rightarrow A'[I_X]

Likewise, ReduceScatterX(A[I]{UX})→A[IX]\text{ReduceScatter}_X(A[I] \{U_X\}) \to A[I_X] in the forward pass implies AllGatherX(A′[IX])→A′[I]\text{AllGather}_{X}(A'[I_X]) \to A'[I] in the backwards pass.

同样,在前向传播中 ReduceScatterX(A[I]{UX})→A[IX]\text{ReduceScatter}_X(A[I] \{U_X\}) \to A[I_X] 意味着在后向传播中 AllGatherX(A′[IX])→A′[I]\text{AllGather}_{X}(A'[I_X]) \to A'[I].

For details on how AllGather and ReduceScatter are derivatives of each other, click here. 展开查看 AllGather 和 ReduceScatter 为什么互为反向传播所用的算子。

This stems from the fact that broadcasts and reductions are transposes of each other as linear operators, and AllGather and ReduceScatter are outer products (also known as Kronecker products) of broadcast and reduce, respectively. Concretely, if we have a vector x∈Rnx \in \mathbb{R}^n, any number of devices p∈Np \in \mathbb{N}, and we let u=(1,…,1)∈Rpu = (1, \ldots, 1) \in \mathbb{R}^p, we can define broadcast and reduce in the following way, which should match your intuitive understanding of them:

广播和归约作为线性算子互为转置,而 AllGather 和 ReduceScatter 分别是广播和归约的外积(也称克罗内克积)。具体来说,给定向量 x∈Rnx \in \mathbb{R}^n 和设备数 p∈Np \in \mathbb{N},令 u=(1,…,1)∈Rpu = (1, \ldots, 1) \in \mathbb{R}^p。广播和归约可定义如下,与通常的直观理解一致:

broadcast:Rn→Rpnbroadcast=u⊗Inreduce:Rpn→Rnreduce=uT⊗In\begin{align*} \text{broadcast} &: \mathbb{R}^n \rightarrow \mathbb{R}^{p n} \\ \text{broadcast} &= u \otimes \mathbf{I}_n \\ \text{reduce} &: \mathbb{R}^{p n} \rightarrow \mathbb{R}^n \\ \text{reduce} &= u^T \otimes \mathbf{I}_n \end{align*}

Let’s see how this looks in an example, where n=1n = 1, p=2p = 2. If x=(7)x = (7), we have broadcast(x)=((11)⊗(1))x=(11)x=(77)∈Rpn\text{broadcast}(x) = \left(\begin{pmatrix} 1 \\ 1 \end{pmatrix} \otimes \begin{pmatrix} 1 \end{pmatrix}\right) x = \begin{pmatrix} 1 \\ 1 \end{pmatrix} x = \begin{pmatrix} 7\\ 7 \end{pmatrix} \in \mathbb{R}^{p n}. This matches what we’d expect, broadcasting a vector in Rn\mathbb{R}^n to Rpn\mathbb{R}^{pn}. Now letting y=(8,9)y = (8, 9), we have reduce(y)=((11)⊗(1))y=(11)(89)=(17)\text{reduce}(y) = \left(\begin{pmatrix} 1 & 1 \end{pmatrix} \otimes \begin{pmatrix} 1\end{pmatrix}\right) y = \begin{pmatrix} 1 & 1 \end{pmatrix} \begin{pmatrix} 8 \\ 9 \end{pmatrix} = \begin{pmatrix} 17 \end{pmatrix}. This again matches what we’d expect, reducing a vector in Rpn\mathbb{R}^{p n} to a vector in Rn\mathbb{R}^{n}. Since (A⊗B)T=AT⊗BT(A \otimes B)^T = A^T \otimes B^T for any two matrices AA and BB, we see that reduce=broadcastT\text{reduce} = \text{broadcast}^T. We recover AllGather and ReduceScatter as the following outer products:

来看一个 n=1n = 1, p=2p = 2 的例子。给定 x=(7)x = (7),有 broadcast(x)=((11)⊗(1))x=(11)x=(77)∈Rpn\text{broadcast}(x) = \left(\begin{pmatrix} 1 \\ 1 \end{pmatrix} \otimes \begin{pmatrix} 1 \end{pmatrix}\right) x = \begin{pmatrix} 1 \\ 1 \end{pmatrix} x = \begin{pmatrix} 7\\ 7 \end{pmatrix} \in \mathbb{R}^{p n}。这正是预期的结果:把 Rn\mathbb{R}^n 中的向量广播到 Rpn\mathbb{R}^{pn}。再令 y=(8,9)y = (8, 9),有 reduce(y)=((11)⊗(1))y=(11)(89)=(17)\text{reduce}(y) = \left(\begin{pmatrix} 1 & 1 \end{pmatrix} \otimes \begin{pmatrix} 1\end{pmatrix}\right) y = \begin{pmatrix} 1 & 1 \end{pmatrix} \begin{pmatrix} 8 \\ 9 \end{pmatrix} = \begin{pmatrix} 17 \end{pmatrix}。这个结果也符合预期:将 Rpn\mathbb{R}^{p n} 中的向量归约为 Rn\mathbb{R}^{n} 中的向量。任意两个矩阵 AA 和 BB 都满足 (A⊗B)T=AT⊗BT(A \otimes B)^T = A^T \otimes B^T,因此 reduce=broadcastT\text{reduce} = \text{broadcast}^T。利用下列外积即可构造 AllGather 和 ReduceScatter:

AllGather:Rpn→Rp2nAllGather=broadcast⊗IpReduceScatter=Rp2n→RpnReduceScatter=reduce⊗Ip\begin{align*} \text{AllGather} &: \mathbb{R}^{p n} \rightarrow \mathbb{R}^{p^2 n} \\ \text{AllGather} &= \text{broadcast} \otimes \mathbf{I}_p \\ \text{ReduceScatter} &= \mathbb{R}^{p^2 n} \rightarrow \mathbb{R}^{p n} \\ \text{ReduceScatter} &= \text{reduce} \otimes \mathbf{I}_p \end{align*}

Here we think of Rp2n\mathbb{R}^{p^2 n} as Rp×pn\mathbb{R}^{p \times p n}, so one Rpn\mathbb{R}^{p n} vector for each of our pp devices. We suggest playing around with small examples, say n=2n = 2, p=3p = 3, to see what these operators look like as matrices. Using the same transposition property, we once more obtain AllGatherT=ReduceScatter\text{AllGather}^T = \text{ReduceScatter}, and of course ReduceScatterT=AllGather\text{ReduceScatter}^T = \text{AllGather}. This transposition will arise during backpropagation, since if we have y=Axy = Ax for some linear operator AA, such as AllGather or ReduceScatter, then during backpropagation we will have the derivative of the loss with respect to yy, ∂L∂y\frac{\partial L}{\partial y}, and we obtain ∂L∂x\frac{\partial L}{\partial x} as ∂L∂x=AT∂L∂y\frac{\partial L}{\partial x} = A^T \frac{\partial L}{\partial y}. This shows how the derivative of AllGather will be ReduceScatter, and vice versa.

这里把 Rp2n\mathbb{R}^{p^2 n} 看作 Rp×pn\mathbb{R}^{p \times p n},也就是 pp 台设备各有一个 Rpn\mathbb{R}^{p n} 向量。可以试一试 n=2n = 2, p=3p = 3 这样的简单例子,看看这些算子写成矩阵是什么样。再次应用同一条转置性质,可得 AllGatherT=ReduceScatter\text{AllGather}^T = \text{ReduceScatter},当然也有 ReduceScatterT=AllGather\text{ReduceScatter}^T = \text{AllGather}。这种转置关系会出现在反向传播中。设 y=Axy = Ax,其中 AA 是 AllGather 或 ReduceScatter 这样的线性算子。反向传播时,已知损失对 yy 的导数 ∂L∂y\frac{\partial L}{\partial y},便可求出 ∂L∂x\frac{\partial L}{\partial x},计算式为 ∂L∂x=AT∂L∂y\frac{\partial L}{\partial x} = A^T \frac{\partial L}{\partial y}。这说明了为什么 AllGather 的反向传播用 ReduceScatter,反过来也一样。

Turning an AllReduce into an AllGather and ReduceScatter also has the convenient property that we can defer the final AllGather until some later moment. Very commonly we’d rather not pay the cost of reassembling the full matrix product replicated across the devices. Rather we’d like to preserve a sharded state even in this case of combining two multiplicands with sharded contracting dimensions:

将 AllReduce 转换为 AllGather 和 ReduceScatter 还有一个方便的特性,即我们可以将最终的 AllGather 推迟到稍后的某个时刻。我们通常不希望支付在设备上复制完整矩阵乘积的成本。相反,我们希望即使在这种组合两个具有分片收缩维度的乘数的情况下,也能保持分片状态:

A[I,JX]⋅B[JX,K]→C[I,KX]A[I, J_X] \cdot B[J_X, K] \rightarrow C[I, K_X]

In this case, we can also perform a ReduceScatter instead of an AllReduce, and then optionally perform the AllGather at some later time, i.e.

在这种情况下,我们也可以执行 ReduceScatter 而不是 AllReduce,然后可以选择在稍后的某个时间执行 AllGather,即

A[I,JX]⋅LOCALB[JX,K]→ C[I,K]{UX}ReduceScatterX,KC[I,K]{UX}→ C[I,KX]\begin{align*} A[I, J_X] \cdot_{LOCAL} B[J_X, K] \rightarrow &\ C[I, K] \{ U_X \} \\ \textbf{ReduceScatter}_{X,K} C[I, K] \{ U_X \} \rightarrow &\ C[I, K_X] \end{align*}

Note that ReduceScatter introduces a sharded dimension, and so has a natural freedom to shard along either the I or K named dimensions in this case. We generally need to choose which named dimension to introduce a new sharding to when using a ReduceScatter (though the choice is usually forced by the larger modeling context). This is why we use the syntax ReduceScatterX,K to specify the axis to shard.

请注意,ReduceScatter 引入了一个分片维度,因此在这种情况下,沿着 I 或 K 命名维度进行分片具有天然的自由度。在使用 ReduceScatter 时,我们通常需要选择哪个命名维度来引入新的分片 (尽管选择通常由更大的建模上下文强制)。这就是为什么我们使用语法 ReduceScatterX,K 来指定要分片的轴。

How to overlap matmul communication with compute如何重叠矩阵乘法的通信和计算

As we discussed in Part 1, we generally assume we can always overlap communication with some useful computation if the comms are fast enough. The collectives in this section generally can be overlapped with the matrix multiplication compute itself, but doing so is non-trivial. The algorithm we use is something called a collective matmul, first described in Wang et al.. Here is a simplified animation of how this overlap can be implemented:

如第 1 章所述,只要通信够快,通常就可以让通信与有用的计算重叠。本章的集合通信一般可以与矩阵乘法本身重叠,但实现起来并不简单。我们用到的算法称为集合矩阵乘法,最早由 Wang 等人提出。下面的简化动画展示了如何实现重叠:

ag matmul

Figure: an animation showing how a single sharded matrix-vector product can be overlapped with the resulting AllReduce (case 3 above). A full matmul is composed of multiple matrix-vector products.

图: 动画演示如何让单次分片矩阵与向量的乘法同随后的 AllReduce 重叠(上文的情况 3)。一次完整的矩阵乘法由多次矩阵与向量的乘法组成。

To put it simply, we can do the matmul for one chunk of the matrix while starting the ring reduction for previous chunks. In some cases we can also tile over the batch dimension or matrix input dimension. We work through a simple JAX implementation in Part 10 and the Mosaic docs also give a good example on GPU. We encourage you to implement a version of this at some point.

简单说,可以在计算一个矩阵分块的乘积时,启动前面若干分块的环式归约。有时还可以沿批次维度或矩阵输入维度分块。第 10 章会推导一个简单的 JAX 实现,Mosaic 文档也给出了一个 GPU 上的示例。建议找机会动手实现一次。

What Have We Learned?我们学到了什么?

  • The sharding of an array is specified by a Mesh that names the physical, hardware axes of our TPU mesh and a Sharding that assigns mesh axis names to the logical axes of the array.
    • For example, A[IXY, J] describes an abstract array A with its first dimension sharded along two mesh axes X and Y. Combined with Mesh(mesh_shape=(4, 8), axis_names=(‘X’, ‘Y’)) or the abbreviated Mesh({‘X’: 4, ‘Y’: 8}), this tells us our array is sharded 32 ways along the first dimension.
  • 数组的分片由一个网格指定,该网格命名了我们 TPU 网格的物理,硬件轴,以及一个分片,该分片将网格轴名称分配给数组的逻辑轴。
    • 例如,A[IXY, J] 描述了一个抽象数组 A,其第一个维度沿两个网格轴 X 和 Y 分片。结合 Mesh(mesh_shape=(4, 8), axis_names=(‘X’, ‘Y’)) 或缩写为 Mesh({‘X’: 4, ‘Y’: 8}),这告诉我们我们的数组沿第一个维度进行了 32 路分片。
  • Arithmetic with sharded arrays works exactly like with unsharded arrays unless you perform a contraction along a sharded axis. In that case, we have to introduce some communication. We consider four cases:
  • 使用分片数组的算术运算与使用未分片数组的算术运算完全相同,除非你沿分片轴执行收缩。在这种情况下,我们必须引入一些通信。我们考虑四种情况:
  1. Neither array is sharded along the contracting dimension: no communication is needed.
  2. One array is sharded along the contracting dimension (or the contracting dimensions are sharded along different axes): we AllGather one of the inputs before performing the operation.
  3. Both arrays are identically sharded along the contracting dimension: we multiply the shards locally then perform an AllReduce or ReduceScatter.
  4. Both arrays are sharded along the same mesh axis along a non-contracting dimension: we AllGather one of the inputs first.
  1. 两个数组都没有沿收缩维度分片:不需要通信。 2. 一个数组沿收缩维度分片 (或者收缩维度沿不同轴分片):我们在执行操作之前对其中一个输入进行 AllGather. 3. 两个数组都沿收缩维度相同地分片: 我们在本地乘以分片,然后执行 AllReduce 或 ReduceScatter. 4. 两个数组都沿同一网格轴沿非收缩维度分片: 我们首先对其中一个输入进行 AllGather.
  • TPUs use roughly 4 core communication primitives:
    1. AllGather: [AX,B]→[A,B][A_X, B] \to [A, B]
    2. ReduceScatter: [A,B]{UX}→[AX,B][A, B] \{U_X\} \to [A_X, B]
    3. AllToAll: [A,BX]→[AX,B][A, B_X] \to [A_X, B]
    4. AllReduce: [AX,B]{UY}→[AX,B][A_X, B]\{U_Y\} \to [A_X, B] (technically not a primitive since it combines a ReduceScatter + AllGather)
  • TPU 大约使用 4 种核心通信原语:
    1. AllGather: [AX,B]→[A,B][A_X, B] \to [A, B]
    2. ReduceScatter: [A,B]{UX}→[AX,B][A, B] \{U_X\} \to [A_X, B]
    3. AllToAll: [A,BX]→[AX,B][A, B_X] \to [A_X, B]
    4. AllReduce: [AX,B]{UY}→[AX,B][A_X, B]\{U_Y\} \to [A_X, B] (技术上不是一个原语,因为它结合了 ReduceScatter + AllGather)
all collectives
  • The cost and latency of each of these operations doesn’t depend on the size of the axis (as long as they’re bandwidth bound), but only on the size of the input arrays and the bandwidth of the link. For a unidirectional AllGather/ReduceScatter:
  • 这些操作的成本和延迟不取决于轴的大小 (只要它们受带宽限制),而只取决于输入数组的大小和链接的带宽。对于单向 AllGather/ReduceScatter:
Tcomm per AllGather or ReduceScatter=Data volumebandwidth⋅Axis−1Axis⟶Data volumebandwidth (bidirectional)T_{\text{comm per AllGather or ReduceScatter}} = \frac{\text{Data volume}}{\text{bandwidth}} \cdot \frac{\text{Axis} - 1}{\text{Axis}} \longrightarrow \frac{\text{Data volume}}{\text{bandwidth (bidirectional)}}
  • An AllReduce is composed of a ReduceScatter followed by an AllGather, and thus has 2x the above cost. An AllToAll only has to pass shards part-way around the ring and is thus ¼ the cost of an AllGather. Here’s a summary:
  • AllReduce 由一个 ReduceScatter 和一个 AllGather 组成,因此成本是上述成本的 2 倍。AllToAll 只需要将分片部分地传递到环上,因此成本是 AllGather 的 ¼。这是一个总结:
Operation
操作
Description
描述
Syntax
语法
Runtime
运行时间
AllGatherGathers all the shards of a sharded array along an axis, removing a subscript.
收集分片数组沿一个轴的所有分片,移除一个下标。
[AX,B]→[A,B][A_X, B] \to [A, B]bytes / (bidirectional ICI bandwidth * num_axes)
字节 / (双向 ICI 带宽 * num_axes)
ReduceScatterSums a partially summed array along an axis and shards it along another axis (adding a subscript).
对一个部分求和的数组沿一个轴求和,并将其沿另一个轴分片 (添加一个下标).
[A,B]{UX}→[AX,B][A, B] \{U_X\} \to [A_X, B]Same as AllGather
与 AllGather 相同
AllReduceSums a partially summed array along an axis. Removes a { Ux }. Combines an AllGather and ReduceScatter.
对一个部分求和的数组沿一个轴求和。移除一个 { Ux }。结合了 AllGather 和 ReduceScatter.
[AX,B]{UY}→[AX,B][A_X, B]\{U_Y\} \to [A_X, B]2 * AllGather
AllToAllGathers (replicates) an axis and shards a different dimension along the same axis.
收集 (复制) 一个轴,并将另一个维度沿同一轴分片。
[A,BX]→[AX,B][A, B_X] \to [A_X, B]AllGather / 4 for a bidirectional ring
双向环的 AllGather / 4

Some Problems to Work一些待解决的问题

Here are some instructive problems based on content in this section. We won’t include all answers at the moment but we’ll write up more answers as we can.

这里有一些基于本节内容的有启发性的问题。我们目前不会包含所有答案,但我们会尽可能多地写出答案。

Question 1 [replicated sharding]: An array is sharded A[IX,J,K,…]A[I_X, J, K, \ldots] (i.e., only sharded across XX), with a mesh Mesh({'X': 4, 'Y': 8, 'Z': 2}). What is the ratio of the total number of bytes taken up by AA across all chips to the size of one copy of the array?

问题 1 [复制分片]:一个数组被分片为 A[IX,J,K,…]A[I_X, J, K, \ldots] (即,仅在 XX 上分片),网格为 Mesh({'X': 4, 'Y': 8, 'Z': 2})。所有芯片上 AA 占用的总字节数与数组一个副本的大小之比是多少?

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

Our array is only sharded along X, which has size 4, so effectively each shard has size [I/4,J,K,…]=sizeof(A)/4[I / 4, J, K, \ldots] = \text{sizeof}(A) / 4. Since our array is replicated across Y and Z, the total size is Y⋅Z⋅sizeof(A)Y \cdot Z \cdot \text{sizeof}(A), so the ratio of total size to single chip size is Y⋅Z⋅sizeof(A)/sizeof(A)=16Y \cdot Z \cdot \text{sizeof}(A) / \text{sizeof}(A) = 16.

我们的数组只在 X 上分片,大小为 4,所以实际上每个分片的大小为 [I/4,J,K,…]=sizeof(A)/4[I / 4, J, K, \ldots] = \text{sizeof}(A) / 4。由于我们的数组在 Y 和 Z 上复制,总大小为 Y⋅Z⋅sizeof(A)Y \cdot Z \cdot \text{sizeof}(A),所以总大小与单个芯片大小之比为 Y⋅Z⋅sizeof(A)/sizeof(A)=16Y \cdot Z \cdot \text{sizeof}(A) / \text{sizeof}(A) = 16.

Question 2 [AllGather latency]: How long should AllGatherX([BX,DY])\text{AllGather}_X([B_X, D_Y]) take on a TPU v4p 4x4x4 slice with mesh Mesh({'X': 4, 'Y': 4, 'Z': 4}) if B=1024B=1024 and D=4096D=4096 in bfloat16? How about AllGatherXY([BX,DY])\text{AllGather}_{XY}([B_X, D_Y])? How about AllReduceZ([BX,DY]{UZ})\text{AllReduce}_Z([B_X, D_Y] \{U_Z \})?

问题 2[AllGather 延迟]: 在 TPU v4p 4x4x4 切片上,网格为 Mesh({'X': 4, 'Y': 4, 'Z': 4}),数组采用 bfloat16,且 B=1024B=1024、D=4096D=4096,执行 AllGatherX([BX,DY])\text{AllGather}_X([B_X, D_Y]) 需要多长时间?执行 AllGatherXY([BX,DY])\text{AllGather}_{XY}([B_X, D_Y]) 呢?执行 AllReduceZ([BX,DY]{UZ})\text{AllReduce}_Z([B_X, D_Y] \{U_Z \}) 呢?

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

We have a wraparound link on all axes because we have a full 4x4x4 cube, so we have 9e10 bidirectional bandwidth to work with.

我们在所有轴上都有一个环绕链接,因为我们有一个完整的 4x4x4 立方体,所以我们有 9e10 的双向带宽可用。

  1. Because we’re just gathering over one axis and the other is sharded, we’re effectively gathering 2BD/Y2BD / Y bytes over 1 axis. If you think about just a single shard along the Y-axis, the AllGather along X looks like an unsharded AllGather with 1 / Y of the bytes. Since our ICI bandwidth for TPU v4p is 9e10 bytes/second bidirectional, this will take 2BD/(9e10⋅Y)=2⋅1024⋅4096/(9e10⋅4)=23μs2BD / (\text{9e10} \cdot Y) = 2 \cdot 1024 \cdot 4096 / (\text{9e10} \cdot 4) = 23 \mu s.
  1. 因为我们只是在一个轴上收集,而另一个轴是分片的,所以我们实际上是在 1 个轴上收集 2BD/Y2BD / Y 字节。如果你只考虑 Y 轴上的一个分片,X 轴上的 AllGather 看起来就像一个未分片的 AllGather,字节数为 1 / Y. 由于我们的 TPU v4p 的 ICI 带宽是双向 9e10 字节/秒,这将需要 2BD/(9e10⋅Y)=2⋅1024⋅4096/(9e10⋅4)=23μs2BD / (\text{9e10} \cdot Y) = 2 \cdot 1024 \cdot 4096 / (\text{9e10} \cdot 4) = 23 \mu s.
  1. We have twice the bandwidth as before but we’re AllGathering the full array, so T = 2BD / (2 * W) = 2*1024*4096 / (2 * 9e10) = 46us. This is far from the latency bound of 4us (1us per hop), so we’re fine.
  1. 我们的带宽是以前的两倍,但我们正在 AllGather 整个数组,所以 T = 2BD / (2 * W) = 2*1024*4096 / (2 * 9e10) = 46us。这远低于 4us 的延迟限制 (每跳 1us),所以我们没问题。
  1. The cost of an AllReduce is twice that of an AllGather. Each shard has size 2BD/(X∗Y)2BD / (X * Y), so the cost is about 4BD/(X∗Y∗W)4BD / (X * Y * W), or roughly 4 * 1024 * 4096 / (16 * 9e10) = 11.6us.
  1. AllReduce 的成本是 AllGather 的两倍。每个分片的大小为 2BD/(X∗Y)2BD / (X * Y),所以成本约为 4BD/(X∗Y∗W)4BD / (X * Y * W),或大约 4 * 1024 * 4096 / (16 * 9e10) = 11.6us.

Fun fact: parts (1) and (2) aren’t actually optimal, because the array is also replicated along the unused Z axis, and we can exploit those idle links: we can first re-shard [BX,DY]→[BXZ,DY][B_X, D_Y] \to [B_{XZ}, D_Y] for free (each device just drops part of its shard) and then perform AllGatherXZ\text{AllGather}_{XZ} (or AllGatherXYZ\text{AllGather}_{XYZ}), reaching the same final state while gathering over more axes. This cuts part (1) to 11.5us and part (2) to 31us — in practice you’d get this by just sharding over more axes up front, which is one reason to shard arrays as finely as possible.

一个有趣的细节:还可以优化第(1)和第(2)小题。数组沿未参与通信的 Z 轴复制,可以利用这些空闲链路。先免费重分片 [BX,DY]→[BXZ,DY][B_X, D_Y] \to [B_{XZ}, D_Y],也就是让各设备丢掉其分片中的一部分,再执行 AllGatherXZ\text{AllGather}_{XZ}(或 AllGatherXYZ\text{AllGather}_{XYZ})。这样可以在更多轴上收集分片,同时得到相同结果。第(1)题可缩短至 11.5us,第(2)题可缩短至 31us。实际通常会从一开始就在更多轴上分片,这也是尽可能细分数组的一个理由。

Question 3 [latency-bound AllGather]: Let’s say we’re performing an AllGatherX([BX])\text{AllGather}_X([B_X]) but BB is very small (say 128). How long should this take on a TPU v4p 4x4x4 slice with mesh Mesh({'X': 4, 'Y': 4, 'Z': 4}) in bfloat16? Hint: you’re probably latency bound.

问题 3 [受延迟限制的 AllGather]:假设我们正在执行一个 AllGatherX([BX])\text{AllGather}_X([B_X]),但 BB 非常小 (比如 128)。在 TPU v4p 4x4x4 切片上,网格为 Mesh({'X': 4, 'Y': 4, 'Z': 4}), bfloat16 格式,这需要多长时间?提示:你可能受延迟限制。

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

Our array in bfloat16 uses only 256 bytes total, and only 64 per device. Since we have an axis of size 4 on a TPU v4p, we have a wraparound link, so we can send the array in both directions. With 4.5e10 of unidirectional bandwidth, each hop would take roughly 64 / 4.5e10 ~ 0, so we’re definitely latency bound. Counting the number of hops, we can do the full gather in only 2 hops, so roughly 2us a good estimate.

我们的 bfloat16 数组总共只使用 256 字节,每个设备只有 64 字节。由于我们在 TPU v4p 上有一个大小为 4 的轴,我们有一个环绕链接,所以我们可以双向发送数组。单向带宽为 4.5e10,每次跳跃大约需要 64 / 4.5e10 ~ 0,所以我们肯定受延迟限制。计算跳跃次数,我们只需 2 次跳跃就可以完成整个收集,所以大约 2us 是一个很好的估计。

Question 4 [matmul strategies]: To perform X[B,D]⋅DY[DX,F]→Z[B,F]X[B, D] \cdot_D Y[D_X, F] \to Z[B, F], in this section we tell you to perform AllGatherX(Y[DX,F])\text{AllGather}_X(Y[D_X, F]) and multiply the fully replicated matrices (Case 2, Strategy 1). Instead, you could multiply the local shards like X[B,DX]⋅DY[DX,F]→Z[B,F]{UX}X[B, D_X] \cdot_D Y[D_X, F] \to Z[B, F] \{U_X\} (Case 3, Strategy 2), and then AllReduceX(Z[B,F]{UX})\text{AllReduce}_X(Z[B, F] \{ U_X\}). How many FLOPs and comms does each of these perform? Which is better and why?

问题 4 [矩阵乘法策略]:为了执行 X[B,D]⋅DY[DX,F]→Z[B,F]X[B, D] \cdot_D Y[D_X, F] \to Z[B, F],在本节中,我们告诉你执行 AllGatherX(Y[DX,F])\text{AllGather}_X(Y[D_X, F]) 并乘以完全复制的矩阵 (情况 2, 策略 1)。相反,你可以像 X[B,DX]⋅DY[DX,F]→Z[B,F]{UX}X[B, D_X] \cdot_D Y[D_X, F] \to Z[B, F] \{U_X\} (情况 3,策略 2) 那样乘以本地分片,然后 AllReduceX(Z[B,F]{UX})\text{AllReduce}_X(Z[B, F] \{ U_X\})。这两种策略各执行多少 FLOPs 和通信?哪种更好,为什么?

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

Let’s start with our baseline (Strategy 1). As we’ve shown, the cost of the AllGather is 2DF/Wici2DF / W_\text{ici}. Once we have the fully replicated arrays, the total compute time is 2BDF/C2BDF / C (where CC is our accelerator FLOPs/s, since each TPU does the same FLOPs). So we have

让我们从我们的基线 (策略 1) 开始。正如我们已经展示的,AllGather 的成本是 2DF/Wici2DF / W_\text{ici}。一旦我们有了完全复制的数组,总计算时间是 2BDF/C2BDF / C (其中 CC 是我们的加速器 FLOPs/s,因为每个 TPU 执行相同的 FLOPs)。所以我们有

Ttotal (Strategy 1)=max⁡(2BDFC,2DFWici)T_\text{total (Strategy 1)} = \max\left(\frac{2BDF}{C}, \frac{2DF}{W_\text{ici}}\right)

By comparison, the new strategy (Strategy 2) does an AllReduce over 2BF2BF bytes, which has cost 4BF/Wici4BF / W_\text{ici} but does 1/X1 / X fewer FLOPs (since the computation is sharded). This means we do 2⋅B⋅D⋅F/X2\cdot B\cdot D\cdot F / X FLOPs and the resulting AllReduce communicates 2⋅2⋅B⋅F2 \cdot 2 \cdot B \cdot F bytes in bfloat16. Thus, our total time for Strategy 2 (no AllGather, just an AllReduce later on) is roughly

相比之下,新策略 (策略 2) 对 2BF2BF 字节进行 AllReduce,成本为 4BF/Wici4BF / W_\text{ici},但执行的 FLOPs 少 1/X1 / X (因为计算是分片的)。这意味着我们执行 2⋅B⋅D⋅F/X2\cdot B\cdot D\cdot F / X FLOPs,并且由此产生的 AllReduce 通信 2⋅2⋅B⋅F2 \cdot 2 \cdot B \cdot F 字节 (bfloat16)。因此,策略 2 (没有 AllGather,只是稍后进行 AllReduce) 的总时间大约是

Ttotal=max⁡(2BDFX⋅C,4BFWici)T_\text{total} = \max\left(\frac{2BDF}{X \cdot C}, \frac{4BF}{W_\text{ici}}\right)

The question is: which of these is bigger? Strategy (2) is compute bound when D/(X⋅C)>2/WiciD / (X \cdot C) > 2 / W_\text{ici}, or when D/2X>C/Wici≈2550→X<D/(2∗2550)D / 2X > C / W_\text{ici} \approx 2550 \rightarrow X < D / (2 * 2550). We might reasonably expect D≈8kD \approx 8k, so this would mean roughly X<2X < 2 which is unlikely – hence we’re basically always comms bound with Strategy 2. With the baseline (Strategy 1), we’re comms bound when B<C/Wici=2550B < C / W_\text{ici} = 2550 which is often but not always true.

问题是:哪个更大? 当 D/(X⋅C)>2/WiciD / (X \cdot C) > 2 / W_\text{ici},或当 D/2X>C/Wici≈2550→X<D/(2∗2550)D / 2X > C / W_\text{ici} \approx 2550 \rightarrow X < D / (2 * 2550) 时,策略 (2) 受计算限制。我们可能合理地期望 D≈8kD \approx 8k,所以这意味着大约 X<2X < 2,这是不可能的 – 因此我们基本上总是使用策略 2 受通信限制。使用基线 (策略 1),当 B<C/Wici=2550B < C / W_\text{ici} = 2550 时,我们受通信限制,这通常是正确的,但并非总是如此。

So if B<2550B < 2550, we’re comms-bound in both cases and we have

所以如果 B<2550B < 2550,我们在两种情况下都受通信限制,我们有

Tcomms for Strategy 2<Tcomms for Strategy 1⇔4BFWici<2DFWiciT_\text{comms for Strategy 2} < T_\text{comms for Strategy 1} \Leftrightarrow \frac{4BF}{W_\text{ici}} < \frac{2DF}{W_\text{ici}}

which is true when D>2BD > 2B where 2B<51002B < 5100. This is often true, so Strategy 2 can sometimes be better if our batch is small. When our batch is large (B>2550B > 2550), we have

当 D>2BD > 2B 且 2B<51002B < 5100 时,这是正确的。这通常是正确的,所以如果我们的批次很小,策略 2 有时会更好。当我们的批次很大 (B>2550B > 2550) 时,我们有

Tcomms for Strategy 2<Tmath for Strategy 1⇔4BFWici<2BDFCT_\text{comms for Strategy 2} < T_\text{math for Strategy 1} \Leftrightarrow \frac{4BF}{W_\text{ici}} < \frac{2BDF}{C}

This is true when 2/Wici<D/C2 / W_\text{ici} < D / C, or when D>2∗2550=5100D > 2 * 2550 = 5100, which is usually true for large models. So this alternative strategy is typically better for large models, unless DD is small.

当 2/Wici<D/C2 / W_\text{ici} < D / C,或当 D>2∗2550=5100D > 2 * 2550 = 5100 时,这是正确的,这对于大型模型通常是正确的。所以这种替代策略对于大型模型通常更好,除非 DD 很小。

Why don’t we always do this? Well, in practice we may do this sometimes, but it’s typically rare to have the contracting dimension of one of the inputs to a matmul sharded along an axis that the other input isn’t sharded over. For instance, if we’re doing FSDP (explained in Section 5), we’ll shard our parameters over the data dimension but our activations will also be sharded along data. So in this sense this doesn’t show up much.

我们为什么不总是这样做? 嗯,在实践中我们有时可能会这样做,但通常很少有一个矩阵乘法的输入的收缩维度在一个轴上分片,而另一个输入没有在该轴上分片。例如,如果我们正在做 FSDP (在第 5 节中解释),我们将在数据维度上分片我们的参数,但我们的激活也将在数据维度上分片。所以从这个意义上说,这种情况不常出现。

Question 5 [minimum latency]: Let’s say I want to do a matmul A[I,J]⋅JB[J,K]→C[I,K]A[I, J] \cdot_J B[J, K] \to C[I, K] on a TPU v4p 4x4x4 with the lowest possible latency. Assume the inputs can be sharded arbitrarily but the result should be fully replicated. How should my inputs be sharded? What is the total FLOPs and comms time?

问题 5[最小延迟]: 假设要在 TPU v4p 4x4x4 上以最低延迟做矩阵乘法 A[I,J]⋅JB[J,K]→C[I,K]A[I, J] \cdot_J B[J, K] \to C[I, K]。输入可以任意分片,但结果必须完整复制。应当怎样分片输入?总 FLOPs 和通信时间各是多少?

Click here for the (partial) answer. 展开查看部分答案。

We won’t provide a full answer here, but we’ll start by describing the four most likely options:

这里先列出最有可能的四种方案,完整计算留给读者:

  1. A[IXYZ,J]⋅B[J,K]A[I_{XYZ}, J] \cdot B[J, K] + AG at the end
  2. A[I,J]⋅B[J,KXYZ]A[I, J] \cdot B[J, K_{XYZ}] + AG at the end
  3. A[I,JXYZ]⋅B[JXYZ,K]A[I, J_{XYZ}] \cdot B[J_{XYZ}, K] + AR at the end
  4. A[I,J]⋅B[J,K]A[I, J] \cdot B[J, K] (fully replicated)
  1. A[IXYZ,J]⋅B[J,K]A[I_{XYZ}, J] \cdot B[J, K],最后做 AllGather。
  2. A[I,J]⋅B[J,KXYZ]A[I, J] \cdot B[J, K_{XYZ}],最后做 AllGather。
  3. A[I,JXYZ]⋅B[JXYZ,K]A[I, J_{XYZ}] \cdot B[J_{XYZ}, K],最后做 AllReduce。
  4. A[I,J]⋅B[J,K]A[I, J] \cdot B[J, K](完整复制)。

We could also consider sharding different axes along different mesh axes, but that isn’t likely to change the final cost. For all but (4), the total FLOPs per TPU is the same, but comms are different for each. We then simply need to calculate the comms cost for each and see which is lowest. The TLDR is that (1) and (2) are equally good.

还可以在不同网格轴上分不同维度,不过这通常不会改变最终成本。除第(4)种外,各方案在每个 TPU 上的总 FLOPs 相同,通信量则不同。因此只要分别计算通信成本,选出最小的即可。结论是第(1)和第(2)种同样好。

Question 6: Let’s say we want to perform A[IX,JY]⋅JB[JY,K]→C[IX,K]A[I_X, J_Y] \cdot_J B[J_Y, K] \to C[I_X, K] on TPU v5e 4x4. What communication do we perform? How much time is spent on communication vs. computation?

问题 6: 假设我们想在 TPU v5e 4x4 上执行 A[IX,JY]⋅JB[JY,K]→C[IX,K]A[I_X, J_Y] \cdot_J B[J_Y, K] \to C[I_X, K]。我们执行什么通信?通信与计算花费的时间各是多少?

  • What about A[IX,J]⋅JB[JX,KY]→C[IX,KY]A[I_X, J] \cdot_J B[J_X, K_Y] \to C[I_X, K_Y]? This is the most standard setting for training where we combine data, tensor, and ZeRO sharding.
  • What about A[IX,J]⋅JB[J,KY]→C[IX,KY]A[I_X, J] \cdot_J B[J, K_Y] \to C[I_X, K_Y]? This is standard for inference, where we do pure tensor parallelism (+data).
  • A[IX,J]⋅JB[JX,KY]→C[IX,KY]A[I_X, J] \cdot_J B[J_X, K_Y] \to C[I_X, K_Y] 呢?这是训练中最标准的设置,我们结合了数据并行、张量并行和 ZeRO 分片。
  • A[IX,J]⋅JB[J,KY]→C[IX,KY]A[I_X, J] \cdot_J B[J, K_Y] \to C[I_X, K_Y] 呢?这是推理的标准设置,我们进行纯张量并行 (+数据).

Question 7: A typical Transformer block has two matrices Win[D,F]W_\text{in}[D, F] and Wout[F,D]W_\text{out}[F, D] where F≫DF \gg D. Say we have a batch size B. Then the full block is In[B,D]⋅Win[D,F]⋅Wout[F,D]In[B, D] \cdot W_\text{in}[D, F] \cdot W_\text{out}[F, D]. Let’s pick D=8192D=8192, F=32768F=32768, and B=128B=128 and assume everything is in bfloat16. Assume we’re running on a TPU v5e 2x2 slice but let’s pretend each TPU only has 300MB of free memory. How should In, WinW_\text{in}, WoutW_\text{out}, and Out be sharded to stay below the memory limit while minimizing overall time? How much time is spent on comms and FLOPs? Hint: the final output doesn’t need to be fully replicated, but it should be sharded the same as the input so the “layer” can be repeated.

问题 7: 典型的 Transformer 块有两个矩阵 Win[D,F]W_\text{in}[D, F] 和 Wout[F,D]W_\text{out}[F, D],其中 F≫DF \gg D。设批次大小为 B,则整个块的计算为 In[B,D]⋅Win[D,F]⋅Wout[F,D]In[B, D] \cdot W_\text{in}[D, F] \cdot W_\text{out}[F, D]。取 D=8192D=8192, F=32768F=32768, B=128B=128,假设所有数据都是 bfloat16。假设在 TPU v5e 2x2 切片上运行,但每个 TPU 只有 300MB 可用内存。应当怎样对 In、WinW_\text{in}、WoutW_\text{out} 和 Out 分片,才能满足内存限制并尽量缩短总耗时?通信和计算各用多少时间?**提示:**最终结果无须完整复制,但要与输入采用同样的分片,才可以重复堆叠这一层。

Click here for the (partial) answer. 展开查看部分答案。

First let’s think about memory. Each of our two big matrices uses 2 * 8192 * 32768 = 536MB. Our activations In have size 2 * 128 * 8192 = 2MB (small enough not to worry about). Since we only have 300MB of spare memory in each device, we clearly need to shard our matmuls.

先看内存。两个大矩阵各占用 2 * 8192 * 32768 = 536MB。激活值 In 占用 2 * 128 * 8192 = 2MB,可以忽略。每台设备只有 300MB 可用内存,因此显然要将矩阵乘法分片。

  1. In[BX,D]∗Win[DXY,F]∗Wout[F,DXY]→Out[BX,D]In[B_X, D] * W_\text{in}[D_{XY}, F] * W_\text{out}[F, D_{XY}] \rightarrow Out[B_X, D] (this is often called FSDP)
  2. In[B,DXY]∗Win[D,FXY]∗Wout[FXY,D]→Out[B,DXY]In[B, D_{XY}] * W_\text{in}[D, F_{XY}] * W_\text{out}[F_{XY}, D] \rightarrow Out[B, D_{XY}] (this is called tensor parallelism)
  1. In[BX,D]∗Win[DXY,F]∗Wout[F,DXY]→Out[BX,D]In[B_X, D] * W_\text{in}[D_{XY}, F] * W_\text{out}[F, D_{XY}] \rightarrow Out[B_X, D](通常称为 FSDP)
  2. In[B,DXY]∗Win[D,FXY]∗Wout[FXY,D]→Out[B,DXY]In[B, D_{XY}] * W_\text{in}[D, F_{XY}] * W_\text{out}[F_{XY}, D] \rightarrow Out[B, D_{XY}](称为张量并行)

The first is pretty bad because we need to AllGather our big weights or our activations first. The second requires an AllGather at the beginning and a ReduceScatter at the end (which is cheaper than an AllReduce). I’ll leave it as an exercise to do the rest of the math.

第一种的效率比较差,因为需要先对大权重或激活值做 AllGather。第二种在开头做 AllGather,在末尾做 ReduceScatter,后者比 AllReduce 便宜。其余计算留给读者完成。

Question 8 [challenge]: Using the short code snippet above as a template, allocate a sharded array and benchmark each of the 4 main communication primitives (AllGather, AllReduce, ReduceScatter, and AllToAll) using pmap or shard_map. You will want to use jax.lax.all_gather, jax.lax.psum, jax.lax.psum_scatter, and jax.lax.all_to_all. Do you understand the semantics of these functions? How long do they take?

问题 8 [挑战]:使用上面的简短代码片段作为模板,分配一个分片数组,并使用 pmap 或 shard_map 对 4 种主要通信原语 (AllGather, AllReduce, ReduceScatter 和 AllToAll) 进行基准测试。你将需要使用 jax.lax.all_gather, jax.lax.psum, jax.lax.psum_scatter 和 jax.lax.all_to_all。你理解这些函数的语义吗?它们需要多长时间?

Question 9 [another strategy for sharded matmuls?]: Above we claimed that when only one input to a matmul is sharded along its contracting dimension, we should AllGather the sharded matrix and perform the resulting contraction locally. Another strategy you might think of is to perform the sharded matmul and then AllReduce the result (as if both inputs were sharded along the contracting dimension), i.e. A[I,JX]∗JB[J,K]→C[I,K]A[I, J_X] *_J B[J, K] \to C[I, K] by way of

问题 9 [分片矩阵乘法的另一种策略?]: 上面 我们声称,当只有一个矩阵乘法的输入沿其收缩维度分片时,我们应该 AllGather 分片矩阵并在本地执行收缩。你可能想到的另一种策略是执行分片矩阵乘法,然后对结果进行 AllReduce (就好像两个输入都沿收缩维度分片一样),即 A[I,JX]∗JB[J,K]→C[I,K]A[I, J_X] *_J B[J, K] \to C[I, K] 通过

  1. C[I,K]{UX}=A[I,JX]⋅B[JX,K]C[I, K] \{ U_X \} = A[I, J_X] \cdot B[J_X, K]
  2. C[I,K]=AllReduce(C[I,K]{UX})C[I, K] = \text{AllReduce}(C[I, K] \{ U_X\})
  1. C[I,K]{UX}=A[I,JX]⋅B[JX,K]C[I, K] \{ U_X \} = A[I, J_X] \cdot B[J_X, K]
  2. C[I,K]=AllReduce(C[I,K]{UX})C[I, K] = \text{AllReduce}(C[I, K] \{ U_X\})

Answer the following:

回答以下问题:

  1. Explicitly write out this algorithm for matrices A[N,M]A[N, M] and B[M,K]B[M, K], using indices to show exactly what computation is done on what device. Assume AA is sharded as A[I,JX]A[I, J_X] across ND devices, and you want your output to be replicated across all devices.
  2. Now suppose you are ok with the final result not being replicated on each device, but instead sharded (across either the N or K dimension). How would the algorithm above change?
  3. Looking purely at the communication cost of the strategy above (in part 2, not 1), how does this communication cost compare to the communication cost of the algorithm in which we first AllGather A and then do the matmul?
  1. 明确写出这个算法,用于矩阵 A[N,M]A[N, M] 和 B[M,K]B[M, K],使用索引来准确显示在哪个设备上完成了什么计算。假设 AA 在 ND 个设备上分片为 A[I,JX]A[I, J_X],并且你希望你的输出在所有设备上复制。
  2. 现在假设你对最终结果不要求在每个设备上复制,而是分片 (跨 N 或 K 维度) 感到满意。上面的算法会如何改变?
  3. 仅从上面策略的通信成本来看 (对应第 2 小题),这个通信成本与我们首先 AllGather A 然后进行矩阵乘法的算法的通信成本相比如何?
Click here for the answer. 点击这里查看答案.
  1. First compute the outer products, storing the result in O[N,K]:okj=∑iakibijO[N, K]: o_{kj} = \sum_i a_{ki} b_{ij}. Note that the repeated index is not the one being contracted, as we are doing an outer product. Here the sum ranges across the set of i values stored on the particular device we are using. So, for example, if we have a contracting axis of size 16, and 4 devices, then on device 0, i would range from {0, 1, 2, 3}; on device 1, i would range from {4, 5, 6, 7}; on device 2, i would range from {8, 9, 10, 11}; and on device 3, i would range from {12, 13, 14, 15}. Then AllReduce the partial-sums of O[N,K]O[N, K] which live on each device, to form the full O[N,K]O[N, K].
  2. Instead of doing an AllReduce in step 2, we could get away with a cheaper ReduceScatter, along either axis: [N,K]{UX}→[NX,K][N, K] \{ U_X \} \to [N_X, K] or [N,K]{UX}→[N,KX][N, K] \{ U_X \} \to [N, K_X].
  3. As described in the main text above, the cost of doing an AllGather (when we are throughput-bound) is the same as that of a ReduceScatter; it is simply given by the size of the full matrix we are processing. So in the gather-then-matmul algorithm, this scales as NMNM (since we are AllGather\text{AllGather}-ing AA); in the matmul-then-reduce-scatter algorithm, this scales as NK (since we are reduce-scattering OO). So the communication cost ratio of the two algorithms is M/K.
  1. 首先计算外积,将结果存储在 O[N,K]:okj=∑iakibijO[N, K]: o_{kj} = \sum_i a_{ki} b_{ij} 中。请注意,重复的索引不是被收缩的索引,因为我们正在进行外积。这里的和范围是我们正在使用的特定设备上存储的 i 值的集合。所以,例如,如果我们有一个大小为 16 的收缩轴,和 4 个设备,那么在设备 0 上,i 的范围是 {0, 1, 2, 3};在设备 1 上,i 的范围是 {4, 5, 6, 7};在设备 2 上,i 的范围是 {8, 9, 10, 11};在设备 3 上,i 的范围是 {12, 13, 14, 15}。然后 AllReduce 每个设备上的 O[N,K]O[N, K] 的部分和,形成完整的 O[N,K]O[N, K].
  2. 我们可以在第 2 步中进行更便宜的 ReduceScatter,而不是进行 AllReduce,沿任一轴:[N,K]{UX}→[NX,K][N, K] \{ U_X \} \to [N_X, K] 或 [N,K]{UX}→[N,KX][N, K] \{ U_X \} \to [N, K_X].
  3. 如上文所述,进行 AllGather 的成本 (当我们受吞吐量限制时) 与 ReduceScatter 的成本相同;它仅由我们正在处理的完整矩阵的大小给出。因此,在 gather-then-matmul 算法中,这与 NMNM 成比例 (因为我们正在 AllGather\text{AllGather}-ing AA);在 matmul-then-reduce-scatter 算法中,这与 NK 成比例 (因为我们正在 reduce-scattering OO)。所以两种算法的通信成本比是 M/K.

Question 10: Fun with AllToAll: In the table above, it was noted that the time to perform an AllToAll is a factor of 4 lower than the time to perform an AllGather or ReduceScatter (in the regime where we are throughput-bound). In this problem we will see where that factor of 4 comes from, and also see how this factor would change if we only had single-direction ICI links, rather than bidirectional ICI links.

问题 10: AllToAll 的乐趣: 在上表中,注意到执行 AllToAll 的时间比执行 AllGather 或 ReduceScatter 的时间低 4 倍 (在我们受吞吐量限制的情况下)。在这个问题中,我们将看到这 4 倍的来源,并看到如果我们只有单向 ICI 链接,而不是双向 ICI 链接,这个因素会如何改变。

  1. Let’s start with the single-direction case first. Imagine we have D devices in a ring topology and want to do either an AllGather or a ReduceScatter on an N x N matrix A[IX,J]A[I_X, J] (say DD divides NN for simplicity). Describe the comms involved in these two collectives, and calculate the total number of scalars (floats or ints) which are transferred across a single ICI link during the entirety of this algorithm.
  2. Now let’s think about an AllToAll, still in the single-directional ICI case. How is the algorithm different in this case than the all-gather case? Calculate the number of scalars that are transferred across a single ICI link in this algorithm.
  3. You should have found that the ratio between your answers to part (a) and part (b) is a nice number. Explain where this factor comes from in simple terms.
  4. Now let’s add bidirectional communication. How does this affect the total time needed in the all-gather case?
  5. How does adding bidirectional communication affect the total time needed in the AllToAll case?
  6. Now simply explain the ratio between AllGather time and AllToAll time in a bidirectional ring.
  1. 让我们先从单向情况开始。想象一下,我们在一个环形拓扑中有 D 个设备,如果我们正在对一个 N x N 矩阵 A 进行 AllGather 或 ReduceScatter,该矩阵被分片为 A[IX,J]A[I_X, J] (假设 DD 整除 NN)。描述这两个集合通信中涉及的通信,并计算在整个算法期间单个 ICI 链接上传输的标量 (浮点数或整数) 的总数。
  2. 现在让我们考虑一个 AllToAll,仍然在单向 ICI 的情况下。在这种情况下,算法与 all-gather 的情况有何不同?计算在此算法中单个 ICI 链接上传输的标量数量。
  3. 你应该发现 (a) 和 (b) 部分的答案之比是一个很好的数字。用简单的术语解释这个因素的来源。
  4. 现在让我们添加双向通信。这如何影响 all-gather 情况下所需的总时间?
  5. 添加双向通信如何影响 AllToAll 情况下所需的总时间?
  6. 现在简单地解释一下双向环中 AllGather 时间和 AllToAll 时间之间的比率。
Click here for the answer. 点击这里查看答案.

(1) Solution: The process is simple: in each step of the algorithm, each device will send a single-shard “strip” of the matrix (totalling ND×N\frac{N}{D} \times N elements in size) to its nearest neighbor. This occurs D−1D-1 times, since each shard needs to be communicated to all of the devices except the one it starts out on. So in total, N2(D−1)D\frac{N^2(D-1)}{D} scalars are transferred by each device, i.e. flow across a single ICI link.

(1) 解决方案: 过程很简单:在算法的每个步骤中,每个设备都会将一个单分片“条带”的矩阵 (总共 ND×N\frac{N}{D} \times N 个元素) 发送给其最近的邻居。这会发生 D−1D-1 次,因为每个分片都需要被通信到除其起始设备之外的所有设备。所以总共,每个设备传输 N2(D−1)D\frac{N^2(D-1)}{D} 个标量,即流经单个 ICI 链接。

Answer: N2(1−1D)N^2 (1-\frac{1}{D}), or simply N2N^2 when D>>1D >> 1.

答案: N2(1−1D)N^2 (1-\frac{1}{D}),或者当 D>>1D >> 1 时,简单地为 N2N^2.

(2) Solution: The key difference between an AllToAll and an AllGather, from the perspective of communications, is that in an AllToAll, the entirety of the shard that lives on a particular device does not need to be communicated to every other device. Imagine the shard stored on a particular device (call it device 0) is [A,B,C,D][A, B, C, D] (here A,B,C,D are matrices and we are imagining a ring with 4 devices for illustration). Now the matrix AA does not need to be communicated anywhere, the matrix BB needs to end up on device 1; matrix CC ends up on device 2; and matrix DD ends up on device 3. So in the first step of the algorithm, we send BB, CC, and DD to device 1; in the next step, device 1 sends CC and DD onwards to device 2; in the final step, device 2 sends just DD on to device 3. The total number of parameters transferred in this case is (size of A/B/C/D)∗(3+2+1)(\text{size of A/B/C/D}) * (3 + 2 + 1). The size of A/B/C/D is (in the general case now) N2D2\frac{N^2}{D^2}, and again in the general case the (3+2+1)(3 + 2 + 1) term becomes ((D−1)+(D−2)+…+1)((D-1) + (D-2) + … + 1), or (D)(D−1)2\frac{(D)(D-1)}{2}. So the total number of bytes transferred across a single ICI link is N2(D−1)D×2\frac{N^2(D-1)}{D \times 2}.

(2) 解决方案: 从通信的角度来看,AllToAll 和 AllGather 之间的关键区别在于,在 AllToAll 中,驻留在特定设备上的整个分片不需要被通信到每个其他设备。想象一下存储在特定设备 (称之为设备 0) 上的分片是 [A,B,C,D][A, B, C, D] (这里 A,B,C,D 是矩阵,我们正在想象一个有 4 个设备的环来说明)。现在矩阵 AA 不需要被通信到任何地方,矩阵 BB 需要最终到达设备 1;矩阵 CC 最终到达设备 2;矩阵 DD 最终到达设备 3。所以在算法的第一步,我们将 BB, CC,和 DD 发送到设备 1;在下一步,设备 1 将 CC 和 DD 继续发送到设备 2;在最后一步,设备 2 只将 DD 发送到设备 3。在这种情况下传输的参数总数是 (size of A/B/C/D)∗(3+2+1)(\text{size of A/B/C/D}) * (3 + 2 + 1). A/B/C/D 的大小是 (在一般情况下) N2D2\frac{N^2}{D^2},并且同样在一般情况下,(3+2+1)(3 + 2 + 1) 项变成 ((D−1)+(D−2)+…+1)((D-1) + (D-2) + … + 1),或 (D)(D−1)2\frac{(D)(D-1)}{2}。所以单个 ICI 链接上传输的总字节数是 N2(D−1)D×2\frac{N^2(D-1)}{D \times 2}.

Answer: N22(1−1D)\frac{N^2}{2}(1-\frac{1}{D}), or simply N22\frac{N^2}{2} when D>>1D >> 1.

答案: N22(1−1D)\frac{N^2}{2}(1-\frac{1}{D}),或者当 D>>1D >> 1 时,简单地为 N22\frac{N^2}{2}.

(3) Solution: The factor is simply 12\frac{1}{2}, i.e. an AllToAll is half as costly as an all-gather/ReduceScatter on a unidirectional ring topology. Looking over the derivations above, this ultimately came from the fact that in the all-gather case, we are transferring the same sized block each of (D−1)(D-1) times, i.e. we’re doing the sum tiny block size∗(D+D+D+…+D) \text{tiny block size} * (D + D + D + … + D), whereas in the AllToAll case, we’re doing the sum tiny block size∗(D+D−1+D−2+…+1)\text{tiny block size} * (D + D-1 + D-2 + … + 1). The factor of two thus essentially comes from the fact that 1+2+…+n=n(n+1)/21 + 2 + \ldots + n = n(n+1)/2.

(3) 解决方案: 因子就是 12\frac{1}{2},即在单向环形拓扑上,AllToAll 的成本是 all-gather/ReduceScatter 的一半。回顾上面的推导,这最终来自于这样一个事实,即在 all-gather 的情况下,我们每次传输相同大小的块 (D−1)(D-1) 次,即我们正在做求和 tiny block size∗(D+D+D+…+D) \text{tiny block size} * (D + D + D + … + D),而在 AllToAll 的情况下,我们正在做求和 tiny block size∗(D+D−1+D−2+…+1)\text{tiny block size} * (D + D-1 + D-2 + … + 1)。因此,2 的因子本质上来自于这样一个事实,即 1+2+…+n=n(n+1)/21 + 2 + \ldots + n = n(n+1)/2.

(4) Solution: The total number of scalars that any one link has to carry now reduces by a factor of 2, since in a bidirectional ring, each “sharded strip” can be sent two ways simultaneously.

(4) 解决方案:现在任何一个链接必须承载的总标量数量减少了 2 倍,因为在双向环中,每个“分片条带”可以同时双向发送。

(5) Solution: In this case, we win a factor of 4 compared to the unidirectional case. This is easiest to see by considering the fate of each of the size-(N2/D2) blocks in a single sharded strip, say the one which originates on device 0. Instead of (as in the unidirectional case) sending one of these blocks a distance of D-1, another block a distance D - 2, etc. all the way to 1, we now divide the strip into blocks which move right or left, moving a maximum distance of floor(D/2). So the corresponding sum now becomes D/2+D/2−1+D/2−2+…=D/2⋅(D/2+1)/2D/2 + D/2 - 1 + D/2 - 2 + … = D/2 \cdot (D/2+1)/2, or D2/8D^2/8 in the limit of large DD. Compare this to D2/2D^2/2 in the unidirectional case, and we see that we’ve won a factor of 4.

(5) 解决方案:在这种情况下,与单向情况相比,我们赢得了 4 倍的优势。这最容易通过考虑单个分片条带中每个大小为 (N2/D2) 的块的命运来看出,比如说源自设备 0 的那个。与 (单向情况) 发送其中一个块距离 D-1,另一个块距离 D - 2,等等一直到 1 不同,我们现在将条带分成向右或向左移动的块,最大移动距离为 ceil(D/2)。所以相应的和现在变成 D/2+D/2−1+D/2−2+…=D/2⋅(D/2+1)/2D/2 + D/2 - 1 + D/2 - 2 + … = D/2 \cdot (D/2+1)/2,或者在 DD 很大时为 D2/8D^2/8。与单向情况下的 D2/2D^2/2 相比,我们看到我们赢得了 4 倍的优势。

(6) Solution: In a unidirectional ring, we saw that the AllToAll time was already twice as fast as the all-gather time; this comes from the fact that we don’t need to send our full strip to every single device. Then, when we added bidirectionality, we saw that it was a 4x win for AllToAll, and only a 2x win for all-gathers. Putting these ratios together, we get our sought after factor of 4.

(6) 解决方案: 在单向环中,我们看到 AllToAll 时间已经比 all-gather 时间快两倍;这来自于我们不需要将我们的完整条带发送到每个设备的事实。然后,当我们添加双向性时,我们看到对于 AllToAll 来说是 4 倍的胜利,而对于 all-gathers 来说只有 2 倍的胜利。将这些比率放在一起,我们得到了我们所寻求的 4 倍因子。

That’s it for Part 3! For Part 4 (about Transformer math), click here!

第三部分到此结束!第四部分 (关于 Transformer 数学),点击 这里!

Footnotes

  1. It’s worth noting that we may also choose to parallelize for speed. Even if we could fit on a smaller number of chips, scaling to more simply gives us more FLOPs/s. During inference, for instance, we can sometimes fit on smaller topologies but choose to scale to larger ones in order to reduce latency. Likewise, during training we often scale to more chips to reduce the step time.

    值得注意的是,我们也可能为了速度而选择并行化。即使我们可以容纳在较少数量的芯片上,扩展到更多芯片只是给了我们更多的 FLOPs/s。例如,在推理期间,我们有时可以容纳在较小的拓扑上,但选择扩展到更大的拓扑以减少延迟。同样,在训练期间,我们经常扩展到更多芯片以减少步骤时间。

    ↩
  2. A GPU AllGather can also work like this, where you create a ring out of the GPUs in a node and pass the chunks around in that (arbitrary) order.

    GPU AllGather 也可以这样工作,你可以从节点中的 GPU 创建一个环,并按 (任意) 顺序传递块。

    ↩
  3. The factor of 2 in the numerator comes from the fact that we’re using the bidirectional bandwidth. We send V/XV / X in each direction, or 2V/X2V / X total.

    分子中的 2 来自于我们使用的是双向带宽。我们在每个方向上发送 V/XV / X,总共 2V/X2V / X.

    ↩
  4. technically, ⌊X/2⌋\lfloor X / 2 \rfloor

    技术上是 ⌊X/2⌋\lfloor X / 2 \rfloor

    ↩
  5. For even-sized bidirectional rings, each device will send (N/2+(N/2−1)+…+1)(N/2 + (N/2-1) + … + 1) chunks right and ((N/2−1)+…+1)((N/2-1) + … + 1) chunks left =0.5⋅(N/2)⋅(N/2+1)+0.5⋅(N/2)⋅(N/2−1)=N2/4= 0.5 \cdot (N / 2) \cdot (N/2 + 1) + 0.5 \cdot (N / 2) \cdot (N/2 - 1) = N^2/4. The size of each chunk (aka shard of a shard) is bytes/N2\text{bytes} / N^2 so the per-device cost is (bytes/N2)⋅N2/4=bytes/4(\text{bytes} / N^2) \cdot N^2 / 4 = \text{bytes} / 4. This result scales across all devices as the total bandwidth scales with device number.

    对于偶数大小的双向环,每个设备将向右发送 (N/2+(N/2−1)+…+1)(N/2 + (N/2-1) + … + 1) 个块,向左发送 ((N/2−1)+…+1)((N/2-1) + … + 1) 个块 =0.5⋅(N/2)⋅(N/2+1)+0.5⋅(N/2)⋅(N/2−1)=N2/4= 0.5 \cdot (N / 2) \cdot (N/2 + 1) + 0.5 \cdot (N / 2) \cdot (N/2 - 1) = N^2/4。每个块 (又名分片的分片) 的大小是 bytes/N2\text{bytes} / N^2,所以每个设备的成本是 (bytes/N2)⋅N2/4=bytes/4(\text{bytes} / N^2) \cdot N^2 / 4 = \text{bytes} / 4。这个结果在所有设备上都适用,因为总带宽随设备数量而扩展。

    ↩

补充说明

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