Training Infrastructure and Economics
local graph
Chapter 20 — Training Infrastructure and Economics
Section titled “Chapter 20 — Training Infrastructure and Economics”Thousands of GPUs splitting a model is necessary but not sufficient. They must be fed data fast enough to never idle, their arithmetic must be wrung out near peak, and the whole enterprise carries a dollar cost that decides whether it happens at all. This chapter covers the supporting infrastructure — storage, kernels, and measurement — and then the economics, where DeepSeek-V3’s headline achievement was not only its quality but the remarkably low cost at which it was trained. Efficiency, it turns out, is the entire game.
20.1 Feeding the GPUs: Storage and Data
Section titled “20.1 Feeding the GPUs: Storage and Data”At trillion-token scale, simply reading the training data can bottleneck the GPUs. The data lives as the packed token shards of Chapter 6, but serving them to thousands of workers at full speed requires a parallel filesystem built for the job. DeepSeek open-sourced 3FS (the Fire-Flyer File System), a high-throughput distributed filesystem optimized for the random-read patterns of training and inference, and smallpond, a lightweight framework for distributed data processing on top of it. The principle from Chapter 2 holds at the cluster level: keep data moving, and never let an expensive resource wait on a cheap one.
20.2 The Open Kernel and Systems Stack
Section titled “20.2 The Open Kernel and Systems Stack”Throughout this book we have met DeepSeek’s individual components; it is worth seeing them as the coherent stack they form, because together they are a near-complete, open blueprint for training and serving a frontier model — something no other lab has published at this depth. Table 20.1 collects them.
| Component | Layer | What it does |
|---|---|---|
| 3FS | storage | high-throughput parallel filesystem for training/inference |
| smallpond | data | distributed data processing on 3FS |
| DeepGEMM | compute | FP8 matrix-multiply kernels with fine-grained scaling |
| FlashMLA | compute | MLA attention/decode kernels for Hopper and Blackwell |
| DeepEP | communication | expert-parallel all-to-all dispatch and combine |
| DualPipe | scheduling | overlapping bidirectional pipeline schedule |
| EPLB | balancing | expert-parallel load balancer |
| profile-data | profiling | shared training/inference profiling traces |
Table 20.1 — DeepSeek’s open-source infrastructure stack
A team with these pieces, the model code of Part IV, and the training recipe of this part has, in principle, the full toolkit a frontier lab uses internally. The remaining barrier is not knowledge but capital — the GPUs themselves — which is exactly what makes the economics worth understanding.
20.3 Measuring Efficiency: Model FLOPs Utilization
Section titled “20.3 Measuring Efficiency: Model FLOPs Utilization”The key efficiency metric is model FLOPs utilization (MFU): the fraction of the GPUs’ theoretical peak arithmetic that the training run actually achieves. It rests on a useful rule of thumb — training costs about 6N floating-point operations per token, where N is the number of (active) parameters: roughly two for the forward pass and four for the backward. MFU compares the achieved rate to the hardware peak:
def mfu(n_active_params, tokens_per_sec, peak_flops_per_gpu, n_gpus): achieved = 6 * n_active_params * tokens_per_sec # ~6N FLOPs per token peak = peak_flops_per_gpu * n_gpus return achieved / peak # fraction of theoretical peakPython — mfu.py: model FLOPs utilization
A well-tuned large run reaches an MFU of roughly 0.3 to 0.5; sustaining above 0.5 is excellent and hard, because communication, memory stalls, and pipeline bubbles all erode it. MFU is the single number that tells you whether the parallelism of Chapter 19 and the kernels above are doing their job — a low MFU means the GPUs are waiting, not computing, and every percentage point recovered is real money saved on a run of this size.
20.4 The Economics of a Run
Section titled “20.4 The Economics of a Run”The cost of pretraining is, to first order, the FLOPs required (about 6ND for N active parameters and D tokens) divided by the FLOPs your hardware delivers per dollar. DeepSeek-V3 made this concrete and startling: it reported a total of roughly 2.79 million H800 GPU-hours — about **2 per GPU-hour — for the full training. For comparison, Llama 3.1 405B reportedly used on the order of 30 million H100 GPU-hours, and frontier closed models are widely estimated to cost far more. Table 20.2 places a few figures side by side.
| Model | GPU-hours (approx.) | Notes |
|---|---|---|
| DeepSeek-V3 (671B / 37B active) | ~2.79M (H800) | ~$5.6M; MoE + FP8 + optimized stack |
| Llama 3.1 405B (dense) | ~30.8M (H100) | dense model, far more active compute |
| Frontier closed models | undisclosed | widely estimated much higher |
Table 20.2 — Approximate pretraining compute for recent large models
Figures are as reported or estimated and not perfectly comparable (different GPUs, scopes, and accounting). The order-of-magnitude gap is the point, and it traces directly to the techniques of this book: a low active-parameter fraction (MoE), FP8 arithmetic, and a communication-and-pipeline stack tuned to hide latency.
Key point DeepSeek-V3’s significance is partly that it collapsed the assumed cost of a frontier model by an order of magnitude — and then published how. Every technique responsible is in this book: MLA and MoE shrink the per-token compute and memory; FP8 halves the arithmetic cost; DualPipe, DeepEP, and EPLB keep the GPUs busy; 3FS keeps them fed. Efficiency is not a footnote to capability — at this scale, it is the capability, because it determines what is affordable to attempt.
The infrastructure is now complete: the model is split, fed, computed efficiently, and costed. One risk remains that no amount of infrastructure removes — that a run lasting weeks simply diverges. The final chapter of Part V is about keeping a large training run alive: detecting instability, surviving loss spikes, and knowing what to watch.
20.5 Worked Example: Sharded Checkpointing
Section titled “20.5 Worked Example: Sharded Checkpointing”At scale no single rank holds the whole model, so checkpoints must be written and read in shards, in parallel. PyTorch’s distributed checkpointing saves each rank’s slice and reloads into the same sharded layout — the exact-resume discipline of Section 17.6 at thousands of GPUs:
import torch.distributed.checkpoint as dcp
# each rank writes only its shard of params and optimizer statedcp.save(state_dict={"model": model, "optim": optimizer}, checkpoint_id=f"ckpt/step_{step}")
# resume is symmetric — load into the same sharded layoutdcp.load(state_dict={"model": model, "optim": optimizer}, checkpoint_id=f"ckpt/step_{step}")Python — distributed checkpoint: every rank writes its own shard
20.6 Fault Tolerance: Surviving Hardware at Scale
Section titled “20.6 Fault Tolerance: Surviving Hardware at Scale”At a thousand GPUs running for weeks, hardware failure is not an exception to plan around — it is a routine event that happens every few hours. A single dead rank takes down the whole synchronous job, because the next collective (Section 19.7) will block forever waiting for it. Two defenses combine: frequent asynchronous checkpoints (Section 20.5) bound how much work a failure can destroy, and an elastic supervisor restarts the job from the last checkpoint with a freshly formed process group.
while step < max_steps: try: loss = train_step(next(loader)) except (RuntimeError, dist.DistBackendError) as e: log.error(f"rank failure at step {step}: {e}") reinit_process_group() # rebuild comm without the dead rank model, optimizer, step = load_checkpoint(latest_checkpoint()) continue # resume from last good state if step % ckpt_every == 0: async_save(model, optimizer, step) # non-blocking (20.5) step += 1Python — infra/elastic.py: catch, restore, continue
The economic logic is direct. If checkpoints are 30 minutes apart and a failure occurs every 4 hours, the expected waste is half a checkpoint interval — 15 minutes — plus restart time, per failure. Halve the interval and you halve the waste, at the cost of more checkpoint I/O; this is the trade-off that sets ckpt_every on a real run, and it is why asynchronous, sharded checkpointing (each rank writes only its own slice, off the critical path) is not a luxury but a requirement.
20.7 Worked Example: Profiling to Find the Bottleneck
Section titled “20.7 Worked Example: Profiling to Find the Bottleneck”Model FLOPs Utilization (Section 20.3) tells you whether a run is slow; the profiler tells you where. A few hundred steps of warmup followed by a short profiled window is usually enough to localize the loss:
from torch.profiler import profile, ProfilerActivity
with profile(activities=[ProfilerActivity.CUDA], record_shapes=True) as prof: for _ in range(8): train_step(next(loader))
print(prof.key_averages().table(sort_by="cuda_time_total", row_limit=10))Python — infra/profile.py: a CUDA profile of the step
The ranked table reads like a diagnosis. If an all_reduce or all_gather kernel dominates, the run is communication-bound — bucket and overlap (Section 19.7) or reconsider the mesh. If a single GEMM dominates but MFU is low, the matrix shapes or dtype may be locking you out of the tensor cores; pad dimensions to multiples of the hardware’s tile and confirm BF16/FP8 inputs (Chapter 18). If host-side data-loading kernels appear at all, the input pipeline (Section 20.1) is starving the GPUs and no amount of model tuning will help until it is fixed.
Measure, then optimize The most common scaling mistake is optimizing the wrong thing — tuning a kernel that is 3% of the step while a hidden all-gather eats 40%. The profiler costs minutes and routinely overturns the intuition about where the time goes.
20.8 When the Data Loader Is the Bottleneck
Section titled “20.8 When the Data Loader Is the Bottleneck”A subtle and common failure at scale is a training run that is slow for a reason that has nothing to do with the model: the GPUs are starving, finishing each step’s computation before the next batch of data is ready. The symptom on a profiler (Section 20.7) is unmistakable — idle gaps between steps while expensive accelerators wait on the CPU. The fix is a properly configured input pipeline:
loader = DataLoader(dataset, batch_size=B, num_workers=8, # parallel CPU prefetch pin_memory=True, # faster host-to-GPU copy prefetch_factor=4) # stay ahead of the GPUPython — data/loader.py: keeping the GPUs fed
Each knob addresses a stage of the pipeline. Multiple worker processes tokenize and assemble batches in parallel so preparation overlaps with GPU computation; pinned memory lets the host-to-device transfer use faster DMA paths; and a prefetch factor keeps several batches queued so a momentary disk hiccup does not stall the step. The deeper fix, when even this is not enough, is to pre-tokenize the corpus once and store token ids directly (Chapter 6), removing tokenization from the hot path entirely. The principle is general: at scale, the GPUs are the most expensive resource in the building, and any second they spend idle waiting for data is the most costly idleness there is.
A starved GPU is the most expensive idle resource you own If accelerators wait on the data loader, the model is irrelevant to the slowdown. Parallel workers, pinned memory, prefetching, and pre-tokenization keep the pipeline ahead of the compute — check this before blaming the model.
20.9 Kernel Fusion and FlashAttention as a Systems Win
Section titled “20.9 Kernel Fusion and FlashAttention as a Systems Win”A subtle truth of GPU performance is that many operations are limited not by arithmetic but by memory traffic: each separate kernel reads its inputs from slow high-bandwidth memory and writes its outputs back, and for cheap element-wise operations that round trip dominates. Kernel fusion attacks this by combining several operations into one kernel that keeps intermediate results in fast on-chip memory, paying the expensive memory round trip once instead of many times.
FlashAttention is the canonical and most consequential example. A naive attention implementation materializes the full T×T score matrix in memory (Section 7.5), reads it back to apply the softmax, reads it again to multiply by the values — an enormous amount of memory traffic that grows quadratically. FlashAttention fuses the entire operation into a single kernel that computes attention in tiles, never writing the full score matrix to memory at all; it recomputes small pieces on the fly in fast memory instead. The result turns attention from a memory-bound operation into a compute-bound one and removes the quadratic memory cost entirely, which is why it — and its successors — are not an optional optimization but the default in every serious training and serving stack. It is the clearest illustration in the book that, at scale, how you move data through the memory hierarchy matters as much as how many operations you perform.
Moving data is the hidden cost Many kernels are bottlenecked by memory traffic, not math. Fusion keeps intermediates on-chip; FlashAttention fuses attention so the quadratic score matrix never touches memory — the reason it is standard everywhere.
20.10 The Roofline Model
Section titled “20.10 The Roofline Model”Before optimizing a kernel, you need to know what is limiting it — and optimizing the wrong thing wastes effort. The roofline model is the standard diagnostic. It plots achievable performance against arithmetic intensity, the ratio of arithmetic operations performed to bytes of memory moved. The plot has two regimes separated by a corner, and every kernel lands in one of them.
Below a threshold intensity, performance is capped by memory bandwidth: the kernel does too little math per byte fetched, so it spends its time waiting on memory and the hardware’s compute units sit underused — the kernel is memory-bound. Above the threshold, performance is capped by compute: there is enough arithmetic per byte to keep the units saturated, so the kernel is compute-bound. The diagnostic value is decisive because the two call for opposite fixes. A memory-bound kernel cannot be sped up by reducing FLOPs — the math was never the bottleneck — but it can be helped by moving less data, which is exactly what kernel fusion and FlashAttention achieve (Section 20.9). A compute-bound kernel is the reverse: data movement is already hidden, and only doing less arithmetic, or using faster arithmetic units (lower precision, Chapter 18), will help. Reading where a kernel falls on the roofline tells you which lever to pull, and saves you from the common mistake of optimizing arithmetic in a kernel whose real problem is memory traffic.
Know the bottleneck before you optimize The roofline model classifies a kernel as memory-bound or compute-bound by its arithmetic intensity. Memory-bound kernels need less data movement, not fewer FLOPs; compute-bound kernels need the reverse. Optimize the limit you actually have.