Build a Gradient Accumulation and Synchronization Engine for Large Batches
distributed-systems performance scalability
AI System Design Deep Dive
Gradient Accumulation and Sync Engine
Sixty-four microbatches, one all-reduce, and only 77 ms of backward to hide it behind.
Think of an armored truck collecting deposits from 64 tellers. The truck cannot leave until the last teller has finished counting, so the only loading that can happen early is the bags that are already final. If the truck needs 331 ms to load and the last teller needs 77 ms to finish, the driver waits 254 ms with the engine running. Gradient accumulation works the same way. Sixty-three microbatches add into a ledger, and the all-reduce can only start moving the totals once the 64th backward pass has made them final.
Here are the numbers. We keep the 70.55B parameter model, the 512 H100 GPUs and the TP=8 x PP=4 x DP=16 layout from the last three posts. The global batch is 4,194,304 tokens, which is 1,024 sequences, so each of the 16 replicas processes 64 sequences as 64 microbatches of one sequence each. Every GPU holds 2.2047B parameters of the model, so its gradient is 4.41 GB in bf16. A ring all-reduce over the 16 replicas moves 8.27 GB per GPU, which is 0.331 s at the 25 GB/s cross-rack rate. The backward pass of one microbatch on one pipeline stage takes only 77 ms.
A naive engine fails in four places. A bf16 gradient buffer that accumulates 64 microbatches carries a relative error of 8.2e-3 against an exact sum, and 6.0e-2 if the run uses 1,024 microbatches (measured below, with an fp32 accumulator at 4e-9). Reducing after every microbatch puts 64 x 0.198 s = 12.7 s of traffic on a step that computes for 8.7 s, and even the flat ring would need 21.2 s. Reducing once, as no_sync() does, leaves only the last microbatch’s 77 ms of backward to overlap a 331 ms reduction, so a flat ring exposes 0.258 s per step. Post 32’s planner priced that exposure at 0.033 s because it let the reduction overlap the whole backward, and accumulation does not allow that. This post corrects the number and builds the engine that gets it down to 0.126 s. And averaging per-microbatch means instead of dividing by the global token count gives a gradient that is wrong by 24 to 28 percent in our synthetic tests, with a size that depends on the data.
On top of that, a batch of 4.19M tokens is a statistical decision. Too large relative to the gradient noise scale and the extra tokens buy almost no progress, and a learning rate carried over from a smaller batch can diverge in the first thousand steps. We need to solve for accumulation precision, exposed communication, and large-batch control simultaneously. The earlier posts chose the layout, the orchestrator and the recovery path. This post builds the layer that turns 64 microbatches of local gradients into one trustworthy update.
Requirements and Constraints
Functional requirements
- Accumulate 64 microbatch gradients per replica without losing precision, and reduce them across 16 replicas exactly once per step.
- Normalize by the global count of valid tokens, so the result equals the gradient of the mean loss for any
(dp, m)split, including the uneven split after a rack loss (post 33). - Decide once per step, identically on all 512 ranks, whether to apply, clip or skip the update.
- Choose the batch size and learning rate as a pure function of tokens consumed, with a batch ramp, a warmup and a cosine decay.
- Measure the gradient noise scale during the run without extra backward passes.
Non-functional requirements
- Numerical error: accumulated gradient within 1e-7 relative of an fp64 sum over 64 microbatches. The
bf16buffer misses this by about five orders of magnitude. - Exactness: gradient identical to a single device run within 1e-12 relative (float64 reference test) at
dp16, 12, 8 and 1. - Exposed communication: at most 0.13 s of gradient synchronization on the critical path per step, 1.5 percent of the 8.7 s step.
- Guard overhead: under 10 ms per step for norms, the replica comparison and the decision.
- Memory: 18 bytes per parameter of live state, 39.7 GB per GPU, inside the 72 GB budget (90 percent of 80 GB) with 11.4 GB of stage 0 activations and 10 GB of workspace.
- Cost: cost per million tokens under $2.10 (the post 32 requirement), and a ramp premium under $5,000.
- Quality: noise scale estimate within 5 percent of truth after 300 steps, and zero silent normalization changes across layout changes.
Constraints
- Hardware per node: 8 H100 (80 GB HBM3 at 3.35 TB/s), 3,200 Gbps of EFA, which is 50 GB/s per GPU inside a rack and 25 GB/s per GPU across the 2:1 oversubscribed spine. The 64 nodes sit in 4 racks, and a data parallel group of 16 has 4 members in each rack.
- Plain data parallelism with
bf16autocast,fp32master weights and AdamW (post 32). No ZeRO and no FSDP. - Step time of 8.7 s at 40 percent MFU, 7.393 s of which is compute after calibrating post 32’s cost model to the 0.126 s exposure this engine achieves. Cluster price $55.04 per
p5.48xlargehour in us-east-1 from third-party trackers (October 2026), so $3,522.56 per cluster hour. - Out of scope: gradient compression,
fp8training, and sequence packing details (the loader delivers valid-token counts).
Every requirement here is about the 77 ms window, the 4.41 GB buffer or the 4.19M token denominator. The three numbers are independent, which is why precision, communication and batch control can be designed as separate components and still add up.
High-Level Architecture
The engine has six components. The Token Counter computes the number of valid tokens in the global batch before the first microbatch runs. The Accumulator adds each microbatch gradient into an fp32 main_grad buffer. The Bucketed Reducer launches a hierarchical all-reduce per bucket during the last backward pass. The Norm Guard compares the 16 replica norms, the global norm and its own history, then picks apply, clip or skip. The Batch Controller serves the batch size and learning rate for the next step and tracks the gradient noise scale. The Metrics Sink writes one step_sync row per step.
A step runs like this. The loader fixes the 1,024 sequence ids from the global step, counts their valid tokens, and the 16 replicas exchange one 8-byte integer each, so every rank knows N_global before forward starts. For microbatches 1 to 63 the backward pass adds bf16 gradients into the fp32 buffer and nothing leaves the GPU. On microbatch 64 each bucket fires its reduction as soon as its layers finish, in three phases that keep 80 percent of the bytes inside the rack.
Because of 1F1B, the pipeline stages finish their last backward 77 ms apart, with stage 3 first and stage 0 last. Stage 3’s reduction finishes inside the drain of the other stages, so only stage 0 pays: it ends its backward at 308 ms on the diagram and its reduction ends at 434 ms. The Norm Guard then makes its decision from numbers that the buckets collected while launching, and the optimizer runs in about 18 ms.
The most important decision is to treat the last microbatch as the only communication window and then shrink what has to cross it. Nothing about bucket sizes matters until the wire time is smaller than the window plus the pipeline skew.
The Accumulator
The Accumulator’s job is to sum 64 microbatch gradients into one buffer without losing the small contributions, and to divide by the right number.
Adding 64 numbers into a bank balance that only stores three significant digits is a bad idea once the balance is large and the deposits are small. A bf16 buffer has 8 bits of mantissa, so every addition rounds to a relative precision of 0.4 percent, and the rounding errors pile up as the running sum grows. The fix is the one banks use: keep the ledger in higher precision than the receipts. Autograd produces bf16 gradients (the cast to fp32 is exact), and the Accumulator adds them into an fp32 main_grad tensor per parameter. I measured this with an emulated bf16 rounding (round to nearest even on the top 16 bits of an fp32 word):
# Accumulation precision: bf16 vs fp32 accumulators over m microbatches (numpy, bf16 emulated by round-to-nearest-even)
import numpy as np
def bf16(x):
u = np.asarray(x, dtype=np.float32).copy().view(np.uint32)
u += 0x7FFF + ((u >> 16) & 1)
u &= 0xFFFF0000
return u.view(np.float32)
def accumulate(m, d=200_000, seed=7):
rng = np.random.default_rng(seed)
signal = rng.standard_normal(d).astype(np.float32) * 1e-3
grads = [bf16((signal + rng.standard_normal(d).astype(np.float32) * 4e-3) / m) for _ in range(m)]
ref = np.sum(np.array(grads, dtype=np.float64), axis=0)
acc16 = np.zeros(d, np.float32)
acc32 = np.zeros(d, np.float32)
for g in grads:
acc16 = bf16(acc16 + g) # what a bf16 .grad buffer does on every backward
acc32 = acc32 + g # what a fp32 main_grad buffer does
err = lambda a: np.linalg.norm(a.astype(np.float64) - ref) / np.linalg.norm(ref)
return err(acc16), err(acc32)
for m in (64, 1024):
e16, e32 = accumulate(m)
print(f"m={m:5d} bf16 accumulator rel err {e16:.2e} fp32 accumulator rel err {e32:.2e}")
# Reduction precision: a 16 replica ring that rounds to bf16 at every hop versus one cast of an fp32 sum
rng = np.random.default_rng(11)
replicas = [bf16(rng.standard_normal(200_000).astype(np.float32) * 1e-3 + 1e-4) for _ in range(16)]
truth = np.sum(np.array(replicas, dtype=np.float64), axis=0)
hop = replicas[0].copy()
for r in replicas[1:]:
hop = bf16(hop + r) # NCCL style: bf16 partial sum on every hop
once = bf16(np.sum(np.array(replicas, dtype=np.float32), axis=0))
rel = lambda a: np.linalg.norm(a - truth) / np.linalg.norm(truth)
print(f"bf16 rounding at every hop {rel(hop):.2e} fp32 sum then one bf16 cast {rel(once):.2e}")
An fp32 accumulator is 4e-9 off at 64 microbatches, and the bf16 buffer is 8.2e-3 off. At 1,024 microbatches the bf16 error grows to 6.0e-2, because late microbatches are small next to the running sum and fall below the rounding step. The second measurement is about the wire. A ring that rounds to bf16 at each of 15 hops is 4.9e-3 off, and one cast of an fp32 sum is 1.7e-3 off. If the gradient noise scale is near 3M tokens (the illustrative value used below), sampling noise at a 4.19M token batch is about 85 percent of the signal, so a 0.5 percent reduction error is noise on top of noise. That is the reason the engine accumulates in fp32 and reduces in bf16.
The torch side is a hook per parameter. It needs GPUs, so this block was not run here:
# Accumulator: autograd bf16 grads are added into fp32 main_grad, then freed (needs a GPU, not run here)
import torch
class Accumulator:
def __init__(self, params, micro_tokens: int = 4096):
self.params = [p for p in params if p.requires_grad]
self.inv_total = None
for p in self.params:
p.main_grad = torch.zeros_like(p, dtype=torch.float32) # 18 bytes per parameter in total, 4.41 GB extra per GPU
p.register_post_accumulate_grad_hook(self._hook)
@staticmethod
def _hook(p: torch.Tensor) -> None:
p.main_grad.add_(p.grad) # fp32 += bf16, exact cast
p.grad = None # release the bf16 gradient immediately
def begin_step(self, valid_tokens_global: int) -> None:
self.inv_total = 1.0 / valid_tokens_global # known before microbatch 0 from the loader
def backward(self, loss_sum: torch.Tensor) -> None:
"""loss_sum is the SUM of per-token losses over the valid tokens of this microbatch."""
(loss_sum * self.inv_total).backward() # no division by m, by dp or by a local count
The normalization is the second job. The loss of each microbatch is a sum over valid tokens, and the only divisor anywhere in the engine is the global valid-token count. In the next block, per-token gradients have a length-dependent scale and each sequence has between 1,500 and 4,096 valid tokens:
# Token-weighted normalization: divide by the global valid-token count, never by m or by a local count
import numpy as np
rng = np.random.default_rng(3)
N, D = 1024, 64 # sequences per step, parameter dimension
valid = rng.integers(1500, 4097, size=N) # valid (unmasked) tokens per sequence
tok_grad = [rng.standard_normal((n, D)) * (1 + (4096 - n) / 4096) for n in valid]
seq_sum = np.stack([g.sum(0) for g in tok_grad]) # d(sum of token losses)/dtheta per sequence
truth = seq_sum.sum(0) / valid.sum() # gradient of the mean over all tokens
def engine(dp, m):
"""Replica r owns sequences r::dp, splits them into m microbatches, divides by the GLOBAL token count."""
total = valid.sum() # known before step starts (loader computes it, one tiny all-reduce)
replicas = []
for r in range(dp):
ids = np.arange(r, N, dp)
acc = np.zeros(D)
for chunk in np.array_split(ids, min(m, len(ids))):
acc += seq_sum[chunk].sum(0) / total
replicas.append(acc)
return np.sum(replicas, axis=0) # all-reduce SUM, no further division
def mean_of_means(dp, m):
ids_all = [np.arange(r, N, dp) for r in range(dp)]
mbs = [c for ids in ids_all for c in np.array_split(ids, min(m, len(ids)))]
per_mb = [seq_sum[c].sum(0) / valid[c].sum() for c in mbs]
return np.mean(per_mb, axis=0)
rel = lambda a: np.linalg.norm(a - truth) / np.linalg.norm(truth)
for dp, m in ((16, 64), (12, 86), (8, 128)):
print(f"dp={dp:2d} m={m:3d} token-weighted rel err {rel(engine(dp, m)):.1e} mean-of-means rel err {rel(mean_of_means(dp, m)):.1e}")
dp=16 m= 64 token-weighted rel err 1.2e-15 mean-of-means rel err 2.8e-01
dp=12 m= 86 token-weighted rel err 1.1e-15 mean-of-means rel err 2.8e-01
dp= 8 m=128 token-weighted rel err 1.1e-15 mean-of-means rel err 2.8e-01Premium Content
Unlock the full article along with everything else in the archive — all in one place.