GPU Inference Concepts
GPUs made deep learning practical, so it is tempting to assume every model should be served on one. Often that is wrong in both directions: a gradient-boosted model or a small logistic regression is faster and far cheaper on a CPU, while a large language model does not even fit in the memory of a single CPU-sized budget and is unusable without a GPU. And a GPU that is chosen correctly can still run at 1 % of its capability because it is fed one request at a time.
This lesson gives the back-of-the-envelope tools to reason about GPU inference without running anything on a GPU: how much memory a model needs, why batch size decides utilisation (arithmetic intensity and the roofline model), what lower precision buys, when a CPU is the better choice, and what happens at start-up. All examples are NumPy arithmetic you can run in the browser. The PyTorch side of devices is in Devices, memory during training in Memory, AMP and DDP.
Memory: weights, activations and the KV cache
A GPU can only compute on data in its own memory (VRAM), and VRAM is small and expensive compared with CPU RAM. Three things live there during inference:
- Weights: the number of parameters times the bytes per parameter. FP32 uses 4 bytes, FP16 and BF16 use 2, INT8 uses 1, 4-bit formats use 0.5.
- Activations: the intermediate outputs of the layers for the current batch. At inference they are short-lived (no gradients, nothing kept for a backward pass), so they are usually small next to the weights, but they grow with batch size and input size (image resolution, sequence length).
- The KV cache (for transformers that generate text): to avoid recomputing attention over the whole prefix for every new token, each layer stores the key and value vectors of every past token. For a model with layers and hidden size , with standard multi-head attention, that is
and the total grows with the number of tokens held, . Variants such as grouped-query attention share keys and values between heads and shrink the cache by the group factor.
import numpy as np
GB = 1e9
bytes_per = {"FP32": 4, "FP16/BF16": 2, "INT8": 1, "INT4": 0.5}
print("weights only (GB):")
print(f"{'parameters':>11s} " + " ".join(f"{k:>10s}" for k in bytes_per))
for params in (125e6, 1.3e9, 7e9, 70e9):
print(f"{params / 1e9:10.3g}B " + " ".join(f"{params * b / GB:10.2f}" for b in bytes_per.values()))
# KV cache of a 7B-class transformer: 32 layers, hidden size 4096, FP16, full multi-head attention
layers, d, b = 32, 4096, 2
per_token = 2 * layers * d * b
print(f"\nKV cache per token: {per_token / 2**20:.2f} MiB")
weights = 7e9 * 2 / GB
for batch, ctx in ((1, 4096), (8, 4096), (32, 4096), (32, 1024)):
kv = per_token * batch * ctx / GB
print(f"batch {batch:2d} x context {ctx}: KV {kv:5.1f} GB + weights {weights:.0f} GB = {kv + weights:5.1f} GB"
f" | fits 24 GB: {kv + weights <= 24 * 0.9}, 80 GB: {kv + weights <= 80 * 0.9}")weights only (GB):
parameters FP32 FP16/BF16 INT8 INT4
0.125B 0.50 0.25 0.12 0.06
1.3B 5.20 2.60 1.30 0.65
7B 28.00 14.00 7.00 3.50
70B 280.00 140.00 70.00 35.00
KV cache per token: 0.50 MiB
batch 1 x context 4096: KV 2.1 GB + weights 14 GB = 16.1 GB | fits 24 GB: True, 80 GB: True
batch 8 x context 4096: KV 17.2 GB + weights 14 GB = 31.2 GB | fits 24 GB: False, 80 GB: True
batch 32 x context 4096: KV 68.7 GB + weights 14 GB = 82.7 GB | fits 24 GB: False, 80 GB: False
batch 32 x context 1024: KV 17.2 GB + weights 14 GB = 31.2 GB | fits 24 GB: False, 80 GB: True
A 7-billion-parameter model needs 28 GB in FP32 and 14 GB in FP16, before anything else; a 70B model needs 140 GB in FP16, more than any single card in this comparison, and 35 GB even at 4 bits. The KV cache of this 7B-class model takes 0.5 MiB per token, so one 4096-token conversation adds 2.1 GB, and 8 of them add 17.2 GB: more than the weights. Batch 8 at 4096 tokens and batch 32 at 1024 tokens need the same 31.2 GB, because the cache depends on the number of tokens held, not on how they are split. For generative models the KV cache, not the weights, usually limits the batch size and therefore the throughput, which is why serving systems manage it carefully (paged allocation, cache quantization, grouped-query attention).
Batch size and utilisation: arithmetic intensity
A GPU has enormous compute (tens to hundreds of TFLOP/s, floating-point operations per second) but its memory bandwidth, though high, is much smaller by comparison (one to a few TB/s). Whether a computation is limited by compute or by memory depends on its arithmetic intensity: floating-point operations per byte moved to or from memory,
The roofline model says the attainable speed is the smaller of the compute peak and what the memory system can feed:
The crossover, , is the ridge point. Below it, the kernel is memory-bound and most of the compute units idle.
A fully connected layer with a weight matrix on a batch of rows needs FLOPs and must read the weights ( values) and read and write the activations ( values). At batch size 1, every weight is read once and used for exactly one multiply-add: FLOP per byte in FP16, far below any GPU's ridge point. Each extra row in the batch reuses the same weights, so grows almost linearly with until the layer becomes compute-bound. That is the physical reason behind dynamic batching.
The numbers below use round illustrative figures, not a specific product: a GPU with 100 TFLOP/s FP16 and 2 TB/s, and a server CPU with 2 TFLOP/s and 0.1 TB/s.
import numpy as np
import matplotlib.pyplot as plt
d, nbytes = 4096, 2 # a 4096 x 4096 layer in FP16
devices = {"GPU": (100e12, 2e12), "CPU": (2e12, 0.1e12)} # (peak FLOP/s, bandwidth bytes/s), illustrative
def layer(batch):
flops = 2 * batch * d * d
moved = (d * d + 2 * batch * d) * nbytes
return flops, flops / moved
for name, (peak, bw) in devices.items():
print(f"{name}: ridge point {peak / bw:.0f} FLOP/byte")
print(f"{'batch':>6s} {'intensity':>10s} {'GPU util':>9s} {'GPU rows/s':>11s} {'CPU rows/s':>11s}")
for batch in (1, 8, 32, 128, 512, 2048):
flops, I = layer(batch)
row = [f"{batch:6d}", f"{I:10.1f}"]
for name, (peak, bw) in devices.items():
attained = min(peak, I * bw)
if name == "GPU":
row.append(f"{attained / peak:8.1%}")
row.append(f"{batch / (flops / attained):11.3g}")
print(" ".join(row))
I = np.logspace(-1, 4, 200)
plt.figure(figsize=(6, 3.4))
for name, (peak, bw) in devices.items():
plt.loglog(I, np.minimum(peak, I * bw) / 1e12, label=f"{name} roofline")
for batch in (1, 32, 512):
plt.axvline(layer(batch)[1], ls=":", c="gray"); plt.text(layer(batch)[1] * 1.1, 0.03, f"b={batch}")
plt.xlabel("arithmetic intensity (FLOP/byte)"); plt.ylabel("attainable TFLOP/s")
plt.title("Roofline, 4096 x 4096 FP16 layer"); plt.legend(loc="upper left"); plt.tight_layout()
plt.show()GPU: ridge point 50 FLOP/byte
CPU: ridge point 20 FLOP/byte
batch intensity GPU util GPU rows/s CPU rows/s
1 1.0 2.0% 5.96e+04 2.98e+03
8 8.0 15.9% 4.75e+05 2.37e+04
32 31.5 63.0% 1.88e+06 5.96e+04
128 120.5 100.0% 2.98e+06 5.96e+04
512 409.6 100.0% 2.98e+06 5.96e+04
2048 1024.0 100.0% 2.98e+06 5.96e+04
At batch 1 the layer does 1.0 FLOP per byte; the GPU reaches 2.0 % of its peak, about 60,000 rows per second. At batch 32 the intensity is 31.5 and utilisation 63 %; from batch 128 on, the layer is compute-bound at the full 100 TFLOP/s and about 3 million rows per second. The GPU's advantage over the CPU is 20 times at batch 1 (both are memory-bound, and the GPU has 20 times the bandwidth) and 50 times once both are compute-bound. Real kernels reach less than the roofline (launch overheads, imperfect tiling), and a whole network has many layers of different shapes, but the lesson carries over: feed a GPU batches, or most of what you pay for idles.
Precision: FP32, FP16, BF16, INT8
Fewer bits per number mean less memory, less bandwidth per value (so higher arithmetic intensity) and, on hardware with matching units, more operations per second. The cost is range and precision:
| Format | Bits (sign, exponent, mantissa) | Largest value | Relative step near 1 | Typical use |
|---|---|---|---|---|
| FP32 | 1, 8, 23 | about | about | training master weights, CPU inference |
| FP16 | 1, 5, 10 | 65504 | about | GPU inference; overflows on large values |
| BF16 | 1, 8, 7 | about | about | GPU training and inference; FP32's range |
| INT8 | integer, with a scale | 127 times the scale | the scale | quantized inference |
FP16 keeps more digits but overflows above 65504; BF16 keeps FP32's exponent range with fewer digits, which is why it became the default for large models. INT8 needs a scale per tensor or per channel that maps real values to integers, and is the subject of the quantization lesson; mixed precision in training is in mixed precision. NumPy has FP16 but no BF16, so the example emulates BF16 by keeping only the top 16 bits of each FP32 number (with rounding).
import numpy as np
def to_bf16(x):
u = np.asarray(x, np.float32).view(np.uint32).astype(np.uint64)
u = (u + 0x7FFF + ((u >> 16) & 1)) & 0xFFFF0000 # round to nearest even, keep top 16 bits
return u.astype(np.uint32).view(np.float32)
def int8(w):
scale = np.abs(w).max(axis=1, keepdims=True) / 127 # one scale per output row
return np.clip(np.round(w / scale), -127, 127) * scale
big = np.array([1.0, 1000.0, 70000.0], np.float32)
with np.errstate(over="ignore"):
print("FP16 of", big.tolist(), "->", big.astype(np.float16).tolist())
print("BF16 of", big.tolist(), "->", to_bf16(big).tolist())
rng = np.random.default_rng(0)
W = rng.normal(0, 0.02, (512, 512)).astype(np.float32) # a layer's weights
x = rng.normal(0, 1, (64, 512)).astype(np.float32) # a batch of activations
ref = x.astype(np.float64) @ W.astype(np.float64).T
for name, (Wq, xq) in {"FP32": (W, x),
"FP16": (W.astype(np.float16).astype(np.float32), x.astype(np.float16).astype(np.float32)),
"BF16": (to_bf16(W), to_bf16(x)),
"INT8 weights": (int8(W), x)}.items():
err = np.abs(xq @ Wq.T - ref).max() / np.abs(ref).max()
print(f"{name:12s} weight bytes {W.size * {'FP32': 4, 'FP16': 2, 'BF16': 2}.get(name, 1) / 1024:5.0f} KiB"
f" | max relative output error {err:.1e}")FP16 of [1.0, 1000.0, 70000.0] -> [1.0, 1000.0, inf]
BF16 of [1.0, 1000.0, 70000.0] -> [1.0, 1000.0, 70144.0]
FP32 weight bytes 1024 KiB | max relative output error 9.8e-07
FP16 weight bytes 512 KiB | max relative output error 3.3e-04
BF16 weight bytes 512 KiB | max relative output error 2.7e-03
INT8 weights weight bytes 256 KiB | max relative output error 8.8e-03
70000 overflows to inf in FP16 but survives in BF16 (as 70144, the nearest BF16 value: only 8 significant bits). On the layer's output, FP16 has the smaller error (3.3e-04, against 2.7e-03 for BF16), because it keeps 3 more mantissa bits; INT8 weights with one scale per row reach 8.8e-03 at a quarter of the FP32 memory. Whether such errors matter is decided on the model's metric, not on one layer: evaluate the converted model on the holdout.
CPU or GPU, and how many models per GPU
The choice is an economic one: cost per prediction at the required latency. A rough procedure:
- Is the model big and dense? Transformers, CNNs, embedding models: large matrix products, high arithmetic intensity at moderate batch sizes, GPU-friendly. Tree ensembles, linear models, small MLPs: little compute per row and irregular memory access, usually CPU-friendly.
- Can you batch? A GPU fed single requests is memory-bound and mostly idle. If traffic is low, or each request must be answered alone within a tight deadline, a CPU may win even for a mid-sized network.
- Compare cost per million predictions at the throughput each option sustains within the latency target, including idle hours.
A GPU running one small model is usually underused. Ways to share it: several model processes on one GPU (each gets its own memory; compute is time-sliced), a serving system that hosts many models in one process (Triton, for example), or hardware partitioning on data-centre GPUs (NVIDIA MIG) for isolation. Memory is the hard limit: the sum of weights, activation peaks and caches must fit, with headroom.
Cold start is the time from "a new replica is scheduled" to "it serves at full speed": pull the container image, read the weights from disk or object storage, copy them to the GPU, initialise the runtime (CUDA context, compiled kernels), and run a few warm-up requests. For large models this is minutes, which matters for autoscaling: a replica added at the start of a traffic spike may be ready only after it. Keep minimum replicas warm, store weights close to the node, and do the warm-up inside the readiness check (FastAPI for production).
import numpy as np
# Illustrative prices and throughputs (not quotes): measure your own model before deciding.
options = {
"CPU node (16 cores)": {"usd_per_h": 0.80, "rows_per_s": 900},
"GPU node, batch 1": {"usd_per_h": 2.50, "rows_per_s": 1_200},
"GPU node, batch 32": {"usd_per_h": 2.50, "rows_per_s": 25_000},
}
need = 3_000 # peak requests per second
for name, o in options.items():
nodes = int(np.ceil(need / (0.6 * o["rows_per_s"]))) # keep nodes at most 60 % busy
per_million = o["usd_per_h"] / (o["rows_per_s"] * 3600) * 1e6
print(f"{name:20s} nodes for {need}/s: {nodes:2d} | ${nodes * o['usd_per_h'] * 24:7.2f} per day"
f" | ${per_million:.3f} per million at full load")
# Pack models into one 24 GB GPU (90 % usable): first-fit decreasing by memory
models = {"llm-7b-int8": 9.5, "embedder": 1.4, "reranker": 2.2, "vision": 3.1, "ocr": 4.0, "llm-7b-fp16": 16.0}
gpus = []
for name, gb in sorted(models.items(), key=lambda kv: -kv[1]):
for g in gpus:
if sum(g.values()) + gb <= 24 * 0.9:
g[name] = gb; break
else:
gpus.append({name: gb})
for i, g in enumerate(gpus):
print(f"GPU {i}: {sorted(g)} = {sum(g.values()):.1f} GB")
# Cold start of a 16 GB model: object storage -> disk -> GPU, plus runtime init and warm-up
size = 16
steps = {"download at 0.5 GB/s": size / 0.5, "disk read at 2 GB/s": size / 2,
"host to GPU at 20 GB/s": size / 20, "runtime init + warm-up": 20}
print(" + ".join(f"{k} {v:.0f} s" for k, v in steps.items()), f"= {sum(steps.values()):.0f} s")CPU node (16 cores) nodes for 3000/s: 6 | $ 115.20 per day | $0.247 per million at full load
GPU node, batch 1 nodes for 3000/s: 5 | $ 300.00 per day | $0.579 per million at full load
GPU node, batch 32 nodes for 3000/s: 1 | $ 60.00 per day | $0.028 per million at full load
GPU 0: ['embedder', 'llm-7b-fp16', 'ocr'] = 21.4 GB
GPU 1: ['llm-7b-int8', 'reranker', 'vision'] = 14.8 GB
download at 0.5 GB/s 32 s + disk read at 2 GB/s 8 s + host to GPU at 20 GB/s 1 s + runtime init + warm-up 20 s = 61 s
With these illustrative numbers, the GPU fed one request at a time is the most expensive option (5 nodes, $300 per day, $0.579 per million predictions at full load), worse than the CPU nodes (6 nodes, $115.20 per day). The same GPU with batches of 32 needs a single node ($60 per day, $0.028 per million). The six models fit on two 24 GB GPUs (21.4 and 14.8 GB) instead of six, and a 16 GB model takes about 61 s from "scheduled" to "ready", most of it downloading: a cache of the weights on the node removes the largest term.
Pitfalls
- Counting only weights. The KV cache, activation peaks for the largest allowed input, the runtime's own memory and fragmentation all need room; plan for about 10 % headroom at least.
- Benchmarking at batch size 1 and concluding the GPU is slow. Or benchmarking at batch 512 and promising latencies that real, sparse traffic cannot deliver. Benchmark with your traffic pattern.
- Assuming lower precision is free. FP16 can overflow, INT8 can lose accuracy on some layers; evaluate the converted model on the holdout before serving it.
- Ignoring cold start. Autoscaling on a metric that reacts in seconds while replicas take minutes to start leads to overload during every spike.
- One model per GPU by habit. Small models leave most of a GPU idle; share it, or use CPUs.
- Testing GPU code without limits. Heavy GPU load raises temperatures quickly; monitor temperature and power, and never run stress tests on a machine that is not built and cooled for them.
Practice
- How much memory do the weights of a 13-billion-parameter model need in FP16, and in INT4?
- A transformer has 40 layers and hidden size 5120 and uses full multi-head attention in FP16. How large is its KV cache for a batch of 4 sequences of 2048 tokens?
- A 4096 x 4096 FP16 layer runs at batch size 4 on the illustrative GPU (100 TFLOP/s, 2 TB/s). Is it compute-bound or memory-bound, and roughly what share of the peak does it reach?
Answers
- FP16: GB. INT4: GB (plus a little for the scales).
- Per token bytes. Tokens: . Total about bytes, 6.7 GB.
- FLOP per byte, far below the ridge point of 50: memory-bound. Attainable is TFLOP/s, about 8 % of the peak.
Test yourself
Why is a GPU poorly used when a dense layer runs at batch size 1?
- The GPU has too little memory
- Each weight is read from memory for a single multiply-add, so the layer is memory-bound and the compute units idle
- Batch size 1 is not supported
- The CPU must do part of the work
What does the KV cache of a generating transformer grow with?
- Only the number of parameters
- The number of tokens held: batch size times context length (and layers times hidden size per token)
- The vocabulary size
- The number of GPUs
What is the main advantage of BF16 over FP16?
- More mantissa bits
- The same exponent range as FP32, so large values do not overflow
- It uses 1 byte per value
- It needs no hardware support
A model service on GPUs autoscales, but every traffic spike still causes timeouts. What is a likely cause?
- The model is too accurate
- Cold start: new replicas need minutes to download weights, load them to the GPU and warm up
- The KV cache is too small
- FP32 is too precise