Chapter 4 · Compute and Systems 4.1
LLM hardware basics: CPUs, GPUs, memory, and moving data
Follow a model request through disk, host and device memory, and CPU and GPU work. Estimate tensor storage and copy time to distinguish capacity, bandwidth, and compute before diagnosing inference.
After this page you will be able to
- Trace weights and request data across storage and memory.
- Use bytes and bytes per second to distinguish capacity from bandwidth.
- Estimate tensor size and ideal copy time.
- Locate common slowdowns at the relevant stage of inference.
On this page
A model request moves data and performs arithmetic. Storage keeps model files, memory holds live data, the CPU prepares and dispatches work, and a GPU can perform many similar numerical operations in parallel. Follow the data through one request before learning about capacity, bandwidth, and compute.
Four resources in one machine
Suppose you open a local model on a laptop, enter a sentence, and wait for a response. Data crosses several layers.
| Resource | Where it lives | Its role in inference | Typical limit |
|---|---|---|---|
| SSD or disk | Persistent storage | Holds model files and tokenizer configuration | Read speed and capacity |
| Host memory | Memory directly accessible by the CPU | Holds process state, inputs, and model data | Available RAM and bandwidth |
| Device memory | Discrete GPU VRAM or shared physical memory | Holds tensors and caches used by GPU work | Available capacity and access bandwidth |
| CPU and GPU | Processors executing instructions | CPU handles tasks such as dispatch and tokenization, GPU handles many operations in parallel | Throughput and launch overhead |
A discrete GPU normally has a path between host and device memory. A unified-memory system can let both processors access the same physical memory. The runtime still has to handle placement and synchronization, and processors can compete for bandwidth.
Follow one request
- Load model weights and tokenizer configuration. Prepared weights can serve multiple requests.
- Convert text to token IDs. Send those integers and generation settings into the runtime.
- Schedule the numerical operations. With a GPU, host code can submit device work through the driver. A kernel is a small program that many device threads can execute.
- Use output scores to select the next token, repeat, and turn generated tokens back into text.
Weights come from the model file. Activations are intermediate results. A KV cache holds some intermediate state reusable for later tokens. Their lifetimes differ. A longer context or more concurrent requests can grow caches and working storage while the weights stay the same size.
Capacity, bandwidth, and compute answer different questions
Capacity says how many bytes fit. Bandwidth says how many bytes can move per second. Compute throughput says how many operations can complete per second. A model file can fit on disk while its weights, cache, and workspace exceed available device memory. A model that fits may still spend time reading memory or waiting for work to launch.
Think of a bookshelf. How many books it holds is capacity, how many you can move each second is bandwidth, and how many calculations you can perform on the pages is compute. Keep units consistent. One MiB is 2**20 bytes. GB and GiB use different conventions, so check how a tool or specification reports them.
Experiment: budget one matrix
Storage and copy-time lab script
Take a matrix with 1024 rows and 1024 columns. Count storage at two and four bytes per value. Then assume a sustained copy rate of 512 MiB/s and divide bytes by the rate. That rate is illustrative. The calculation excludes startup, queues, and contention. This example ran on an Apple M2 Max with Python 3.12.14.
from __future__ import annotations
from math import prod
def tensor_bytes(shape: tuple[int, ...], bytes_per_value: int) -> int:
if bytes_per_value <= 0 or any(size < 0 for size in shape):
raise ValueError("nonnegative axes and positive item size required")
return prod(shape) * bytes_per_value
def copy_seconds(size_bytes: int, bytes_per_second: int) -> float:
"""Ideal duration at the given sustained copy rate."""
if size_bytes < 0 or bytes_per_second <= 0:
raise ValueError("need nonnegative size and positive copy rate")
return size_bytes / bytes_per_second
mib = 2**20
small = tensor_bytes((1024, 1024), 2)
large = tensor_bytes((1024, 1024), 4)
elapsed_ms = 1000 * copy_seconds(small, 512 * mib)
assert small == 2 * mib and large == 4 * mib
assert elapsed_ms == 3.90625
print("storage:", small // mib, large // mib, "MiB")
print("ideal copy time:", f"{elapsed_ms:.3f} ms")
storage: 2 4 MiB
ideal copy time: 3.906 ms
Physical storage can also include alignment, tiling, quantization metadata, caches, and allocator overhead. A model file gives a useful clue. A file can include tensors and auxiliary state that the runtime handles differently.
Diagnose a slow run or an out-of-memory error
| Symptom | Measure separately | Continue with |
|---|---|---|
| First request is slow | Loading, warmup, and steady-state inference | First inference service |
| Weights fit and longer conversations run out of memory | Fixed weights and cache growth per token | KV cache |
| Device work is short with gaps between launches | CPU dispatch, synchronization, and input supply | GPUs and the roofline |
| Precision changes speed at the same operation count | Bytes moved and device arithmetic formats | Numerical precision |
| Multiple GPUs do not scale proportionally | Device communication and waits | Collective communication |
Start with a fixed small request. Record the device, model, data type, and input and output lengths. For steady-state measurements, warm up and report the median of repeated runs. Change one thing at a time to distinguish hardware, runtime, cache, and input effects.
Summary and exercises
- Model files, resident weights, activations, and caches have different locations and lifetimes.
- Capacity, bandwidth, and compute have different units. Locate the limiting stage.
- Estimate bytes and time first, then measure a fixed workload.
Quick self-check
1. What stores model files between runs?
- A disk or SSD.
- GPU registers.
Persistent storage retains files after the process exits.
2. Which unit can express copy bandwidth?
- MiB.
- MiB/s.
Bandwidth counts bytes moved per unit time.
3. At the same shape, what happens when values grow from two to four bytes?
- The storage doubles.
- Storage stays the same.
There are the same number of values at twice the size.
4. What can still affect latency after a model fits?
- Only unused disk space.
- Transfer, compute, and scheduling.
Runtime work includes data movement, queueing, and computation.
Change the size of a matrix
How large is a matrix of 2048 rows and 1024 columns at two bytes per value? Estimate the copy time at 512 MiB/s and identify two reasons a measurement could be longer.
Worked answer
The matrix occupies 4 MiB and its ideal copy time is 7.8125 ms. Launch overhead, bus contention, alignment, or allocator delays can add time. Record copying and computation separately in a real inference trace.
Further reading
- NVIDIA CUDA Programming Model on hosts, devices, and memory.
- Continue with the GPU roofline and GPU kernels.
- Continue the four exercises with your first inference service.
FAQ
- What does the CPU do when inference uses a GPU?
- The CPU often prepares inputs, runs some work, submits commands, and handles results. The GPU performs parallel numerical operations.
- Does more VRAM always make inference faster?
- Capacity governs what fits. Speed also depends on memory traffic, arithmetic throughput, scheduling, and input shape.
- Does unified memory remove bandwidth limits?
- Unified memory can reduce explicit copies. Access still takes time and processors may compete for bandwidth.