Sub topic 2
Why batching makes accelerators more efficient
This chapter assumes you know how a model is served behind an HTTP or gRPC endpoint, and that you can read p50 and p99 latency figures. It also assumes you can read short Python snippets. It explains the hardware reason batching raises throughput, so that the batching parameters in later chapters make sense.
The core idea: one weight read, many requests
A GPU or similar accelerator runs a model layer by layer. Each layer must read its weights from device memory before it can use them. For a large layer, that read can take longer than the arithmetic.
Consider a request that arrives alone (batch size 1). The accelerator reads the whole weight matrix, multiplies it by one input vector, and discards the weights from the compute units. If 32 requests are grouped, the accelerator reads the weights once and multiplies them by 32 input vectors. The memory cost is nearly the same, and the useful arithmetic is 32 times larger.
Batching therefore gives you more useful work for each byte moved. Throughput rises sharply, and per-request latency rises only a little until the hardware runs out of spare compute.
Memory-bound and compute-bound work
Two quantities decide how long a layer takes:
- Memory time is the bytes that must be moved divided by memory bandwidth.
- Compute time is the floating-point operations divided by the peak compute rate.
The layer takes roughly the larger of the two. Arithmetic intensity is the number of operations performed per byte moved. A workload with low intensity is memory-bound, and one with high intensity is compute-bound.
For a dense layer with a d × d weight matrix in 16-bit floats and a batch of B inputs, the operation count is about 2·B·d². The weights take 2·d² bytes. When d is large, the intensity is about B operations per byte. Intensity grows linearly with batch size.
Every accelerator has a ridge point. This is the intensity at which compute time equals memory time. It is the peak compute rate divided by the memory bandwidth. As an illustration, take an accelerator with about 312 TFLOP/s of 16-bit compute and about 2 TB/s of memory bandwidth. Its ridge point is about 156 operations per byte. Below a batch of roughly 156, a large dense layer waits on memory.
A worked example
Take one layer with d = 8192 in 16-bit precision, on the accelerator above. The simplified model ignores activation traffic, caches, and kernel overhead.
- Weights:
2 × 8192²bytes, about 134 MB. Reading them at 2 TB/s takes about 67 µs. - Compute for one input: about 134 MFLOP. At 312 TFLOP/s that takes about 0.43 µs.
| Batch size | Compute time (µs) | Memory time (µs) | Layer latency (µs) | Compute utilization |
|---|---|---|---|---|
| 1 | 0.4 | 67 | 67 | 0.6% |
| 16 | 6.9 | 67 | 67 | 10% |
| 64 | 27.5 | 67 | 67 | 41% |
| 128 | 55.0 | 67 | 67 | 82% |
| 256 | 110.1 | 67 | 110 | 100% |
Going from batch 1 to batch 128 leaves the layer latency unchanged at 67 µs. In this model, the throughput is 128 times higher. Past the ridge point, at batch 256, latency grows in proportion to the batch and throughput gains flatten.
Measuring the effect yourself
The same effect appears on a CPU, because a CPU also pays to stream a weight matrix through its caches. The script below times one matrix multiply at several batch sizes and prints the time per item. The numbers depend on your machine, but the per-item time should fall as the batch grows.
import time
import numpy as np
rng = np.random.default_rng(0)
d = 2048
weights = rng.standard_normal((d, d), dtype=np.float32)
def seconds_per_call(batch_size, repeats=30):
x = rng.standard_normal((batch_size, d), dtype=np.float32)
x @ weights # warmup, so one-time setup is not timed
start = time.perf_counter()
for _ in range(repeats):
x @ weights
return (time.perf_counter() - start) / repeats
print(f"{'batch':>6} {'ms/call':>9} {'us/item':>9} {'items/s':>10}")
for b in [1, 2, 4, 8, 16, 32, 64, 128]:
t = seconds_per_call(b)
print(f"{b:>6} {t * 1e3:>9.3f} {t / b * 1e6:>9.1f} {b / t:>10.0f}")Look at the ms/call column as well as items/s. Calls take longer as the batch grows, but they do not take proportionally longer. That gap is the gain from batching.
Other sources of inefficiency at small batch sizes
Memory bandwidth is the main reason, but it is not the only one.
- Kernel launch overhead. Every operation on a GPU is launched by the host and costs a few microseconds. For small models, or small batches, these fixed costs can exceed the arithmetic. A batch pays them once for all its requests.
- Underfilled hardware. A GPU has thousands of arithmetic units. A single small matrix multiply cannot occupy them all, so most sit idle. More rows in the batch give the scheduler more parallel work.
- Fixed per-call costs in the server. Serialization, host-to-device copies, and framework dispatch each have a fixed part. Batching spreads that part over more requests.
Where the gains stop
Batching does not help forever. Four limits matter in practice.
- Compute saturation. Past the ridge point, doubling the batch roughly doubles the time. Throughput flattens, and each request waits longer.
- Device memory. Activations and, for LLMs, the attention cache grow with batch size. An oversized batch causes out-of-memory errors rather than slowdown.
- Padding waste. Most tensor frameworks need inputs in a batch to share a shape. If you batch texts of 10 and 500 tokens, the short one is padded to 500, and the accelerator does work that produces nothing. Padding lowers the real gain from batching. Grouping requests of similar length reduces it.
- Time spent forming the batch. The server often has to wait for requests to arrive. That wait is added to every request's latency. Later chapters cover how to bound it.
Common errors
- Benchmarking with a single repeated input. A cold first call includes one-time setup such as kernel compilation and memory allocation. Warm up, then time many calls, as the script above does.
- Reporting only throughput. A benchmark that shows 10x more items per second but hides a p99 that doubled can lead to a bad deployment. Always report latency percentiles next to throughput.
- Extending the measured gain to other models. A small model, or a layer with a small
d, is already near the ridge point at a low batch size. Its gain is smaller and it saturates sooner. Large dense models, and the decode step of LLMs, gain the most. - Forgetting that real models mix layer types. Different layers cross their ridge points at different batch sizes. End-to-end profiling, not a single-layer estimate, gives the batch size to use.
- Ignoring shape-specific behavior. Some runtimes compile or tune kernels per input shape. A server that sees many different batch sizes may pay a warmup cost for each one. Fixing a set of allowed shapes avoids this.
Why this matters for the rest of the tutorial
The curve in this chapter is the reason servers batch at all. It also sets the trade-off that the batching parameters control. A bigger batch buys throughput and costs waiting time. The batch size at which the curve flattens tells you the largest batch worth forming. Autoscaling then adds replicas when one replica running at its best batch size can no longer carry the load.
Exercise
A layer has a 4096 × 4096 weight matrix in 16-bit floats, on an accelerator with 200 TFLOP/s of compute and 1 TB/s of memory bandwidth. Using the simplified model from this chapter (operations 2·B·d², bytes 2·d², activations ignored), estimate the batch size at which the layer stops being memory-bound. What happens to latency and throughput if you raise the batch well above that size?
Show answer
The ridge point is peak compute divided by bandwidth: 200e12 / 1e12 = 200 operations per byte. With 16-bit weights the intensity is about B operations per byte, so the layer stops being memory-bound at a batch size of about 200. You can check this directly. The weights are 2 × 4096² ≈ 33.6 MB, which takes about 33.6 µs to read at 1 TB/s. Compute for one input is about 33.6 MFLOP, or about 0.168 µs, so compute time matches memory time at B ≈ 200. Above that, the layer is compute-bound. Latency then grows roughly in proportion to the batch size, and throughput stays near the peak and stops improving. Extra batching only adds waiting time.
Exercise
Name two reasons, other than memory bandwidth, why batch size 1 wastes accelerator capacity. Then name two limits that stop you from raising the batch size indefinitely.
Show answer
Reasons for waste at batch size 1: kernel launch and per-call server overhead are paid for each request, and a small multiply cannot fill the thousands of arithmetic units, so most sit idle. Limits on raising the batch size: device memory (activations and attention caches grow with the batch, causing out-of-memory errors), and the time spent waiting for the batch to form. Compute saturation and padding waste are also valid answers.