45A sharding sheet
45 A sharding sheet
A candidate reports an Anthropic session that estimated compute, memory and network costs for different ways to shard a model, in a tool like a spreadsheet (1 source). This is the sheet, as code: practice in that shape, not a leaked question.
Set a 45-minute timer. Read one level at a time, and run only that level's tests until they pass:
pytest problems/45_sharding_sheet -k level1. Earlier levels must keep passing.
Sizes are in bytes and bandwidths in bytes a second. tp, pp and dp are the tensor, pipeline and data parallel
sizes, and a plan uses tp * pp * dp GPUs.
Level 1. Memory. train_bytes_per_gpu(params, tp, pp, dp, zero=0) is the training state on one GPU: 2 bytes a
parameter for bf16 weights, 2 for gradients and 12 for fp32 Adam states, with the parameters split evenly over
tp * pp GPUs. ZeRO stage 1 also divides the states by dp, stage 2 the gradients too, and stage 3 the weights too.
serve_bytes_per_gpu(params, bytes_per_param, kv_bytes, tp, pp) is the weights plus the KV cache, split evenly over
tp * pp GPUs.
Level 2. Time on the network. allreduce_seconds(size_bytes, n, bandwidth) is the best case for an all-reduce
over n GPUs: each GPU sends 2 * (n - 1) / n times the data at bandwidth, so the seconds are
2 * (n - 1) / n * size_bytes / bandwidth, and one GPU takes no time. dp_sync_seconds(params, tp, pp, dp, bandwidth, zero=0) all-reduces one GPU's bf16 gradients, 2 bytes for each of its parameters, over the
dp replicas, and ZeRO stage 3 moves 1.5 times as much (stages 1 and 2 move the same as stage 0). tp_seconds_per_layer(tokens, hidden, tp, bandwidth) is
tensor parallelism's cost for one layer: two all-reduces forward and two backward, each of tokens * hidden bf16
values over tp GPUs.
Level 3. Pipelines and plans. bubble(pp, microbatches) is the pipeline bubble as a share of the ideal compute
time: (pp - 1) / microbatches. plans(params, gpus, per_node, memory_bytes, zero=1) lists every (tp, pp, dp)
that uses exactly gpus GPUs, has tp a power of two no bigger than per_node, so tensor parallelism stays inside
one node, and fits: train_bytes_per_gpu at the given zero stage is at most memory_bytes. pp and dp can be
any whole numbers from 1 up. Sort them with the fewest model-parallel GPUs (tp * pp) first, and on a tie the fewest pipeline stages first.
Things to get right: 16 bytes a parameter for training, which ZeRO stage shards what, the 2 * (n - 1) / n factor,
four all-reduces a layer, and the order of the plans. Follow-ups from the lesson: hiding communication behind
compute, why tensor parallelism stays inside a node, and serving a model too big for one GPU.