Pidoku

CPU Architecture

Module 3 Lesson 3.a 1h Difficulty 2/5

Prerequisites 2.e, 2.g


Before you start: six words#

WordPlain meaning
InstructionOne tiny step a CPU can do: add two numbers, load a value from memory, jump to another place in the program.
Clock cycleOne tick of the CPU’s internal clock. A 3 GHz CPU ticks 3 billion times a second.
CoreOne independent processor inside the chip. A server CPU in 2026 has 64–288 of them.
ThreadOne stream of instructions being run. A core runs one or two threads at a time.
BranchA point where the program chooses what to do next: an if, a loop end, a function call through a pointer.
IPC (instructions per cycle)How many instructions a core finishes per clock tick, on average. The single best summary of how well a piece of code suits the hardware.

1. What is it?#

A CPU (central processing unit) is a machine that repeatedly fetches an instruction from memory, decodes what it means, executes it, and writes the result. A modern core does these four stages for hundreds of instructions at once — out of order and on guesses — so that it finishes several instructions in every clock cycle.

For an inference engineer, the CPU is not where the model runs. It is where everything else runs: the HTTP server, the tokenizer, the scheduler that decides which requests run next, the sampling logic, and the Python code that tells the GPU what to do. A GPU worth tens of thousands of dollars can only work as fast as the CPU feeds it instructions. A saturated CPU starving an expensive GPU is one of the most common and most avoidable problems in production.


2. Why does it exist?#

Programs are sequential and unpredictable, and memory is slow. Almost everything complicated about a modern CPU is a response to one of those two facts:

ProblemThe CPU’s answerWhere it is taught
Each instruction depends on the one beforepipelining, out-of-order executionthis lesson
The program’s path is unpredictablebranch prediction and speculationthis lesson
Memory is about 100x slower than the corecaches and prefetchers3.b
One instruction per number is slowSIMD — one instruction on many numbers3.d
One thread cannot keep a core busySMT (hyperthreading) and many coresthis lesson, 3.e

3. Simple analogy#

An assembly line run by someone who guesses.

The line has stages: fetch the part, read the blueprint, do the work, inspect, ship. Several items are on the line at once, each at a different stage — that is pipelining.

At a fork in the blueprint (“if the part is red, do X”), the worker does not stop to find out. They guess “red” and keep the line moving. If the guess was wrong, everything after the fork is thrown away and restarted — a pipeline flush, which costs 15–20 cycles. Modern predictors guess right 95–99% of the time, which is why the trick pays off.

Why you care: tokenizers and samplers are full of branches, so they run well below the CPU’s peak, and the Python interpreter is the worst case — a giant switch statement with unpredictable jumps and pointers to follow everywhere.


4. Tiny example#

Branch prediction, measured. The same loop runs over the same numbers twice; the only difference is their order.

Go
// branch.go — the same loop over the same numbers, in a different order.
package main

import (
	"fmt"
	"math/rand"
	"slices"
	"time"
)

//go:noinline
func work(total *int64, v int32) { *total += int64(v) } // a real call, so the `if` stays a branch

func sumIfGreater(data []int32) (total int64) {
	for _, v := range data {
		if v > 128 {
			work(&total, v)
		}
	}
	return total
}

func main() {
	data := make([]int32, 50_000_000)
	for i := range data {
		data[i] = rand.Int31n(256)
	}

	// Unsorted: the branch is unpredictable
	t0 := time.Now()
	a := sumIfGreater(data)
	unsorted := time.Since(t0)

	slices.Sort(data) // sorted: a long run of "no", then a long run of "yes"
	t0 = time.Now()
	b := sumIfGreater(data)
	sorted := time.Since(t0)

	fmt.Printf("unsorted %v   sorted %v   ratio %.2fx   (same sum: %v)\n",
		unsorted.Round(time.Millisecond), sorted.Round(time.Millisecond),
		float64(unsorted)/float64(sorted), a == b)
}

In Go or C this typically shows a 3–6x difference: same data, same instructions, and the only change is whether the CPU can guess the if. Write the same loop in pure Python and you may see only 1.1–1.3x — not because prediction stopped mattering, but because the interpreter is so slow that hardware effects disappear beneath it. A tokenizer written in pure Python leaves 10–50x on the table, which is why Hugging Face’s tokenizers library is written in Rust.


5. Technical explanation#

The pipeline#

FETCH → DECODE → RENAME → DISPATCH → EXECUTE → WRITEBACK → RETIRE
 read    work out  give each  queue it   run it on an   save the     commit results
 bytes   what it   value a    for a      arithmetic,    result       in program order
         means     private    free unit  vector or
                   register              memory unit

What a 2025–26 server core looks like (AMD Zen 5, Intel Redwood Cove/Lion Cove-class P-cores, Arm Neoverse V2/V3):

  • Decodes about 6–8 instructions per cycle.
  • Keeps 400–600 instructions “in flight” (the reorder buffer) while it waits for slow ones.
  • Has 8–16 execution units: several integer units, 2–4 vector/floating-point units, 3–4 load units.
  • Peaks at roughly 6–8 instructions finished per cycle.

Real-world IPC tells you what kind of work you are doing:

dense numerical code       2–4
Python interpreter         0.5–1.2
pointer-chasing code       0.2–0.5   (waiting on memory most of the time)

perf stat reports IPC for any program (exercise B). It is the fastest diagnostic you have.

Superscalar and out-of-order#

a = b + c;     ← independent
d = e * f;     ← independent      the core runs these three at the same time
g = h - i;     ← independent

x = a + d;     ← needs a and d; must wait for them

The hardware finds this parallelism automatically. Your job is to make it available: avoid long chains where every step needs the previous result.

SMT (hyperthreading)#

Simultaneous multithreading lets two threads share one core’s execution units. When one thread waits on memory, the other uses the idle units. Typical gain: 15–30% on mixed workloads. It can be negative on numerical code that already saturates memory bandwidth or cache, because the two threads evict each other’s data.

For inference hosts, SMT usually helps — the work is a mix of networking, Python and system calls. For CPU-side numerical kernels, test with it off. lscpu shows how many threads each core runs.

Clocks, turbo and heat#

A CPU rated at 3.8 GHz may run at 2.4 GHz when every core is busy with wide vector instructions, because those draw more power. So:

  • A 2-second benchmark sees turbo clocks; production sees sustained clocks. Warm up and measure steady state.
  • An isolated microbenchmark can be misleading when the same code later runs beside 100 other busy threads.

The CPUs in AI servers today#

Checked on 11 November 2026.

CPUCoresWhere you meet it
AMD EPYC 9005 “Turin” (Zen 5 / 5c)up to 192Most x86 GPU servers shipping since 2025
AMD EPYC “Venice” (Zen 6, 2 nm)up to 256Ramping in 2026; host CPU of AMD’s Helios racks (7.h)
Intel Xeon 6 “Granite Rapids” (P-cores)up to 128x86 GPU servers
Intel Xeon 6+ “Clearwater Forest” (E-cores, Intel 18A)up to 288Dense CPU-only serving; the P-core successor “Diamond Rapids” is expected in 2027
NVIDIA Grace (Arm Neoverse V2)72GH200 and GB200/GB300 superchips (7.c)
NVIDIA Vera (custom Arm “Olympus”)88Vera Rubin racks (7.e)

Two trends matter for you:

  • Arm hosts are now normal. NVIDIA’s rack-scale systems pair GPUs with its own Arm CPUs over a fast chip-to-chip link. Your container images, Python wheels and profilers must work on arm64.
  • CPU demand per GPU is rising. Agents run tools, code sandboxes and retrieval on CPUs between model calls, and tokenisation, structured-output checking and request handling all scale with the token rate. Plan CPU capacity explicitly (section 8).

6. Under the hood#

What the CPU actually does when Python code asks a GPU to generate a token:

CPU thread:
  interpret Python bytecode         ← low IPC, branch-heavy, pointer chasing
  build the arguments for a kernel  (a "kernel" is one function that runs on the GPU, 5.b)
  call the CUDA driver to launch it (user-space, but real driver work)
  ... repeat 200–2,000 times per token ...
  occasionally: copy memory or wait for the GPU to finish (blocks the thread!)

Every one of these steps is CPU work on the critical path of every token. This is why:

  • A slow CPU shows up as gaps between GPU kernels and low GPU utilisation.
  • CUDA graphs help so much: they record thousands of launches once and replay them with one call (5.f).
  • Engines keep moving the hot loop out of Python (vLLM’s Rust frontend, 19.h; asynchronous scheduling, 17.d).

Check it on a real server: watch top under load. If a Python thread sits at 100% of one core while the GPU is 60% busy, you are CPU-bound on the launch path.


7. Performance implications#

CPU-side work in an inference serverTypical costRisk
HTTP parsing and JSON decoding50–500 µs per requesthigh at high request rates
Tokenization10 µs – 5 mshigh for long prompts
Scheduler bookkeeping50–500 µs per stephigh at large batch
Kernel launches (no CUDA graph)1–10 ms per stepvery high at small batch
Sampling (if done in Python)100 µs – 2 mshigh
Detokenization and streaming20–200 µs per tokenhigh at high token rates
Logging and metrics10–100 µsmedium

Add these up for a server producing 5,000 tokens per second and you can easily need 4–8 dedicated cores per GPU. A node with 8 CPU cores for 8 GPUs will starve.


8. Production implications#

  • Provision 8–16 CPU cores per GPU for language-model serving, more for agent workloads that run tools beside the model. Check your cloud instance types; some GPU instances are CPU-poor.
  • Pin threads. Give the tokenizer pool, the engine loop and the GPU communication threads separate cores on the same NUMA node as their GPU (3.c, 3.h).
  • Use compiled tokenizers (the Rust tokenizers library, not a Python loop).
  • Keep the per-token Python path tiny. Custom logits processors written in Python are a classic cause of slow inter-token latency.
  • Monitor CPU beside GPU. A dashboard with only GPU metrics hides this bottleneck.
  • Build for arm64 and amd64. Grace and Vera hosts are Arm.

9. Common mistakes#

“The model runs on the GPU, so the CPU doesn’t matter.” The CPU drives the GPU.

Benchmarking with turbo and no warm-up. Overstates sustained performance by 20–40%.

Running a thread on every core for numerical work. Too many threads cause context switching and cache thrashing (3.e). Set OMP_NUM_THREADS deliberately.

Ignoring SMT. Test both ways for CPU-heavy paths.

Writing per-token logic in Python. A callback run 5,000 times a second at 100 µs each uses half a core and adds directly to inter-token latency.


10. Hands-on exercise#

A. Read your CPU. Run lscpu, cat /proc/cpuinfo | head -30 and lstopo (from hwloc). Write down: cores, threads per core, sockets, L1/L2/L3 sizes, architecture (x86_64 or aarch64), and vector extensions (avx2, avx512, amx on x86; sve, sve2 on Arm).

B. Measure IPC.

Shell
perf stat -e cycles,instructions,branch-misses,cache-misses python your_script.py

Do it for (i) a pure Python loop, (ii) a NumPy operation, (iii) a model server under load. Compare the IPC values and explain the differences.

C. Branch prediction. Run branch.go above, then perf stat -e branch-misses go run branch.go. Change the threshold from 128 to 250. What happens to the ratio, and why?

D. Find CPU starvation. Run a model server under load with nvidia-smi dmon and top side by side. Is GPU utilisation limited by the CPU? How would you prove it? (Lesson 22.h shows the profiler evidence.)


11. Interview questions#

  1. Why does a fast GPU need a fast CPU for language-model inference?
  2. What is IPC, and what does a low IPC tell you about a workload?
  3. Explain branch prediction and give an example from an inference server where it matters.
  4. When does hyperthreading hurt?
  5. How many CPU cores would you provision per GPU for LLM serving, and what changes for agents?
  6. You see gaps between GPU kernels in a profiler timeline. List three causes.

12. Further reading#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in