Learning Systems
A learning system is the software–hardware stack that turns data, models, and objectives into trained, deployed, continuously usable models under real limits on memory, bandwidth, and compute. The model defines what to learn; the system determines whether it can be trained, scaled, optimized, and deployed. Most of the progress described in Ch. 9 and Ch. 10 depended as much on systems as on algorithms. This chapter goes up the stack in four layers: frameworks, compilers, distributed training, and serving.
13.1 Frameworks
13.1.1 TensorFlow: Learning as a Static Graph
Definition 13.1 (Dataflow Graph) In a dataflow graph, every computation and every piece of state is a node: operations (matrix multiply, convolution, ReLU) are nodes, tensors flow along the edges, and variables are stateful nodes that own mutable buffers. The program first builds the graph, then the runtime optimizes, places, and partitions it, then executes it repeatedly.
TensorFlow (Abadi et al., 2016) was designed to replace DistBelief’s parameter server, where optimizers and update rules were built into privileged C++ code that researchers could not easily change.
- One graph for compute and state. Mutable variables recover parameter-server semantics, and everything else (optimizers such as SGD, Adam, or L-BFGS; consistency schemes) is user-level code built from primitive operations.
- Automatic differentiation as a graph rewrite: walk back from the loss to the parameters and add the backward operations to the same graph.
- Distribution by partitioning: each operation is placed on a device, and edges that cross devices become Send/Recv pairs automatically. Very large embedding tables are sharded, and only the rows actually used are read and updated.
- Fault tolerance by ordinary Save/Restore operations (checkpoints); synchronous training with backup workers takes the first \(m\) of \(n\) gradient updates, so slow machines do not stall the step.
Its main weakness: static graphs are awkward for dynamic models (control flow that depends on data, deep RL loops, tree-structured networks), and debugging happens one step removed from the code.
13.1.2 PyTorch: Learning as a Python Program
PyTorch (Paszke et al., 2019) makes the opposite trade-off: models, losses, control flow, and training loops are ordinary Python that runs immediately (eager, define-by-run execution). Its principles: be Pythonic, put researchers first, deliver pragmatic performance (giving up 10% of speed for simplicity is acceptable, 100% is not), and prefer a simple, slightly incomplete design (“worse is better”).
Definition 13.2 (Strided Tensor) A tensor is a view into a storage, a flat 1-D buffer of bytes on some device. The view records a storage offset, the sizes (shape), the strides (how many elements to step along each dimension), and a dtype. Element \((i,j)\) of a 2-D tensor lives at
\[ \text{offset}+i\cdot\text{stride}_0+j\cdot\text{stride}_1. \]
A tensor is contiguous when its strides follow row-major order.
A contiguous \(2\times3\) tensor holding \(0,\dots,5\) has strides \((3,1)\): element \((1,2)\) is at \(1\cdot3+2\cdot1=5\). Its transpose is a \(3\times2\) tensor over the same storage with strides swapped to \((1,3)\): element \((2,1)\) of the transpose is at \(2\cdot1+1\cdot3=5\), the same number. No data moves. Slicing (x[:, 0]) or expanding similarly only changes the offset, sizes, or strides, and an in-place change through one view is visible through the other. The transpose is no longer contiguous, so some kernels first call .contiguous(), which does copy.
- Dispatch. Each operation such as
torch.addis dispatched on the layout (strided, sparse, …), the device (CPU, CUDA, …), and the dtype. Adding a backend means registering kernels, not editing call sites. New operators are declared once in a schema file with their per-backend kernels and their derivative formula, and code generation produces the Python bindings and the backward function. - Autograd as a tape. Each differentiable operation records a node (
grad_fn) as the forward pass runs;loss.backward()walks these nodes in reverse topological order (Ch. 1). The graph is re-recorded every iteration, so Pythonifandwhilejust work. - Control on the CPU, data on the GPU. Python runs ahead and enqueues GPU kernels asynchronously on a CUDA stream; the GPU consumes the queue at its own pace, hiding interpreter overhead. Synchronization happens only when a value returns to Python (e.g.
.item()). - Memory.
cudaMallocandcudaFreesynchronize the device, so PyTorch keeps a caching allocator that reuses freed blocks per stream. Tensors are reference-counted, so memory is freed the moment the last reference disappears, with no unpredictable garbage-collection spikes.
With these, PyTorch ran within about 17% of the fastest framework on every benchmark tested (most frameworks share the same cuDNN and cuBLAS kernels), and by mid-2019 it appeared in about 45% of arXiv papers that named a framework. Usability and speed are compatible when the runtime is built for it.
13.1.3 Ray: Distributed Applications
Supervised learning fits batch training followed by serving. Reinforcement learning couples training, serving, and simulation in one application, with millions of fine-grained tasks per second lasting from milliseconds to hours on mixed CPUs and GPUs. Ray (Moritz et al., 2018) is not a replacement for PyTorch but the runtime layer that scales it.
- Tasks are stateless remote functions (
f.remote(args)returns a future,ray.getwaits for it): easy to balance and recovered by re-execution. Actors are stateful processes whose methods run serially: suited to parameter servers, GPU trainers, and simulators. Both run on one dynamic task-graph engine. - Architecture: a sharded, replicated global control store holds all control state, so every other component is stateless; a per-node shared-memory object store gives zero-copy reads; scheduling is bottom-up: tasks go to the local scheduler first and are forwarded to a global scheduler only if the node is overloaded or lacks a resource such as a GPU.
- It scales to over \(1.8\times10^6\) tasks per second on 100 nodes, and matches specialized systems for distributed training, policy serving, and RL simulation.
13.2 Compilers
Hand-tuning kernels and parallel strategies does not scale: there are hundreds of operators, many hardware targets, and many ways to parallelize. Compilers move these decisions from people into software.
- TVM (Chen et al., 2018) compiles models from any framework to any back-end (server and mobile GPUs, embedded CPUs, FPGAs, accelerators) without vendor libraries.
- Graph level: operator fusion (e.g. convolution + batch norm + ReLU in one kernel, which avoids writing intermediates to memory, worth 1.2–2×), constant folding, memory planning, layout transformations.
- Operator level: describe what to compute as a tensor expression and how with a separate schedule (tiling, loop reordering, unrolling, vectorization, thread binding, tensorization onto hardware intrinsics).
- Auto-tuning: the space of schedules has billions of options, so a learned cost model (gradient-boosted trees on loop features) predicts run times and guides a search, with real measurements fed back.
- GSPMD (Xu et al., 2021) parallelizes a single-device program from a few sharding annotations (
mesh_split(tensor, mesh, dims_mapping): which tensor dimension is split across which axis of a logical device mesh, or replicated). The compiler propagates shardings to every other tensor and emits one SPMD program run by all devices, so data, tensor, expert, spatial, and pipeline parallelism all come from one API. About 7 annotations per transformer layer (under 1% of tensors) sufficed to train a \(10^{12}\)-parameter model on 2048 TPU cores at 50–62% of peak FLOPs. - Alpa (Zheng et al., 2022) searches for the plan automatically by viewing all parallelism as two kinds:
- intra-operator (split each operator’s tensors across devices; heavy collective communication, so map it to fast links inside a node), chosen per operator by an integer linear program minimizing compute + communication + resharding cost;
- inter-operator (split the graph into pipeline stages; light point-to-point communication but idle “bubbles”, so map it across nodes), chosen by dynamic programming over stage and device-mesh slicings to minimize pipeline latency \(\sum_it_i+(B-1)\max_jt_j\) for \(B\) micro-batches.
@parallelizedecorator it matched hand-tuned Megatron-LM on GPT models and was 3.5–9.7× faster than DeepSpeed on mixture-of-experts models.
13.3 Distributed Training
The baseline is data parallelism: every device holds a full model copy, processes a different slice of the batch, and the gradients are averaged (all-reduce) before each update. When the model itself no longer fits, a different strategy is needed for each bottleneck:
| bottleneck | strategy | example |
|---|---|---|
| parameters too large | split the layers into stages (pipeline) | GPipe |
| matrix operations too large | split tensors within layers | Megatron-LM |
| optimizer states too large | shard states and gradients across data-parallel ranks | ZeRO |
| compute too expensive | route tokens to sparse experts | GShard |
13.3.1 Pipeline Parallelism
GPipe (Huang et al., 2019) partitions a network of \(L\) layers into \(K\) consecutive cells, one per accelerator, splits each mini-batch into \(M\) micro-batches, and pipelines them through the cells forward and then backward. Gradients are accumulated over all micro-batches and applied once per mini-batch, so updates are synchronous and the result does not depend on \(K\).
Proposition 13.1 (Pipeline Bubble) With \(K\) stages and \(M\) micro-batches of equal cost, each pass takes \(M+K-1\) time slots, of which each device is busy for \(M\). The idle bubble fraction is
\[ \frac{K-1}{M+K-1}, \]
which is negligible when \(M\ge4K\).
- The first micro-batch needs \(K\) slots to traverse the pipeline, and the last one enters \(M-1\) slots after the first, hence \(M+K-1\) in total. For example, \(K=4\) and \(M=16\) give a bubble of \(3/19\approx16\%\); \(M=32\) gives \(3/35\approx9\%\).
- Re-materialization: keep only the activations at cell boundaries and recompute the rest during the backward pass, reducing peak activation memory to \(O\bigl(N+\frac LK\cdot\frac NM\bigr)\) for batch size \(N\).
- Only boundary activations cross devices, so it works even with slow interconnects. GPipe trained a 557M-parameter AmoebaNet to 84.4% ImageNet top-1 and a single 6B-parameter, 128-layer translation model covering over 100 languages.
13.3.2 Tensor Parallelism
Megatron-LM (Shoeybi et al., 2019) splits the matrices inside each transformer layer, in native PyTorch with no new compiler.
Proposition 13.2 (Tensor-Parallel MLP) For the MLP \(Z=\mathrm{GeLU}(XA)\,B\) on two devices, split \(A=[A_1,A_2]\) by columns and \(B=\begin{bmatrix}B_1\\B_2\end{bmatrix}\) by rows. Then
\[ Z=\mathrm{GeLU}(XA_1)\,B_1+\mathrm{GeLU}(XA_2)\,B_2, \]
so device \(i\) computes its term independently, and a single all-reduce sums the results.
- The column split works because GeLU is elementwise: \(\mathrm{GeLU}([XA_1,XA_2])=[\mathrm{GeLU}(XA_1),\mathrm{GeLU}(XA_2)]\). Splitting \(A\) by rows instead would require \(\mathrm{GeLU}(X_1A_1+X_2A_2)\), which needs a synchronization before the nonlinearity.
- Self-attention is split by heads (the \(Q,K,V\) projections column-wise, the output projection row-wise), so each layer needs only two all-reduces forward and two backward. The vocabulary embedding is split too, and the output layer is fused with the cross-entropy so that only scalar losses, not full logits, are communicated.
- An 8.3B-parameter model on 512 GPUs sustained 15.1 PFLOP/s, 76% scaling efficiency, and set new language-modeling records.
13.3.4 Expert Parallelism
Definition 13.3 (Mixture-of-Experts Layer) A mixture-of-experts (MoE) layer replaces a transformer’s FFN with \(E\) expert FFNs and a learned gate. For each token \(x\), compute gate scores \(g(x)=\mathrm{softmax}(W_gx)\) and send \(x\) only to the top \(k\) experts (top-2 in GShard):
\[ y=\sum_{e\in\mathrm{top}\text{-}k(g(x))}g_e(x)\,\mathrm{FFN}_e(x). \]
- Conditional computation: each token activates a small subnetwork, so the FLOPs per token stay roughly constant as \(E\) grows with the number of devices: parameters scale up while compute does not.
- Load balancing: an expert capacity of \(O(N/E)\) tokens caps overflow, and an auxiliary loss spreads tokens evenly across experts.
- GShard (Lepikhin et al., 2020) adds three annotations (
replicate,split,shard) and an SPMD partitioner in XLA, so compilation time does not grow with the number of devices. Experts are distributed one per device, and an all-to-all sends each token to its experts. A 600B-parameter multilingual MoE was trained on 2048 TPU cores in 4 days; growing the model 16× (37.5B to 600B) cost only 3.6× more compute.
Scaling laws (Ch. 10, Ch. 12) turned compute into a planning variable: modern training is about allocating compute across parameters, tokens, and training time, and the systems above determine how much of that compute is actually usable.
13.4 Serving and Kernels
Training systems are mature; in practice, cost, latency, and throughput are now dominated by serving. The new bottlenecks are memory traffic and scheduling.
13.4.1 FlashAttention
Attention is memory-bound: standard implementations write the \(N\times N\) score and probability matrices to the GPU’s large but slow HBM (about 1.5 TB/s, tens of GB) and read them back, while the fast on-chip SRAM (about 19 TB/s) holds only about 20 MB. Reducing FLOPs with approximate attention rarely gives wall-clock speedups. FlashAttention (Dao et al., 2022) computes exact attention while minimizing HBM traffic: tile \(Q,K,V\) into blocks that fit in SRAM, fuse matmul, mask, softmax, dropout, and matmul into one kernel, and in the backward pass recompute the attention blocks instead of storing them. The key is that softmax can be computed block by block.
Proposition 13.4 (Online Softmax) For one query row, process the scores in blocks while keeping a running maximum \(m\), a running normalizer \(\ell\), and a running output \(O\). On a new block with scores \(s_j\) and values \(v_j\):
\[ m'=\max\bigl(m,\max_js_j\bigr), \qquad \ell'=e^{m-m'}\ell+\sum_je^{s_j-m'}, \qquad O'=\frac{e^{m-m'}\ell\,O+\sum_je^{s_j-m'}v_j}{\ell'}. \]
After the last block, \(O=\mathrm{softmax}(s)^\top V\) exactly.
By induction, after processing a set \(S\) of positions, \(m=\max_{j\in S}s_j\), \(\ell=\sum_{j\in S}e^{s_j-m}\), and \(O=\sum_{j\in S}e^{s_j-m}v_j/\ell\), which is softmax attention restricted to \(S\). When the maximum changes from \(m\) to \(m'\), every old term \(e^{s_j-m}\) must become \(e^{s_j-m'}=e^{m-m'}e^{s_j-m}\), which is exactly the rescaling applied to \(\ell\) and to the unnormalized output \(\ell O\). Subtracting the running maximum keeps every exponent \(\le0\), so nothing overflows.
- IO complexity. Standard attention needs \(\Theta(Nd+N^2)\) HBM accesses; FlashAttention needs \(\Theta(N^2d^2/M)\) for SRAM size \(M\), up to \(9\times\) fewer for typical head dimensions, and no exact algorithm can do asymptotically better for all \(M\). Memory grows linearly in \(N\).
- Results: up to 3× faster GPT-2 training, 15% faster than the MLPerf BERT record, and longer contexts that improve quality: the first transformers to beat chance on the Path-X (16K tokens) and Path-256 (64K) benchmarks.
13.4.2 PagedAttention and vLLM
During generation, each layer caches the keys and values of all previous tokens (the KV cache), and this cache, not compute, limits how many requests fit in a batch.
Per token, the cache stores a key and a value vector for every layer: \(2\times L\times d\times(\text{bytes per number})\). For OPT-13B (\(L=40\) layers, \(d=5120\), fp16):
\[ 2\times40\times5120\times2\ \text{bytes}=819{,}200\ \text{bytes}\approx0.8\ \text{MB per token}, \]
so a 2048-token sequence needs about \(1.7\) GB, comparable to a large fraction of the model weights, and it grows one token at a time to an unknown final length.
- The waste: systems that preallocate a contiguous buffer for each request’s maximum length suffer reserved-but-unused slots and internal and external fragmentation; only 20–38% of KV-cache memory held useful data. Contiguous buffers also prevent sharing between sequences.
- PagedAttention (Kwon et al., 2023) applies virtual memory to the KV cache: split each sequence’s cache into fixed-size blocks of \(B\) tokens, stored anywhere in GPU memory, with a per-request block table mapping logical to physical blocks, like a page table. Attention is computed block by block.
- Blocks are allocated on demand, so the only waste is part of the last block.
- Copy-on-write with reference counts lets parallel samples, beam-search candidates, and shared system prompts share blocks.
- When memory runs out, whole sequence groups are preempted and swapped to CPU memory or recomputed later.
- vLLM, built on it, serves 2–4× the throughput of the previous state of the art, more with beam search or shared prefixes.
13.4.3 SGLang
Agents, tree-of-thought, retrieval pipelines, and structured outputs are LM programs: many generation calls with control flow and structured input and output. SGLang (Zheng et al., 2024) provides a Python-embedded language for them (gen, select, fork/join for parallel branches) and a runtime that exploits their structure:
- RadixAttention keeps KV caches in a radix tree keyed by token prefixes, so calls that share a prefix (system prompts, few-shot examples, chat history, branches of a search) reuse the cache automatically, with LRU eviction and cache-aware scheduling;
- a compressed finite-state machine for constrained decoding (e.g. JSON) decodes runs of tokens forced by the grammar in a single step.
Together they give up to 6.4× higher throughput than earlier systems; in a production chatbot arena, cache hit rates reached 52–74%.
13.5 Supplementary Notes
13.5.1 Key Results
- Definition 13.1: static dataflow graph (TensorFlow) versus eager define-by-run (PyTorch).
- Definition 13.2: element \((i,j)\) at offset \(+\,i\,\text{stride}_0+j\,\text{stride}_1\); views share storage.
- Proposition 13.1: pipeline bubble \((K-1)/(M+K-1)\).
- Proposition 13.2: tensor-parallel MLP: column-split \(A\), row-split \(B\), one all-reduce.
- Proposition 13.3: mixed-precision Adam needs \(16\Psi\) bytes; ZeRO-3 cuts it to \(16\Psi/N_d\).
- Definition 13.3: MoE layer \(y=\sum_{\text{top-}k}g_e(x)\mathrm{FFN}_e(x)\).
- Proposition 13.4: online softmax makes tiled exact attention possible; HBM traffic \(\Theta(N^2d^2/M)\).
- KV cache per token \(=2Ld\times\) bytes per number.