Lecture 1 · Course Overview and the Modern AI Stack: Large-Scale AI as an End-to-End Engineering Discipline

Scalable AI: Bridging Theory, Understanding, and Practice · Lecture 01。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: UC Berkeley EE 290/194 Scalable AI, Fall 2026 Lecture 1 (Aug 26, 2026), slides lecture1.pdf (48 slides); Spring 2026 Lecture 1 (Jan 20, 2026) has the same content in 46 slides. Instructors: Anant Sahai, Jiantao Jiao. Recommended readings (from the course schedule): R. Sutton, The Bitter Lesson (2019); S. Hooker, The Hardware Lottery (2020); J. Hoffmann et al., Training Compute-Optimal Large Language Models (“Chinchilla”, 2022); R. Turner, An Introduction to Transformers (2023). Other sources: the course syllabi (Fall and Spring 2026); the Llama 3 report (Llama Team, The Llama 3 Herd of Models, 2024) for scale, MFU and failure statistics; Besiroglu et al., Chinchilla Scaling: A Replication Attempt (2024); Sardana et al., Beyond Chinchilla-Optimal (2023); Kaplan et al. (2020); Korthikanti et al. (2022); Rajbhandari et al., ZeRO (2020); Young (1974) and Daly (2006) on checkpoint intervals; NVIDIA’s H100 datasheet and Hopper architecture whitepaper. The slides are an outline; this lecture expands them and adds the numbers. Every number labelled measured comes from code/lecture01/ run on the author’s laptop (Apple M4 Pro, 24 GB, Python 3.13, PyTorch 2.14). Computed numbers come from the same code’s formulas; reported numbers are cited. Code: code/lecture01/: six demos plus shared modules (hardware specs, Transformer accounting, a small PyTorch Transformer, scaling laws, a fleet simulator). Every script finishes in seconds; demo 04 takes ~20 s. Reading time: ~2 hours for the prose; ~30 more minutes to run and read the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Explain why, at today’s scale, training a model is only one part of a system, and why quality, cost and reliability must be designed across the stages of a model’s life rather than stage by stage.
  2. Use the course’s two maps: the lifecycle (Stages 0–6, each producing a named artifact) and the stack (five layers from GPUs to workloads). Say which stage and which layer a given problem belongs to.
  3. Hold the model view (quality) and the systems view (latency, throughput, memory, cost, reliability) at the same time, and recognise the failure modes of holding only one.
  4. Count a Transformer’s parameters, FLOPs per token (≈ 2N forward, ≈ 6N training, plus an attention term) and memory (≈ 16 bytes per parameter of training state, activations, KV cache). Know when these shortcuts break.
  5. Quote the H100’s headline numbers (989 TFLOP/s dense BF16, 3.35 TB/s, 80 GB, NVLink 900 GB/s) and turn them into time estimates. Explain the ridge point (≈ 295 FLOPs/byte).
  6. Name the five scaling walls (compute, memory capacity, memory bandwidth, communication, data) plus reliability, put a number on each for a real workload, and say which one binds.
  7. State the Chinchilla scaling law, derive the compute-optimal split of a FLOP budget, and explain why modern small models are deliberately over-trained once serving cost is counted.
  8. Connect Sutton’s Bitter Lesson and Hooker’s Hardware Lottery to the engineering choices of the course.
  9. Explain how failures scale with cluster size, choose a checkpoint interval (Young’s formula), and say what goodput depends on.
  10. Know how the course is organised and what makes a research project in it strong: a crisp hypothesis, strong baselines, ablations and honest trade-offs.

0.2 Prerequisites and scope

  • Prerequisites: Python; linear algebra (matrix products); basic probability; what a neural network and gradient descent are. No GPU programming or distributed-systems background is assumed.
  • Scope: this is the map of the whole course. Each idea appears once, concretely and with numbers. The deeper treatment comes in later lectures, and the text points forward each time. The goal is that after today you can do back-of-envelope estimates for any large-model workload, and know which lecture sharpens which estimate.
  • Not in scope today: the roofline model in detail (Lecture 2), GPU kernels and profilers (Lecture 3), how parallelism works (Lectures 5–6), how each lifecycle stage is actually engineered (Lectures 9 onward).

0.3 Section → code map

SectionIdeaDemo in code/lecture01/
§2the lifecycle and stack maps; one Stage-1 decision propagated to Stage-4 cost01_decisions_propagate.py
§4parameters, FLOPs and memory of a Transformer, checked against PyTorch02_transformer_accounting.py (uses model_math.py, tiny_transformer.py)
§5hardware numbers; measuring your own machine’s ceilingshw_specs.py, 04_measure_your_machine.py Parts A–C
§6the five scaling walls, in numbers03_scaling_walls.py
§7the Hardware Lottery in miniature; Chinchilla; inference-aware sizing; the Bitter Lesson as a number04_measure_your_machine.py Part D, 05_chinchilla.py (uses scaling_laws.py)
§8failures, checkpoints, restarts, goodput06_fleet_goodput.py (uses fleet.py)

0.4 Notation and units

SymbolMeaning
NNnumber of model parameters
DDnumber of training tokens
CCtraining compute in FLOPs (C≈6NDC \approx 6ND)
V,d,L,h,hkv,dh,dffV, d, L, h, h_{kv}, d_h, d_{ff}vocabulary size, model width (d_model), layers, query heads, key/value heads, head dimension, MLP hidden width
sssequence (context) length
CpeakC_{\text{peak}}peak dense FLOP/s of a chip at a given precision
BWBWmemory bandwidth in bytes/s
MFUmodel FLOPs utilization = achieved model FLOP/s ÷ CpeakC_{\text{peak}}
MTBFmean time between failures

Conventions (as in SYLLABUS.md §4.3): a multiply-accumulate is 2 FLOPs (浮点运算次数); peak FLOP/s are dense (no 2:4 sparsity); bandwidth and capacity use decimal prefixes (1 GB = 10⁹ bytes) as vendors quote them; binary prefixes (GiB) only when stated.


1. Why this course exists

1.1 A training run is not a system

Ask someone what it takes to “build a large language model” and the answer is often a training run: a dataset, an architecture, an optimizer, a cluster, a few weeks. The course’s opening thesis is that in 2026 this picture is wrong in an important way. The slides put it in one line: “a training run” is not a system. What a team actually ships is three things, each built on the one before:

  1. a base model (基座模型): pre-trained weights, a tokenizer, and an evaluation discipline that says how good they are;
  2. a post-trained model (后训练模型): the same network made to follow instructions, use tools, refuse harmful requests and specialise to tasks;
  3. a usable system (可用系统): the model behind a serving engine, with safety layers, tools, monitoring and the product’s latency and cost constraints.

Most of the value, and most of the pain, sits in the third item. But the third cannot be good unless the first two were engineered for it. A model, in this view, is not a file of weights. It is a computational graph that has to be trained, specialised, evaluated, deployed, monitored and iterated on, under hard constraints from hardware, data and serving economics. Hence the course’s subtitle: large-scale AI as an end-to-end engineering discipline (端到端工程学科).

1.2 Why “engineering”, and why now: the scale

Three numbers set the scene (all from the Llama 3 report, 2024):

  • Compute. Llama 3.1 405B was pre-trained with about 3.8×10253.8 \times 10^{25} FLOPs on 15.6 trillion tokens. That is 38 yotta-FLOPs: a laptop doing 3 TFLOP/s would need about 400,000 years.
  • Hardware. The run used up to 16,384 H100 GPUs, and the model card reports 30.84 million H100-hours.
  • Utilization. Those GPUs achieved 38–43% model FLOPs utilization (MFU, 模型算力利用率): the fraction of the hardware’s peak arithmetic that went into the model’s math. The other 57–62% was lost to memory traffic, communication, pipeline bubbles and other overheads.

At this scale every percentage point is worth roughly a million GPU-hours. A choice that looks minor in a notebook gets multiplied by the size of the run: the precision of a number format, the order in which GPUs talk to each other, how often the job saves its state. That multiplication makes the engineering a first-class part of the research. It is also why the course runs on real hardware: each student group gets a full 8×H100 node for the semester.

The trend makes this more pressing every year. Epoch AI’s database of notable models shows training compute growing by roughly 4–5× per year since 2010. A course that taught only the algorithms would be teaching the part that changes least.

1.3 Small upstream mistakes get expensive downstream

The slides’ main argument for treating the lifecycle as one system is that problems rarely stay in the stage where they are made. Errors compound (逐级放大):

A problem in …… shows up later as
architectureunstable training, or brutal serving costs
pre-trainingno headroom for post-training to “fix” things
post-trainingbehaviour that demos well and fails in real applications
inferencelatency or cost that kills the user experience
applicationsusers who leave even though the weights are strong

The prescription is equally short: do not design the stages independently. Design them as a coupled system, then measure relentlessly. §2.4 works through one example with real numbers. A single architectural knob (how many key/value heads attention has) changes the cost of serving a 70B model by more than 8×.


2. Two maps you will use all semester

A course this broad is easy to get lost in. The slides give two coordinate systems and promise to reuse them until you are sick of them. One is a time map, the lifecycle; the other is a layer map, the stack. Every later lecture can be placed on both.

2.1 The lifecycle (time): Stages 0–6

The course is strict about stage names, and about one rule: every stage emits artifacts (产物) you can point to, measure and version. If you cannot name the artifact, you are not done with the stage. Each stage also has a characteristic bottleneck, and naming it is half the job.

StageGoalArtifactWhere it usually hurts
0 Targetsturn ambition into concrete success criteriathe target distribution (chat, code, math, tools, …), a quality definition (benchmarks + human feedback + product metrics), a cost envelope (training budget, inference SLOs)capabilities nobody measures quietly regress
1 Architecturea model family that can plausibly meet the target inside the envelopea randomly initialized model definitionserving cost (KV cache), training stability
2 Pre-traininggeneral capabilities from large-scale data, reproduciblya base model, a versioned tokenizer and data format, many checkpoints with a selection story, training telemetrycompute, data, reliability
3 Post-trainingturn “capable” into “controllable and useful”a serving-ready post-trained modeldata quality, reward design, evaluation
4 Efficient inferenceserve real traffic within latency SLOs and costa production serving configuration (often with quantized variants)memory bandwidth, KV memory, tail latency
5 Applicationssolve a task reliably for real usersan end-to-end product you can measurecontext, tools, reliability, safety
6 Researcha credible claim that tightens the next iterationevidence, positive or negativeunclear hypotheses, weak baselines

Some details from the slides are worth keeping:

  • Stage 0 is where the course’s recurring theme first appears: you get what you measure. If a capability is not measured, expect it to regress silently. “We will measure it later” has never helped anyone.
  • Stage 1 choices set both the training dynamics and the economics of serving: the layer structure (attention, MLP, normalization), how context is used (full vs sparse or linear attention), how parameters are allocated (dense vs mixture of experts, MoE (混合专家)), and how inference memory is handled (KV cache, GQA, latent compression). Lecture 4 is about these knobs.
  • Stage 2 is “industrial-scale self-supervised learning”, and it is three coupled problems: data (acquisition, filtering, deduplication, decontamination), training (loss, schedule, stability, throughput) and systems (distributed strategy, memory management, fault tolerance). Lectures 9–15.
  • Stage 3 changes the data and the evaluation. Datasets become structured (instructions, preference pairs, environments with rewards). Evaluation moves from perplexity to behaviour: task success, refusals, tool success, schema validity. Lectures 16–20.
  • Stage 4 asks: what is the cost per token? What is the latency per request, including the tail (长尾)? How do we batch without hurting the user experience? What happens when contexts grow? Lectures 21–24.
  • Stage 5 is where most users actually meet the model: context engineering, tool loops, agents, schema-constrained outputs, retries, guardrails. A single weak link upstream can make strong weights unusable here. Lectures 25–27.
  • Stage 6 is research done with an understanding of the stack. Is a bottleneck fundamental, or does it come from today’s hardware? Which architectural change lowers total cost without hurting quality? Lectures 28–29, and the course project.

2.2 The stack (layers): what runs it

The second map decomposes the machinery:

Layer (top → bottom)ExamplesWhat it buys youLectures
AI workloadsdata pipelines, (post-)training, evaluation, serving, monitoring, safetythe reason the stack exists9–29
Frameworks & enginesPyTorch/JAX; NeMo AutoModel; Megatron, FSDP, DeepSpeed; vLLM, SGLang, TensorRT-LLM; NVIDIA Dynamoturning math into efficient kernels and parallel plans3, 5–8, 22–23
Distributed compute enginesRay, Spark, custom servicesrunning many processes as one job (data curation, RL rollouts)10, 19
Containers / orchestrationKubernetes, SLURM, VMsscheduling, isolation, restarts14
Compute substrateGPUs, NVLink and network, storage; cloud or on-premFLOP/s, bytes/s, capacity2–3, 24

The slides add one instruction for using this map. When something is slow, expensive or unreliable, locate the bottleneck in the stack, then choose the minimal intervention at the right layer. A slow decode step might be fixed by a better kernel (framework layer), a different batch policy (workload layer), more memory bandwidth (substrate layer) or fewer KV heads (the architecture, which is the workload’s definition). Each fix has a very different cost. Knowing which layer owns the problem is the skill the course trains.

2.3 Training frameworks vs inference engines: same weights, different physics

The same weights run in two very different kinds of software, and the course insists you understand both:

Training frameworks (Megatron, FSDP, DeepSpeed, NeMo AutoModel)Inference engines (vLLM, SGLang, TensorRT-LLM, Dynamo)
optimise forthroughput (吞吐量): eat tokens fastlatency (延迟) at high concurrency (并发)
the hard partnumerical stability under backpropagation; synchronising gradients; memory for optimizer state and activationsrequest scheduling and continuous batching; KV-cache (键值缓存) management (“memory is the boss”); timeouts, retries, back-pressure
typical batchlarge and fixedmany small, changing requests

The slides’ warning: if you only ever train models, inference will surprise you, and vice versa. §4–§6 show the physics behind the difference. A training step does a lot of math for every byte it reads, so it can be compute-bound (计算受限). Generating one token at a time does very little math per byte, so it is almost always memory-bandwidth-bound (访存带宽受限).

2.4 Worked example: one Stage-1 knob, three serving envelopes

To make “decisions propagate” concrete, take the shape of Llama-3-70B (80 layers, d=8192d = 8192, 64 query heads of dimension 128, MLP width 28,672, a 128k vocabulary) and vary one thing: the number of key/value heads.

  • Multi-head attention, MHA (多头注意力): 64 KV heads, one per query head (the original Transformer).
  • Grouped-query attention, GQA (分组查询注意力) with 8 KV heads, each shared by 8 query heads (what Llama 3 uses; Ainslie et al. 2023).
  • Multi-query attention, MQA (多查询注意力): a single KV head shared by all 64 (Shazeer 2019).

The KV-head count barely matters for the parameter count, but it decides the size of the KV cache. To generate token t+1t+1, attention needs the keys and values of all previous tokens in every layer. Recomputing them is wasteful, so engines cache them. The cache costs

KV bytes per token=2×L×hkv×dh×bytes per element,\text{KV bytes per token} = 2 \times L \times h_{kv} \times d_h \times \text{bytes per element},

which for GQA-8 in bf16 is 2×80×8×128×2=327,6802 \times 80 \times 8 \times 128 \times 2 = 327{,}680 bytes = 320 KiB per token of context, per request. An 8k-token conversation holds 2.5 GiB. With MHA it would hold 20 GiB.

Now serve the model on one 8×H100 node. Use tensor parallelism (张量并行) with TP = 8 (each GPU holds 1/8 of every layer; Lecture 6). Assume every request holds an 8k context, keep 10% of memory in reserve, and let one decode step make one token for every request in the batch. The step takes at least max(bytes read ÷ bandwidth, FLOPs ÷ peak) on each GPU; this is the roofline (屋顶线) bound of Lecture 2. Demo 01 computes (assuming a hypothetical $2.50 per GPU-hour):

attentionparamsKV per requestKV replicasmax batchsteptokens/s$ per 1M tokens
MHA (64 KV heads)79.9 B20.0 GiB1×1921.2 ms8976.20
GQA-8 (Llama 3)70.6 B2.50 GiB1×16221.5 ms7,5380.74
MQA (1 KV head)69.4 B320 MiB8×16221.4 ms7,5690.73

Four lessons are in this small table:

  1. An 8.4× difference in serving cost from one Stage-1 knob. GQA-8 fits 162 concurrent requests where MHA fits 19, and the throughput follows. MHA even has 9.4 B more parameters (the K/V projections are 8× larger), so it is no “smaller, cheaper” alternative.
  2. MQA buys nothing here, for a systems reason. MQA’s cache is 8× smaller than GQA-8’s, but with TP = 8 a single KV head cannot be split across 8 GPUs, so it is replicated on all of them. Per-GPU memory, batch and throughput come out identical to GQA-8. Below 8 KV heads, an 8-GPU node saves no memory at all. A model-view argument (“fewer KV heads is always cheaper”) fails against a systems-view fact.
  3. An invariant worth remembering. Every row’s step takes about 21.5 ms. That is the usable HBM per GPU divided by its bandwidth: 72 GB ÷ 3.35 TB/s. When the batch fills memory, each decode step reads almost all of it: the weights once plus every request’s KV cache. Throughput is then simply (requests that fit) ÷ 21.5 ms, so anything that shrinks the cache per request raises tokens/s in proportion.
  4. Stage 0 matters as much. Keep GQA-8 and change only the product’s context target: 4k → 8k → 32k → 128k gives max batch 324 → 162 → 40 → 10 and cost per million tokens 0.37→0.37 → 0.74 → 2.96→2.96 → 11.83, a factor of 32. That decision was made in a product meeting, before any architecture work.

These are upper bounds: no communication between the 8 GPUs, no scheduling overhead, every request at full context. Real engines reach some fraction of them (Lectures 22–23). The ratios between rows are what the lifecycle couples, and they are robust.


3. Two views you must hold at once

The slides frame constraint-driven engineering as two consistent viewpoints that good teams switch between explicitly.

The model view (模型视角)The systems view (系统视角)
optimisesquality: loss, benchmarks, behaviourconstraints: latency, throughput, memory, cost, operational reliability
typical moveschoose architectures that scale on the target distribution; curate data to drive specific capabilities (not just “more tokens”); train within the budget while monitoring learning and evaluation; iterate with ablations, not guessesstart from the serving constraints (SLOs, budget, memory ceilings); design architecture + deployment that can satisfy them; then train and post-train to reach the quality bar inside that envelope
failure mode if it is your only viewgreat weights that cannot hit latency, memory or cost budgetsan efficient model that cannot learn enough to be useful

The slides give a useful test. If your discussion has no numbers (latency, throughput, memory, tokens, dollars, failure rates), you are probably not doing systems. If it has no evaluation design or data/task alignment, you are probably not doing modelling.

GQA is a good example of the two views agreeing. The model view finds that sharing K/V across groups of query heads costs little quality (Ainslie et al. 2023). The systems view finds that it cuts the dominant serving cost by the group size, and §2.4 showed that “8” fits an 8-GPU node. §7.6 gives a second example: the compute-optimal model size changes once the cost of serving it is counted.


4. The Transformer as a computational graph

The recommended reading by Turner (2023) describes the Transformer in precise mathematical terms. Here we take one more step: we treat it as a graph whose cost can be counted before it runs. Almost every estimate in the course starts from the counts in this section. So we derive them, apply them to real models, and check them against PyTorch.

4.1 The data flow, and what each part is for

A decoder-only Transformer (the GPT/Llama family) processes a sequence of ss tokens:

  1. Embedding (嵌入): each token id indexes a row of a V×dV \times d table, giving a dd-dimensional vector. The vectors form the residual stream (残差流), an s×ds \times d matrix that every block reads from and adds to.
  2. LL blocks, each doing two things in pre-norm (前置归一化) form:
    • x←x+Attention(Norm(x))x \leftarrow x + \text{Attention}(\text{Norm}(x)): tokens exchange information. Each token forms a query, compares it with the keys of earlier tokens, and takes a weighted average of their values. It is the only place where positions interact.
    • x←x+MLP(Norm(x))x \leftarrow x + \text{MLP}(\text{Norm}(x)): each token is transformed on its own by a two-layer network (or a gated three-matrix one, SwiGLU, in Llama-style models).
  3. Final norm and LM head: a d×Vd \times V matrix turns each position’s vector into logits (未归一化对数概率) over the vocabulary; softmax turns them into next-token probabilities.

Two intuitions from Turner’s description are useful later. Attention is communication and the MLP is computation: the first mixes information across the sequence, the second processes each position. And the residual stream means every block makes an additive update, which is why very deep stacks train stably and why layers can be studied one at a time.

For the systems view, the key observation is that almost all of the work is matrix multiplication: the Q/K/V/O projections, the MLP matrices, the LM head, and the two attention products QK⊤QK^\top and PVPV. Everything else (norms, softmax, activations, residual adds, RoPE) is elementwise and costs O(d)O(d) per token instead of O(d2)O(d^2). Those cheap operations are a rounding error in FLOPs, but not in memory traffic, as Lecture 2 shows.

4.2 Counting parameters

Walk the graph and add up the weight matrices (biases and norm scales are vectors, negligible at scale):

ComponentParameters
attention, per layerd⋅hdhd \cdot h d_h (Q) +2⋅d⋅hkvdh+ 2 \cdot d \cdot h_{kv} d_h (K, V) +hdh⋅d+ h d_h \cdot d (O)
MLP, per layer3⋅d⋅dff3 \cdot d \cdot d_{ff} (SwiGLU: gate, up, down) or 2⋅d⋅dff2 \cdot d \cdot d_{ff} (GELU)
normsdd per RMSNorm (2d2d per LayerNorm), 2 per layer + 1 final
embedding, LM headVdV d each (the head is 0 extra if tied to the embedding)

Worked example, Llama-3-8B (V=128,256V = 128{,}256, d=4096d = 4096, L=32L = 32, h=32h = 32, hkv=8h_{kv} = 8, dh=128d_h = 128, dff=14,336d_{ff} = 14{,}336, untied):

  • attention per layer: 4096⋅4096⋅2+4096⋅1024⋅2=41,943,0404096 \cdot 4096 \cdot 2 + 4096 \cdot 1024 \cdot 2 = 41{,}943{,}040;
  • MLP per layer: 3⋅4096⋅14,336=176,160,7683 \cdot 4096 \cdot 14{,}336 = 176{,}160{,}768;
  • norms per layer: 2⋅4096=8,1922 \cdot 4096 = 8{,}192; per layer total 218,112,000; times 32 = 6,979,584,000;
  • embedding and head: 2⋅128,256⋅4096=1,050,673,1522 \cdot 128{,}256 \cdot 4096 = 1{,}050{,}673{,}152; final norm 4,096.

Total: 8,030,261,248, exactly the tensor count in Meta’s checkpoint. model_math.param_breakdown reproduces the checkpoints of Llama-2-7B, Llama-3-8B, Llama-3-70B and Llama-3.1-405B to the parameter (demo 02 Part A; the counts were checked against the Hugging Face checkpoint metadata). Where the parameters live (demo 02, computed):

modelembed + headattentionMLP12Ld212Ld^2 / non-embedding N
GPT-3 175B0.4%33.2%66.4%1.00
Llama-2-7B3.9%31.9%64.2%0.99
Llama-3-8B13.1%16.7%70.2%0.92
Llama-3-70B3.0%17.1%79.9%0.94
Llama-3.1-405B1.0%17.7%81.3%1.01

Two things stand out. First, the classic rule Nnon-emb≈12Ld2N_{\text{non-emb}} \approx 12 L d^2 (from GPT-style blocks: 4d24d^2 attention + 8d28d^2 MLP) still holds within 10%. Second, GQA moved weight from attention to the MLP: with 8 KV heads, attention is only ~17% of a Llama 3 model. At 8B, the 128k vocabulary is 13% of the whole model, a reminder that “small” models pay heavily for their vocabulary.

4.3 Counting FLOPs: 2N, 6N, and when they break

The forward pass. A weight ww in a matrix that a token’s vector passes through costs exactly 2 FLOPs for that token: one multiply, one add. So the matmul FLOPs per token are 2×2 \times (number of weights the token meets). The token meets every block matrix and the LM head. The input embedding is a table lookup (查表), a gather that does no arithmetic. Then there are the two attention products, which multiply activations by activations and have no weights at all. With full attention over ss positions they cost 4sdh4 s d_h per head per layer (2sdh2 s d_h for QK⊤QK^\top, 2sdh2 s d_h for PVPV):

FLOPsfwd/token=2 Nmatmul+4 L h dh s(use s+12 instead of s if the kernel skips the masked half).\text{FLOPs}_{\text{fwd}}/\text{token} = 2\,N_{\text{matmul}} + 4\,L\,h\,d_h\,s \quad\big(\text{use } \tfrac{s+1}{2} \text{ instead of } s \text{ if the kernel skips the masked half}\big).

The backward pass costs twice the forward. Each forward matmul Y=XWY = XW needs two matmuls of the same size backward: ∂X=∂Y W⊤\partial X = \partial Y\, W^\top to keep backpropagating, and ∂W=X⊤∂Y\partial W = X^\top \partial Y for the gradient we want. So training costs 1+2=3×1 + 2 = 3\times the forward pass. With Nmatmul≈NN_{\text{matmul}} \approx N and the attention term ignored, this gives the famous estimate (Kaplan et al. 2020):

Ctrain≈6ND.C_{\text{train}} \approx 6 N D.

Checked against PyTorch. tiny_transformer.py builds a real model from the same configuration object, and PyTorch’s FlopCounterMode counts the FLOPs it actually executes. Demo 02 Part B tries five tiny configurations covering every switch: GQA, MHA with tied embeddings, MQA, a GPT-style model (GELU, LayerNorm, biases, learned positions), and a head dimension different from d/hd/h. On all five, parameters and forward FLOPs match the formulas exactly (identical integers), and training FLOPs are exactly 3.0000× the forward pass.

The same demo found a warning. Switch the attention to PyTorch’s fused scaled_dot_product_attention (the path that becomes FlashAttention on a GPU) and run it on the CPU. The counter now misses 5.8–9.1% of the forward FLOPs, because it has no formula for that kernel and silently counts its attention-score matmuls as zero. A FLOP counter is a tool with blind spots. If you compute MFU from one, know what it counts (Lecture 3).

When 6N goes wrong (demo 02 Part C, computed, causal attention):

model2k8k32k128k
Llama-3-8B: exact ÷ 6N0.9681.0681.4693.074
Llama-3-70B: exact ÷ 6N1.0041.0611.2892.203

At short contexts, 6N is slightly too high. For Llama-3-8B at 2k it is 3.2% too high, because it charges FLOPs to the 525 M-entry embedding table, and a lookup does no math. At long contexts it is far too low: at 128k, the parameter-free attention products are 70% of Llama-3-8B’s training FLOPs. Setting the causal attention term equal to the 6N6N term gives a rule of thumb: attention matters once

s≳NL d≈12 d(for N≈12Ld2),s \gtrsim \frac{N}{L\,d} \approx 12\,d \quad (\text{for } N \approx 12 L d^2),

about 61k tokens for Llama-3-8B. Long-context training is a different compute regime, which is why Llama 3 trained long contexts in a separate phase, and why Lecture 7’s attention kernels matter.

4.4 Counting memory: training state, activations, KV cache

Training state. Standard mixed-precision (混合精度) training with Adam keeps, per parameter: bf16 weights (2 bytes) and bf16 gradients (2) for the forward and backward pass, plus an fp32 master copy (主权重) of the weights (4) and Adam’s two fp32 moments (4 + 4) for the update. That is 16 bytes per parameter (the accounting of the ZeRO paper). Pure fp32 Adam is also 16 bytes (4 + 4 + 4 + 4). Mixed precision makes the math faster (Tensor Cores) and shrinks the activations; it does not shrink the state.

modelbf16 weightstraining stateH100s just to hold it
Llama-3-8B16.1 GB128 GB1.6
Llama-3-70B141 GB1.13 TB14.1
Llama-3.1-405B812 GB6.49 TB81.2

An 8B model, small by today’s standards, cannot even be trained on one 80 GB GPU without sharding its state. This memory wall (内存墙) forces sharding (ZeRO/FSDP, Lecture 5) long before compute does.

Activations (激活值). The backward pass needs the inputs of every forward matmul and nonlinearity, so training memory also grows with batch × sequence. Korthikanti et al. (2022) estimate, for a GPT-style layer in 16-bit precision, s b d (34+5 h s/d)s\,b\,d\,(34 + 5\,h\,s/d) bytes per layer (b = micro-batch). The second term is the s×ss \times s attention-score matrices. For one 8k sequence through Llama-3-8B, that is about 380 GB without recomputation. Keeping only what FlashAttention-style recomputation needs (“selective”) leaves 36.5 GB. Recomputing whole layers (“full”) leaves 2.15 GB, at the price of an extra forward pass. The estimate is a scaling guide, not a measurement; Lecture 3 measures.

KV cache (from §2.4): 2Lhkvdh×2 L h_{kv} d_h \times bytes per token of context, per request. It is what limits serving batch size.


5. The hardware: what the numbers are

5.1 The two ceilings of an accelerator

The course’s Lecture 2 opens with two headline numbers that every estimate uses:

  1. peak compute CpeakC_{\text{peak}} (峰值算力), in FLOP/s;
  2. peak memory bandwidth BWBW (内存带宽), in bytes/s, between the chip and its HBM (high-bandwidth memory, 高带宽显存).

If an operation must do FF FLOPs and move QQ bytes to or from HBM, no implementation can beat

T ≥ max⁡ ⁣(FCpeak, QBW).T \ \ge\ \max\!\left(\frac{F}{C_{\text{peak}}},\ \frac{Q}{BW}\right).

For the NVIDIA H100 SXM (the course’s GPU; numbers from the datasheet and the course slides, all dense):

H100 SXM
BF16 / FP16 Tensor Core989 TFLOP/s
FP8 Tensor Core1,979 TFLOP/s
TF32 Tensor Core / FP32 (CUDA cores)495 / 67 TFLOP/s
HBM3 capacity / bandwidth80 GB / 3.35 TB/s
on chip132 SMs, 4 Tensor Cores each (528 total, nearly all of CpeakC_{\text{peak}}); 256 KB registers and up to 228 KB shared memory per SM; 50 MB L2
NVLink 4 (to the other GPUs in the node)900 GB/s total = 450 GB/s each way
network NIC (to other nodes)400 Gb/s = 50 GB/s per GPU
powerup to 700 W

NVIDIA also quotes 2× these FLOP rates “with sparsity” (2:4 structured sparsity); the course, and these notes, never use those. Vendors quote NVLink as a bidirectional total; collective-communication math needs the one-way number. hw_specs.py stores both.

5.2 The ridge point: the single most useful ratio

Divide the two ceilings:

ridge point=CpeakBW=989.4×10123.35×1012≈295 FLOPs per byte (H100, BF16).\text{ridge point} = \frac{C_{\text{peak}}}{BW} = \frac{989.4 \times 10^{12}}{3.35 \times 10^{12}} \approx 295\ \text{FLOPs per byte (H100, BF16)}.

An operation’s arithmetic intensity (算术强度) is its FLOPs per byte moved. Below about 295 the operation must be memory-bound: it cannot keep the Tensor Cores fed, whatever the kernel does. Above it, it can be compute-bound. Two quick examples:

  • A training matmul of 4096 × 4096 matrices in bf16 does 2⋅409632 \cdot 4096^3 FLOPs on 3⋅40962⋅23 \cdot 4096^2 \cdot 2 bytes, an intensity of about 1,365. That is comfortably compute-bound.
  • Decoding one token multiplies each weight by one activation: 2 FLOPs per 2-byte bf16 weight read, an intensity of 1. That is 295× below the ridge. A decode step at batch 1 uses well under 1% of the GPU’s arithmetic (§6.3).

This one ratio explains §2.3’s “same weights, different physics”. Lecture 2 builds the full roofline model (屋顶线模型) on it.

5.3 The node and the network

The course’s unit of hardware is an 8×H100 node (DGX/HGX H100): 640 GB of HBM, 26.8 TB/s of aggregate memory bandwidth, 7.9 PFLOP/s of dense BF16. Its 8 GPUs are joined by NVLink through NVSwitches (scale-up (纵向扩展)). Nodes are joined by a network of 400 Gb/s NICs, one per GPU (scale-out (横向扩展)). A GPU talks to its node-mates at 450 GB/s one way, but to another node at 50 GB/s, 9× slower. Much of Lectures 5–6 is about keeping the chattiest communication inside the node.

5.4 Measuring your own machine

The slides’ rule is to say which wall you are hitting and how you know it from measurements. Demo 04 measures the same two ceilings on the laptop these notes were written on. Every number here is measured, machine-specific, and varies by a few percent from run to run.

  • Compute ceiling. Square fp32 matmuls on the CPU (which has Apple’s matrix-multiply unit) peak at 3.30 TFLOP/s. They reach half of that only from n=256n = 256, and a 32×3232 \times 32 matmul gets 2.5%: small matrices cannot keep a machine busy.
  • Bandwidth ceiling. Copying a 512 MiB array runs at 235 GB/s (the M4 Pro’s DRAM is specified at 273 GB/s). A 16 MiB array runs at up to 386 GB/s, because it stays in on-chip caches. That is a memory hierarchy, measured.
  • Ridge point: 3.30 TFLOP/s ÷ 235 GB/s ≈ 14 FLOPs/byte, against 295 on an H100. The laptop is far less lopsided than a datacenter GPU, whose arithmetic has grown much faster than its memory.
  • A roofline for decode-shaped matmuls XB×4096W4096×4096X_{B\times4096} W_{4096\times4096} (fp32 intensity ≈ B/2B/2). As the batch BB grows, the operation moves from memory-bound to compute-bound. Speed first reaches half of peak at B=128B = 128. On the Apple GPU (--device mps), every batch size lands at 0.80–1.14 of the roofline min(peak, intensity × bandwidth), so two measured numbers predict the whole curve. On the CPU, B=1B = 1 reaches 0.77 of it, but B=2B = 2 to 3232 reach only 0.10–0.23: the math library switches to a kernel poorly suited to those shapes. So the roofline is a ceiling, not a prediction. Awkward small-batch shapes are exactly where real kernels fall short, on GPUs too (Lecture 3).

6. The five scaling walls

The slides list the classic scaling walls (扩展瓶颈): compute, memory capacity, memory bandwidth, communication, data. Across all of them the stack is trading off three things: correctness (the computation matches the math), performance (tokens per second at acceptable cost) and reliability (reproducibility, fault tolerance). Demo 03 puts a number on each wall for real workloads. Every result below is computed, and every assumption is stated.

6.1 Compute

Time = FLOPs ÷ (GPUs × peak × MFU). With 6ND and an assumed 40% MFU:

modeltokensC=6NDC = 6NDH100-hoursone node (8)course cluster (64)16,384 GPUs
Llama-3-8B15 T7.2×10237.2 \times 10^{23}507 K7.2 years330 days1.3 days
Llama-3.1-405B15.6 T3.8×10253.8 \times 10^{25}26.7 M380 years47.5 years68 days

For the 405B run Meta reported 30.84 M H100-hours. So about 86% of the GPU time it paid for became model FLOPs at that rate. The rest went to failures, restarts, evaluation and slower phases such as long-context training. (The course’s Lecture 8 slides do the same estimate and get 85%.) Even the 8B model would occupy the entire course cluster for most of a year. That is why course projects study recipes on small models, and why Lecture 9 is about planning with small runs.

6.2 Memory capacity

From §4.4: training state alone needs 1.6 H100s for 8B, 14 for 70B and 81 for 405B. Even serving 70B in bf16 needs 1.8 GPUs’ memory for the weights, before any KV cache. Activations come on top. Capacity decides how a model must be split, and that brings in communication.

6.3 Memory bandwidth

Decode Llama-3-70B on one node (TP = 8). At batch 1 a step must read 141 GB of weights at 26.8 TB/s: 5.27 ms, a bound of 190 tokens/s. Its math takes 17.6 µs, so 0.3% of the node’s FLOP/s are used. Batching helps because the weights are read once for the whole batch, and intensity grows roughly like BB. Without KV caches the node would turn compute-bound somewhere above 162 requests (at 1,024 it is).

But each request also reads its own KV cache, and that traffic grows with the batch too. With 8k-token contexts, intensity can never exceed

FLOPs per tokenKV bytes per request≈1.50×10112.68×109≈56 FLOPs/byte,\frac{\text{FLOPs per token}}{\text{KV bytes per request}} \approx \frac{1.50 \times 10^{11}}{2.68 \times 10^{9}} \approx 56\ \text{FLOPs/byte},

far below the ridge of 295. Long-context decode stays memory-bound at any batch size. At the largest batch that fits (162), the node uses 14% of its FLOP/s. This one fact motivates most of Part IV of the course: GQA and MLA, KV quantization, paged and prefix caches, disaggregated prefill/decode, and decode-specialised hardware.

6.4 Communication

In data parallelism (数据并行) every GPU holds a model replica, processes its share of the batch, and the GPUs then all-reduce (全规约) their gradients. A ring all-reduce sends 2(p−1)/p2(p-1)/p times the gradient size out of every GPU (Lecture 5 derives it). Inside a node it runs over NVLink. Across nodes it is done hierarchically: a reduce-scatter inside each node, an all-reduce of each 1/8 shard across nodes with every GPU using its own NIC, then an all-gather inside the node. For Llama-3-8B (16.1 GB of bf16 gradients), a 4M-token global batch (Llama 3’s initial batch size) and 40% MFU:

GPUs (pure DP)tokens per GPU per stepcomputeall-reduce (bandwidth-only lower bound)ratio
6462,5007.61 s133 ms0.02
2,0481,953238 ms142 ms0.60
16,38424429.7 ms143 ms4.8

The all-reduce time barely changes with scale: its bandwidth term depends on the gradient size, not on pp. But the compute per GPU shrinks as the fixed batch is split thinner. At 64 GPUs communication is 2% of compute and easily overlapped with it. At 16,384 it is nearly 5× the compute, and it is a lower bound, because the latency term (about 2(p−1)α2(p-1)\alpha for a flat ring) grows with pp. Pure data parallelism hits the communication wall (通信墙). The remedies are larger batches (limited by optimization, Lecture 12), parallelism that shrinks what each GPU synchronises (Lectures 5–6), overlap, and topology-aware algorithms.

6.5 Data

How many tokens does each model “want”? With the refit Chinchilla law (§7), a compute-optimal model wants about 17–20 tokens per parameter.

modelcompute-optimal D for its sizeused (reported)over-trained by
Llama-3-8B165 B15 T91×
Llama-3-70B1.3 T15 T11.5×
Llama-3.1-405B6.9 T15.6 T2.3×

Fifteen trillion tokens is about the size of FineWeb, a filtered public web dataset (Penedo et al. 2024). It is around 5% of one estimate of the entire stock of public human-written text (~300 T tokens; Villalobos et al. 2024). The models people can afford to serve are small, so they are trained on far more than their compute-optimal tokens (§7.5). Once you do that, good data, not FLOPs, becomes the scarce input. The course’s Lecture 9 shows small models trained far past Chinchilla-optimal. Lectures 10–11 cover filtering, deduplication, repetition (up to ~4 epochs is almost as good as new data) and synthetic data.

6.6 Which wall, and how do you know?

workloadbinding wallthe number that shows it
pre-train 405Bcompute (then reliability)26.7 M H100-hours at 40% MFU; 68 days on 16k GPUs
train 8B on one GPUmemory capacity128 GB of state > 80 GB
serve 70B at long contextmemory bandwidthintensity ≤ 56 vs ridge 295
data-parallel 8B on 16k GPUscommunicationall-reduce ≥ 4.8× compute
small model, many tokensdata15 T tokens ≈ one FineWeb
anything at 16k+ GPUsreliability (§8)a failure every ~3 hours

The method the course teaches, and that demos 03 and 04 rehearse, has four steps. First estimate with counts and hardware numbers. Then measure with a profiler or a timer. Then compare the two: a large gap means an overhead you have not modelled. Finally intervene at the layer that owns the gap. The rest of the course fills in each step for each stage.


7. Compute, hardware and scaling laws: the readings

The four readings fit together as one argument. Sutton says scale wins. Hooker says scale wins for ideas that fit the hardware. Hoffmann et al. say how to spend a compute budget. Turner describes the object being scaled (§4). This section covers the first three and adds what changes when serving is counted.

7.1 The Bitter Lesson (Sutton, 2019)

Sutton looks back over 70 years of AI and draws one lesson. General methods that leverage computation (search and learning) eventually beat methods that build in human knowledge about the domain, and usually by a wide margin. His examples: in chess and Go, deep search and learned evaluation beat hand-coded knowledge; in speech recognition, statistical models beat systems built on human phonetics; in computer vision, learned features beat hand-designed ones. The lesson is “bitter” because building in what we know feels productive and helps in the short term. Then it plateaus, and it is overtaken once computation grows enough, because computation keeps getting cheaper (Moore’s law and its successors).

What the essay means for this course:

  • If compute keeps winning, then using compute efficiently is where the leverage is. A 2× gain in MFU is a 2× bigger model, or more data, for the same budget. The whole of Parts I–IV is this argument made practical.
  • The lesson is about methods that scale with compute, not about compute alone. A method that cannot use more compute (one that saturates, or cannot be parallelized) loses even when compute is plentiful. Scalability is a property you design for.
  • §7.7 shows the lesson as a number: along the compute-optimal frontier, loss falls as a smooth power law in compute.

A fair reading also notes the limits. Architecture, data curation, objectives and post-training all embed human choices, and the course spends half its time on them. The lesson argues against hard-coding domain knowledge in place of learning. It does not say that engineering choices do not matter. In the course’s framing, those choices decide how well the compute is used.

7.2 The Hardware Lottery (Hooker, 2020)

Hooker’s essay is the counterweight. A research idea often wins because it suits the available hardware and software, not because it is better in general; she calls this a hardware lottery (硬件彩票). Her historical examples include Babbage’s analytical engine, an idea without a manufacturing base, and neural networks. Neural networks were largely abandoned for decades. They took off once GPUs, built for graphics, turned out to be ideal for their dense matrix products. The success of deep learning is partly a lottery win, and the Transformer won the next draw: its computation is almost entirely large matmuls, the one thing accelerators do best.

Demo 04 Part D runs the lottery in miniature on a laptop: the same 2.15 billion FLOPs, done six ways (measured, CPU):

same FLOPs, done as …timeachievedslower than best
one 1024³ matmul695 µs3.09 TFLOP/s1×
one batched matmul of 512 × 128³3.09 ms695 GFLOP/s4×
a Python loop of 512 matmuls of 128³3.75 ms573 GFLOP/s5×
a Python loop of 32,768 matmuls of 32³72 ms30 GFLOP/s104×
elementwise multiply-adds over a 256 MiB vector72 ms30 GFLOP/s103×
plain Python float arithmetic (extrapolated)14 s0.15 GFLOP/s20,514×

On the Apple GPU the spread is even wider: the loop of tiny matmuls is 1,617× slower than one big matmul, because every small operation pays a fixed dispatch cost. An algorithm whose natural form is “many small matmuls”, “elementwise work” or “irregular control flow” is not worse as an idea. It simply loses the lottery on today’s hardware. For this course, that means two things:

  • When you evaluate a new architecture or optimizer, ask how well it maps onto large matmuls. The answer often decides adoption more than the loss curve does. Lecture 4 (MoE, sparse attention) and Lecture 13 (Muon’s Newton–Schulz iterations are pure matmuls) return to this.
  • The lottery can be changed by co-design: kernels that fuse many small operations into one (Lectures 3, 7), compilers, and hardware built for a workload (Lecture 24’s decode chips). Several of the course’s research directions are exactly this.

7.3 The Chinchilla scaling law (Hoffmann et al., 2022)

The question. Given a training budget of CC FLOPs, how should it be split between model size NN and training tokens DD, with C≈6NDC \approx 6ND? Kaplan et al. (2020) had concluded that model size should grow much faster than data, and the large models of 2020–21 followed that advice: GPT-3 used 175 B parameters on only 300 B tokens. Hoffmann et al. trained over 400 models from 70 M to 16 B parameters, on 5 B to 500 B tokens, and reached a different answer.

The law. One of their three methods (“Approach 3”) fits a parametric form:

L(N,D)=E+ANα+BDβ.L(N, D) = E + \frac{A}{N^{\alpha}} + \frac{B}{D^{\beta}}.

Each term has a meaning. EE is the irreducible loss (不可约损失), the entropy of text itself, which no model can beat. A/NαA/N^\alpha is what a model of finite size cannot represent. B/DβB/D^\beta is what finite data cannot teach.

The optimum. Substitute D=C/(6N)D = C/(6N) and set ∂L/∂N=0\partial L/\partial N = 0:

αAN−α=βB(6NC)β  ⟹  Nopt=G(C6)βα+β,Dopt=C/6Nopt,G=(αAβB)1α+β.\alpha A N^{-\alpha} = \beta B \left(\frac{6N}{C}\right)^{\beta} \;\Longrightarrow\; N_{\text{opt}} = G \left(\frac{C}{6}\right)^{\frac{\beta}{\alpha+\beta}},\quad D_{\text{opt}} = \frac{C/6}{N_{\text{opt}}},\quad G = \left(\frac{\alpha A}{\beta B}\right)^{\frac{1}{\alpha+\beta}}.

With exponents near 0.5, model size and data should grow at about the same rate: double the compute, and grow both by about 2\sqrt2. Their headline result was about 20 tokens per parameter. They tested it by training Chinchilla (70 B parameters, 1.4 T tokens) with roughly the compute of their earlier Gopher (280 B, 300 B tokens). Chinchilla was better on nearly every benchmark, while being 4× cheaper to serve.

A lesson in rigour: two fits of the same law. The paper prints E=1.69E = 1.69, A=406.4A = 406.4, B=410.7B = 410.7, α=0.34\alpha = 0.34, β=0.28\beta = 0.28. Besiroglu et al. (2024) recovered the paper’s data points from its figure and refitted. They found the printed constants inconsistent with the paper’s own other two approaches, and obtained E=1.8172E = 1.8172, A=482.01A = 482.01, B=2085.43B = 2085.43, α=0.3478\alpha = 0.3478, β=0.3658\beta = 0.3658. Demo 05 shows how much this matters:

budget CCprinted fit: NN, DD, D/ND/Nrefit: NN, DD, D/ND/N
102110^{21}1.8 B, 91 B, 502.8 B, 60 B, 22
5.76×10235.76 \times 10^{23} (Chinchilla’s)32 B, 3.0 T, 9372 B, 1.3 T, 18
102510^{25}117 B, 14 T, 122312 B, 5.3 T, 17

At Chinchilla’s own budget, the printed constants say 32 B parameters at 93 tokens each. The refit says 72 B at 18 tokens each, which matches the model the paper actually trained. A 2.2× disagreement in model size, from a famous paper’s printed numbers! The fit is also fragile in a structural way. Tokens per parameter scale as C(α−β)/(α+β)C^{(\alpha-\beta)/(\alpha+\beta)}, so whether the ratio rises or falls with compute depends only on whether α>β\alpha > \beta, and the two fits disagree on that too. These notes use the refit, and the lesson stands: check a fitted constant against the data it claims to summarise before you build a plan on it.

7.4 The IsoFLOP curve

Fix C=5.76×1023C = 5.76 \times 10^{23} and vary NN, with D=C/(6N)D = C/(6N) (demo 05 Part B, refit). The loss is U-shaped in log⁡N\log N. It is flat near the minimum: 50 B or 100 B parameters cost only 0.001 nats more than the optimum (72 B). It is steep far from it: 5 B costs 0.076 nats more, and 280 B costs 0.019. Gopher (280 B, 300 B tokens) is predicted 0.026 nats worse than Chinchilla, which used only 17% more compute. Gopher reached about 50% compute efficiency: a compute-optimal model would match its loss with half its compute. A flat minimum is good news for engineering, because a model a little off the optimal size loses very little. That freedom is what §7.6 spends.

7.5 Where real models sit

Compute efficiency of real models = (compute a compute-optimal model would need to reach the same loss) ÷ (compute actually spent). Demo 05 Part C, refit; losses are on Chinchilla’s data distribution, so they are comparable to each other only:

modelNNDDtokens/paramcompute efficiency
GPT-3175 B300 B1.761% (under-trained)
Gopher280 B300 B1.150%
Chinchilla70 B1.4 T20~100%
Llama-2-7B6.7 B2.0 T29753%
Llama-3-8B8.0 B15 T1,86818%
Llama-3-70B70.6 B15 T21258%
Llama-3.1-405B406 B15.6 T3894%

The pendulum swung. The 2020 models were under-trained; today’s small models are trained ~90× past Chinchilla-optimal. Llama-3-8B’s loss could have been reached with 18% of its training compute by a bigger, compute-optimal model. This was a deliberate choice, and the reason is the next section.

7.6 Inference-aware scaling: what serving changes

Chinchilla optimizes training compute. But a model is trained once and served for its whole life, and every served token costs about 2N2N FLOPs. If a model will process DinfD_{\text{inf}} tokens over its lifetime, the right objective is lifetime compute (Sardana et al. 2023):

min⁡N 6 N D(N)⏟training+2 N Dinf⏟servingsubject toL(N,D(N))=target.\min_N\ \underbrace{6\,N\,D(N)}_{\text{training}} + \underbrace{2\,N\,D_{\text{inf}}}_{\text{serving}} \quad\text{subject to}\quad L(N, D(N)) = \text{target}.

A smaller model needs more training tokens to reach the target loss, so training costs more. But every served token is cheaper. Take Llama-3-8B’s loss as the target (demo 05 Part D, refit):

lifetime tokens servedbest NNtrain tokenstokens/paramlifetime compute saved vs Chinchilla-optimal
033.9 B647 B190%
101210^{12}23.3 B1.0 T436.7%
101310^{13}13.5 B2.6 T19241%
101410^{14}8.75 B9.9 T1,13667%
101510^{15}6.77 B46 T6,73777%

The more a model will be used, the smaller and longer-trained it should be. In this model, an 8 B model on 15 T tokens is the lifetime optimum when it will serve about 1.9×10141.9 \times 10^{14} tokens. That is a plausible volume for a popular open model. The real case for small models is stronger still. Decode runs at far lower MFU than training (§6.3), so a served token costs more than 2N2N worth of training-efficient FLOPs. Small models are also faster per token, a latency requirement no FLOP count captures. This is Stage 0 (the cost envelope and the expected traffic) reaching back to set Stage 1 (the size) and Stage 2 (the data budget): the two views of §3 in one optimization. It is also where the data wall of §6.5 comes from.

7.7 The Bitter Lesson as a number

Along the compute-optimal frontier both error terms scale the same way, so the reducible loss (可约损失) falls as a power law:

Lopt(C)−E∝C−γ,γ=αβα+β.L_{\text{opt}}(C) - E \propto C^{-\gamma},\qquad \gamma = \frac{\alpha\beta}{\alpha+\beta}.

For the refit, γ=0.178\gamma = 0.178. Each 10× of compute multiplies the reducible loss by 0.66, and halving it takes 49× more compute (91× with the printed constants). This is the quantitative form of Sutton’s essay, with both of its sides. The returns are steady and predictable, so it pays to invest in scale. And they are diminishing, so it pays even more to use the compute efficiently.


8. Reliability: the fleet view

8.1 Failure rates add up

The slides introduce NVIDIA’s MARS team, which runs the company’s AI/HPC fleet: heterogeneous clusters on-premises and in the cloud, thousands of GPUs and petabytes of storage, sized to train frontier models. Their published concerns are resource fairness, GPU occupancy, reducing GPU waste, application resilience, performance, power and orchestration. (A Fall 2026 guest lecture goes inside such a fleet; it is Lecture 14 here.) The slides add one sobering point. Each course group owns a node outright and never queues. At fleet scale nobody owns anything, and a GPU you hold but do not use is one somebody else needed.

Reliability becomes a wall because component failures are independent, so their rates add. Llama 3’s report (Table 5) lists 419 unexpected interruptions in a 54-day window on 16,384 H100s:

causecountcausecount
faulty GPU148GPU SRAM19
GPU HBM3 memory72GPU system processor17
software bug54NIC7
network switch or cable35NCCL watchdog timeout7
unplanned host maintenance32silent data corruption6
other (host, power, SSD, …)22total419

That is one interruption every 54×24/419=3.0954 \times 24 / 419 = 3.09 hours, about 78% of them hardware. Per GPU, though (with its share of host, network and software), it is one failure per 3.09×16,384≈50,7003.09 \times 16{,}384 \approx 50{,}700 hours, or 5.8 years. Scale the same hardware and the job’s MTBF (平均故障间隔时间) shrinks in proportion (demo 06 Part A): 33 days on 64 GPUs, 3.1 hours on 16,384, 23 minutes on 131,072.

8.2 Checkpointing and Young’s formula

A job survives failures by periodically writing a checkpoint (检查点). The checkpoint holds everything needed to resume exactly: fp32 master weights, optimizer state, the learning-rate scheduler, the data loader’s position and the RNG states. Writing it blocks training for δ\delta; a failure loses everything since the last checkpoint, plus a restart time RR. With checkpoints every Δ\Delta and failures every MM on average, the fraction of time wasted is to first order

waste≈δΔ+Δ+δ2M+RM.\text{waste} \approx \frac{\delta}{\Delta} + \frac{\Delta + \delta}{2M} + \frac{R}{M}.

The terms are: time spent writing, half a segment lost per failure on average, and restarts. Minimizing over Δ\Delta gives Young’s formula (1974):

Δ⋆=2 δ M.\Delta^\star = \sqrt{2\,\delta\,M}.

The course’s Lecture 8 example: M=3M = 3 h and δ=1\delta = 1 min give Δ⋆≈19\Delta^\star \approx 19 min and about 10% overhead. Check it: 1/19+19/360≈0.053+0.0531/19 + 19/360 \approx 0.053 + 0.053.

8.3 What the simulation shows

Demo 06 simulates 30-day jobs (20 seeded runs each) with failures drawn at the Llama 3 rate. The checkpoint and restart times are assumptions, labelled as such. Main results at 16,384 GPUs, with 1-minute checkpoints and 10-minute restarts:

checkpoint every2 min5 min10 min19.3 min (Young)30 min1 h2 h4 h
goodput (simulated)62.8%77.9%83.8%85.4%84.5%79.0%67.2%46.9%

The simulated optimum is Young’s interval. The optimum is flat (10–30 minutes are all within 2 points), but the edges are steep: checkpoint too often and you pay for the writes, too rarely and you pay by redoing lost work. Goodput (有效吞吐), the fraction of wall-clock time that becomes kept progress, depends at least as much on the checkpoint and restart engineering:

checkpoint writerestartgoodput
10 s (asynchronous)2 min (automated)94.8%
1 min10 min85.4%
20 min30 min52.1%

And it collapses with scale if nothing else changes: with 1-minute checkpoints and 10-minute restarts, goodput is 97% at 1,024 GPUs, 85% at 16,384, 51% at 131,072 and 34% at 262,144. Llama 3 reported more than 90% effective training time at 16,384 GPUs, and only 3 interruptions needed significant manual intervention. In this model that requires both cheap checkpoints and fast, automated restarts. Reliability engineering is not an afterthought to performance engineering. At 100k GPUs, a 2× faster kernel is worth less than a 2× faster restart.


9. How the course works, and how to do research in it

9.1 Modules follow the lifecycle

ModuleWhat you should walk away withLectures in these notes
1. ArchitectureTransformers; scaling trade-offs; parallelism; why inference constraints shape design1–8
2. Pre-trainingdata and tokenization; stability at scale; throughput engineering; base-model evaluation9–15
3. Post-trainingSFT and preference-optimization intuition; RL with verifiable rewards and environments; dataset engineering; alignment and task-success evaluation16–20
4. Efficient inferenceengine architecture; batching and scheduling; KV-cache pressure; quantization; throughput/latency trade-offs21–24
5. Applicationscontext engineering; tool use; reliability patterns; evaluation loops from product metrics back to training25–27
6. Researchopen directions; formulating hypotheses; convincing experiments on real systems28–29

The course works hands-on with the NVIDIA stack and common open-source engines: NeMo AutoModel (training), NeMo Curator (pre-training data), NeMo Data Designer (post-training data), NeMo RL and NeMo Gym (RL), Minitron/Puzzletron (deployment-efficiency preparation), Dynamo, TensorRT-LLM, vLLM and SGLang (serving), NeMo Guardrails and Garak (safety). These notes run on a laptop instead (see SYLLABUS.md §0.4). They rebuild the core of each tool small enough to read, and use the real tools’ documentation as further reading.

9.2 Assessment

There are no exams. Fall 2026 weights: research project 50%, four group assignments 35% (of which 10% is for enhancing one assignment, e.g. adding questions or making its programming part harder), an explainer video 10%, attendance and participation 5%. Failing any component fails the course. The assignments combine conceptual questions with hands-on implementation, profiling, scaling and analysis, and each ends in an in-person oral checkoff where the group defends its results.

9.3 The research project: what “good” looks like

The project’s goal is a result that could support an arXiv preprint or a workshop paper: publication-quality work, whether or not it is published. It is graded on technical quality (40%) and impact (10%). Impact means evidence the work is useful outside the classroom: a merged PR in a public repository, a released benchmark, a public report or preprint with runnable artifacts. Peer review by another group is required and feeds into the technical grade. Projects come from two tracks:

  • Track A, systems research: can we make it faster, cheaper or more reliable? (custom kernels, DSLs, quantization and compression, serving strategies, training throughput)
  • Track B, model research: can we make it better, smarter or safer? (training objectives, preference optimization, architectures, pre-training data pipelines, synthetic data for reasoning and tool use, benchmarks)

Technical quality has four parts, and they are worth reading as a checklist for any systems research:

part (weight)what excellent looks likecommon failure
Framing (35%)a problem that is new (not a rename), important, with a meaningful potential delta, general beyond one setting, with a mechanism (“why should it work?”) and a constraints-aware statement of what is held fixeda “cool” idea with no concrete value; an unfalsifiable claim; a cherry-picked setting
Evidence & rigour (30%)a strong baseline at comparable compute; ablations that isolate the cause; correct metrics (task success, cost, latency, memory, robustness); contamination awareness; an honest list of what got worsea weak or missing baseline; no ablations; demos instead of metrics
Engineering sophistication (20%)an end-to-end pipeline that runs reliably; profiling-driven work with evidence; deterministic configs, checkpointing, logging; modular codenotebook glue; guessed bottlenecks
Communication & reproducibility (15%)one command reproduces the key results; versioned configs; clear metric definitions; figures that match what the code outputs; limitations stated plainlyscreenshots of logs; results nobody can rerun

The course is explicit that negative results can earn a strong grade. A good negative result has a plausible, well-motivated hypothesis; a correct and fair test against a baseline; a diagnosis of what broke (optimization? data? hardware? evaluation?) with evidence; and a narrower follow-up hypothesis. “We tried many things and nothing worked”, with no baselines, ablations or diagnosis, is the bad kind. The milestones pace the work so a group does not discover in week 12 that its idea cannot be tested: research directions, group formation, a one-paragraph hypothesis with a success metric, a 2–3-page proposal (method, evaluation plan, risks), a midterm check-in, a draft for peer review, talks, a poster session, final code and report, and an impact update.

9.4 From an idea to a hypothesis: a worked example

Suppose demo 01 gave you the idea “store the KV cache in FP8 to serve more requests”. Here is the same idea sharpened into something the rubric rewards:

  • Hypothesis. On Llama-3-8B served by vLLM on one H100, storing the KV cache in FP8 (E4M3, per-head scales) instead of BF16 raises the maximum concurrent 32k-context requests by ≥ 1.8× and decode throughput at that concurrency by ≥ 1.5×. Accuracy drops by at most 0.5 points on a long-context retrieval benchmark and 1 point on a reasoning benchmark.
  • Mechanism. §2.4: at full batch, throughput ≈ (requests that fit) ÷ (HBM ÷ bandwidth), and the KV bytes per request halve.
  • Baseline. BF16 KV cache, same engine version, same scheduler settings, same hardware.
  • Ablations. Per-tensor vs per-head scales; K and V quantized separately (keys are usually more sensitive); short vs long contexts.
  • Metrics. Requests that fit; tokens/s and time per output token at fixed SLOs; accuracy with confidence intervals (Lecture 16); memory measured from the engine, not computed.
  • Risks and trade-offs. Dequantization overhead could eat the bandwidth win at small batch; accuracy may degrade only at long range, so measure by context length.
  • Impact path. If it holds, a benchmark script and results posted upstream; if it fails, a diagnosis of where (scales? dequant kernel? attention numerics?).

The chain is idea → mechanism → measurable claim → fair test → possible failure modes. That chain separates a project from a demo.


10. Summary

  1. Large-scale AI is end-to-end engineering. What ships is a base model, a post-trained model and a usable system. Errors in one stage compound in the next, so the stages must be designed as a coupled system and measured relentlessly.
  2. Two maps: the lifecycle (Stages 0–6, each with a named, versioned artifact and a typical bottleneck) and the stack (substrate → orchestration → distributed engines → frameworks and engines → workloads). Locate the bottleneck, then intervene at the right layer.
  3. Two views: the model view (quality) and the systems view (constraints). A discussion without numbers is not systems work; one without evaluation design is not modelling.
  4. A Transformer is countable. NN follows from the shapes, exactly (Llama checkpoints reproduced to the parameter). Forward ≈ 2N2N FLOPs per token, training ≈ 6N6N, plus an attention term that dominates beyond s≈N/(Ld)≈12ds \approx N/(Ld) \approx 12d. Training state ≈ 16 bytes per parameter; the KV cache costs 2Lhkvdh2Lh_{kv}d_h × bytes per token per request.
  5. The H100 in five numbers: 989 TFLOP/s BF16 dense, 3.35 TB/s, 80 GB, 450 GB/s NVLink each way, 50 GB/s network. Ridge point ≈ 295 FLOPs/byte; decode has intensity ≈ 1.
  6. Five walls plus one. Compute (405B ≈ 27 M H100-hours), capacity (8B state > one GPU), bandwidth (long-context decode is memory-bound at any batch), communication (data-parallel all-reduce outgrows compute at large scale), data (small models are over-trained; good tokens are scarce), and reliability (16k GPUs fail every ~3 hours).
  7. Scaling laws: L=E+A/Nα+B/DβL = E + A/N^\alpha + B/D^\beta; compute-optimal ≈ 20 tokens per parameter (refit). Fitted constants can be fragile (a 2.2× disagreement). Counting serving cost makes small, long-trained models optimal for heavily used deployments.
  8. Bitter Lesson and Hardware Lottery: methods that scale with compute win, but only if they map onto the hardware. The same FLOPs run 4× to 20,000× apart depending on their form.
  9. Reliability: failure rates add up. Checkpoint every 2δM\sqrt{2\delta M}. Goodput depends on cheap checkpoints and fast, automated restarts as much as on fast kernels.

11. Common pitfalls

  • Quoting sparse FLOP/s. NVIDIA’s “with sparsity” numbers are 2× the dense ones and apply only to 2:4-sparse matrices. Use dense peaks for MFU and time estimates.
  • Bidirectional vs one-way bandwidth. NVLink’s “900 GB/s” is both directions summed. A ring all-reduce is limited by the 450 GB/s each way.
  • Bits vs bytes. Network links are quoted in Gb/s: 400 Gb/s is 50 GB/s.
  • 6N everywhere. It ignores attention (wrong by 2–3× at 128k) and counts the embedding lookup as math (slightly wrong at short context). Write out the attention term when ss is a sizeable fraction of 12d12d.
  • “Mixed precision halves memory.” It does not halve the training state (16 bytes/param either way). It shrinks activations and speeds up the math.
  • “Fewer KV heads is always cheaper.” Not below the tensor-parallel degree: the heads get replicated (§2.4).
  • Timing GPU code without synchronising. GPU calls return before the work is done. Synchronise (torch.cuda.synchronize(), torch.mps.synchronize()) before reading the clock, and warm up first.
  • Trusting one tool’s count. A FLOP counter can miss fused kernels. A profiler can attribute time to the wrong layer. Cross-check against a formula.
  • Using a scaling-law fit outside its range or without checking its constants. The printed Chinchilla constants and the refit differ by 2.2× in recommended model size.
  • Treating reliability as someone else’s problem. At 16k GPUs, checkpoint and restart engineering is worth tens of percent of the cluster.

12. Exercises

  1. Parameters by hand. Llama-2-13B has V=32,000V = 32{,}000, d=5120d = 5120, L=40L = 40, h=hkv=40h = h_{kv} = 40, dff=13,824d_{ff} = 13{,}824, RMSNorm, untied embeddings. Compute NN exactly.
Answer

Attention per layer 4⋅51202=104,857,6004 \cdot 5120^2 = 104{,}857{,}600; MLP per layer 3⋅5120⋅13,824=212,336,6403 \cdot 5120 \cdot 13{,}824 = 212{,}336{,}640; norms 2⋅5120=10,2402 \cdot 5120 = 10{,}240. Per layer 317,204,480; × 40 = 12,688,179,200. Embedding + head 2⋅32,000⋅5120=327,680,0002 \cdot 32{,}000 \cdot 5120 = 327{,}680{,}000; final norm 5,120. N = 13,015,864,320, exactly the tensor count of the Hugging Face checkpoint (which also stores 2,560 fp32 RoPE buffers that are not parameters).

  1. Training time. How long would pre-training Llama-2-13B on 2 T tokens take on the course’s 64 H100s at 40% MFU, with perfect goodput?
Answer

C=6⋅13.016×109⋅2×1012=1.56×1023C = 6 \cdot 13.016 \times 10^9 \cdot 2 \times 10^{12} = 1.56 \times 10^{23} FLOPs. Rate 64⋅0.4⋅989.4×1012=2.53×101664 \cdot 0.4 \cdot 989.4 \times 10^{12} = 2.53 \times 10^{16} FLOP/s. Time ≈ 6.17×1066.17 \times 10^6 s ≈ 71 days: a whole semester for one mid-sized 2023 model, before any goodput loss.

  1. KV cache. (a) KV bytes per token of Llama-3-8B in bf16? (b) For a 128k-token context? (c) How many 128k-token requests fit on one H100 next to the bf16 weights, keeping 10% in reserve?
Answer

(a) 2⋅32⋅8⋅128⋅2=131,0722 \cdot 32 \cdot 8 \cdot 128 \cdot 2 = 131{,}072 bytes = 128 KiB. (b) 128 KiB×131,072=16128\ \text{KiB} \times 131{,}072 = 16 GiB. (c) Usable 0.9⋅80=720.9 \cdot 80 = 72 GB, minus 16.06 GB of weights = 55.9 GB; 55.9/17.18=3.2655.9 / 17.18 = 3.26, so 3 requests. Long context on one GPU is a capacity problem before it is anything else.

  1. Decode bound. What is the best possible decode speed of Llama-3-8B at batch 1 on one H100 (bf16 weights), and what limits it?
Answer

Each token must read all 16.06 GB of weights: 16.06×109/3.35×1012=4.7916.06 \times 10^9 / 3.35 \times 10^{12} = 4.79 ms, i.e. at most ≈ 209 tokens/s. Memory bandwidth limits it. The math, 2N≈162N \approx 16 GFLOP, would take 16 µs.

  1. Why 3×? Explain without equations why the backward pass of a linear layer costs twice its forward pass, and say which of the two backward products could be skipped for the very first layer of a network whose inputs are fixed data.
Answer

The forward pass does one matmul (Y=XWY = XW). Backward needs the gradient with respect to the weights (X⊤∂YX^\top \partial Y, to update WW) and with respect to the input (∂YW⊤\partial Y W^\top, to pass the error to the layer below). Each is a matmul of the same size. If the input is fixed data that needs no gradient, the input-gradient product can be skipped for that layer. (In a Transformer the first matmul’s input is the embedding output, which does need a gradient, so the full 3× holds, as demo 02 measured.)

  1. Young’s interval. A job’s MTBF is 1 hour and a checkpoint takes 30 seconds. What interval should it use, and what overhead should it expect (ignore restarts)?
Answer

Δ⋆=2⋅30 s⋅3600 s=465\Delta^\star = \sqrt{2 \cdot 30\ \text{s} \cdot 3600\ \text{s}} = 465 s ≈ 7.7 minutes. Overhead ≈ 30/465+465/7200=6.5%+6.5%≈30/465 + 465/7200 = 6.5\% + 6.5\% \approx 13%. At the optimum the two terms are equal, as always for a/Δ+bΔa/\Delta + b\Delta.

  1. Which way does tokens-per-parameter move? Show that under the Chinchilla law the compute-optimal D/ND/N scales as C(α−β)/(α+β)C^{(\alpha-\beta)/(\alpha+\beta)}. Which fit in §7.3 says over-training should grow with budget, and which says it should shrink?
Answer

Nopt∝Cβ/(α+β)N_{\text{opt}} \propto C^{\beta/(\alpha+\beta)} and Dopt∝Cα/(α+β)D_{\text{opt}} \propto C^{\alpha/(\alpha+\beta)}, so D/N∝C(α−β)/(α+β)D/N \propto C^{(\alpha-\beta)/(\alpha+\beta)}. The printed constants have α=0.34>β=0.28\alpha = 0.34 > \beta = 0.28, so the ratio rises with compute (32 → 93 → 153 tokens/param in demo 05). The refit has α=0.348<β=0.366\alpha = 0.348 < \beta = 0.366, so it falls slowly (24 → 18 → 16). A small change in exponents flips a qualitative recommendation, which is another reason to check fits.

  1. Communication wall. In §6.4, by what factor would the global batch have to grow for the 16,384-GPU data-parallel run to bring its all-reduce down to 10% of compute? Why can the batch not simply grow that much?
Answer

Compute per step scales with the batch, while the all-reduce does not. The ratio is 4.8 now, and 10% needs 0.1, so the batch must grow 48×, from 4 M to ~190 M tokens. Beyond a critical batch size, more tokens per step stop reducing the number of steps needed, so the extra compute is wasted (Lecture 12). The practical answers are other forms of parallelism, which shrink what each GPU must synchronise, and overlapping communication with computation (Lectures 5–6).

  1. The lottery. In demo 04 Part D, the loop of 32,768 tiny matmuls and the elementwise version run at about the same speed on the CPU (~30 GFLOP/s), but for different reasons. What limits each?
Answer

The tiny matmuls are limited by per-call overhead: each call does only 65,536 FLOPs, so Python dispatch and kernel setup (a few µs) dominate. On a GPU this is kernel-launch overhead, and it is why CUDA graphs and fusion exist (Lecture 3). The elementwise version is limited by memory bandwidth. Each in-place pass (mul_ or add_) does 1 FLOP per element and moves 8 bytes (read + write of fp32), an intensity of 0.125 FLOPs/byte. At ~235 GB/s that caps it at about 29 GFLOP/s, almost exactly the measured 30. Fusing the two passes into one (Lecture 3) would double the intensity and the speed.

Fall 2026 A1, Performance Engineering (released with Lecture 2, due four weeks later; the course site uses this name, while the Fall syllabus PDF still lists it as “Parallelism”), and Spring 2026 A1, Parallelism. Both build directly on today’s accounting. You count FLOPs and bytes for Transformer operators, predict whether each is compute- or memory-bound, write and profile kernels (Fall: Triton kernels, starting from a canonical memory-bound operation), and compute MFU from measured step times. The concepts from this lecture you will need: the 2-FLOPs-per-MAC convention and the 2N/6N estimates with their attention correction (§4.3); dense peak numbers and one-way vs bidirectional bandwidth (§5.1); the ridge-point test (§5.2); and the discipline of estimate → measure → compare (§6.6). Assignment solutions are not reproduced in these notes.

14. Research directions from this lecture

  • Inference-aware scaling with real costs. §7.6 costs serving at training-efficient FLOPs. Redo the optimum with measured decode MFU, latency SLOs and KV-cache memory (§2.4) as constraints. Does the optimal size shrink further, and how does it depend on context length?
  • Co-designing attention with the parallel layout. §2.4 showed MQA’s savings vanishing under TP = 8. What attention variants (GQA group sizes, latent attention, cross-layer KV sharing) are optimal given a deployment’s tensor-parallel degree and memory?
  • Measuring what counters miss. Build an MFU tool that cross-checks FLOP counters, analytical counts and profiler traces, and flags fused kernels whose FLOPs are invisible (§4.3).
  • Goodput at 100k GPUs. Asynchronous and in-memory checkpointing, faster failure detection, elastic restarts: quantify which reduces lost time most at scale, with failure statistics calibrated to public reports (§8).
  • Re-fitting scaling laws. Reproduce a published fit from its released runs, report the uncertainty of its constants, and show how much a compute-optimal recommendation moves within that uncertainty (§7.3).

15. Further reading

  • R. Sutton, The Bitter Lesson, 2019 (incompleteideas.net). Two pages; read it first.
  • S. Hooker, The Hardware Lottery, Communications of the ACM 64(12), 2021 (arXiv:2009.06489).
  • J. Hoffmann et al., Training Compute-Optimal Large Language Models, NeurIPS 2022 (arXiv:2203.15556), and T. Besiroglu et al., Chinchilla Scaling: A Replication Attempt, 2024 (arXiv:2404.10102).
  • N. Sardana, J. Portes, S. Doubov, J. Frankle, Beyond Chinchilla-Optimal: Accounting for Inference in Language Model Scaling Laws, ICML 2024 (arXiv:2401.00448).
  • J. Kaplan et al., Scaling Laws for Neural Language Models, 2020 (arXiv:2001.08361): the source of C≈6NDC \approx 6ND and of the earlier, model-heavy allocation.
  • R. Turner, An Introduction to Transformers, 2023 (arXiv:2304.10557).
  • Llama Team, The Llama 3 Herd of Models, 2024 (arXiv:2407.21783): §3.3 on infrastructure, parallelism and reliability is a model of systems writing.
  • V. Korthikanti et al., Reducing Activation Recomputation in Large Transformer Models, 2022 (arXiv:2205.05198); S. Rajbhandari et al., ZeRO, SC 2020 (arXiv:1910.02054).
  • J. Austin et al., How to Scale Your Model (the “Scaling Book”, jax-ml.github.io/scaling-book): chapters 1, 4 and 7 are the reading for Lecture 2. H. He, Making Deep Learning Go Brrrr From First Principles (horace.io/brrr_intro.html).
  • J. Ainslie et al., GQA, 2023 (arXiv:2305.13245); N. Shazeer, Fast Transformer Decoding: One Write-Head is All You Need, 2019 (arXiv:1911.02150).
  • J. W. Young, A first order approximation to the optimum checkpoint interval, CACM 1974; J. T. Daly, A higher order estimate of the optimum checkpoint interval for restart dumps, FGCS 2006.

16. Next lecture

Lecture 2 · All About Performance I: Hardware Ceilings and the Roofline. Today’s ridge point becomes a full model. We tour an H100 from the node down to a Tensor Core and count FLOPs and bytes for every operator of a decoder block: attention with MHA vs GQA, the MLP, and the “glue” (residual adds, LayerNorm, softmax). Then we use arithmetic intensity and the roofline to predict which operators are compute-bound and which are bandwidth-bound for training, prefill and decode shapes, and why so many Transformer operations are bandwidth-bound unless they are fused.


术语表 (Glossary, English → 中文)

English中文
end-to-end engineering discipline端到端工程学科
base model / post-trained model / usable system基座模型 / 后训练模型 / 可用系统
lifecycle / stage / artifact生命周期 / 阶段 / 产物
target distribution / success criteria / cost envelope目标分布 / 成功标准 / 成本约束范围
SLO (service-level objective)服务等级目标
stack / layer / compute substrate技术栈 / 层 / 计算底座
orchestration编排(调度管理)
training framework / inference engine训练框架 / 推理引擎
model view / systems view模型视角 / 系统视角
co-design协同设计
computational graph计算图
decoder-only Transformer仅解码器 Transformer
embedding / residual stream / pre-norm嵌入 / 残差流 / 前置归一化
attention / MLP (feed-forward network)注意力 / 多层感知机(前馈网络)
query / key / value查询 / 键 / 值
multi-head / grouped-query / multi-query attention多头 / 分组查询 / 多查询注意力
logits / softmax未归一化对数概率 / 归一化指数函数
parameter count / non-embedding parameters参数量 / 非嵌入参数
FLOP / FLOP/s / multiply-accumulate (MAC)浮点运算次数 / 每秒浮点运算次数 / 乘加运算
forward pass / backward pass / backpropagation前向传播 / 反向传播 / 误差反向传播
table lookup (gather)查表(收集)
mixed precision / master weights / optimizer state混合精度 / 主权重 / 优化器状态
activation / activation recomputation激活值 / 激活重计算
KV cache键值缓存
context length / sequence length上下文长度 / 序列长度
accelerator / GPU / Tensor Core / SM加速器 / 图形处理器 / 张量核心 / 流式多处理器
HBM (high-bandwidth memory)高带宽显存
peak compute / memory bandwidth峰值算力 / 内存带宽
dense vs structured (2:4) sparsity稠密 vs 结构化(2:4)稀疏
number format: BF16 / FP16 / FP8 / TF32数值格式:BF16 / 半精度 / 8 位浮点 / TF32
arithmetic intensity / ridge point / roofline算术强度 / 屋脊点 / 屋顶线模型
compute-bound / memory-bandwidth-bound计算受限 / 访存带宽受限
memory hierarchy / cache存储层次 / 缓存
node / scale-up (NVLink) / scale-out (network)节点 / 纵向扩展(节点内互联) / 横向扩展(节点间网络)
NIC / interconnect / topology网卡 / 互联 / 拓扑
throughput / latency / tail latency / concurrency吞吐量 / 延迟 / 尾延迟 / 并发
decode / prefill / batch解码 / 预填充 / 批
tensor parallelism / data parallelism张量并行 / 数据并行
all-reduce / reduce-scatter / all-gather / ring全规约 / 规约散射 / 全收集 / 环形算法
collective communication集合通信
MFU (model FLOPs utilization)模型算力利用率
scaling wall扩展瓶颈(扩展之墙)
scaling law / power law缩放定律 / 幂律
compute budget / compute-optimal计算预算 / 计算最优
irreducible loss / reducible loss不可约损失 / 可约损失
IsoFLOP curve等算力曲线
tokens per parameter / over-training每参数 token 数 / 过度训练
compute efficiency计算效率
inference-aware scaling / lifetime compute考虑推理成本的缩放 / 全生命周期算力
fit / refit / replication拟合 / 重新拟合 / 复现
critical batch size临界批大小
The Bitter Lesson / The Hardware Lottery苦涩的教训 / 硬件彩票
kernel / kernel launch / dispatch overhead / fusion算子(内核) / 内核启动 / 调度开销 / 算子融合
FLOP counter / profiler浮点运算计数器 / 性能剖析器
fleet / cluster / scheduling / occupancy集群舰队 / 集群 / 调度 / 占用率
failure rate / MTBF故障率 / 平均故障间隔时间
checkpoint / checkpoint interval / asynchronous checkpointing检查点 / 检查点间隔 / 异步检查点
restart / fault tolerance / goodput重启 / 容错 / 有效吞吐
silent data corruption静默数据损坏
hypothesis / baseline / ablation / negative result假设 / 基线 / 消融实验 / 负面结果
contamination (benchmark)(基准)数据污染
reproducibility / peer review可复现性 / 同行评审
← 返回课程目录