# LLM Distributed Training: A Comprehensive Guide

> This article provides an in-depth look at the core technologies behind LLM distributed training. It covers MPI and NCCL communication primitives, point-to-point and collective communications (AllReduce, AllGather, etc.), Data Parallelism (DP), Pipeline Parallelism (PP), 3D Parallelism, ZeRO memory optimization, and Alpa's automated parallelization search strategies.

- Source: https://www.waytoagi.com/en/kb/learning-path/llm-distributed-training-overview
- Original (Feishu, Chinese): https://waytoagi.feishu.cn/wiki/IKrdwdaFSizOSTk1iracN234nrg
- Updated: 2026-12-02

---

> Author: Xiao A, aaronxic, [Zhihu Profile](https://www.zhihu.com/people/aaronxic)
>
> Publication Date: July 8, 2023
>
> Original Article: https://zhuanlan.zhihu.com/p/664604792
![](https://www.waytoagi.com/api/kb-media/AYPFbCfsaoNPjtx2qDXci6Tencf)


# Introduction

Hello everyone, I’m Xiao A. In the previous articles, we explored how Transformers are applied in LLM, multimodal, and AIGC algorithm domains. Starting from this article, we will shift our focus to the engineering side. This post will center on distributed training in LLMs and answer the following four questions:

- What are the common distributed communication primitives?
- How does 3D parallelism actually work?
- How does ZeRO reduce the memory footprint of data parallelism?
- How does Alpa use automated search to approach the optimal solutions designed by human experts?

PS: Long-read warning — this article is approximately 20,000 words. Following and bookmarking it for a better reading experience on a computer is highly recommended~ (^_^)


# Distributed Communication Primitives

Distributed training of LLMs typically involves multiple machines and multiple GPUs, making communication one of the most fundamental challenges. Therefore, before diving into parallelization algorithms, let’s first understand the commonly used distributed communication primitives.

There are generally two types of distributed communication:

- Point-to-point Communication (P2P): Communication between two nodes
- Collective Communication (CC): Communication within a group of nodes

The most widely used distributed communication libraries are MPI and NCCL. In engineering practice, MPI is typically used on CPUs, while NCCL is used on GPUs.


## **MPI**

MPI (Message Passing Interface) is a specification that defines a set of interfaces for message passing. One of the most popular open-source implementations is OpenMPI. It is commonly used in compute clusters and supercomputers, and has been heavily optimized for communication between CPUs.

Today, MPI is widely used for node management, but its optimization for GPU-to-GPU communication is relatively poor, as it lacks dedicated optimizations for GPUs.

When compiling C/C++ files with MPI support, you need to use the `mpicxx` compiler.


## **NCCL**

NCCL (NVIDIA Collective Communication Library) is NVIDIA’s dedicated collective communication library designed for its own GPUs and networking infrastructure. It enables high-speed interconnect communication for both single-node multi-GPU and multi-node multi-GPU setups.

This [repo](https://github.com/muriloboratto/NCCL) contains clear and easy-to-understand examples of all NCCL usage patterns. Feel free to check it out if you’re interested. Note that when compiling NCCL-related `.cu` files, you need to link the `-lnccl` library.


## **Point-to-Point Communication Primitives**

Point-to-point operations are relatively straightforward, consisting of only two operations: send and receive.

- When sending, you need to specify the send buffer and the ID of the target peer.
- When receiving, you need to specify the receive buffer and the ID of the source peer.

The interfaces for NCCL and MPI are shown below:

![](https://www.waytoagi.com/api/kb-media/JJkFbpGnwoMA0Nx33iHcnxp3nXf)

**Common Primitives in Collective Communication**

Collective communication refers to mutual communication within a group of nodes. In MPI, it is generally divided into three categories:

- One-to-Many. Examples include Broadcast and Scatter.
- Many-to-One. Examples include Reduce and Gather.
- Many-to-Many. Examples include AllReduce, AllGather, ReduceScatter, and AllToAll.

It is worth noting that in NCCL, there are fewer primitives than in MPI — only five in total: Broadcast, Reduce, AllGather, ReduceScatter, and AllReduce.

> 📊 Feishu embedded content (table/whiteboard, etc.) is shown here. [View the full version in the Feishu knowledge base](https://waytoagi.feishu.cn/wiki/IKrdwdaFSizOSTk1iracN234nrg)

**Broadcast and Scatter**

Broadcast sends the same single piece of data to N nodes, while Scatter distributes N different pieces of data to N nodes. Their commonality is that both send data from one node to multiple nodes. The difference is that Broadcast sends identical data, whereas Scatter sends distinct data.

![](https://www.waytoagi.com/api/kb-media/OVGrbPCecoA5wyxBzsYccdDZnzY)

**Reduce and Gather**

- Reduce collects data from N nodes and performs a reduction operation on them, such as SUM, MIN, MAX, PROD, etc.
- Gather collects data from N nodes and produces an array of length N.

![](https://www.waytoagi.com/api/kb-media/CPrnbll95obuNlxPhlOceyuEndh)

**AllGather**

Each node starts with one unique piece of data. Through exchange, all N nodes end up with all N pieces of data.

- Naive implementation: achieved via Gather + Broadcast.
- SOTA implementation: direct parallel sending.

![](https://www.waytoagi.com/api/kb-media/BgF6bTJTEoYrvjxKO5zcweqBnBd)

**ReduceScatter**

There are N nodes, each holding data of length N. First, a reduction is performed across the corresponding elements to obtain data of length N, which is then scattered so that each node receives data of length 1.

- Naive implementation: achieved via Reduce + Scatter.
- SOTA implementation: direct parallel sending.

![](https://www.waytoagi.com/api/kb-media/PaxzbO5OZo4sdVxC0mOcv6CxnLh)

**AllReduce**

Collects data from N nodes, performs a reduction on the resulting array, and then broadcasts the result back to all N nodes.

- Naive implementation: achieved via Reduce + Broadcast.
- SOTA implementation: ReduceScatter + AllGather.

![](https://www.waytoagi.com/api/kb-media/UWeSbzoY2oO44UxK8jNcvBGfnHc)

**AllToAll**

Similar to AllGather, but while AllGather results in every node receiving identical data, AllToAll results in each node receiving different data.

![](https://www.waytoagi.com/api/kb-media/EFxvbGjGNohnQAxPPEvcHjTTnhe)

# Data Parallel (DP)

Data Parallel (Data Parallelism) is the most widely used parallelization method and offers excellent acceleration. This is because each data slice can be completely decoupled; only an AllReduce on the gradients is required at the end of each mini-batch.

Data Parallel can be divided into centralized and decentralized approaches, corresponding to PyTorch’s DataParallel and DistributedDataParallel.

The biggest difference between these two lies in how gradients and reduction are computed:

- DataParallel gathers all outputs to device 0 after the forward pass, computes the loss on device 0, scatters the loss back to all devices, performs independent backward passes to compute gradients, and finally gathers the gradients back to device 0. This requires an additional communication step between forward and backward.
- DistributedDataParallel lets each device perform its own forward and backward passes independently, then performs an AllReduce on the gradients across all devices. Therefore, no communication is needed between forward and backward.

![](https://www.waytoagi.com/api/kb-media/N9W5bONXKo0VM0xgbl8cGWDOnCb)

# Pipeline Parallel (PP)

When a model's parameter count is too large to fit on a single device, the model must be partitioned. Pipeline Parallelism (Pipeline Parallel) is one such partitioning method. Specifically:

- The model is divided into *p* segments along its topological order, with each segment becoming a **stage**. This creates *p* logically sequential stages.
- A mini-batch of size *N* is further split into *m* micro-batches of size *M*, so that *N = m · M*.
- These micro-batches are fed sequentially into the *p* stages above.

We first examine how the per-stage execution time changes after pipeline partitioning compared to the original setup:

- **Assumption 1**: A node with compute power of 1 takes *t_f* and *t_b* time to perform the forward and backward pass, respectively, for one micro-batch of the full model.
- **Corollary 1**: A node with compute power of 1/*p* processing one micro-batch of the full model requires *p · t_f* and *p · t_b* for forward and backward passes.
- **Corollary 2**: A node with compute power of 1 processing one micro-batch of a 1/*p* model requires *t_f / p* and *t_b / p* for forward and backward passes.
- **Corollary 3**: A node with compute power of 1/*p* processing one micro-batch of a 1/*p* model requires *t_f* and *t_b* for forward and backward passes.

From Corollary 3, we can see that the time taken by full compute power to process the entire model is the same as the time taken by 1/*p* compute power to process a 1/*p* segment of the model.

Next, we analyze the execution time under various strategies.


## **Theoretical Upper Bound**

We first consider the ideal optimal case. In this scenario, GPU memory is infinite, so no pipeline parallelism is needed. A single pass can directly perform forward and backward computation on the entire mini-batch, with time proportional to the number of samples. From Assumption 1, the best-case time *b_best* is:

t_{\text{best}} = m \cdot (t_f + t_b)


## **Naive Sequential**

Now consider the most basic sequential approach, similar to the single-cycle processor era of CPUs. Each micro-batch is processed sequentially with both forward and backward passes, as shown below:

![](https://www.waytoagi.com/api/kb-media/ZssybCKqSoUJ60xkVmbcg8S6nmd)

Here, blue represents the forward pass and green represents the backward pass. We roughly assume the backward pass takes twice as long as the forward pass. From Corollary 3, we know that one micro-batch takes *p · (t_f + t_b)*. Therefore, the total time for one mini-batch *t_sequential* is:

t_\text{sequential} = mp \cdot (t_f + t_b)

This is *p* times slower than the theoretical upper bound. A large amount of compute resources remain idle, resulting in very low hardware utilization.


## **GPipe**

Next, we look at GPipe’s basic pipeline parallelism, analogous to the pipelined processor era of CPUs. All micro-batches use a *p*-stage pipeline to perform forward and backward passes. Note that the backward pass can only begin after all micro-batches have completed their forward passes.

![](https://www.waytoagi.com/api/kb-media/Gfi3bvBIWoUa21xsrlxcndWznWh)

Analysis shows that the total execution time *t_naive* is:

t_\text{naive} = p \cdot (t_f + t_b) + (m-1) \cdot (t_f + t_b) = (m + p - 1) \cdot (t_f + t_b)

**Bubble Analysis**

![](https://www.waytoagi.com/api/kb-media/Ap1ebVuImoPgITxjiVRc6J53nZb)

The image above is taken from [this article](https://siboehm.com/articles/22/pipeline-parallel-training). It is easy to see that \( t_{\text{naive}} \) takes significantly more time than \( t_{\text{best}} \). This extra time is visually represented by the three bubble regions in the diagram. The more bubbles there are, the more hardware idle time exists. Therefore, the **bubble ratio** is commonly used to measure how much a pipeline algorithm wastes hardware resources. The smaller the ratio, the higher the pipeline efficiency.

There are two equivalent ways to calculate the bubble ratio. Physically, it represents the proportion of the area occupied by the bubble (idle) regions relative to the total area.

**Calculation Method 1:** Using \( t_{\text{naive}} \) and \( t_{\text{best}} \)

$$
\text{bubble ratio} = \frac{t_\text{naive}-t_{\text{best}}}{t_\text{naive}} = \frac{(m+p-1)(t_f+t_b) - m(t_f+t_b)}{(m+p-1)(t_f+t_b)} = \frac{p-1}{m+p-1}
$$

**Calculation Method 2:** Compute the bubble proportion directly from the diagram, which is equivalent to 1 minus the utilization ratio.

$$
\text{bubble ratio} = 1 - \frac{2\cdot pm}{p\cdot2(m+p-1)}=\frac{p-1}{m+p-1}
$$

From the formulas above, we can see that the larger \( m \) is relative to \( p \), the smaller the bubble area becomes. In practice, when \( m \ge 4p \), the bubble overhead is generally considered negligible.

## **Re-materialization**

In GPipe, to reduce GPU memory usage, the **checkpoint** technique (also known as **re-materialization**) is used. Only the input activations of each stage are saved. Whenever the backward pass needs the activations of a certain layer, the stage is re-forwarded from the beginning. As a result, each stage is executed forward twice in total.

## **PipeDream (Non-Interleaved 1F1B)**

To further reduce bubble overhead, one approach is to increase the number of micro-batches \( m \). However, in GPipe, all micro-batches must complete their forward passes before any backward pass begins. This leads to a large amount of intermediate activations being cached in memory.

Similar to how DataParallel was evolved into DistributedDataParallel in data parallelism, we can decouple the forward and backward passes of different micro-batches within the same mini-batch, allowing them to run independently. The only requirement is that after the last micro-batch finishes its backward pass, the gradients from all micro-batches are averaged before performing the `optimizer.step()`.

![](https://www.waytoagi.com/api/kb-media/OV0FbIufdovYKYxSGFEct7V2n4Q)

The advantage of PipeDream’s approach is that it further reduces memory consumption, allowing \( m \) in the formula \( \frac{p-1}{m+p-1} \) to be increased even more, thereby lowering the bubble ratio.

It is worth noting that in the original PipeDream paper, the parallelism granularity was at the **mini-batch** level rather than the **micro-batch** level. As a result, each device would process multiple mini-batches with interleaved forward-backward and gradient updates, requiring it to store multiple versions of the model weights.

Subsequent works that further optimize PipeDream’s memory usage include **PipeDream-2BW** and **PipeMare**. Interested readers can explore them on their own.

**Interleaved 1F1B**

Interleaved 1F1B is a technique introduced in Megatron-LM, aiming to further improve pipeline utilization and reduce bubble (idle time) ratio. The core idea is to apply the second inference approach mentioned earlier: for each device, with fixed compute power, the micro-batches and pipeline stages are partitioned more finely so that the number of pipeline stages each device is responsible for doubles. Compared with the original setup, the time per stage on each device is halved, while the total number of stages doubles.

Let’s take a concrete example, as shown below:

- There are 4 micro-batches, each consisting of a blue part and a gray part. For instance, micro-batch 1 consists of blue1 (abbreviated as b1) and gray1 (abbreviated as g1).
- There are 4 devices (abbreviated as d1–d4).

In the original **Non-Interleaved 1F1B**, the mapping between data and devices is:

`(b1,d1)-(g1,d1)-(b2,d2)-(g2,d2)-(b3,d3)-(g3,d3)-(b4,d4)-(g4,d4)`

In the new **Interleaved 1F1B**, the mapping becomes:

`(b1,d1)-(g1,d2)-(b2,d3)-(g2,d4)-(b3,d1)-(g3,d2)-(b4,d3)-(g4,d4)`

![](https://www.waytoagi.com/api/kb-media/A4lPbcHenoNYalxL2lVcJu1SnXc)

At first glance, this “increase one, decrease one” rearrangement may seem pointless. However, a closer analysis reveals that after finer partitioning, the previously idle bubble time now has useful work to do — shown as the red portions in the figure above.

Of course, this improvement is not free. The cost is increased communication volume. Nevertheless, from an end-to-end perspective, the benefits outweigh the drawbacks.

# Tensor Parallelism (TP)

When model parameters continue to grow, in addition to pipeline parallelism, **Tensor Parallelism (TP)** — previously often referred to as Model Parallelism — can be used to alleviate the pressure.

Let’s take the most basic matrix multiplication as an example. When multiplying an activation matrix **A** with a weight matrix **B**, we can consider either column-partitioning or row-partitioning of **B**, leading to two schemes:

- **Scheme 1**: Split by column. Matrix **A** remains unchanged. Each column is computed independently, and the final results are concatenated.
- **Scheme 2**: Split by row. Matrix **A** must also be column-partitioned accordingly. The two parts are computed independently, and the final results are summed.

![](https://www.waytoagi.com/api/kb-media/YHoCbRHCxoa9s3x8tlTcxPgpnjb)

**Megatron**

In Megatron, the authors provide a detailed analysis of the specific partitioning schemes for each component in the Transformer architecture, as shown below:

![](https://www.waytoagi.com/api/kb-media/Qa44bHDU7o7OuqxFfaBc8F43nJe)

![](https://www.waytoagi.com/api/kb-media/CYEKbTU8woZOZqxtRqkcghvMnaf)

**FFN-expansion Matrix Multiplication**

- After the first expansion matrix multiplication in the FFN, an element-wise GELU is applied. Therefore:
  - With Scheme 2, an AllReduce must be performed first before applying GELU.
  - With Scheme 1, GELU can be applied independently on each shard, and the AllReduce can be deferred until much later.

- Hence, Scheme 1 is preferable.

**FFN-contraction Matrix Multiplication**

- After the FFN-expansion stage, the shape of the new activation values is (BL, 4D), and Scheme 1 has been used to shard the column dimension (4D).

- Therefore, in the FFN-contraction stage, it is sufficient to perform row-wise partitioning on the weight matrix of the FFN-contraction. This satisfies the requirements of the above Scheme 2.

- Finally, an AllReduce Sum is performed.

**f and g**

Here, f and g form a dual pair of operations:

- In the forward pass, f is the identity operation and g is AllReduce.
- In the backward pass, g is the identity operation and f is AllReduce.

**MHA**

- Each attention head is naturally partitioned along the 0th dimension and can be computed completely independently.

- Similar to the FFN, Scheme 1 is chosen. After completing the input projection and attention computation, row-wise partitioning is applied to the weight matrix of the output projection.

- Finally, an AllReduce Sum is performed.

**Input Embedding**

- Assume the word embedding matrix is \( E_{H \times v} \), where \( H \) is the feature dimension and \( v \) is the vocabulary size.

- The typical computation is \( E_{H \times v} X \). Therefore, Scheme 2 can be used: \( E = [E_1, E_2] \), \( X = [X_1; X_2] \).

- An AllReduce Sum is then performed on the result.

**Output Embedding**

- At output time, each token must compute a dot product with every vector in the vocabulary, followed by softmax to return the word with the highest probability:

  $$
  \text{GEMM}[Y_1, Y_2] = [XE_1, XE_2]
  $$

- Here, \( X \) has shape (BL, H), \( E_1 \) has shape (H, \( v_1 \)), and \( E_2 \) has shape (H, \( v_2 \)).

- Since softmax must be computed next, a naive approach would require communicating the entire (BL, v) matrix. However, because \( v \) is very large, the communication volume would be excessive.

- The optimized strategy is to compute the sum of the exponential denominators for softmax locally on each shard, obtaining a vector of length BL. An AllReduce is then performed on this sum vector, after which the softmax values can be calculated. This reduces the communication volume from \( BL \times v \) down to \( BL \).

## **Communication Volume Issues**

![](https://www.waytoagi.com/api/kb-media/OUcAbvrNpo1DZzx2E3tclPIcnxb)

From a macro perspective, there are two parameterized modules within each Transformer block: MHA and FFN. In tensor parallelism mode, the parameters of these two modules are evenly distributed across multiple nodes. AllReduce operations are required between modules and must be performed serially. Each forward and backward pass requires a total of 4 AllReduce operations, and computation and communication cannot be overlapped.

Compared to pipeline parallelism, where communication only occurs between stages, tensor parallelism requires communication within every layer. As a result, the communication volume of tensor parallelism is significantly larger than that of pipeline parallelism. Tensor parallelism is therefore typically used only within the same high-speed interconnected island.

# ZeRO

The motivation behind ZeRO is to optimize memory usage in data parallelism. In standard data parallelism, every device holds a complete copy of the model weights, gradients, and optimizer states. This is highly redundant.

**GPT-2 Memory Usage Analysis**

Before diving into the specific memory optimization techniques of ZeRO, let’s first carefully analyze how a GPT-2 model can be trained on a single 32G GPU using a naive training strategy with a batch size of 32.

The basic parameters are as follows:

- GPT-2 model parameter count Ψ = 1.5B
- Sequence length L = 1024
- Batch size B = 32
- Feature dimension D = 768
- Total of 12 transformer blocks

- GPU VRAM size: 32G

Memory consumption can be roughly divided into 4 parts: parameters + gradients + optimizer states + activations. The total size is:

2Ψ + 2Ψ + KΨ + 7.2G = (2 + 2 + 14)Ψ + 7.2G = 18Ψ + 7.2G = 31.2G

Detailed breakdown is as follows:

- Parameters (fp16): 2Ψ = 3GB
- Gradients (fp16): 2Ψ = 3GB
- Optimizer states: typically KΨ, where the coefficient K varies by optimizer. For Adam, K = 12, so:
  - Parameters (fp32): 4Ψ = 6GB
  - Momentum (fp32): 4Ψ = 6GB
  - Variance (fp32): 4Ψ = 6GB
- Activations and other residual states (approximately 7.2GB):
  - Activations (fp16): The activation volume for one transformer block is at least 12BLD. For 12 blocks, this becomes 144BLD = 3.6G activations, which consumes roughly 7.2G of VRAM.
  - Temporary buffers: includes space for all_reduce operations, etc.
  - Fragmented memory: memory fragmentation

## **What if the model doesn’t fit in memory?**

If the model continues to grow and no longer fits on a single card, we naturally need to reduce memory usage from two major aspects: weights and activations. Common approaches include:

- **Parameter Server (PS)**: The parameter server paradigm, where model weights are stored centrally once across the entire cluster, and other workers fetch them on demand.
- **Pipeline Parallelism (PP)**: Split the network into multiple stages along the depth dimension, placing the weights of each stage on different GPUs. The classic implementation is GPipe.
- **Tensor Parallelism (TP)**: Decompose matrix multiplications so that weight matrices are evenly split across multiple GPUs. The representative work is Megatron-LM.
- **Re-materialization (Checkpointing)**: Can reduce memory usage to 1/√N of the original, but introduces an extra forward pass, incurring approximately 33% additional computation.
- **CPU Offloading**: Directly move activations to CPU memory and load them back during backpropagation.

ZeRO draws on ideas from the above methods and optimizes memory usage for both weights and activations. These two aspects are called **ZeRO-DP** and **ZeRO-R** respectively.

**ZeRO-DP Memory Optimization**

ZeRO-DP has three levels of memory optimization: ZeRO-1, ZeRO-2, and ZeRO-3.

![](https://www.waytoagi.com/api/kb-media/DyTIbYJ8do2Ie1xo5VVcXvp7nLh)

The following section analyzes the communication volume and memory optimization achieved by each strategy.

**Strategy 1: Naive DP Communication Volume**

- Continues to use the previously mentioned data-parallel **DistributedDataParallel**. It performs a single AllReduce only during the gradient update phase, after which each GPU independently runs the optimizer step.
- Performs AllReduce on gradients using ReduceScatter + AllGather, resulting in a total communication volume of Ψ + Ψ = 2Ψ.
- No memory optimization. Parameters, gradients, and optimizer states are fully replicated on every GPU, leading to a memory footprint of 16Ψ = 120GB.

**Strategy 2: ZeRO-1 (P_{os})**

- Partitions only the optimizer states (**P_{os}**).
- After computing gradients on each GPU, a ReduceScatter is used to send them to the corresponding GPU. Communication volume: Ψ.
- After each GPU updates its optimizer states and weights, an AllGather is performed on the weights. Communication volume: Ψ.
- Total communication volume remains 2Ψ, identical to naive DP.
- In terms of memory: parameters and gradients remain the same as in naive DP, but optimizer states are reduced to 1/N_d = 1/64. Total memory usage becomes 4Ψ + 12/64Ψ = 4.1875Ψ = 31.4GB, approximately 1/4 of Strategy 1.

**Strategy 3: ZeRO-2 (P_{os+g})**

- Partitions both optimizer states and gradients (**P_{os+g}**). The situation is similar to ZeRO-1.
- Communication volume is also Ψ + Ψ = 2Ψ, the same as naive DP.
- In terms of memory: parameters remain the same as naive DP, while both gradients and optimizer states are reduced to 1/N_d = 1/64. Total memory usage becomes 2Ψ + 14/64Ψ = 2.22Ψ = 16.6GB, approximately 1/8 of naive DP.

**Strategy 4: ZeRO-3 (P_{os+g+p})**

- Partitions optimizer states, gradients, **and** weights (**P_{os+g+p}**).
- During the forward pass, an AllGather on weights is required to compute activations for each layer. Communication volume: Ψ.
- During the backward pass, another AllGather on weights is needed to compute gradients for each layer. Communication volume: Ψ.
- Gradients for each layer are sent to the corresponding GPU via ReduceScatter. Communication volume: Ψ.
- Total communication volume is 3Ψ, which is 1.5× that of naive DP (a 50% increase).
- In terms of memory: parameters, gradients, and optimizer states are all reduced to 1/N_d = 1/64. Total memory usage becomes 16/64Ψ = 1.9GB, approximately 1/32 of naive DP.

The table below shows memory consumption for models of different sizes under varying degrees of DP parallelism and different ZeRO strategies.

![](https://www.waytoagi.com/api/kb-media/CQapbl0h4oKpj8xF904cjJvcnAh)

## **ZeRO-R Memory Optimization**

“R” stands for **Residual States** — all memory consumption other than parameters, gradients, and optimizer states. This includes:

- **Activations**: Uses activation checkpointing (also known as re-materialization) on already-sharded activations.
- **Temporary buffers**: Uses a fixed-size buffer.
- **Fragmented memory**: Employs an on-the-fly memory allocation strategy to eliminate fragmentation. Specifically:
  - Forward pass: Alternating long-lived activations (retained) and short-lived activations (deleted) create memory fragments.
  - Backward pass: Long-lived weight gradients and short-lived input tensors required for computing weight gradients.

# Summary of DP / PP / TP

- **DP** offers excellent compute and communication efficiency, but is memory-unfriendly for model weights because every GPU holds a full copy. ZeRO addresses this aggressively by drawing inspiration from the Parameter Server architecture. In particular, ZeRO-3 allows each GPU to maintain only a portion of the model weights, gradients, and optimizer states.
- **PP** (Pipeline Parallelism) requires a sufficiently large batch size within each mini-batch to hide the pipeline bubble overhead. However, excessively large batch sizes significantly increase activation memory usage.
- **TP** (Tensor Parallelism) is very memory-friendly for weights, with no redundancy. However, it is less favorable in terms of compute and communication efficiency. It requires very high communication volume, and performance degrades rapidly once it spans beyond a single island.

# Alpa

The methods mentioned earlier are all manually designed parallelization strategies, whereas Alpa is a method for automatically searching parallelization strategies. It draws heavily on ideas from AI compilers. Notably, the first author of this paper is also the first author of Ansor, the automatic search method used in TVM.

![](https://www.waytoagi.com/api/kb-media/YEUPbZBpxoqlj2xxR15csPxfncQ)

Alpa primarily addresses the allocation problem between computation graphs and hardware clusters. It proposes a two-stage automatic parallelization strategy search algorithm consisting of **Inter-op** and **Intra-op**. The overall algorithm follows a two-level loop structure. For an intuitive understanding, see the diagram below:

![](https://www.waytoagi.com/api/kb-media/Jg4jbHrAQoTO4wxRpTTcselNnIe)

- **Outer loop (Inter-op)**: Partitions the sequence of operations (ops) in the computation graph into different stages, while also dividing the hardware cluster into different mesh grids, forming multiple stage-mesh pairs.

- **Inner loop (Intra-op)**: For each stage-mesh pair, uses integer programming to estimate the computation and communication costs.

- **Runtime Orchestration**: Inserts necessary within-mesh and cross-mesh communication send/receive nodes, compiles a complete executable runtime, and obtains the full end-to-end execution speed.

## **Problem Definition**

In the author’s view, Alpa’s greatest contribution is its mathematical modeling of the computation graph and hardware cluster allocation problem, along with the use of reasonable simplifications and corresponding mathematical techniques to solve it. Let’s first briefly introduce the computation graph and hardware cluster allocation problem.

- Assume a computation graph has *K* nodes and is a DAG with topological order *o₁ → o₂ → ⋯ → o_K*.

- Assume a compute cluster consists of *N × M* compute devices. Typically, each row forms a high-speed interconnected “island,” while connections between different rows are slightly slower. For example:
  - In a GPU cluster, a single node usually has 8 GPUs, so *M = 8*.
  - In a TPU cluster, the maximum unit is a Pod consisting of 512 TPUs, so *M = 512*.

Distributed computing essentially involves finding an allocation strategy that first divides the *K* nodes into *S* stages, where each stage contains a set of computation graph operators *sᵢ*. At the same time, the compute cluster is also partitioned into *S* blocks, each of size *nᵢ × mᵢ*, denoted as **Mesh**(nᵢ, mᵢ). The stage *sᵢ* is then assigned to **Mesh**(nᵢ, mᵢ) for computation, as illustrated below:

![](https://www.waytoagi.com/api/kb-media/XTfkbLfxAoubcYxwUHAckiV1nQe)

Note that **Mesh**(nᵢ, mᵢ) is constrained to be a rectangular block of shape *nᵢ × mᵢ*, with only two possible shape categories:

- **1D case**: (1,1), (1,2), (1,4), (1, 2^b), i.e., height = 1 and width = a power of 2.
- **2D case**: (1, M), (2, M), (a, M), i.e., height = any positive integer and width = fixed *M*.

It can be proven that for any arbitrary *N × M* compute cluster, it is always possible to further partition it into a series of meshes {(n₁,m₁), ⋯, (n_S, m_S)} such that these sub-meshes completely cover the original cluster without overlap or omission.

Therefore, solving the computation graph and hardware cluster allocation problem can be done as follows:

- First, define the inner-loop (Intra-op) latency interface as *t_intra(sᵢ, Mesh(nᵢ, mᵢ))*.
- The outer loop (Inter-op) then repeatedly enumerates different partitioning schemes and calls the Intra-op latency interface.
- Ultimately, it finds the allocation strategy with the shortest end-to-end latency.

In the following sections, we will first examine the details of the inner loop (Intra-op), then see how the outer loop (Inter-op) performs partitioning search.

**Intra-op**

The input to the Intra-op module is a computational subgraph \( s_i \) and a compute resource mesh \( \text{Mesh}(n_i, m_i) \). The output is the optimal sharding strategy together with the corresponding actual execution time.

Since we adopt an SPMD execution model, all devices within \( \text{Mesh}(n_i, m_i) \) are equal peers, and every device executes the same program for each operator. This allows us to turn the problem into a greedy algorithm: we only need to decide, one operator at a time, how each input tensor of an operator in \( s_i \) should be partitioned and distributed across the \( n_i \times m_i \) devices. Once the partitioning for all operators is determined, the complete allocation strategy for both \( s_i \) and \( \text{Mesh}(n_i, m_i) \) is fixed.

As a side note, here is a brief introduction to several common terms in distributed computing: SIMD, SIMT, and SPMD.

- **SIMD (Single Instruction Multiple Data)**: Also known as vectorized instruction sets. A single instruction operates on multiple data elements. Examples include X86 SSE/AVX and ARM NEON.

- **SIMT (Single Instruction Multiple Threads)**: Multiple threads within a thread block execute the same program. The most common example is CUDA programming.

- **SPMD (Single Program Multiple Device)**: Multiple devices run identical programs in a completely peer-to-peer fashion and exchange information through collective communication primitives.

Returning to the per-operator sharding process in Intra-op. For each operator, we only need to decide how its input tensors are sharded. In general, there are three choices: Row-partitioned, Column-partitioned, and Replicated.

![](https://www.waytoagi.com/api/kb-media/FTXbb0khIoAT9xxwzFUcdYConLd)

Taking matrix multiplication (matmul) as an example:

- In data parallelism: the input is Row-partitioned and the weight is Replicated.
- In tensor parallelism: the input is Replicated, and the weight is either Row-partitioned or Column-partitioned.

To conveniently describe how a tensor is partitioned across devices, we introduce the concept of **Sharding Spec**. This is analogous to the layout of an operator. For instance, a conv2d operator can use either NHWC or NCHW layout. When the output layout of the preceding operator does not match the input layout required by the current operator, we simply insert a layout transformation.

The following example shows nine Sharding Specs defined by Alpa for a 2D tensor distributed over a 2×2 device mesh:

![](https://www.waytoagi.com/api/kb-media/TGrTbMB1GoOwuGxuQF7c4AesnUh)

The notation is defined as follows:

- The number of letters matches the number of tensor dimensions. Each letter has only two possible meanings: **R** stands for Replicated and **S** stands for Split. Therefore, RR means fully replicated, SR means split along the first dimension (row), RS means split along the second dimension (column), and SS means split along both dimensions.
- To describe the device mapping, a superscript number is added to S letters to indicate which dimension of the device mesh the split is mapped to. The special case \( S^{01}R \) means the tensor is evenly divided into 4 parts along the row dimension (and similarly for \( RS^{01} \)).
- Each column in the table shows the concrete data residing on each device after the original tensor A is sharded.

With the Sharding Spec defined above, whenever a mismatch occurs we introduce a **Spec transformation**, i.e., **Resharding**. Note that, just like a layout transformation may require memory rearrangement, a Spec transformation can incur additional communication overhead, as illustrated below:

![](https://www.waytoagi.com/api/kb-media/UgCCbH2AYo6RedxB7oXcphWLnWl)

As we can see, every tensor of every operator has multiple possible Sharding Specs, and mismatched specs introduce extra communication cost via Resharding. This problem can be reduced to an integer programming problem whose objective function is defined as:

$$
\min_{s} \left\{ \sum_{v \in V} s_v^T (c_v + d_v) + \sum_{(v,u) \in E} s_v^T R_{vu} s_u \right\}
$$

where

- \( V \) represents all tensors whose specs need to be determined; \( v \) is any one of them.
- \( s_v \) is the one-hot vector representing the chosen spec for tensor \( v \). The corresponding vectors \( c_v \) and \( d_v \) are the communication cost and computation cost of that spec, respectively.
- \( R_{vu} \) is the Resharding cost matrix that measures the communication cost between adjacent tensors \( v \) and \( u \).

Solving the above objective function is essentially a mathematical optimization problem. Several practical techniques are used:

- Flatten the quadratic matrix \( R_{vu} \) into a 1-dimensional vector and convert it into a linear one-hot selection similar to the first term. This transforms the integer programming problem into an Integer Linear Programming (ILP) problem, which can be solved by mature Python packages.
- Following prior work, the computation cost \( d_v \) is set to 0 for two reasons:
  - For compute-intensive operators, the replicated strategy is not allowed. Under SPMD, the amount of computation is identical for any valid sharding, so it can be safely set to 0.
  - For non-compute-intensive operators, the computation itself is negligible, so it can also be set to 0.
- Communication cost is approximated by dividing the communication volume by the bandwidth.

At this point, given a computational subgraph \( s_i \) and a device mesh \( \text{Mesh}(n_i, m_i) \), the optimal intra-op execution time \( t_{\text{intra}}^*(s_i, \text{Mesh}(n_i, m_i)) \) can be obtained by solving the ILP described above.

**Inter-op**

How to partition the original computation graph into *S* subgraphs *s_i*, and how to further divide the computation mesh *Mesh(N, M)* into *S* sub-meshes *Mesh(n_i, m_i)*, are the core problems that Inter-op needs to solve.

Partitioning a computation graph is essentially the process of pipeline parallelism. We consider the Gpipe or synchronous 1F1B pipeline schedule. Suppose the network is divided into 4 stages, with each stage placed on a different compute node. These stages are logically connected in series to form a pipeline, as shown below:

![](https://www.waytoagi.com/api/kb-media/IKPAbAu7OoLbRDxm2gLcfpxgnpg)

Since the computational throughput of each stage is not identical, some stages run faster while others run slower. Assuming the forward pass times for each stage are *t₁ ∼ t₄*, the total forward pass time for the entire mini-batch is:

*t_pipeline = t₁ + t₂ + t₃ + t₄ + (m−1)·max{t₁, t₂, t₃, t₄}*

where *max{tᵢ}* corresponds to the slowest stage (the bottleneck).

Generalizing to the general case, when the graph is partitioned into *S* subgraphs, the overall end-to-end execution time becomes:

*T*^* = min_{s₁,⋯,s_S \atop (n₁,m₁),⋯,(n_S,m_S)} { ∑_{i=1}^S t_i + (B−1)·max_{1≤j≤S}{tⱼ} }*

where *tᵢ* is the execution time of subgraph *sᵢ*, and *B* is the micro-batch size used in pipeline parallelism (in the example above, *B = 8*).

Solving the above expression directly is extremely difficult because both the partitioning strategy and the maximum operation are unknown. Upon closer analysis, if we assume that the maximum stage time across all stages is *t_max* (i.e., the second term is known), the problem reduces to optimizing only the summation term. Thus, the original problem can be reformulated as an optimization problem with a maximum-value constraint:

\begin{equation}
T^* = \min_{\substack{s_1,\cdots,s_S \\ (n_1,m_1),\cdots,(n_S,m_S)}} \left\{\sum_{i=1}^{S}{t_i} + (B-1)\cdot t_\text{max} \right\} , \ \text{subject to} \ t_i \le t_\text{max}
\end{equation}

To further account for the partitioning of both subgraphs and compute resources, we solve this using dynamic programming (DP) and define a 3-dimensional state function *F(s, k, d; t_max)*:

- It represents the minimum time allocation scheme for partitioning the computation graph from operator *o_k* to *o_K* into *s* subgraphs and placing them on *d* devices.
- Note that the original graph contains *K* operators in topological order: *o₁ → o₂ → ⋯ → o_K*.
- Each subgraph is constrained to have a maximum execution time of *t_max*.

From *F(s, k, d; t_max)* we obtain the following state transition equation:

\begin{split}F(s,k,d;t_{max})=  \min_{ k \le i \le K} \left\{t_{\text{intra}}((o_k,\cdots,o_i),\text{Mesh}(n_s,m_s),s) +F(s-1,i+1,d-n_s \cdot m_s;t_{max}) \atop| t_{intra} ((o_k,\cdots,o_i),\text{Mesh}(n_s,m_s),s) \le t_{max}\right\}\end{split}

The equation is complex but can be understood as follows:

- We consider cutting the segment *o_k → ⋯ → o_K* at operator *o_i*. The portion from *o_k* to *o_i* forms a new stage and is placed on mesh *Mesh(n_s, m_s)*. Its execution time is computed by calling the previously defined Intra-op function.
- The remaining subproblem is *F(s−1, i+1, d−n_s·m_s; t_max)*.
- Note that *Mesh(n_s, m_s)* enumerates all feasible values where *n_s · m_s ≤ d*.

It then follows that:

\begin{equation}T^*(t_{max})=\min_{s}\{F(s,0,N\cdot M;t_{max})\}+(B-1)\cdot t_{max}\end{equation}

The above 3D DP process has high computational complexity. Several tricks can be used to reduce it:

- During the enumeration of *t_max* from small to large, if *B·t_max* already exceeds the current best *T**, the algorithm can be pruned and terminated early.
- Pre-fusing non-compute-intensive operators (such as ReLU) in the original computation graph can significantly reduce the search space.

**Runtime Orchestration**

To obtain the final runnable binary, additional post-processing is required, such as inserting within-mesh and cross-mesh communication operators. Here, *cross-mesh* refers to communication between different stages. Since the communication bandwidth between stages is often limited, specific optimization strategies are needed, as shown below:

![](https://www.waytoagi.com/api/kb-media/Y0zFb80vgohT6Mxi53WcvyYSn9b)

The red edges represent slower cross-mesh communication links, while the green edges represent fast intra-mesh communication links.

For intra-mesh communication:

- If two adjacent meshes are of equal size, use the scatter-gather approach shown in (a).
- If the meshes are of unequal size, use the all-gather scheme shown in (c).

## **Experimental Results**

Alpa outperforms Megatron-LM, Inter-op Only, and Intra-op Only strategies, but still falls slightly short compared to the best manually designed solutions.

![](https://www.waytoagi.com/api/kb-media/T9ivb4u7lovAnZxWYy4cOeGvnoc)

![](https://www.waytoagi.com/api/kb-media/BO2VbRIrXoxNb2xJGxgcPPmynSd)

The search results for Wide-ResNet on 16 GPUs are also visualized.

![](https://www.waytoagi.com/api/kb-media/U2e0bSuWxo2uyexgL2RcQc1vnhg)

# Final Remarks

To summarize, this article mainly covers four key topics:

- Distributed communication primitives include point-to-point communication and collective communication methods. Collective communication encompasses one-to-many Broadcast and Scatter, many-to-one Reduce and Gather, and many-to-many AllReduce, AllGather, ReduceScatter, and AllToAll.

- 3D parallelism consists of Data Parallelism (DP), Pipeline Parallelism (PP), and Tensor Parallelism (TP).
  - DP offers excellent compute and communication efficiency, but is memory-unfriendly for model weights since each device holds a full copy.
  - PP requires a sufficiently large batch size within the mini-batch to hide the pipeline overhead. However, excessively large batch sizes increase activation memory consumption.
  - TP is very memory-friendly for weights with no redundancy. However, it is less favorable in terms of compute and communication efficiency, requiring large communication volumes. Performance degrades quickly once communication crosses an island boundary.

- To address the high memory consumption of data parallelism, ZeRO draws inspiration from the Parameter Server architecture and introduces ZeRO-1, ZeRO-2, and ZeRO-3 optimizations. Among them, ZeRO-2 allows each device to maintain only a portion of the gradients and optimizer states, reducing memory usage to 1/8 of the original while keeping communication bandwidth unchanged.

- Alpa adopts ideas from AI compilers to model 3D parallelism and uses automated search to discover parallel strategies that are second only to the best hand-crafted ones.

**PS:** Since the author (Xiao A) has not personally implemented all the details mentioned above, most of the content was summarized in a bottom-up manner through studying code and carefully reading excellent articles. Essentially, this is a knowledge aggregation effort — a “paper-based discussion.” Therefore, I sincerely welcome experts with real-world experience to provide feedback and corrections. Only through the collision of ideas can sparks fly and truth emerge through debate.

**If you want to learn about Transformer algorithms in NLP, multimodal, and AIGC, distributed training techniques, as well as how to perform PTQ quantization and deployment on TVM, feel free to follow me — aaronxic~**

# Series Navigation

[[Transformer 101 Series] What Exactly Is the Perplexity Metric?](https://zhuanlan.zhihu.com/p/633757727)

[[Transformer 101 Series] A First Look at LLM Foundation Models](https://zhuanlan.zhihu.com/p/640784855)

[[Transformer 101 Series] How Is a ChatBot Built?](https://zhuanlan.zhihu.com/p/642282717)

[[Transformer 101 Series] The Path Toward Multimodal Unification](https://zhuanlan.zhihu.com/p/643969218)

[[Transformer 101 Series] The Composition Principles of AIGC (Part 1)](https://zhuanlan.zhihu.com/p/646149258)

**References**

[Transformer Math 101](https://blog.eleuther.ai/transformer-math/)

[Summary of Distributed Training Frameworks for Large Language Models (LLMs) — PaperWeekly Blog on CSDN](https://blog.csdn.net/c9Yv2cf9I06K2A9E/article/details/130570164)

[NLP (12): DeepSpeed Inference — An Exploration of Optimizations for LLM Inference](https://zhuanlan.zhihu.com/p/629085568?utm_medium=social&utm_oi=29233275469824&utm_psn=1642573008278724608&utm_source=wechat_session)

[DeepSpeed ZeRO++: Reduces Network Communication by 4× and Significantly Improves Training Efficiency for Large Models and ChatGPT-like Models](https://zhuanlan.zhihu.com/p/639002087)

[Common Distributed Parallel Strategies — OneFlow](https://docs.oneflow.org/master/parallelism/01_introduction.html)

[Summary of Distributed Training Frameworks for Large Language Models (LLMs) — PaperWeekly Blog on CSDN](https://blog.csdn.net/c9Yv2cf9I06K2A9E/article/details/130570164)

[AI Frameworks: Distributed Systems (Part 1) — Notes](https://zhuanlan.zhihu.com/p/598859721)

[Collective Operations — NCCL 2.18.1 Documentation](https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/usage/collectives.html)

[Tutorials · MPI Tutorial](https://mpitutorial.com/tutorials/)

[Distributed Data Parallel Training Using PyTorch on AWS](https://www.telesens.co/2019/04/04/distributed-data-parallel-training-using-pytorch-on-aws/)

[Pipeline Parallelism: Distributed Training via Model Partitioning](https://siboehm.com/articles/22/pipeline-parallel-training)

[CPU Pipeline — myseries — Blog Garden](https://www.cnblogs.com/myseries/p/14458367.html)

[An Overview of Pipeline Parallelism and Its Research Progress](https://medium.com/nerd-for-tech/an-overview-of-pipeline-parallelism-and-its-research-progress-7934e5e6d5b8)

[Performance Analysis of Pipeline Parallelism for Large Model Training](https://zhuanlan.zhihu.com/p/618590870)

[Practice: Pipeline Parallel (Simplified Version)](https://zhuanlan.zhihu.com/p/626202865)

[DeepSpeed ZeRO Series: Taking VRAM Optimization to the Extreme](https://zhuanlan.zhihu.com/p/513571706)

[https://docs.google.com/presentation/d/1CQ4S1ff8yURk9XmL5lpQOoMMlsjw4m0zPS6zYDcyp7Y/edit#slide=id.g136a86a0982_0_234](https://docs.google.com/presentation/d/1CQ4S1ff8yURk9XmL5lpQOoMMlsjw4m0zPS6zYDcyp7Y/edit#slide=id.g136a86a0982_0_234)

[https://www.youtube.com/watch?v=oVC3SB3GqrI](https://www.youtube.com/watch?v=oVC3SB3GqrI)

[Integer Programming (10): Quadratic Integer Programming](https://www.zhihu.com/tardis/zm/art/465088321?source_id=1003)

[Integer Programming (1): Overview of Integer Programming Problems](https://www.zhihu.com/tardis/zm/art/406262088?source_id=1003)
