Links to Sections章节目录
This series is probably longer than it needs to be, but we hope that won’t deter you. The first three chapters are preliminaries and can be skipped if you’re already familiar with the material, although they introduce notation used later. The final three parts might be the most practically useful, since they explain how to work with real models.
本书或许比实际需要的稍长,希望你别因此却步。前三章是预备知识,熟悉内容的读者可以跳过,但其中引入了后面会用到的一些记号。最后三个部分可能最实用,因为那里会讨论如何处理实际的模型。
Part 1: Preliminaries
第一部分:预备知识
- Chapter 1: A Brief Intro to Roofline Analysis. Algorithms are bounded by three things: compute, communication, and memory. We can use these to approximate how fast our algorithms will run.
- 第 1 章:屋顶线分析简介。算力、通信和内存共同限制算法的性能。我们可以据此估算算法的运行速度。
- Chapter 2: How to Think About TPUs. How do TPUs work? How does that affect what models we can train and serve?
- 第 2 章:认识 TPU。TPU 如何工作?它的工作原理怎样影响我们能训练和部署哪些模型?
- Chapter 3: Sharded Matrices and How to Multiply Them. Here we explain model sharding and multi-TPU parallelism by way of our favorite operation: (sharded) matrix multiplications.
- 第 3 章:分片矩阵及其乘法。我们以分片矩阵乘法为例,讲解模型分片和多 TPU 并行。
Part 2: Transformers
第二部分:Transformer
- Chapter 4: All the Transformer Math You Need to Know. How many FLOPs does a Transformer use in its forward and backward pass? Can you calculate the number of parameters? The size of its KV caches? We work through this math here.
- 第 4 章:Transformer 的计算与参数。Transformer 的前向传播和反向传播各需要多少 FLOPs?有多少参数?KV 缓存有多大?这一章逐一推算。
- Chapter 5: How to Parallelize a Transformer for Training. FSDP. Megatron sharding. Pipeline parallelism. Given some number of chips, how do I train a model of a given size with a given batch size as efficiently as possible?
- 第 5 章:如何并行训练 Transformer。FSDP、Megatron 分片和流水线并行。如果芯片数量、模型规模和批次大小都已确定,怎样才能尽可能高效地完成训练?
- Chapter 6: Training LLaMA 3 on TPUs. How would we train LLaMA 3 on TPUs? How long would it take? How much would it cost?
- 第 6 章:在 TPU 上训练 LLaMA 3。如何在 TPU 上训练 LLaMA 3?需要多久?成本是多少?
- Chapter 7: All About Transformer Inference. Once we’ve trained a model, we have to serve it. Inference adds a new consideration — latency — and changes up the memory landscape. We’ll talk about how disaggregated serving works and how to think about KV caches.
- 第 7 章:详解 Transformer 推理。模型训练完就要部署。推理还需要考虑延迟,内存用量的构成也会变。我们将解释分离式推理服务如何工作,以及如何估算 KV 缓存。
- Chapter 8: Serving LLaMA 3 on TPUs. How much would it cost to serve LLaMA 3 on TPU v5e? What are the latency/throughput tradeoffs?
- 第 8 章:在 TPU 上部署 LLaMA 3。用 TPU v5e 部署 LLaMA 3 需要多少钱?延迟与吞吐量之间如何取舍?
Part 3: Practical Tutorials
第三部分:实践教程
- Chapter 9: How to Profile TPU Code. Real LLMs are never as simple as the theory above. Here we explain the JAX + XLA stack and how to use the JAX/TensorBoard profiler to debug and fix real issues.
- 第 9 章:TPU 代码的性能剖析。真实的大语言模型比上面的理论复杂得多。我们会介绍 JAX 和 XLA 软件栈,并用 JAX/TensorBoard 性能分析器定位和修复实际问题。
- Chapter 10: Programming TPUs in JAX. JAX provides a bunch of magical APIs for parallelizing computation, but you need to know how to use them. Fun examples and worked problems.
- 第 10 章:用 JAX 编写 TPU 程序。JAX 提供了一系列用于并行计算的 API,前提是知道如何用。这一章包含一些有趣的示例和带解答的练习。
Part 4: Conclusions and Bonus Content
第四部分:结语和补充内容
- Chapter 11: Conclusions and Further Reading. Closing thoughts and further reading on TPUs and LLMs.
- 第 11 章:结语和延伸阅读。关于 TPU 和大语言模型的总结及延伸阅读。
- Chapter 12: How to Think About GPUs. A bonus section about GPUs, how they work, how they’re networked, and how their rooflines differ from TPUs.
- 第 12 章:认识 GPU。这一补充章节介绍 GPU 如何工作、怎样互连,以及 GPU 和 TPU 的屋顶线有何差异。
Much of deep learning still boils down to a kind of black magic, but optimizing the performance of your models doesn’t have to — even at huge scale! Relatively simple principles apply everywhere — from dealing with a single accelerator to tens of thousands — and understanding them lets you do many useful things:
深度学习的许多做法仍像黑魔法,但即便是在很大的规模上,优化模型性能也有章可循。从单块加速器到数万块,加速器上的计算都遵循一些相对简单的原则。理解这些原则,你就能做到以下几件事。
- Ballpark how close parts of your model are to their theoretical optimum.
- Make informed choices about different parallelism schemes at different scales (how you split the computation across multiple devices).
- Estimate the cost and time required to train and run large Transformer models.
- Design algorithms that take advantage of specific hardware affordances.
- Design hardware driven by an explicit understanding of what limits current algorithm performance.
Expected background: We’re going to assume you have a basic understanding of LLMs and the Transformer architecture but not necessarily how they operate at scale. You should know the basics of LLM training and ideally have some basic familiarity with JAX. Some useful background reading might include this blog post on the Transformer architecture and the original Transformer paper. Also check out this list for more useful concurrent and future reading.
预备知识: 我们假设你对大语言模型和 Transformer 架构有基本了解,但未必熟悉它们如何大规模运行。你应当了解大语言模型训练的基础知识,最好也对 JAX 有所了解。可以先读这篇介绍 Transformer 架构的文章和 Transformer 原论文。延伸阅读列表也整理了适合配合本书或读完后继续阅读的材料。
Goals & Feedback: By the end, you should feel comfortable estimating the best parallelism scheme for a Transformer model on a given hardware platform, and roughly how long training and inference should take. If you don’t, email us or leave a comment! We’d love to know how we could make this clearer.
目标与反馈: 读完本书,你应当能够为特定硬件平台上的 Transformer 模型选出合适的并行方案,并大致估算训练和推理时间。如果读完还有困惑,欢迎来信或留言,告诉我们哪些地方还可以讲得更清楚。
Why should you care?为什么要了解这些?
Three or four years ago, I don’t think most ML researchers would have needed to understand any of the content in this book. But today even “small” models run so close to hardware limits that doing novel research requires you to think about efficiency at scale.1 A 20% win on benchmarks is irrelevant if it comes at a 20% cost to roofline efficiency. Promising model architectures routinely fail either because they can’t run efficiently at scale or because no one puts in the work to make them do so.
三四年前,在我看来,多数机器学习研究人员用不上本书的内容。但如今连所谓的“小模型”也已逼近硬件极限。要开展新的研究,就得考虑模型在大规模下的运行效率。1 如果以降低 20% 的屋顶线效率为代价,换来基准测试上 20% 的提升,这样的提升就没有意义。 许多看起来很有前景的模型架构最终没能成功,原因要么是它们无法高效地扩展,要么是没人投入精力使其高效运行。
The goal of “model scaling” is to be able to increase the number of chips used for training or inference while achieving a proportional, linear increase in throughput. This is known as “strong scaling”. Although adding additional chips (“parallelism”) usually decreases the computation time, it also comes at the cost of added communication between chips. When communication takes longer than computation we become “communication bound” and cannot scale strongly.2 If we understand our hardware well enough to anticipate where these bottlenecks will arise, we can design or reconfigure our models to avoid them.3
Our goal in this book is to explain how TPU (and GPU) hardware works and how the Transformer architecture has evolved to perform well on current hardware. We hope this will be useful both for researchers designing new architectures and for engineers working to make the current generation of LLMs run fast.
本书解释 TPU 和 GPU 硬件如何工作,以及 Transformer 架构怎样演变得更适合在这些硬件上运行。我们希望它既能帮助研究人员设计新架构,也能帮助工程师让当前的大语言模型运行得更快。
High-Level Outline内容大纲
The overall structure of this book is as follows:
本书的结构如下。
Section 1 explains roofline analysis and what factors can limit our ability to scale (communication, computation, and memory). Section 2 and Section 3 talk in detail about how TPUs work, both as individual chips and — of critical importance — as an interconnected system with inter-chip links of limited bandwidth and latency. We’ll answer questions like:
- How long should a matrix multiply of a certain size take? At what point is it bound by compute or by memory or communication bandwidth?
- How are TPUs wired together to form training clusters? How much bandwidth does each part of the system have?
- How long does it take to gather, scatter, or re-distribute arrays across multiple TPUs?
- How do we efficiently multiply matrices that are distributed differently across devices?
- 给定尺寸的矩阵乘法需要花多久?什么情况下瓶颈在计算吞吐量、内存带宽或通信带宽?
- TPU 如何互连成训练集群?系统各部分的带宽是多少?
- 在多块 TPU 之间收集、分发或重新分布数组需要多长时间?
- 如何高效地计算分片布局不同的两个矩阵的乘积?
Figure: a diagram from Section 2 showing how a TPU performs an elementwise product. Depending on the size of our arrays and the bandwidth of various links, we can find ourselves compute-bound (using the full hardware compute capacity) or memory-bound (bottlenecked by memory loading).
图: 第 2 节用这幅图演示 TPU 如何执行逐元素乘法。数组大小和不同链路的带宽决定了计算是受算力限制(充分利用硬件算力),还是受内存限制(瓶颈在于从内存加载数据)。
Five years ago ML had a colorful landscape of architectures — ConvNets, LSTMs, MLPs, Transformers — but now we mostly just have the Transformer[1]. We strongly believe it’s worth understanding every piece of the Transformer architecture: the exact sizes of every matrix, where normalization occurs, how many parameters and FLOPs4 are in each part. Section 4 goes through this “Transformer math” carefully, showing how to count the parameters and FLOPs for both training and inference. This tells us how much memory our model will use, how much time we’ll spend on compute or comms, and when attention will become important relative to the feed-forward blocks.
Section 5: Training and Section 7: Inference are the core of this book, where we discuss the fundamental question: given a model of some size and some number of chips, how do I parallelize my model to stay in the “strong scaling” regime? This is a simple question with a surprisingly complicated answer. At a high level, there are four primary parallelism techniques used to split models over multiple chips (data, tensor, pipeline, and expert), and a number of other techniques to reduce the memory requirements (rematerialization, optimizer/model sharding (aka ZeRO), host offload, gradient accumulation). We discuss many of these here.
Finally, Section 9 and Section 10 look at how to implement some of these ideas in JAX and how to profile and debug your code when things go wrong. Section 12 is a new section that dives into GPUs as well.
Throughout we try to give you problems to work for yourself. Please feel no pressure to read all the sections or read them in order. And please leave feedback. For the time being, this is a draft and will continue to be revised. Thank you!
书中各处都有练习,供你自己推导。你可以只读感兴趣的章节,也可以跳着读。欢迎反馈。原书目前还是草稿,会继续修订。谢谢!
We’d like to acknowledge James Bradbury and Blake Hechtman who derived many of the ideas in this book.
感谢 James Bradbury 和 Blake Hechtman,本书中的许多想法源自他们的推导。
Without further ado, here is Section 1 about TPU rooflines.
下面进入第 1 节,讨论 TPU 的屋顶线。
Without further ado, here is Section 1 about TPU rooflines.
下面进入第 1 节,讨论 TPU 的屋顶线。
References参考文献
- Attention is all you need. Vaswani, Ashish and Shazeer, Noam and Parmar, Niki and Uszkoreit, Jakob and Jones, Llion and Gomez, Aidan N and Kaiser, Lukasz and Polosukhin, Illia. 2017.
Footnotes
-
↩
Historically, ML research has followed something of a tick-tock cycle between systems innovations and software improvements. Alex Krizhevsky had to write unholy CUDA code to make CNNs fast but within a couple of years, libraries like Theano and TensorFlow meant you didn’t have to. Maybe that will happen here too and everything in this book will be abstracted away in a few years. But scaling laws have pushed our models perpetually to the very frontier of our hardware, and it seems likely that, for the foreseeable future, doing cutting-edge research will be inextricably tied to an understanding of how to efficiently scale models to large hardware topologies.
纵观机器学习的发展,系统创新与软件改进往往交替出现。Alex Krizhevsky 曾不得不编写极其繁复的 CUDA 代码来加速 CNN。几年之内,Theano 和 TensorFlow 等库就让人们省去了这项工作。也许几年后,本书的内容也会被软件抽象起来。不过,缩放定律不断把模型推向硬件能力的极限。在可预见的未来,前沿研究很可能仍然离不开对如何将模型高效扩展到大型硬件拓扑的理解。
-
↩
As your computation time decreases, you also typically face bottlenecks at the level of a single chip. Your shiny new TPU or GPU may be rated to perform 500 trillion operations per second, but if you aren’t careful it can just as easily do a tenth of that if it’s bogged down moving parameters around in memory. The interplay of per-chip computation, memory bandwidth, and total memory is critical to the scaling story.
随着计算时间缩短,通常也会遇到单芯片层面的瓶颈。新款 TPU 或 GPU 的标称性能可能达到每秒 500 万亿次运算,但如果大量时间耗在内存中的参数搬运上,实际性能很可能只剩十分之一。每块芯片的算力、内存带宽和内存总量如何共同作用,是理解扩展的关键。
-
↩
Hardware designers face the inverse problem: building hardware that provides just enough compute, bandwidth, and memory for our algorithms while minimizing cost. You can imagine how stressful this “co-design” problem is: you have to bet on what algorithms will look like when the first chips actually become available, often 2 to 3 years down the road. The story of the TPU is a resounding success in this game. Matrix multiplication is a unique algorithm in the sense that it uses far more FLOPs per byte of memory than almost any other (N FLOPs per byte), and early TPUs and their systolic array architecture achieved far better perf / $ than GPUs did at the time they were built. TPUs were designed for ML workloads, and GPUs with their Tensor Cores are rapidly changing to fill this niche as well. But you can imagine how costly it would have been if neural networks had not taken off, or had changed in some fundamental way that TPUs (which are inherently less flexible than GPUs) could not handle.
硬件设计者面对的是反过来的问题:如何尽可能降低成本,又恰好为算法提供所需的算力、带宽和内存。这种软硬件协同设计的压力可想而知:第一批芯片通常要两三年后才会问世,你必须押注那时的算法会是什么样。TPU 正是这种设计的成功案例。矩阵乘法每字节数据所需的 FLOPs 高达 N,比几乎所有其他算法都多。早期 TPU 借助脉动阵列,单位成本所提供的性能远超同期 GPU。TPU 是为机器学习负载设计的,GPU 也正借助 Tensor Core 迅速补足这一能力。倘若神经网络没有兴起,或其计算方式发生了 TPU 无法适应的根本变化,专用硬件的投入成本可想而知。毕竟 TPU 的灵活性低于 GPU。
-
↩
FLoating point OPs, basically the total number of adds and multiplies required. While many sources take FLOPs to mean “operations per second”, we use FLOPs/s to indicate that explicitly.
FLOPs 是浮点运算次数,基本相当于所需的加法和乘法总数。许多资料用 FLOPs 表示每秒运算次数,本书用 FLOPs/s 明确表示速率。