4 Compute and Systems 1 / 5
  1. In this chapter
  2. LLM hardware basics
  3. GPUs and the Roofline Model
  4. GPU kernels
  5. Numerical Precision
  6. Collective Communication
All chapters →

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.

Beginner 6 min read Updated Companion code ↓

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
  1. Four resources in one machine
  2. Follow one request
  3. Capacity, bandwidth, and compute answer different questions
  4. Experiment: budget one matrix
  5. Diagnose a slow run or an out-of-memory error
  6. Summary and exercises
  7. Quick self-check
  8. Change the size of a matrix
  9. Further reading
  10. FAQ

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.

Data and compute path during model inference Model files move from solid-state storage into system memory and then GPU memory. The CPU prepares requests and submits work, the GPU processes tensors, and results return to the CPU for text decoding. SSD / diskmodel files Host RAMprocess and input GPU memoryweights, activations, KV GPU coresparallel tensor ops CPUtokenize, prepare, schedule Scores return to the CPU for decoding
Capacity determines what fits, bandwidth governs data movement, and compute units determine parallel arithmetic throughput.

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.

ResourceWhere it livesIts role in inferenceTypical limit
SSD or diskPersistent storageHolds model files and tokenizer configurationRead speed and capacity
Host memoryMemory directly accessible by the CPUHolds process state, inputs, and model dataAvailable RAM and bandwidth
Device memoryDiscrete GPU VRAM or shared physical memoryHolds tensors and caches used by GPU workAvailable capacity and access bandwidth
CPU and GPUProcessors executing instructionsCPU handles tasks such as dispatch and tokenization, GPU handles many operations in parallelThroughput 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

  1. Load model weights and tokenizer configuration. Prepared weights can serve multiple requests.
  2. Convert text to token IDs. Send those integers and generation settings into the runtime.
  3. 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.
  4. 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

SymptomMeasure separatelyContinue with
First request is slowLoading, warmup, and steady-state inferenceFirst inference service
Weights fit and longer conversations run out of memoryFixed weights and cache growth per tokenKV cache
Device work is short with gaps between launchesCPU dispatch, synchronization, and input supplyGPUs and the roofline
Precision changes speed at the same operation countBytes moved and device arithmetic formatsNumerical precision
Multiple GPUs do not scale proportionallyDevice communication and waitsCollective 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

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.