CS231n Completed

CS231n Computer Vision: Large-Scale Distributed Training (Lecture 11)

The real constraint of the trillion-parameter model is not the peak computing power but the video memory and bandwidth: the calculation is divided along the four axes of batch, sequence, layer, and dimension, and then MFU is used to determine whether each cutting method is worthwhile.

On this page

Course information

  • Course name: Stanford CS231n: Deep Learning for Computer Vision(Spring 2025)
  • Topic of this lecture: Lecture 11. Large Scale Distributed Training
  • Lecturer: Justin Johnson
  • Teaching date: 2025-05-06
  • Course homepage: cs231n.stanford.edu/2025 ↗
  • Official courseware: lecture_11.pdf ↗ (148 pages, page-by-page illustrations in the book)
  • Subtitle source: cs231n_sp25_kor_sub · eng ↗ (Publicly transcribed in English, Chinese rewritten by this book)
  • Copyright statement: The copyright of the slides and course materials belongs to Stanford University and the instructors; this book is an unofficial study note and is only used for study and research.

Lecture 11 Title Page: Large-Scale Distributed Training

More than ten years ago, the standard configuration for training a model was a graphics card; today, the default configuration for cutting-edge models is thousands to tens of thousands. This is not “running the same code several times” - it completely changes the meaning of “a gradient update”: an update needs to be synchronized among thousands of devices, and a forward needs to cross a four-layer network with decreasing bandwidth, and in addition to the weights and gradients, dozens of GB of intermediate activations must be stuffed into the video memory. This lecture aims to answer the physics and algorithms behind these two things: what exactly is in the card, and how to cut the training of a network into tens of thousands of parts while still maintaining mathematical equivalence.

The course here has reached its tenth year (Stanford CS231n 10th Anniversary is printed on the slide footer), and the lecturer’s judgment is straightforward: large-scale has become the norm for deep learning, not the privilege of a few laboratories. The first few lectures in the book are concerned with “what the model can do” - the previous lecture dealt with video input with a time dimension; this lecture retreats to a lower level and is concerned with “how these models are calculated.” The reference throughout is Llama3-405B: not because it is the strongest, but because it exposes training clusters, parallel recipes and throughput figures, and is one of the few industrial-grade cases that can be checked item by item.

1. An H100 ledger: the computing power lies in Tensor Core, and the bottleneck lies in the video memory

(Reference time: 00:00:05 – 00:14:39|Lecture 11)

Course Affairs Page: May 9 Midterm Review, May 13 Class Midterm

There are only two schedules on the second page: midterm review on Friday, May 9th, and class midterm on Tuesday, May 13th. The lecturer did not stop at this page. This position itself illustrates the positioning of this lecture - it is ranked before the midterm, and what it requires is closer to judgment than derivation: faced with a training task, can you tell which kind of parallelism should be used and at what cost.

Today's agenda: Hardware on the left, "How to train on tens of thousands of cards" on the right

There are only two halves of the agenda: A bit about GPU hardware and How to train on lots of GPUs. This dichotomy is not a typography decoration. The answer to “Why talk about the video memory layer first and then the parallel strategy” every time later is in these two lines: Each parallel strategy corresponds to a kind of communication volume, and the quality of communication is determined by the hardware topology. Let’s look at the hardware first so that every subsequent judgment of “communication is required here” has a price tag.

Running example page: GPT-4’s refusal to disclose details, and the openness of Llama3

Two passages of material are juxtaposed on the page. One paragraph is the famous sentence in the GPT-4 technical report: Considering the competitive landscape and the security impact of large models, the report will no longer disclose any details such as architecture (including model size), hardware, training computing power, data construction and training methods. The other section is Llama3, a model open sourced by Meta in April 2024. The paper discloses a large number of model and training details, especially the system infrastructure. The reason why the lecturer uses it as a running example is very real: if you want to know how today’s large models are trained, Llama3 is one of the few samples where the account books can be found; as for Llama4, which will be released in April 2025, the initial model is available, but the paper is not yet available.

The first frame of the chapter separator page: two panels light up at the same time, left "GPU Hardware" and right "How to Train"

This separator page will appear four times throughout the lecture. It is a progress bar-style design: the photo of the GPU board on the left represents the hardware half, and the photo of the cabinet on the right represents the algorithm half. Both sections are in the first frame, and the title is GPUs and How to Train On Them, which means “Both of these things need to be discussed.”

The second frame of the chapter separator page: the left half is lit, the right half is darkened, entering the hardware half

In the second frame, only the left half is left bright: the photo of the computer room on the right fades to a gray background, while the photo of the board on the left maintains contrast. This is a pure emphasis switch, with no new text on the page - it’s saying “just look at the card itself for the rest of this time”. The following six pages are a layer-by-layer enlargement of this board.

Panoramic view of H100 board: the computing core is in the center, surrounded by HBM memory particles

GPU is Graphics Processing Unit, originally created for graphics and now a general-purpose parallel processor. The physical layout of the H100 can be directly seen in this photo: the square in the middle is the computing core, and a circle of small dark squares around it are the video memory particles. The legacy left by the graphics era is that “the same set of instructions must be applied to a large number of pixels”, which is why it can be transformed into a general-purpose parallel processor - all parallelism later in this lecture essentially uses this structure of “the same operation spreads over the entire array”.

The first layer of H100 board labeling: the computing core area is framed

This frame has an additional label box on the photo, which circles the central computing core. The reason why it needs to be boxed separately is because all the subsequent figures about computing power only occur in this box, and the video memory is only responsible for supplying materials. Seeing “calculation” and “existence” physically separately is the prerequisite for understanding all subsequent bottlenecks.

H100 board marked second tier: 80 GB HBM, 3352 GB/s bandwidth

One frame further forward, the annotation adds video memory: 80 GB of HBM (High Bandwidth Memory), and a bandwidth of 3352 GB/s between the core and the video memory. These two numbers should be read together - the capacity determines “whether the model can be put in”, and the bandwidth determines “no matter how fast the calculation is, it will not be enough”. The lecturer’s original words were that it can move data at a speed of about 3 TB per second. This speed sounds great, but it only makes sense when compared with the 4096 FLOP/cycle number in the next section.

Computational core area enlargement: densely packed small squares are SM

The camera advanced into the interior of the computing core, and the screen turned into a whole field of regularly arranged small squares. This picture is visually very similar to the core layout of a CPU, but the order of magnitude is completely different: a CPU has several to dozens of cores, and here is one. It is worth noting that there are finer structures sandwiched between the blocks. Those are caches and interconnects, which determine how data travels between cores.

Core area annotation: 50 MB L2 cache across the center

This frame marks 50 MB of L2 cache. It’s three orders of magnitude smaller than 80 GB of video memory, but is physically close to the compute unit and has much lower access latency. Put that together with 80 GB, and you get the H100’s storage hierarchy: VRAM big and far away, L2 small and close. The lecturer inserted a self-deprecating sentence here - “You think you are learning deep learning, but you are actually learning computer architecture” - and this hierarchical structure is the battlefield for all subsequent performance optimizations.

The core area is marked: 132 SMs, and the footer indicates that there are 144 physical ones.

The last level of annotation gives the protagonist: 132 Streaming Multiprocessors (SM), which are parallel cores independent of each other. There is also a line of small text on the page that is very critical - there are actually 144 drawn on the picture, and only 132 are enabled because of yield (yield). This is called binning in chip manufacturing: It is impossible for all 144 units in a whole chip to be intact. The manufacturer classifies shipments according to “at least 132 usable”, thereby selling most of the wafers. This detail usually does not affect writing code, but it explains why paper specifications always have to be discounted a little.

Close-up of a single SM: something between a CPU core and a vector machine

Zoom in one more level and go inside a single SM. The analogy the slide gives is “kind of like a CPU core with vector instructions.” This analogy needs to be remembered on both sides: it can process more data (vectors/matrices) simultaneously than a CPU core, but has a slower clock and much weaker branch prediction capabilities, so it doesn’t make sense to compare it one-to-one with a CPU core; it’s more accurate to think of it as “a small shop willing to do a lot of repetitive arithmetic.”

SM internal first level: 256 KB L1 cache and 256 KB registers

This frame complements the SM’s internal storage: 256 KB of L1 cache and 256 KB of register file. There are three tiers of storage here - 256 KB L1, 50 MB L2, and 80 GB HBM. The closer the computing power is, the smaller and faster it is. This rule is the same in GPU and CPU. People who write high-performance kernels spend a lot of time on “the timing of moving data between three levels” rather than on arithmetic itself.

Second layer inside SM: 128 FP32 cores, 256 FLOPs per cycle

Next comes the arithmetic unit: 128 FP32 cores, each doing one job per clock cycle a⋅x+ba\cdot x+b, that is, one multiplication and one addition, calculating 2 floating point operations. So the entire SM outputs per cycle on FP32 128×2=256128\times2=256 FLOP. Remember this number, it is the reference for the next frame.

SM internal third layer: 4 Tensor Cores, 4096 FLOPs per cycle

The last frame is the 4 Tensor Cores marked in red. The lecturer thinks that the name is a bit misleading. They are actually “matrix kernels”: they only do one thing, which is fixed-size matrix multiplication and addition. Each Tensor Core on H100 is calculated once per cycle [16×4]⋅[4×8]+[16×8][16\times4]\cdot[4\times8]+[16\times8], one floating-point operation is calculated for each multiplication and each addition, that is 16×4×8×2=102416\times4\times8\times2=1024 FLOPs; the four Tensor Cores combined are 4096 FLOPs/cycle, which is exactly 16 times the FP32 path. Almost all the throughput of the entire chip comes from this 16 times, so if you want the GPU to run at full capacity, the calculation must be done as matrix multiplication, and it must be done on the Tensor Core.

There is another pitfall that is very easy to step on in engineering: Tensor Core does mixed precision - input 16 bits and accumulate 32 bits. If you forget to convert the model to 16-bit in PyTorch, the calculation will fall back to the FP32 core, which can be as slow as one-twentieth in actual measurements. The lecturer calls this “the one that is most easily regarded as a detail and the easiest to overturn in real projects.”

1.1 Three-level storage and a ratio: how many multiplications are required to move 1 byte

By arranging the above numbers together, you can calculate a ratio that will be used throughout the lecture. The peak Tensor Core of H100 is 989.4 TFLOP/s (16 bits), and the memory bandwidth is 3352 GB/s. The two are divided by approximately 295 FLOP/byte. In other words, every time 1 byte of data is moved from the video memory to the computing unit, nearly 300 floating point operations must be performed for the Tensor Core to be considered idle.

This ratio explains almost all subsequent designs: the arithmetic density of matrix multiplication is high (N×NN\times N multiply N×NN\times N The multiplication of is O(N3)O(N^3) Operation O(N2)O(N^2) data), so it can be fed; and the arithmetic density of element-wise operations (activation, residual, LayerNorm) is constant level, destined to run on the FP32 core, and is bandwidth limited. The same principle is put to the cluster scale, and it becomes the question of “can communication be covered by calculation?” This is a recurring theme after Chapter 3.

By the way, a checkable backend is made: 132 SMs each have 4096 FLOP/cycle, totaling 540,672 FLOP/cycle; divided by 989.4 TFLOP/s, an effective clock of approximately 1.83 GHz is obtained. This book works backwards from the slide numbers, assuming that all SMs are fully loaded and the clock is constant - this magnitude is consistent with the public H100 specifications, indicating that the numbers on the page are self-consistent with each other.

1.2 1,000 times in fifteen years: This curve is the fuel for deep learning to take off

GPU throughput curve: 5 TFLOP/s for K40 in 2013 to 5000 TFLOP/s for B200 in 2025

The horizontal axis of this graph is time (2012 to 2025), and the vertical axis is the peak throughput of a single device. The blue line is the FP32 and the green line is the Tensor Core. A few points are worth looking at one by one: the K40 in 2013 only had 5 TFLOP/s FP32; the P100 around 2016 was 10.6; the V100 was 15.7 FP32 plus 125 Tensor Core——V100 is the first card to introduce Tensor Core, and the green line only appears from here; A100 is 19.5 vs. 312; H100 is 67 vs. 989; B200 in 2025 is 83.3 vs. 5000.

The reading is more important than the numbers: the blue line has only increased about 16 times in twelve years, the green line has increased 40 times, and the green line is the real throughput. The lecturer used K40 during his PhD. He said: the weight, size and feel of the two cards are almost the same in the hand, but the speed difference is 1000 times.

Annotation on the same curve: 1000 times improvement since 2013

This frame adds a line of notes to the picture: 1000 times faster than in 2013. The lecturer gave a judgment criterion - anything that changes 1,000 times in ten years is worthy of stopping and taking it seriously, because it will definitely change the boundaries of technical capabilities. He calls this the main reason for the progress of deep learning in the past ten years: it is not that the algorithm suddenly becomes smarter, but that there is a sudden increase in computing power by three orders of magnitude that can be eaten up.

Add another line to the same curve: we can also train with more than one GPU

The second frame adds another sentence: we can also use more than one GPU. This sentence connects the story of the single card curve to the cluster - if 1000 times a single card is enough to explain the past ten years, then stacking thousands of such cards is the real source of scale for these models today. The next chapter will go from “a card” to “a data center”.

2. From 8-card server to 24,576-card cluster: bandwidth at each layer drops by an order of magnitude

(Reference time: 00:15:08 – 00:26:10|Lecture 11)

Leaflet H100: 3352 GB/s bandwidth inside the chip

Start from this picture and work your way up. The first layer is an H100: 3352 GB/s from video memory to computing unit. This is the fastest connection in the entire system and the only connection with “enough bandwidth to feed Tensor Core”. Each time you go up a level, this number will drop, and how much it drops directly determines which parallel strategy can be placed at which level.

One server: 8 H100 cards, 900 GB/s between cards

The second tier is a GPU server: almost all GPU servers come in 8-card boxes, with about 900 GB/s between any two cards. Compared to the 3352 GB/s on the card, this is a drop of about 3.7 times. This “only 3.7 times drop” is critical - it means that it is cost-effective to do parallelism that requires frequent weight exchanges (such as FSDP and tensor parallelism to be discussed later) within 8 cards.

One rack: 2 servers, 16 cards, the same bandwidth between cards

The third level is the rack: the Llama3 cluster crams two 8-card servers into a rack, for a total of 16 cards. The connection within the rack still uses the high-speed link within the server, and the bandwidth has not dropped again. The page doesn’t give a new number for the rack, just the fact that it’s “16 cards” - the real cliff is at the next level.

One Pod: 192 racks, 3072 cards, any two cards 50 GB/s

The fourth layer is the Pod: 192 racks connected, 3072 cards, interconnected by high-bandwidth connectors, about 50 GB/s between any two cards. Compared to the 900 GB/s in the server, this is another 18 times drop. Physically, this is a room that you can walk into, and there must be a passage for people to walk between the racks; this is why “Pod” is a real building unit, not a logical concept.

One cluster: 8 Pods, 24,576 cards, less than 50 GB/s across Pods

The fifth level is a complete cluster: 8 Pods make up 24,576 cards, and the bandwidth across Pods is “less than 50 GB/s” - the lecturer could not find the exact number from the paper, but can only confirm that it is slower than within the Pod. This ambiguity is precisely the point: at this level, the connection is no longer a line that can be calculated, but a network that needs to be routed. The Llama3 cluster is not yet the largest in the world. Clusters of 50,000 cards and 100,000 cards already exist, but they are not public enough to be cited one by one.

flowchart TD
    A["1 Zhang H100<br/>80 GB HBM<br/>3352 GB/s"] --> B["1 servers<br/>8 card<br/>900 GB/s"]
    B --> C["1 racks<br/>2 servers = 16 card<br/>Bandwidth no longer drops"]
    C --> D["1 a Pod<br/>192 rack = 3072 card<br/>50 GB/s"]
    D --> E["1 clusters<br/>8 a Pod = 24,576 card<br/>lower than 50 GB/s"]
    E --> F["train once Llama3 level model<br/>in months"]

The way to read this picture is to ask “how many times it dropped” every step you take from top to bottom: 3352 to 900 is 3.7 times, 900 to 50 is 18 times, and you can’t test it any higher. The choice of parallel strategy is essentially to arrange the most communication-intensive part of the calculation on the layer with the highest bandwidth. This sentence will appear repeatedly in the form of FSDP, HSDP, and ND parallelism.

2.1 What kind of machine does 24,576 cards put together?

Cluster ledger: 1.875 PB video memory, 415 million FP32 cores, 13 million Tensor Cores, 24.3 EFLOP/s

Treating 24,576 cards as a machine for accounting, we get this set of numbers: 1.875 PB of GPU memory, 415 million FP32 cores, 13 million Tensor Cores, 24.3 EFLOP/s (i.e. 24.3×101824.3\times10^{18}). Here’s a check worth doing: 1.875 PB÷24576≈76 GB1.875\ \text{PB} \div 24576 \approx 76\ \text{GB}, slightly less than the 80 GB per card, the difference being the portion of each card that is reserved for the system and runtime.

The instructor’s attitude was “treat it like a computer”: don’t think you’re dealing with 24,576 cards, but rather a machine with 24,576 cores, 1.875 PB of memory, and 24.3 EFLOP/s. This mental model directly determines how all subsequent algorithms are written - what you have to do is to arrange a schedule for this machine in which “all cores have work to do”.

Following this number, you can do an accounting: If this machine is fully loaded for two consecutive months (approximately 5.2×1065.2\times10^{6} seconds), can be delivered approx. 24.3×1018×5.2×106≈1.3×102624.3\times10^{18}\times5.2\times10^{6}\approx1.3\times10^{26} FLOP. This magnitude is an estimate derived from the book’s slide numbers and “full load” assumptions, multiplied by a 30%–40% utilization discount for real training (see MFU in Chapter 6). The intuition it gives is: the amount of floating point operations consumed by a cutting-edge training today is 102510^{25}–102610^{26} this interval.

As for “how long does the training take?”, the instructor’s experience is that the longest batch of training in ten years was measured in months, and the restriction was not mainly technical - scheduling, collaboration, and personnel all had to keep up. Training that ran for more than a year at a time was extremely difficult to maintain organizationally.

TPU v5p: 459 TFLOP/s BF16, 95 GB video memory, single Pod up to 8960 pcs

The biggest rival besides GPU is Google’s TPU (Tensor Processing Unit), which has been iterated to the sixth generation. The page gives the specifications of v5p: each 459 TFLOP/s (BF16), 95 GB video memory, and can form up to 8960 Pods. It is of the same order as H100. The difference lies in the way of obtaining it - TPU cannot be purchased and can only be used within Google or rented on Google Cloud. The lecturer judged by the way: The Gemini series almost certainly runs on TPU, but the official does not say so.

Two other training chips: AMD MI325X and AWS Trainium2

The page also lists two companies: AMD’s MI325X, 1300 TFLOP/s (BF16), 256 GB video memory; AWS’s Trainium2, 667 TFLOP/s (BF16), 96 GB video memory, installed in a set of 64 UltraServers. The parameters on paper are not weak. The lecturer’s judgment is that NVIDIA and TPU are still far ahead in terms of ecology and usability, and the others are catching up. The component of this paragraph is not in the parameter table, but as a reminder: the abstraction layer of the parallel algorithm (all-reduce, broadcast, sharding) must be designed to be independent of the specific chip, otherwise it will have to be rewritten for a new generation of hardware.

Chapter separator page: The photo of the computer room on the right half lights up, transitioning to the algorithm half

The hardware half ends here, and the separator page returns to the “two panels” form. The relationship between light and dark on both sides of this frame begins to reverse, suggesting that the following content no longer looks at the chip, but at the computer room.

Final frame of the chapter separator page: the title changes to Today, and the computer room on the right becomes the main body

The title of the last frame changes to Today: GPUs and How to Train On Them. The cabinet photo on the right becomes the clear subject and the board on the left is darkened. So far, the “stuck” thing is over: the computing power is concentrated on the 16 times Tensor Core, and the bandwidth decreases in four levels: server, rack, Pod, and cluster. The remaining five chapters can be summarized in just one sentence——How to make these thousands of cards work at the same time, and do the same thing.

3. Data parallelism: split the batch and only pay one more all-reduce

(Reference time: 00:26:12 – 00:40:53|Lecture 11)

Four-axis overview page: DP cuts Batch, CP cuts Sequence, PP cuts layers, TP cuts Dim

The algorithm map of the entire lecture is this page. one LL The layer model acts on a three-dimensional tensor of shape (Batch, Sequence, Dim), so there are exactly four possible directions: Data Parallelism (DP) cuts batch, Context Parallelism (CP) cuts sequence, Pipeline Parallelism (PP) cuts layers, and Tensor Parallelism (TP) cuts feature dimensions. The names of the four sound different, but when placed in this picture, there is only one sentence: They are all cutting the same three-dimensional tensor plus a layer axis.

The second frame of the same four-axis overview page: the layout and text remain unchanged.

This frame is exactly the same as the previous frame in terms of text, and is the second freeze frame of the animation. Its function is not to provide new information, but to make these four abbreviations present: the following 114, 126, 134, and 144 will return to this overview page repeatedly, and each time a parallel is finished, it will come back and light up a grid - it is the progress bar of the whole lecture.

3.1 Mathematically it is an equivalent transformation, not an approximation

The starting point of data parallelism: the loss is the average of N samples

The starting point is a familiar fact: mini-batch losses are usually NN average the samples. This sentence is an “implementation detail” on a single card, but it becomes the basis for segmentation in distributed systems - because averaging and summing are both linear.

The idea of data parallelism: use a large batch of MN samples, cut it into M parts and distribute them to M cards

The idea is very straightforward: if you can put it on a card NN I have a sample on hand MM If you have a card, use it M×NM\times N A large batch of , each card is assigned NN . There is only one question left: the gradient calculated in this way, and running on a card MNMN Are the gradients of the two samples the same thing?

Gradient formula: The outer layer sums M cards, and the inner layer is the backward of each card.

The answer is the same. Write the loss of large batch as

L=1MN∑i=1M∑j=1Nℓ(xi,j,W)L=\frac{1}{MN}\sum_{i=1}^{M}\sum_{j=1}^{N}\ell\left(x_{i,j},W\right)

Yes WW Taking the derivative and changing the order of summation, we get

∂L∂W=1M∑i=1M(1N∑j=1N∂ℓ(xi,j,W)∂W)\frac{\partial L}{\partial W}=\frac{1}{M}\sum_{i=1}^{M}\left(\frac{1}{N}\sum_{j=1}^{N}\frac{\partial \ell\left(x_{i,j},W\right)}{\partial W}\right)

The item in brackets happens to be “on a certain card.” NN Do a normal backward” on each sample. Because the gradient is linear, the order of summation and averaging can be changed at will., so this is not an approximation, it is the same number - the lecturer emphasized this point by saying “we just used a little algebraic cleverness”.

The inner layer is done independently by each card: it computes the gradient on its own N samples

So the inner layer does not need any communication: each card is in its own NN Go forward and reverse on each sample to get a local gradient. This part is “true parallel”, the cards are independent of each other and do not need to be synchronized.

The outer layer is a cross-card average: M local gradients are synthesized into the global gradient

The rest is the outer one 1M∑\frac{1}{M}\sum: Average the local gradients of all cards. This communication is the entire cost of data parallelism—an all-reduce. Other than that, DP doesn’t change any math.

3.2 Six-step execution and that all-reduce

DP Step 1: Each card has a complete model and optimizer state

Landing on the device, the first step is for each card to save a complete copy of the model weights, optimizer state and gradient buffer. The instructor specifically said here, “Only 3 cards are shown in the picture because the layout can accommodate them, and the real number is much greater than 3.” This step also determines the ceiling of DP: the entire set of parameters, gradients and optimizer states must be accommodated in the video memory.

DP Step 2: Each card loads its own mini-batch

The second step is to load the data separately: GPU 1 takes x1,⋅x_{1,\cdot}, GPU 2 takes x2,⋅x_{2,\cdot}, GPU 3 takes x3,⋅x_{3,\cdot}. The lecturer inserted a real bug story here: his and his student’s code accidentally caused all cards to load the same batch of data - that way the training would not report an error, it would just run in vain, and it would be extremely difficult to see from the loss curve. “The data must be different for each card” is the first correctness condition of DP.

DP Step 3: Each card moves forward independently to obtain its own local loss

The third step is to move forward individually and obtain local losses. L1,L2,L3L_1,L_2,L_3. There is zero communication and zero dependence in this step - the three cards can complete their forward motion completely asynchronously.

DP step 4: Each card reverses independently to obtain its own local gradient.

The fourth step is to reverse each direction to obtain the local gradient of the four weight matrices. ∂Li/∂W1…∂Li/∂W4\partial L_i/\partial W_1 \dots \partial L_i/\partial W_4. Also zero communication: each card has a complete copy of the weights, so it can calculate the gradient of the entire link locally.

DP step 5: cross-card all-reduce, the red arrow is to summarize the gradient to the global

The fifth step is communication: all-reduce. It does two things at the same time - each card broadcasts its own gradient, and it collects the gradients of all cards at the same time. In implementation it is usually O(log⁡M)O(\log M) done within the wheel instead of MM Round point-to-point; after this step, each card has exactly the same average gradient for the entire macro-batch.

DP Step 6: Each card updates its own weight using the same gradient

Step 6: Each card updates its own weight with the same gradient. Because the starting point is the same and the gradient is the same, the updated weights are also the same (provided that it is determined arithmetic). This step is zero communication again - the price was paid in step five.

Key optimization of DP: Steps 4 and 5 can be overlapped

The real engineering gist is in this frame: steps 4 (reverse) and 5 (communication) can be parallelized. Backpropagation is pushed forward from the last layer. Once the gradient of the last layer is calculated, you can perform all-reduce on the last layer while continuing to calculate the reverse direction of the penultimate layer. The deeper the layer, the greater the space for “communication hidden behind calculations”. Ideally, the gradients have been summarized when the reverse calculation is completed, and there is no need to wait for weight updates.

But it’s not free: when the lecturer was asked “Whether step 4 or 5 will be the bottleneck”, the answer was “it depends” - it depends on how fast the device is, how big the model is, how big the mini-batch is, and how fast the interconnection between cards is. In large-scale training, the answer to almost all questions is “test it on your cluster.”, this sentence is worth remembering as a methodology.

Incidentally, there is an asymmetry at the implementation level: within a single card, many asynchronous copies of CUDA are automatically scheduled by the hardware; but at the cluster level, no hardware will arrange such a schedule for you, and the overlap of communication and calculation must be explicitly orchestrated by the software. PyTorch DistributedDataParallel It is the layer that encapsulates this set of orchestration, allowing the model code written in ordinary way to obtain overlapping capabilities almost transparently.

3.3 Why not just go their separate ways: the old path of asynchronous SGD

Someone in class asked a natural rhetorical question: Since communication is so expensive, why not just let each card take a few steps and sync it occasionally? The lecturer said that this road has really been walked by some people, and it is called asynchronous SGD (asynchronous SGD): maintaining multiple copies of the model, updating each independently, and averaging once every other time. Google had used this set before developing its own TPU Pod, and some networks in the early 2010s were trained this way.

Its problem is not theoretical, but engineering: training is more unstable, debugging and reproduction are extremely difficult, and the final effect is usually a little worse. So as long as the synchronization solution works, everyone still chooses synchronization——Because synchronization allows the whole thing to be reasoned about and reproduced. The lecturer also left an open judgment: as the cluster continues to grow larger, “no one machine can have a God’s perspective on the whole situation” will become more and more prominent, and asynchronous methods may come back in new forms.

There is another conceptual distinction that is easily overlooked: during backpropagation, each card only needs its own “local upstream gradient” to calculate, but to get the “global upstream gradient” it must communicate. The two look the same in the code, but they are two different things in the distribution -All all-reduce is changing “local” into “global”, and each conversion requires bandwidth.

3.4 Ceiling for this path: 8 bytes per weight

Data parallelism problem: model size is locked by single card graphics memory

DP cuts the data very cleanly, but the weights are copied rather than divided, so the model size is locked by the single-card graphics memory. The page calculates the account very carefully: each weight requires four numbers - the weight itself, its gradient, and Adam’s two second-order moments. β1,β2\beta_1,\beta_2; If 16-bit precision is used, each number is 2 bytes, totaling 8 bytes/parameter. So 1 billion parameters requires 8 GB, and 10 billion parameters requires 80 GB - exactly the entire video memory of an H100. That is, the upper limit of pure DP is around 10 billion parameters, while the target model is one to two orders of magnitude larger than this.

Preview of the solution to data parallelism: switch the model weights to different cards

The solution given on the page is only one line: cut the model weights to multiple cards. This line is all about the next chapter - it changes “copy” to “sharding” at the cost of going from “one all-reduce” to “two broadcasts plus one gradient summary per layer”.

4. FSDP and HSDP: cutting weights on top of data parallelism

(Reference time: 00:41:03 – 00:53:22|Lecture 11)

Let me first explain the naming: the section title of the courseware refers to this mechanism as FSPD, while the text page, summary page and ZeRO paper are all written as FSDP (Fully Sharded Data Parallelism). This book uses FSDP uniformly.

Static layout of FSDP: each weight W_i is owned by a card and manages its gradient and optimizer state

The starting point of FSDP is to convert each weight matrix WiW_i Assigned to an “owner” card that is responsible for the global gradient and optimizer state of this weight. The granularity of segmentation is a layer rather than a single scalar - what you manage is a “weight matrix of a certain layer”, not a number. The picture shows a 2-card, 4-layer network: GPU 1 has W1,W2W_1,W_2, GPU 2 has W3,W4W_3,W_4. After this step, the resident video memory of each card is reduced from “full set weight” to ”1/M1/M Set weight plus its gradient and optimizer state”.

FSDP Step 1: Before forwarding to a certain layer, the owner broadcasts the layer weight to all cards

But after the weights are cut, the forward direction cannot be calculated directly: the calculation of the first layer requires a complete W1W_1, and only GPU 1 has it in hand. So step 1 is broadcast - before counting ii before layer, WiW_i The owner issues it to all cards. This step is pure communication without any calculation.

FSDP Step 2: All cards use this weight to calculate the forward direction, and then delete the local copy

Step 2: Get all cards WiW_i Then each moves forward, delete the local copy immediately after the calculation, and return the video memory to the next layer. Therefore, the property of “weight sharding” is restored at the end of each layer: at any time, each card only has the complete weight of the current layer (and the next layer in prefetch), and the remaining layers only have the piece it owns.

Pipelining of FSDP: while calculating the forward direction of the i-th layer, prefetch the weight of the i+1-th layer

This frame adds a key optimization to the entire solution: prefetching. Since it needs to be deleted at the end of step 2, what about the next step? ii You can layer it at the same time Wi+1W_{i+1} Pull over - green “Fetch Wi+1W_{i+1} while computing forward with WiW_i“That’s it. Without this step, each layer would have to stop and wait for a broadcast. The deeper the network, the greater the waste; with it, communication is stuffed into the calculation time of the previous layer.

FSDP animation advancing to layer 3: W3 is flowing from GPU 2 to GPU 1, W4 is still gray

In this frame you can see prefetching in progress: GPU 1 W1,W2W_1,W_2 It’s already solid (calculated), W3W_3 It’s a light-colored block being pulled from GPU 2 by the red arrow. W4W_4 Still gray (not picked up yet). The list on the left still stops at items 1 and 2, indicating that it shows “the same two-step process repeated layer by layer” rather than a new mechanism.

FSDP animation frame continuation: The list is still items 1 and 2, and the diagram on the right continues to advance layer by layer.

051 is the next frame of this animation. There is no addition of text, and the diagram on the right continues to move forward. What it wants to convey is actually already written in the list: steps 1 and 2 will be repeated exactly on each layer, so The forward communication volume is equal to “the entire set of weights is completely broadcast once”——The weight of each layer must undergo a transfer from the owner to the owner.

FSDP animation last frame: the last freeze frame of the same page

052 is the last freeze-frame of the same animation, and there is also no new text. Looking at the three frames together, it is not about a new mechanism but a rhythm: as long as the weights are fragmented, each layer must be taken first, calculated and then thrown away. The more layers, the longer the pipeline, and the more communications that prefetching can cover.

FSDP Step 3: Before reversing a certain layer, the owner broadcasts the weight of the layer again

After the reverse starts, the same process has to be repeated: count the ii Before the reverse of the layer, WiW_i The owner of broadcasts again. This time the broadcast reuses the same weight, but it has been deleted at the end of the forward direction, so it must be retransmitted.

A small optimization of FSDP: do not delete the weight of the last layer at the end of the forward direction

The first optimization is given in the upper right corner of the page: do not delete the weight of the last layer at the end of the forward direction. Because all the cards have just received it and will use it in the reverse direction immediately, it is a waste to delete it and then upload it again. This optimization only saves “one layer” of communication traffic, but it is zero cost and will be done in practice.

FSDP Step 4: Each card uses the broadcast weight to calculate the reverse, obtain the local dL/dW_i, and then delete the weight

Step 4: Use this weight to calculate the ranking of each card. ii The reverse of the layer, get your own part of the dL/dWi\mathrm{d}L/\mathrm{d}W_i, and then delete the weights. Note that the gradient generated here is “local” - it only reflects the card’s NN samples.

FSDP step 5: Each card sends the local gradient back to the owner and deletes the local gradient

Step 5: Each card sends the local gradient to the owner and deletes it locally. This is different from DP’s all-reduce: DP is “everyone needs a global gradient”, FSDP is “only the owner needs a global gradient” - according to the lecturer’s description, each card only needs to send the gradient back to the owner, and there is no need to broadcast it to everyone. As the direction of communication changes, so does the flow.

FSDP Step 6: The owner accumulates the complete gradient and updates his own weight in place

Step 6: The owner accumulates the received local gradients into complete gradients and updates them in place WiW_i. There is no need to broadcast again after the update - it will be used naturally next time forward, and then it needs to be sent out.

The steady state of FSDP: taking weights, calculating reverse, summarizing and updating, three things are flying at the same time

Starting from this frame, the page demonstrates the “steady state of the reverse phase”. Green annotations mark how three things overlap: Count Wi−1W_{i-1} When in reverse direction, the Wi+1W_{i+1} weight, summarize and update WiW_i. So at any time, there are three levels moving on the assembly line at the same time.

FSDP steady state continues: GPU 2 has saved dL/dW4

There is a red mark on the right side of this frame ∂L1/∂W4\partial L_1/\partial W_4 with ∂L2/∂W4\partial L_2/\partial W_4: Both local gradients of the last layer have arrived at the owner GPU 2 and are being synthesized into the global gradient. You can see that the gradient is gradually accumulated by “layer”, starting from the last layer forward.

FSDP Steady State Continuation 2: dL/dW3 also begins to summarize

One frame further forward, ∂L/∂W3\partial L/\partial W_3 Came in too. A rule can be seen here: every time a layer is advanced in the reverse direction, the gradient of one layer is summarized and a weight update is triggered, while at the same time the weight of the next layer is being prefetched - the three things are strictly staggered by one layer.

Three things of FSDP are in the same frame: update W3, reverse transmission W2, and prefetch W1

This frame writes the steady state into three lines, which is also the summary of the whole page: All at the same time——Send W3W_3 gradient and update W3W_3, use W2W_2 Run reverse, prefetch W1W_1. The lecturer’s description of this paragraph is “In a very deep network, these three things are always happening at the same time in the steady state.”

FSDP steady-state final frame: all four gradients on GPU 1

062 and 063 respectively complete the gradient panels on the two devices: GPU 1 and GPU 2 each collect four layers of local gradients. At this point, a complete FSDP iteration is closed.

The other side of the FSDP steady state: the same set of arrows from the GPU 2 perspective

Comparing the two pictures, you can see the structural difference between FSDP and DP: in DP, each card has four complete gradients, while in FSDP, only its own copy is “complete”, and the rest are parts sent by others.

FSDP ending: Replace the next batch of data and start again. The data loading has been prefetched during the forward and backward periods.

The last frame adds the data side: replace the next batch of data and repeat the entire process; and the data loading is completed asynchronously during this round of forward and reverse (usually running on the server CPU). The lecturer calls this type of system a “parallelized machine” - GPUs must overlap internally, GPUs must overlap, and data loading must also overlap. There is only one goal: Keep Tensor Cores as free of idle cycles as possible.

4.1 HSDP: Layering traffic according to topology

The layout of HSDP: N = M×K cards are divided into M groups, and K cards in each group are used for FSDP.

FSDP can already train large models, but its communication volume is proportional to the number of cards. After expanding to hundreds of cards, communication begins to overwhelm computing. HSDP (Hybrid Sharded Data Parallelism) method is to divide the card into MM group, each group KK Zhang: Do FSDP within the group (cut the weights into KK portion), do ordinary DP between groups (save a complete weight for each group). The example given on the page is M=2M=2, K=4K=4, and indicate KK can arrive O(100)O(100) this magnitude.

Second frame of HSDP: Read this image as a 2D grid

This frame adds a key sentence: This is multidimensional parallelism -Use two different parallel strategies simultaneously, arrange the GPUs into a two-dimensional grid. The coordinates of each GPU in the grid (m,k)(m,k) It also determines its role in two strategies: kk is its serial number in the FSDP group, mm is its group number in the DP dimension.

HSDP communication account: 3 times the weighted traffic within the group, 1 times the weighted traffic between groups

This page is the reason for the existence of HSDP, and it is also the most practical account in the whole lecture: FSDP within a group requires three weight-level communications (once in the forward direction, once in the reverse direction, and another gradient transmission in the reverse direction), while DP between groups only requires one time (gradient all-reduce). Since you have to pay 3 times the amount within the group, you should put it on the fastest layer - the same server or the same Pod; it is acceptable for the line between groups to be slower because it only happens once.

This line of reasoning connects the bandwidth ladder from Chapter 2 directly to the algorithm here: It’s not “which kind of parallelism is faster”, but “which kind of communication should be placed on which level of line”. The 900 GB/s in the server can handle 3 times the traffic, and the cross-pod <50 GB/s can only handle 1 times the traffic, and the account will be even.

DP family ledger: 100B parameters 800 GB, 10 GB per card after switching to 80 cards

Looking at DP, FSDP, and HSDP together, the benefits are in magnitude: the account of 1 billion parameters has just been calculated (8 GB), here it is replaced by 100 billion parameters - 8 bytes/parameter requires 800 GB, which cannot be installed on one card, but if it is cut to 80 cards, it will be 10 GB per card. The constraint “the model cannot fit into a card” is no longer valid from this page.

The new bottleneck: activation value. Llama3-405B requires 63 GB just for FFN hidden layer activation

But after the weights are solved, the second bottleneck immediately comes up: the activation value. The page calculated an account using Llama3-405B: 126 layers, model dimensions D=16384D=16384, sequence length 4096, only the activation of the FFN hidden layer is 2×126×(4×16384)×40962\times126\times(4\times16384)\times4096 Bytes ≈ 63 GB. Take it apart and look at this formula: 2 is the number of bytes of 16 bits, 4D=655364D=65536 is the middle width of FFN, 4096 is the sequence length, 126 is the number of layers——This is the amount that a sample takes up in one forward direction., not counting attention and other intermediate results.

Solution preview: Do not save all activations, recalculate as needed when reversing

The solution on the page is another line: Do not store all activations in the video memory, and recalculate when needed. This may sound like a cliché of “trading time for space,” but the curve it creates is pretty neat - figure that out in the next chapter.

5. Activation Checkpointing: Exchange computing power for video memory, to O(N√N)

(Reference time: 00:53:27 – 00:55:53|Lecture 11)

The formal starting point of activation checkpoint: each layer is a "forward function" and a "reverse function"

To settle this account, first look at the network from a different perspective: each layer is actually two functions. Forward position ii The activation of the layer becomes the i+1i+1 layer activation, Ai+1=Fi→(Ai)A_{i+1}=F_i^{\rightarrow}(A_i);Reversely take the upstream gradient and the activation of this layer to calculate the gradient of this layer, Gi=Fi←(Ai,Gi+1)G_i=F_i^{\leftarrow}(A_i,G_{i+1}).The key is to have both in the reverse input AiA_i and Gi+1G_{i+1}——This is why ordinary training must retain the activation of each layer.

Another question on the same page: Assuming that each forward/reverse is O(1) calculation and O(1) memory, how much is the total cost?

The page asks a question that can be calculated by hand: if each F→F^{\rightarrow} with F←F^{\leftarrow} All O(1)O(1) The calculated sum of O(1)O(1) How much does it cost to perform a complete forward and reverse operation of video memory? In order to be able to count clearly, using a 4-layer network as an example, two counters are given in the upper right corner of the page: Current Memory and Peak Memory.

Accounting frame 1: Completed layer 1 forward, current 1, peak 1

The first forward end, A1A_1 After landing, the current video memory is 1, and the peak value is also 1. The counter starts running.

Accounting frame 2: Layer 2 forward completed, current 2, peak 2

The second level is finished. A2A_2 Also keep it, the current video memory becomes 2, and the peak value rises to 2. It can be seen that under the naive approach, “current” and “peak” are the same number - because it only increases but does not decrease.

Accounting frame 3: Layer 3 forward completed, current 3, peak 3

The third level is calculated, current 3, peak 3. The pattern is already clear here: the peak value of simple approach is equal to the number of layers.

Accounting frame 4: All four forward layers are completed, current 4, peak 4

All four floors are completed forward, A1A_1 Arrive A4A_4 All in video memory, current 4, peak 4. Yes NN layer network, which is O(N)O(N) Video Memory – Also where those 63 GB at the end of Chapter 4 come from.

Accounting frame 5: Forward ends, reverse has not yet started, video memory stops at peak 4

Nothing changes in the frame before the reverse starts: current is still 4, peak is still 4. The function of this frame is to nail the concept of “peak value” - all subsequent optimizations only suppress the peak value, not the average.

Accounting frame 6: After calculating the 4th layer reverse direction, activate A4 to release, current 3, peak 4

The reverse direction starts from the last layer. Finished G4G_4 after A4A_4 It is useless, delete it, and the current video memory drops back to 3; but the peak value is already recorded at 4 and will not drop.

Accounting frame 7: Layer 3 reverse completed, current 2, peak 4

Moving on, current 2, peak 4. The curve begins to decrease monotonically, but the peak value does not move.

Accounting frame 8: Reverse travel completed, current 1, peak 4

The reverse direction ends, and there is currently only 1 left, and the peak is still 4. The conclusion of these four frames can be summarized in one sentence: The time for simple training is O(N)O(N), the memory peak is also O(N)O(N), and the peak value appears at the moment when the forward direction just ends.

Conclusion frame: forward plus reverse = O(N) computation, O(N) memory

The page writes the conclusion on the right: Forward+backward Yes O(N)O(N) calculation, O(N)O(N) video memory. There is no new mechanism here, it just changes “why the video memory is not enough” from a feeling to a formula.

Propose a plan: recalculate the activation when going reverse instead of saving it

The real idea is in the last line: Idea - recalculate activation during the reverse process. Since AiA_i Can be obtained from Ai−1A_{i-1} Calculate it again, then don’t save it and calculate it when you use it. The cost is clear: more computation.

Recalculate frame 1: only forward to layer 1, immediately discard A1, current 1, peak 1

The second round of demonstration changed the strategy: go forward to level 1 and get A1A_1 It is discarded immediately, and only a count of the “starting point” state is retained. Current 1, Peak 1.

Recalculate the 2nd frame: After completing the 2nd layer in the same way, the peak value is still 1

The second layer is processed in the same way, and the video memory does not increase. This is what “no memory activation” means literally: the memory curve is squeezed to 1.

Recalculate frame 3: continue flattening, current 1, peak 1

Frame 3, the count is still 1. This round has exposed the shape of the cost: every time you want to use activation, you have to start from the nearest starting point and calculate forward. The closer you are to the front end of the network, the more layers you have to go through at a time——N2N^2 It just grew out of here.

Recalculate the 4th frame: the entire forward path is completed, the video memory is always 1

After walking the entire forward direction, the peak value is still 1. Compared with the peak value of 4 in the first round, Video memory from O(N)O(N) dropped O(1)O(1).

Recalculation Frame 5: End of forward, only the last layer of activations in hand

But the price is immediately apparent: now I only have the activation of the last layer in my hand. To calculate the reverse of the third layer, I have to first activate it. A3A_3 Calculate it again.

Recalculate frame 6: In order to calculate the last layer of inversion, first recalculate the activation before A4, current 2, peak 2

Recalculation begins and the counter increases from 1 to 2. Note that the peak value has also changed from 1 to 2 - the recalculation itself also takes up a bit of video memory.

Recalculation Frame 7: Alternate recalculation and reverse, current 2, peak 2

This frame enters an alternating rhythm: one layer of recalculation and one layer of reverse transmission. Current 2, Peak 2.

Recalculate frame 8: continue alternating, video memory does not increase

Continue to alternate, the video memory stabilizes at 2 and no longer increases. This is exactly the desired effect: No matter how deep the network is, the peak value does not increase with the number of layers.

Recalculation frame 9: one recalculation completed, one release, current 1, peak 2

This frame the current value falls back to 1: the activation just recalculated is released after the backpropagation. The peak value is still 2.

Recalculation frame 10: Entering the next round of recalculation, current 2, peak 2

Another round, now back to 2: This time the starting point is further forward, and you have to count several levels in succession to get the required activation.

Recalculation frame 11: alternation continues, peak stabilizes

In frame 11, the rhythm remains unchanged: one layer of recalculation, one layer of reverse pass, and one layer of release. The peak value is pinned to 2 and does not move.

Recalculation 12th frame: another release, current 1, peak 2

Currently back to 1, another temporary activation is released after the backpass.

Recalculate frame 13: There are two layers left to process, current 2, peak 2

Current 2, the next period of recalculation begins. The further you go toward the front end, the more layers you need to recalculate at a time, but the peak value remains the same—what changes is the time.

Recalculate frame 14: Reach the front end of the network, current 1, peak 2

Last release, current 1, peak 2. By the end of the entire reverse, the peak is locked at 2 instead of 4.

The first line of the general ledger: Full recalculation requires O(N²) calculation and O(1) video memory

The page places three curves side by side. Article 1: Full recalculation. Video memory is O(1)O(1), the calculation is O(N2)O(N^2)——Because the first NN The reverse direction of the layer needs to be recalculated N−1N-1 layer, no. N−1N-1 Layer needs to be recalculated N−2N-2 layers, which add up to N+(N−1)+⋯+1N+(N-1)+\dots+1.

General Ledger Line 2: N² is too expensive to compute

Followed by a comment: N2N^2 calculation is unacceptable. For 126-layer Llama3, this means redoing the forward direction hundreds of times - the memory saved is wasted because computing power becomes the new bottleneck.

The third line of the general ledger: Do not recalculate the entire amount, save a checkpoint for each C layer

Compromise: Each CC A checkpoint is stored in each layer and is only recalculated within this segment. The number of layers between checkpoints becomes smaller, and the cost of recalculation drops from “the entire network” to “a segment of the network”.

General ledger line 4: C checkpoints = O(N²/C) computation, O(C) video memory

Written as a formula: CC checkpoint corresponding to O(N2/C)O(N^2/C) The calculated sum of O(C)O(C) of video memory. Intuitive understanding - the length of each paragraph is about N/CN/C, the cost of intra-segment recalculation is (N/C)2(N/C)^2, a total of CC segment, total N2/CN^2/C; while the resident video memory only needs to store CC checkpoint.

The fifth line of the general ledger: Take C = √N, and get O(N√N) calculation and O(√N) video memory

To balance the two exponents, take C=NC=\sqrt{N}, get O(NN)O(N\sqrt{N}) The calculated sum of O(N)O(\sqrt{N}) of video memory. This result is worth a pause: Video memory from O(N)O(N) down to O(N)O(\sqrt N), calculated only from O(N)O(N) rise to O(NN)O(N\sqrt N). For layer 126, 126≈11\sqrt{126}\approx11, the video memory is reduced to about 1/11, and the calculation is increased by about 11 times - this is exactly what the lecturer said “activation checkpointing is annoying because it makes everything slower, but it does allow you to train much larger models.”

6. From recipe to compass: HFU vs. MFU

(Reference time: 00:56:01 – 01:03:03|Lecture 11)

Scaling Recipes: From DP to FSDP, Checkpoint, HSDP, to CP/PP/TP

At this point, I already have four tools in hand, and I can give you a recipe that can be followed directly:

  • first stage: The model has about 1 billion parameters and the number of cards is within about 128. It can be parallelized with ordinary data and it works very well.
  • second stage: Each card batch is always opened to the maximum value that the video memory can bear. This is almost always true.
  • The third stage: The model exceeds 1 billion parameters, consider FSDP; further up, you will encounter the activation memory bottleneck, turn on the activation checkpoint - it will slow down the training, but it will allow you to continue to grow.
  • Stage 4: When the number of cards reaches several hundred (it says >256 on the page), FSDP communication becomes uneconomical, so switch to HSDP.
  • The fifth stage: Only when the number of cards exceeds a thousand, the model exceeds 50 billion parameters, and the sequence length exceeds 16K, more complex means such as CP, PP, and TP are needed.

There is also a line of small print under the recipe, which is the turning point of the whole lecture: The problem is that there are too many knobs to adjust - global batch, batch per card, dimensionality of HSDP, dimensionality of FSDP, how many layers to recalculate - how to set it? The answer is to optimize a metric: Model FLOPs Utilization (MFU).

6.1 HFU: How full can the hardware go?

HFU’s question: H100 theory 989.4 TFLOP/s, how much can you get in practice?

The theoretical peak of the H100 at 16-bit matrix multiplication is 989.4 TFLOP/s. This number is the upper bound of “if everything is perfect”, so a natural question arises: How much can you actually get? The metric that measures this is called Hardware FLOPs Utilization (HFU) - what percentage of the matrix multiplication performance you can theoretically achieve is actually achieved.

The definition of HFU: the ratio of the actual matrix multiplication throughput to the theoretical value

The definition itself is very simple, but the difficulty is to measure it accurately. The instructor emphasizes that this is nothing complicated: write a few lines of PyTorch, run a loop, time it, divide it.

HFU test method: only matrix multiplication is run, and CUDA_LAUNCH_BLOCKING=1 must be turned on

The benchmark test given on the page is deliberately “optimal”: it only runs dense matrix multiplication and does nothing else. There is also a very practical pitfall - it must be set up CUDA_LAUNCH_BLOCKING=1, otherwise the GPU kernel is started asynchronously, and the time you measure on the Python side is not the real time consumption of the kernel at all, and the number will be completely wrong. This is the most common type of error in performance measurement: What is being measured is not what you think it is being measured.

The result of HFU: when the matrix is large enough, about 80% on H100

The horizontal axis is the matrix size (from 512 to 32000) and the vertical axis is the HFU. The curve converges to about 80% at large matrices: This shows that the simply written PyTorch matrix multiplication can achieve 80% of the theoretical peak as long as the scale is large enough. This also explains why “small batch training” is inefficient - the matrix is ​​too small, and 80% will drop to a very low level.

The problem with HFU: it does not include "peripheral" calculations such as activation checkpoints, data augmentation, optimizers, etc.

But HFU has a fatal flaw: it only counts matrix multiplications. Real training also includes activation functions, normalization, residuals, data loading and enhancement, optimizer updates, and recalculations caused by activation checkpoints - these are not in HFU. So an indicator is needed that takes into account the “entire training cycle”.

6.2 MFU: How much does the model really get?

MFU's five-step algorithm: calculate theoretical FLOP, check peak value, calculate theoretical time, measure actual time, divide

The definition of Model FLOPs Utilization is: What proportion of the theoretical peak of the GPU is used in the “model” forward and reverse directions. The algorithm is divided into five steps:

  1. Calculate a matrix multiplication FLOP of forward plus reverse according to the model structure. The reverse can be approximately 2 times the forward; ignore element-wise operations such as nonlinearity, normalization, and residual, because they run on the FP32 core.
  2. Check the theoretical peak value of the device, H100 is 989 TFLOP/s.
  3. Calculate theoretical time ttheoretical=FLOPtheoretical/FLOP/speakt_{\text{theoretical}}=\text{FLOP}_{\text{theoretical}}/\text{FLOP/s}_{\text{peak}}.
  4. The actual measurement time of a complete iteration includes data loading, forward, reverse, and optimizer updates.
  5. Divide the two, MFU=ttheoretical/tactual\text{MFU}=t_{\text{theoretical}}/t_{\text{actual}}.

Example of MFU: Wide MLP increases batch size, about 49% on a single H100

The page gives a measured example: a wide MLP with only ReLU, a very large batch, a single H100, and the MFU is about 49%. This number is much lower than 80% of HFU, and the difference is the overhead that is “not included in matrix multiplication” - this is exactly what MFU wants to expose.

Usage of MFU: Turn all knobs and adjust MFU to maximum

Therefore, there is only one objective function for parameter adjustment: adjust all adjustable knobs to the maximum MFU. The instructor’s statement is “When you are lost in the ocean of GPU parallelism, MFU is your guiding light.”

Experience threshold: MFU above 30% is considered good, MFU above 40% is considered excellent

The experience threshold is very simple: above 30% is considered good, significantly below 30% indicates a huge bottleneck in the system, and above 40% is already a good level.

Industry Reference: Llama3-405B on 8000 to 16000 H100 sheets, MFU in high 30% to early 40%

Compare with real numbers: Llama3-405B used 8,000 to 16,000 H100 sheets in the final stage, and the MFU was roughly over 30% to early 40%. The instructor said that’s good enough - it’s basically impossible to go much higher on the H100.

Counter-intuitive page: The newer the device, the lower the MFU is sometimes.

The last page is the most counter-intuitive conclusion of the entire lecture: new generations of devices often have lower MFU than the previous generation. The reason is that the computing power increases faster than the bandwidth - from A100 to H100, the theoretical computing power is about 3.1 times, and the memory bandwidth is only about 2.1 times. The numerator rises quickly and the denominator cannot keep up, so the ratio of utilization rate naturally declines. This also explains why it was sometimes over 50% on previous generation cards.

7. Three remaining axes: CP, PP, TP and ND in parallel

(Reference time: 01:03:09 – 01:12:07|Lecture 11)

The lecturer confessed one thing here: the first ones (DP, FSDP, HSDP, checkpoint, MFU) are what most people will really use, because few people can encounter a cluster of 10,000 cards; the next three axes are more about “knowing that it exists and knowing what problems it solves.” But they are not abstract - each corresponds to a specific communication pattern and a specific performance curve.

The four-axis overview page appears again: this time we will talk about the CP on the right and the PP and TP below.

The progress bar returns to the starting point. The focus of this round is on the remaining three squares; the lecturer took the precaution first - they appear much less frequently than the previous set of punches, but each one corresponds to a specific communication mode, and the cost of understanding is very low. It is enough knowledge to “know that it exists and what problem it solves”.

The second frame of the four-axis overview page: the same layout, used to switch to the next section

This frame has the same text as the previous frame, and its function is to realign the screen to “Talk about CP from scratch”.

7.1 Context Parallelism: cut sequence

CP’s idea: split a long sequence into multiple cards, and each card processes one of its segments

Context Parallelism (CP) cuts the sequence dimension: one LL Long sequences are no longer occupied by one card, but different positions are allocated to different GPUs. The page is specifically marked Usually for Transformers - because its entire discussion is based on the premise that “the model has a sequence axis that can be stretched very long”.

The easy part of CP: LayerNorm and residuals have no weight and can naturally be divided by position

The good news is that most of the structures in Transformer are position-by-position independent of the sequence: LayerNorm and residual connections have no weights, just cut them apart, and there is no need for communication.

The middle part of CP: MLP can be cut, but has weights, and the gradients must be synchronized like DP

MLP can also be cut - each token passes through the same MLP independently - but there is weight in MLP. So each card retains a complete weight, and synchronizes the gradient once in reverse, exactly the same as the DP in Chapter 3. Therefore, the cost of CP on MLP is equal to a small DP on this layer.

The difficulty of CP: Attention requires all positions to interact in pairs

The real trouble is attention. This is also the watershed between CP and DP: the data of each card in DP is irrelevant to each other, while attention requires interaction between any two positions in the sequence.

The structure of the attention matrix: Q, K, and V are each cut into three segments, and the score matrix is a 3×3 all-to-all block.

This picture draws the difficulty very clearly: after the sequence is cut into 3 segments, Q1,Q2,Q3Q_1,Q_2,Q_3 with K1,K2,K3K_1,K_2,K_3 To multiply two by two, we get a 3×33\times3 The score block matrix of Ai,jA_{i,j}, then do softmax and multiply VV get YY.As long as the sequence is cut, this matrix must cross device boundaries.

The first solution to CP: QKV projection is treated the same as MLP

The first step is to deal with the simple parts first: QKV projection is just a linear transformation by position, which can be divided into sequences. The gradient synchronization method is consistent with DP.

The fork in the road of CP: attention operator is the most difficult piece to parallelize

The rest is the core attention operator. The page gives two routes.

Route 1 Ring Attention: Divide attention into chunks, inner loop K/V, outer loop Q

Ring Attention cuts the complete attention matrix into blocks and distributes them to each GPU, allowing them to process them in turn in the correct order: the outer loop query block, the inner loop key/value block, and the blocks are passed along the ring. Complex to implement, but scalable to extremely long sequences.

Route 2 Ulysses: Instead of cutting the attention matrix, split it according to the head of multi-head attention.

Ulysses’ idea is more ingenious: Since Transformer uses multi-head attention, it should be divided according to “heads” - each card is responsible for a part of the head, and the attention matrix itself is not cut. The implementation is much simpler, but the upper limit of parallelism is the number of heads.

Industrial usage: Llama3 first stage 8192 does not cut, second stage 131072 uses 16-way CP

The actual usage is in stages: the first stage of Llama3 training has a sequence length of 8192, without using CP at all; in the second stage, the sequence is stretched to 131,072, and 16 context parallelism is enabled. Therefore, each sequence is processed collaboratively by 16 cards, and each card is responsible for 8192 positions. The lecturer added a very intuitive conversion: This is equivalent to the batch size becoming 1/16 - each card cannot even get a complete sample.

7.2 Pipeline Parallelism: Slicing, and Bubbles

Four-axis overview page: After CP, let’s go back to the map

The contextual parallelism ends here, and the screen returns to the four-axis overview page. The next thing to look at is the grid in the lower left corner - cut the layers out.

The second frame of the four-axis overview page: the same four grids, giving a clean starting point for the next section

This frame is literally the same as the previous frame, and is a re-alignment before entering the pipeline parallelism.

PP’s idea: assign the layers to different GPUs and transport activations at the boundaries

Pipeline Parallelism (PP) cuts the layer axis: 4 cards, each responsible for a continuous layer, and activation values are transferred between layers.

Problem with PP: There are sequential dependencies between layers, and the GPU waits most of the time

The problem is order dependence: GPU 2 must wait for GPU 1 to finish computing before starting, and in reverse has to wait for the downstream gradient. Drawing the timeline, the busy intervals of the four GPUs are staggered steps.

The theoretical upper limit of PP: N-channel pipeline, the highest MFU is only 1/N

This timing diagram gives a cruel conclusion: NN The upper limit of MFU of road PP is 1/N1/N. 8-way PP is 12.5%, 4-way is 25% - unacceptable numbers for training purposes.

The white space in PP has a name: bubble

The empty space on the diagram is labeled Bubble. The bubble is the time the GPU is waiting for upstream data., which is the core contradiction of PP: the finer the cut, the smaller the pressure on a single card’s video memory, but the higher the proportion of bubbles.

PP’s solution: run multiple microbatches at the same time and streamline them

The solution is to cut a batch into several microbatches and let them flow on the same pipeline at staggered peaks: when GPU 1 is calculating the forward direction of microbatch 2, GPU 2 is calculating the forward direction of microbatch 1. This way the bubble is filled with other microbatch calculations.

4-way PP, 4 microbatch: MFU increased from 25% to 16/28 ≈ 57.1%

Quantified results on this page: 4-way PP with 4 microbatch, ideal MFU from 1/4=25%1/4=25\% promoted to 16/28≈57.1%16/28\approx57.1\%. The denominator 28 is the total number of time slots, and the numerator 16 is the number of active slots. This explains why PP always appears together with microbatch in practice -PP alone makes little sense.

But microbatch is not free: each flying microbatch must retain its own activation, so the video memory has increased again and must cooperate with the activation checkpoint in Chapter 5. The lecturer said the most honest sentence in the whole lecture here: Should we cut more pipelines, use less microbatch, or recalculate more radically? ——As usual, turn the MFU to the maximum.

Four-axis overview page: After PP, only TP remains

The progress bar returns to the overview page again, with only the lower right corner of the four grids left untouched. It makes sense to leave it to the end: the first three cut “different data, different layers, different positions”, only TP cuts different columns in the same multiplication - so its communication mode is also different from the first three.

7.3 Tensor Parallelism: cutting dimensions, and the two-layer trick

The starting point of TP: a linear layer is XW = Y

Tensor Parallelism (TP) cuts the feature dimension. Most calculations in Transformer are XW=YXW=Y: XX is [N×D][N\times D], WW is [D×D][D\times D], YY is [N×D][N\times D].

TP cutting method: cut W into 4 parts by column, and each card only counts as part of Y

The approach is to WW cut into columns W1…W4W_1\dots W_4, each card uses its own WiW_i multiply by the complete XX, get YY of a piece. This is block matrix multiplication: the block shape is [1×1][1\times1], [1×4][1\times4], [1×4][1\times4]. Note the difference between it and FSDP——FSDP cuts “different layers”, while TP cuts “the same matrix in the same layer”.

TP’s problem: After moving forward, we need to put together the pieces of Y, but this time the communication cannot cover it.

The problem is: the next layer needs to be complete YY, so each piece must be aggregated once after each layer. What’s worse is that this communication cannot be masked by calculation - it is stuck between the two layers, a hard synchronization point. Once per layer, too many layers is unacceptable.

TP’s technique: two consecutive layers, one layer cut by columns and one layer divided by rows, the communication in the middle disappears

The solution is given on the page: If you use TP for two consecutive layers, let the first layer be cut by columns and the second layer by rows. In this way, the intermediate results do not need to be assembled into a complete matrix, and each card can continue to be calculated locally.

Layout of two-layer TP: XW=Y on the first layer, YU=Z on the second layer

Spread out the two layers and look at them: the first layer XW=YXW=Y, second floor YU=ZYU=Z. four YiY_i Separate four cards, four UiU_i Also separated are four cards.

Block shape of two-layer TP: W is [1×4], U is [4×1]

The corresponding block shape is WW: [1×1] [1×4] [1×4][1\times1]\,[1\times4]\,[1\times4], UU: [4×1] [1×1][4\times1]\,[1\times1].The first layer is cut into columns and the second layer is cut into rows, the dimensions are just right.

Algebra of two levels of TP: Z is the sum of four local products

Algebraically, Z=Y1U1+Y2U2+Y3U3+Y4U4Z=Y_1U_1+Y_2U_2+Y_3U_3+Y_4U_4. Each item only uses what is already available locally on one card——YiY_i It just calculated it, UiU_i is what it holds.

Execution of two-layer TP: calculate a local product term for each card

So each card is counted first XWi=YiXW_i=Y_i, then calculate YiUiY_iU_i, get ZZ an addend. There is no communication during the entire process.

The end of the two-layer TP: each of the four cards counts a Z, and then broadcasts the sum.

There is only one communication left: adding the four addends. The page says “Each card counts. ZZ one item and then broadcast it to other cards” - a one-time all-reduce replaces the original once-per-layer aggregation. The reason why this technique is particularly useful in Transformer is that FFN is naturally a two-layer MLP., which can be applied in pairs.

7.4 ND parallel: four axes open at the same time

Four-axis overview page: All four grids have been explained

After the four axes are finished, the screen returns to the overview page. What we are talking about here is that we have four separate knives in our hands, and the first thing to do in real training is to decide how to stack these four knives - which leads to the last picture.

The last frame of the four-axis overview page: Which one is used for the largest model? Use them all

A question and answer has been added to the page: Which one should be used for the largest model? The answer is All of them. This is not to be clever - the HSDP in Chapter 4 is already two-dimensional, and the current situation in industry is four-dimensional.

ND parallelism: Arrange the GPU into a four-dimensional grid, and each coordinate determines its rank on the four axes

The ND parallel approach is to open TP, CP, PP, and DP at the same time, and arrange the GPUs into a four-dimensional grid. The coordinates of each GPU are its ranks in the four parallel dimensions. The table in the lower right corner of the page is the actual configuration of Llama3-405B:

Number of GPUsTPCPPPDPsequence lengthper DP batchGlobal token numberTFLOPs/GPUBF16 MFU
8,1928116648,1923216M43043%
16,38481161288,1921616M40041%
16,384816168131,0721616M38038%

This table is worth reading line by line: the first and second lines only change the DP dimension (64 → 128), the number of cards is doubled, and the MFU drops from 43% to 41%, indicating that more parallelism is not better; the third line increases the sequence to 131,072, opens the CP to 16, reduces the DP to 8, and the MFU further drops to 38%. The same model, the same batch of cards, different recipes, the throughput difference is 5 percentage points——This is why Chapter 6 uses the MFU as a compass.

The lecturer finally added a methodology: Different parallel mechanisms have different communication requirements. If you arrange the various axes along different levels of the cluster (put the axis with the densest communication on the fastest line), you can reap the dividends of the bandwidth ladder in Chapter 2. This sentence sews the two halves of the whole story together -The topology of the hardware determines the price of communication, and the price of communication determines the parallel recipe, and MFU is the only acceptance criterion.

Summary

(Reference time: 01:12:10 – 01:12:44|Lecture 11)

Summary page: GPU is a parallel processor, the cluster is a large machine, four axes plus a checkpoint technique

The summary page divides the entire lecture into two columns: on the left is “A GPU is a parallel processor with hundreds of cores, and a cluster is a large machine with tens of thousands of cards”; on the right is “Split along four axes (Batch, Seq, Dim), use activation checkpoints to save video memory, and use MFU to accept recipes.”

Preview of the next lecture: Self-Supervised Learning

The last page only contains the topic of the next lecture: Self-Supervised Learning. The parallelism and scheduling discussed in this lecture are all based on one premise - the training data has artificial labels; in the next lecture, we switch to the path without labels, and the model relies on the data itself to construct supervision signals.

Take away judgment:

  • The throughput of a GPU almost entirely comes from Tensor Core, and its arithmetic density requirement is about 295 FLOP/byte; operators that cannot feed the bandwidth are destined to run on the FP32 core.
  • The performance of a cluster is not a number, but a four-level bandwidth ladder (3352 / 900 / 50 / <50 GB/s); the quality of a parallel strategy depends on which level it places communication.
  • The cost of data parallelism is only one all-reduce, which is mathematically equivalent; but the weights are copied, and each weight’s 8-byte account seals the model to about 10 billion parameters.
  • FSDP also splits the weights, at the cost of three weight-level communications per layer; the value of HSDP is not in algorithm updates, but in putting 3 times the traffic on the fast line and 1 times the traffic on the slow line.
  • Activate checkpoints to move the video memory from O(N)O(N) pressed to O(N)O(\sqrt N), the cost is calculated from O(N)O(N) rise to O(NN)O(N\sqrt N); It is the knob between “can it be trained” and “how fast can it be trained”.
  • MFU is the only indicator that can horizontally compare all formulas: less than 30% indicates a hard bottleneck, and more than 40% is already an excellent level on the H100; while the MFU of new cards is lower structurally, because the computing power increases faster than the bandwidth.
  • The difficulty of CP is only in attention, the difficulty of PP is only in bubbles, and the difficulty of TP is only in aggregation between layers - each of the three axes has its own hard bone, and the rest are “position-by-position independent” for nothing.
  • The largest model does not choose one type of parallelism, but stacks four axes into a four-dimensional grid; the three-row configuration of Llama3-405B shows that different recipes can make the throughput of the same batch of cards vary by 5 percentage points.

Machine-assisted translation · Read Chinese original