Talking CPUs and GPUs
Talking about CPUs and GPUs.
CPUs and GPUs
Talk of AI is all but unavoidable, and as a result so is discussion about Graphics Processing Units or “GPUs”… the required computer component that facilitates training many AI models. GPUs are not new, however, and their capabilities vary widely. The goal of this article is to explore algorithm performance across computer environments with and without GPUs. I hope to expose some common sense aspects to this technology and point out where and what kind of GPUs make the most sense in different scenarios.
A CPU example (slow code.)
Long before the AI revolution, and even before GPUs existed, we had our trusty Central Processing Units or “CPUs”. Machines that ran exclusively on CPUs gave rise to many fascinating discoveries including the discovery of the Lorenz attractor, the discovery of a counterexample to Euler’s sum-of-power conjecture, the discovery of the Feigenbaum constant, and played an important role in the first computer-assisted proof of the Four Color Theorem. We will begin with an exploration of one of these discoveries, the Mandelbrot Set.
Some historical background on the Mandelbrot set (according to AI.) The Mandelbrot set grew out of complex dynamics, which Pierre Fatou and Gaston Julia pioneered in the early 20th century. Without computers, they could not visualize what they were studying.
Robert Brooks and Peter Matelski made the first known computer picture of the set in 1978, as part of research on Kleinian groups. It was published in 1981 in the proceedings of the 1978 Stony Brook Conference. Benoit Mandelbrot published his own images in a 1980 paper that was exploratory, not proof-based. He even conjectured that the set was disconnected, a guess later disproved. Who deserves credit for the discovery is still disputed. Mandelbrot argued he published first, while Brooks and Matelski say they circulated a preprint in early 1979.
In short, Brooks and Matelski made the first computer picture, and Mandelbrot explored the set and brought it wide attention. Adrien Douady and John Hubbard named it after Mandelbrot in the early 1980s and proved it is connected in 1982.
The Mandelbrot set is a famous fractal formed by testing points (c) in the complex plane. For each point, the formula (z_{n+1}=z_n^2+c) is repeatedly evaluated, starting with (z_0=0). If the value remains bounded after many iterations, the point is treated as part of the set; if its magnitude exceeds 2, it escapes and lies outside the set. Images typically color points according to how quickly they escape, revealing the set’s intricate, self-similar boundary.
Here is a very short program that generates the Mandelbrot set using Python 3.13. Following the program is the rendered image.
%%time
from matplotlib import pyplot as plt
import numpy as np
real = np.linspace(-2, 1, 1000)
imaginary = np.linspace(-1.5, 1.5, 1000)
set = []
for x in real:
for y in imaginary:
c = complex(x, y)
z = 0
n = 0
for i in range(100):
if abs(z) <= 2 and n < 100:
z = z*z + c
if abs(z) <= 2:
set.append((x, y))
plt.scatter([p[0] for p in set], [p[1] for p in set], s=0.1)
plt.show()

CPU times: user 13.9 s, sys: 52.9 ms, total: 14 s
Wall time: 13.8 s
A CPU example (faster code.)
While the above code works, it is hardly efficient. We can see that it took the computer and its CPU 13.9 seconds to complete the task. The CPU in this case was an Intel(R) Core(TM) i5-7600K CPU @ 3.80GHz that dates back to 2017. Despite the fact that it is almost a decade old, it is still an OK CPU for most tasks. To make the code more efficient, we can rewrite it so that it stops iterating a point as soon as it escapes, and so that it takes advantage of the fact that the CPU is capable of multiple threads. This means that the CPU can actually do multiple tasks at the same time. Here is that re-written code, and the result of running it. (In the interest of space, I won’t include the exact same graphic again.)
%%time
from concurrent.futures import ThreadPoolExecutor
import os
import numpy as np
from matplotlib import pyplot as plt
real = np.linspace(-2, 1, 1000)
imaginary = np.linspace(-1.5, 1.5, 1000)
MAX_ITER = 100
def compute_chunk(xs):
"""Return the (x, y) points in the Mandelbrot set for a chunk of real values."""
points = []
for x in xs:
for y in imaginary:
c = complex(x, y)
z = 0
for _ in range(MAX_ITER):
if abs(z) > 2:
break
z = z * z + c
if abs(z) <= 2:
points.append((x, y))
return points
n_workers = os.cpu_count() or 4
chunks = np.array_split(real, n_workers * 4) # more chunks than workers evens out the load
with ThreadPoolExecutor(max_workers=n_workers) as executor:
results = executor.map(compute_chunk, chunks)
mandelbrot_points = [p for chunk in results for p in chunk]
plt.scatter(
[p[0] for p in mandelbrot_points],
[p[1] for p in mandelbrot_points],
s=0.1,
)
plt.show()
CPU times: user 2.8 s, sys: 35 ms, total: 2.84 s
Wall time: 2.83 s
So, the final result was that our rewrite reduced the overall time to draw the Mandelbrot set from 13.8s down to 2.84s! One caveat: the CPU time is almost identical to the wall time, which means the threads were not actually running in parallel (Python’s Global Interpreter Lock lets only one thread run Python code at a time). Most of the improvement therefore came from stopping early on points that escape, not from the threads.
A GPU example
Now… let’s see if we can do this even faster by adding a GPU. Unfortunately, it is not as simple as just plugging in a card to your computer and you’re done. The GPU and the CPU have to work together with the CPU understanding exactly what work it is going to give the GPU. There are a couple of important things to consider including how much memory the GPU needs to store, and how fast the CPU can shuffle information in and out of the GPU. We will come back to those later, but for this example, I am going to use an older GPU to illustrate what kind of performance gain can be experienced. Here are some of the details of the 1080ti GPU that is in this system:
GPU: NVIDIA GeForce GTX 1080 Ti
Compute capability: 6.1
SMs: 28
CUDA cores: 3584 (assuming 128 per SM)
Memory: 10.9 GiB
Memory bus: 352-bit at 5505 MHz
Theoretical bandwidth: 484 GB/s
Since we want the computer to utilize the GPU and not the CPU for the Mandelbrot calculations, we have to rewrite the code fairly dramatically. This code leverages a Python package called “cupy”. The developer site for cupy describes the package as…
“CuPy is a NumPy/SciPy-compatible array library for GPU-accelerated computing with Python. CuPy acts as a drop-in replacement to run existing NumPy/SciPy code on NVIDIA CUDA or AMD ROCm platforms.”
Here is our Mandelbrot set code rewritten to leverage the GPU via Cupy.
%%time
import numpy as np
import cupy as cp
from matplotlib import pyplot as plt
Granularity = 1000
MaxIters = 100
WIDTH, HEIGHT = Granularity, Granularity
MAX_ITER = MaxIters
X_MIN, X_MAX = -2.0, 1.0
Y_MIN, Y_MAX = -1.5, 1.5
N_TRAIN = 2_000_000
# One thread per pixel: iterate z = z^2 + c and count steps until |z| > 2
mandelbrot_kernel = cp.ElementwiseKernel(
in_params="float64 cr, float64 ci, int32 max_iter",
out_params="int32 count",
operation="""
double zr = 0.0, zi = 0.0;
int n = 0;
while (n < max_iter && (zr*zr + zi*zi) <= 4.0) {
double t = zr*zr - zi*zi + cr;
zi = 2.0*zr*zi + ci;
zr = t;
n++;
}
count = n;
""",
name="mandelbrot",
)
# Training data: random points, labeled by the kernel (label 1 = never escaped)
rng = np.random.default_rng(0)
tx = rng.uniform(X_MIN, X_MAX, N_TRAIN)
ty = rng.uniform(Y_MIN, Y_MAX, N_TRAIN)
tcounts = cp.asnumpy(mandelbrot_kernel(cp.asarray(tx), cp.asarray(ty), MAX_ITER))
tlabels = (tcounts == MAX_ITER).astype(np.float32)
# Evaluation grid: same as your original code, shape (HEIGHT, WIDTH)
cr = cp.linspace(X_MIN, X_MAX, WIDTH, dtype=cp.float64)[None, :]
ci = cp.linspace(Y_MIN, Y_MAX, HEIGHT, dtype=cp.float64)[:, None]
grid_counts = cp.asnumpy(mandelbrot_kernel(cr, ci, MAX_ITER))
np.savez("mandel_data.npz",
tx=tx, ty=ty, tcounts=tcounts, tlabels=tlabels,
grid_counts=grid_counts, max_iter=MAX_ITER,
bounds=np.array([X_MIN, X_MAX, Y_MIN, Y_MAX]))
print("saved; fraction in set:", tlabels.mean())
# Build the grid on the GPU; broadcasting gives a (HEIGHT, WIDTH) result
cr = cp.linspace(X_MIN, X_MAX, WIDTH, dtype=cp.float64)[None, :]
ci = cp.linspace(Y_MIN, Y_MAX, HEIGHT, dtype=cp.float64)[:, None]
counts_gpu = mandelbrot_kernel(cr, ci, MAX_ITER)
cp.cuda.Stream.null.synchronize()
counts = cp.asnumpy(counts_gpu) # copy back to the host for plotting
plt.figure(figsize=(8, 8))
plt.imshow(
counts,
extent=(X_MIN, X_MAX, Y_MIN, Y_MAX),
origin="lower",
cmap="magma",
)
plt.xlabel("Re(c)")
plt.ylabel("Im(c)")
plt.savefig("mandelbrot.png", dpi=150)
plt.show()

CPU times: user 1.02 s, sys: 204 ms, total: 1.23 s
Wall time: 1.06 s
So, we can see that the addition of the GPU made our app more than 2.5 times faster again (2.84 s down to 1.06 s). I should note here that the code above is actually doing significantly more than the threaded CPU code including saving the information used to render the Mandelbrot set. For now, however, the key take-aways are that the simple CPU code performed slower than the threaded CPU code, which performed slower than the even more complicated GPU code!
Compare different GPUs.
Up to now, this post has compared CPU and GPU performance. We now will focus specifically on comparing one GPU with another GPU. As a motivational example, consider the following code.
import cupy as cp
N = 256 * 1024 * 1024 # 256M float32 = 1 GiB per array (fits in 11 GB)
REPS = 20
a = cp.random.random(N, dtype=cp.float32)
b = cp.random.random(N, dtype=cp.float32)
out = cp.empty_like(a)
# Warm-up so kernel compilation isn't timed
cp.add(a, b, out=out)
cp.cuda.Device().synchronize()
start, end = cp.cuda.Event(), cp.cuda.Event()
start.record()
for _ in range(REPS):
cp.add(a, b, out=out) # reads 2 arrays, writes 1: pure memory traffic
end.record()
end.synchronize()
ms = cp.cuda.get_elapsed_time(start, end)
bytes_moved = 3 * a.nbytes * REPS
print(f"{ms / REPS:.2f} ms per pass, {bytes_moved / (ms / 1000) / 1e9:.0f} GB/s")
This is just about as basic a GPU program you can get. It simply adds two large arrays together, and performs no computation other than that. Now, let’s run this on our nearly decade old 1080ti, and our newer GB10 systems and see what we get for performance. Any guesses???
If you guessed that the old, trusty 1080ti would be faster than the GB10, you’d be absolutely correct. Here are the results:
1080ti: 8.21 ms per pass, 392 GB/s
GB10: 13.30 ms per pass, 242 GB/s
So, what is going on. Well, despite the fact that the GB10 is much larger in terms of memory and cores than the old 1080ti… the 1080ti has much higher bandwidth for running things in and out of the GPU.
This has a very interesting implication when we consider which to use for large language models.
An AI perspective.
Up to now, we have been doing fairly simple (and even some trivial) mathematical calculations directly on the GPU itself. For this example, we will use the GPU to host a trained large language model. We have to be somewhat careful about which model we will use, however. Large language models are basically neural networks that consist of billions and billions of parameters. Finding one that is small enough to fit into the less than 10GB that we have on the 1080ti is a bit of a challenge, but a few do exist. For this example, we will use the Llama 3 8B model from Meta. This model is available on HuggingFace, and the 4-bit quantized version that ollama serves is about 4.7GB when loaded onto a GPU.
To explore this behavior we will use a combination of python code and the ollama server that wraps the LLMs and allows us to interact with the models. Again, we will execute the same python code on the 1080ti and the GB10. The following python code will drive the test:
import json, statistics, urllib.request, uuid
URL = "http://localhost:11434/api/generate"
MODEL = "llama3"
RUNS = 5
def generate(prompt, num_predict, num_ctx=8192):
body = {"model": MODEL, "prompt": prompt, "stream": False, "keep_alive": "10m",
"options": {"temperature": 0, "seed": 42,
"num_predict": num_predict, "num_ctx": num_ctx}}
req = urllib.request.Request(URL, json.dumps(body).encode(),
{"Content-Type": "application/json"})
return json.load(urllib.request.urlopen(req))
# --- Generation test: short prompt, fixed 512-token output ---
gen_prompt = ("Write a detailed history of the Ottoman Empire, covering its origins, "
"its major contributions to Western civilization, and its decline. "
"Be thorough and write at least 1,500 words.")
generate(gen_prompt, 16) # warm-up: loads the model
gen_rates = []
for _ in range(RUNS):
r = generate(gen_prompt, 512)
gen_rates.append(r["eval_count"] / r["eval_duration"] * 1e9)
print(f"Generation: median {statistics.median(gen_rates):.1f} tokens/s "
f"(runs: {[round(x, 1) for x in gen_rates]})")
# --- Prompt-processing test: long unique prompt, 1-token output ---
paragraph = ("The Ottoman Empire grew out of the political fragmentation of Anatolia "
"in the late thirteenth century, expanding across the Balkans, the Middle "
"East, and North Africa over the following centuries. ")
doc = paragraph * 120 # roughly 3,000 tokens
pp_rates = []
for _ in range(RUNS):
prompt = f"[run-ID-{uuid.uuid4().hex}] Here is a document: {doc} In one word, what is this about?"
r = generate(prompt, 1)
pp_rates.append(r["prompt_eval_count"] / r["prompt_eval_duration"] * 1e9)
assert r["prompt_eval_count"] > 2000, "prompt too short or cached"
print(f"Prompt eval: median {statistics.median(pp_rates):.0f} tokens/s "
f"(runs: {[round(x) for x in pp_rates]})")
And here are the results:
1080ti:
Generation: median 64.1 tokens/s (runs: [64.2, 64.0, 64.1, 64.1, 64.0])
Prompt eval: median 1134 tokens/s (runs: [1134, 1134, 1134, 1129, 1132])
GB10:
Generation: median 52.3 tokens/s (runs: [52.4, 52.3, 52.3, 52.2, 52.3])
Prompt eval: median 3563 tokens/s (runs: [3573, 3563, 3558, 3585, 3557])
Now, let’s be careful about these numbers. They are showing us tokens/second so, in this case higher is better!
So… Not all GPUs are fast at the same things!
“Use a GPU” is not the whole story. A GPU is a bundle of different resources, and which one limits your program decides which GPU wins. We can see this in these results where we ran a local LLM (Llama 3 via Ollama) on two very different cards: the old GeForce GTX 1080 Ti and the much newer NVIDIA GB10. Here is a basic reformatting of the results to make it easier to see the comparison:
- Generation (decode): producing 512 tokens from a short prompt.
- Prompt processing (prefill): reading a ~3,000-token prompt and producing one token.
| GTX 1080 Ti | GB10 | Winner | |
|---|---|---|---|
| Generation | 64.1 tokens/s | 52.3 tokens/s | 1080 Ti (~1.2x) |
| Prompt processing | 1,134 tokens/s | 3,563 tokens/s | GB10 (~3.1x) |
Each card came out on top in one test. The reason is that the two tasks stress different parts of the hardware.
Generation is limited by memory bandwidth
To produce each new token, the GPU has to read essentially the entire model from memory. It does very little math per byte it reads, so the speed limit is how fast memory can feed the chip.
On paper, the 1080 Ti has about 484 GB/s of dedicated GDDR5X memory. The GB10 shares about 273 GB/s of LPDDR5X with the CPU. More bandwidth means faster generation, so the old card wins this round.
The gap is smaller than the bandwidth numbers alone would predict (about 1.2x instead of about 1.8x). The GB10 appears to use its bandwidth more efficiently, probably thanks to newer hardware and software kernels.
Prompt processing is limited by compute
When the model reads a long prompt, it processes thousands of tokens at once. Each weight loaded from memory gets reused across many tokens, so the work becomes huge matrix multiplications. Now the limit is raw arithmetic throughput, not memory.
This is where the GB10’s modern architecture pays off. It has tensor cores, which are specialized units for matrix math. The 1080 Ti predates them and has to do the work the slow way. The result is a roughly 3x win for the newer chip.
What this means in practice
- Short prompt, long answer (chat, creative writing): the 1080 Ti feels faster.
- Long prompt, short answer (summarizing documents, retrieval-augmented Q&A): the GB10 is much faster.
- Somewhere in between, they can come out about even. In my numbers, a 3,000-token prompt with a 500-token answer takes roughly 10 seconds on either card.
The lesson is the same one this post has been building toward. Fast code on slow hardware, slow code on fast hardware, and the wrong hardware for your workload can all leave performance on the table. Knowing whether your problem is bound by memory or by compute tells you which resources to care about, whether you’re choosing a GPU or deciding how to write your code.
Conclusions and takeaways:
Bad code on CPU < Good code on CPU < Code on GPU
Not all GPUs are the same. Memory and bandwidth vs Number and capability of cores.
LLM considerations for memory, bandwidth and cores.