Skip to content
quboliu
⚙

How to Scale Your Model如何扩展你的模型

A Systems View of LLMs on TPUs

从系统角度理解 TPU 上的大语言模型

Training LLMs often feels like alchemy, but understanding and optimizing the performance of your models doesn't have to. This book aims to demystify the science of scaling language models: how TPUs (and GPUs) work and how they communicate with each other, how LLMs run on real hardware, and how to parallelize your models during training and inference so they run efficiently at massive scale. If you've ever wondered "how expensive should this LLM be to train" or "how much memory do I need to serve this model myself" or "what's an AllGather", we hope this will be useful to you.

训练大语言模型常常像在炼金,但理解和优化模型性能有章可循。本书解释 TPU 和 GPU 如何工作、相互通信,模型如何在实际硬件上运行,以及如何通过并行化提高大规模训练和推理的效率。如果你想估算训练成本、计算部署所需的内存,或弄懂 AllGather,本书可以帮上忙。

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

第一部分:预备知识

  • 第 2 章:认识 TPU。TPU 如何工作?它的工作原理怎样影响我们能训练和部署哪些模型?

Part 2: Transformers

第二部分:Transformer

  • 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 缓存。

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.

Part 4: Conclusions and Bonus Content

第四部分:结语和补充内容

  • 第 12 章:认识 GPU。这一补充章节介绍 GPU 如何工作、怎样互连,以及 GPU 和 TPU 的屋顶线有何差异。

dragon

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.
  • 粗估模型各部分的实际性能与理论上限相差多少。
  • 针对不同规模选择合适的并行方案,也就是决定如何把计算分配到多台设备上。
  • 估算训练和运行大型 Transformer 模型所需的成本和时间。
  • 设计能够利用特定硬件特性的算法。
  • 找出当前算法的性能瓶颈,以此指导硬件设计。

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

模型扩展的目标是增加用于训练或推理的芯片数量,同时让吞吐量随芯片数量线性增长。 这叫作强扩展。增加芯片进行并行计算,通常能缩短计算时间,同时也增加了芯片之间的通信。一旦通信耗时超过计算耗时,通信就会成为瓶颈,强扩展也就无法继续。2 只要充分了解硬件,能预判瓶颈出现在哪里,就可以设计或重新配置模型来避开这些瓶颈。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:

第 1 节介绍屋顶线分析,并说明通信、计算和内存怎样制约扩展。第 2 节和第 3 节详解 TPU 的工作原理,既介绍单块芯片,也介绍由多块芯片组成的系统。后者尤其重要,因为芯片之间的链路有带宽和延迟限制。我们将讨论以下问题。

  • 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 之间收集、分发或重新分布数组需要多长时间?
  • 如何高效地计算分片布局不同的两个矩阵的乘积?
pointwise product

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.

五年前,机器学习的模型架构百花齐放,常见的有卷积网络、LSTM、MLP 和 Transformer。如今 Transformer[1] 几乎一统天下。我们认为有必要理解 Transformer 架构的每个部分,包括矩阵的确切尺寸、归一化的位置、各部分的参数量和 FLOPs。4第 4 节细讲这些计算,展示如何估算训练和推理的参数量与 FLOPs。由此可以判断模型需要多少内存、计算与通信各要花多长时间,以及注意力的开销何时会赶上前馈块。

transformer diagram

Figure: a standard Transformer layer with each matrix multiplication (matmul) shown as a dot inside a circle. All parameters (excluding norms) are shown in purple. Section 4 walks through this diagram in more detail.

图: 标准 Transformer 层。用圆内的点表示矩阵乘法,紫色表示除归一化参数以外的所有参数。第 4 节深入解读此图。

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.

第 5 节:训练和第 7 节:推理是本书的核心。我们要回答的是:给定模型规模和芯片数量,怎样并行化模型才能保持强扩展?问题简单,答案却复杂。将模型分布到多块芯片上的主要手段有四种:数据并行、张量并行、流水线并行和专家并行。降低内存用量的手段还有重计算、优化器或模型分片(即 ZeRO)、卸载到主机和梯度累积。本书将讨论其中多种方法。

We hope by the end of these sections you should be able to choose among them yourself for new architectures or settings. Section 6 and Section 8 are practical tutorials that apply these concepts to LLaMA 3, a popular open-source model.

读完这些章节,你应当能够为新的架构或运行条件自行选择方案。第 6 节和第 8 节提供实践教程,将这些概念应用于广受使用的开源模型 LLaMA 3。

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.

第 9 节和第 10 节介绍如何在 JAX 中实现其中一些方法,以及代码出问题时如何做性能剖析和调试。新增的第 12 节则深入介绍 GPU。

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 的屋顶线。

References参考文献

  1. 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.

BibTeX

Footnotes

  1. 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 等库就让人们省去了这项工作。也许几年后,本书的内容也会被软件抽象起来。不过,缩放定律不断把模型推向硬件能力的极限。在可预见的未来,前沿研究很可能仍然离不开对如何将模型高效扩展到大型硬件拓扑的理解。

    ↩
  2. 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 万亿次运算,但如果大量时间耗在内存中的参数搬运上,实际性能很可能只剩十分之一。每块芯片的算力、内存带宽和内存总量如何共同作用,是理解扩展的关键。

    ↩
  3. 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。

    ↩
  4. 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 明确表示速率。

    ↩

补充说明

*Work done at Google DeepMind, now at MatX.

*这项工作完成于 Google DeepMind,现任职于 MatX。

引用

For attribution in academic contexts, please cite this work as:

学术写作中请按以下格式引用本书。

Austin et al., "How to Scale Your Model", Google DeepMind, online, 2025.

or as a BibTeX entry:

也可使用以下 BibTeX 条目。

@article{scaling-book,
  title = {How to Scale Your Model},
  author = {Austin, Jacob and Douglas, Sholto and Frostig, Roy and Levskaya, Anselm and Chen, Charlie and Vikram, Sharad
    and Lebron, Federico and Choy, Peter and Ramasesh, Vinay and Webson, Albert and Pope, Reiner},
  publisher = {Google DeepMind},
  howpublished = {Online},
  note = {Retrieved from https://jax-ml.github.io/scaling-book/},
  year = {2025}
}
原版章节与讨论