GPUs and Hardware for AI
AI hardware is the processors and memory that train and run models. Neural networks spend nearly all their time on one operation, matrix multiplication: millions of independent multiply-adds. A GPU (graphics processing unit) has thousands of small cores that do those operations in parallel, which is why GPUs, and chips designed like them, power modern AI.
This lesson is optional. It explains why training large models costs so much, and what the hardware words in AI news mean.
Why Parallel Arithmetic
| Processor | Built for | Cores | Strength |
|---|---|---|---|
| CPU | General tasks, one step after another | A few to dozens of powerful cores | Complicated, branching logic |
| GPU | Graphics, then AI | Thousands of simple cores | The same math on huge arrays at once |
| TPU and other AI chips | Neural networks only | Large matrix-multiply units | Even more math per watt |
Example: Loops vs Vectorized Math
This program multiplies two 200 × 200 matrices with plain Python loops, then with NumPy.
import time
import numpy as np
n = 200
rng = np.random.default_rng(0)
A, B = rng.random((n, n)), rng.random((n, n))
def loops(A, B): # one multiply-add at a time
C = [[0.0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
s = 0.0
for k in range(n):
s += A[i, k] * B[k, j]
C[i][j] = s
return np.array(C)
start = time.perf_counter()
slow = loops(A, B)
loop_time = time.perf_counter() - start
start = time.perf_counter()
fast = A @ B # NumPy hands the whole job to optimized, parallel code
numpy_time = time.perf_counter() - start
print(f"{n}x{n} matrix multiply = {n ** 3:,} multiply-adds")
print(f"Python loops: {loop_time:.2f} s")
print(f"NumPy: {numpy_time * 1000:.2f} ms ({loop_time / numpy_time:,.0f}x faster)")
print("Same answer:", np.allclose(slow, fast))200x200 matrix multiply = 8,000,000 multiply-adds
Python loops: 0.80 s
NumPy: 0.08 ms (10,243x faster)
Same answer: TrueOne run on an Apple M5 Mac. Your times will differ, but the gap will be huge on any computer.
Explanation: Both compute the same 8 million multiply-adds and give the same answer. The Python loops handle one multiply-add at a time, with Python's overhead on each. NumPy hands the whole job to optimized code that uses the processor's vector instructions and all its cores, and is about 10,000 times faster. This is the same idea a GPU takes much further.
Example: CPU vs GPU in PyTorch
This program times a much bigger multiplication, 4096 × 4096, on every device PyTorch finds.
import time
import torch
def sync(device): # GPUs work in the background; wait until they finish before timing
if device == "cuda":
torch.cuda.synchronize()
elif device == "mps":
torch.mps.synchronize()
def time_matmul(device, n=4096, repeats=10):
A, B = torch.rand(n, n, device=device), torch.rand(n, n, device=device)
A @ B # warm-up run, not timed
sync(device)
start = time.perf_counter()
for _ in range(repeats):
A @ B
sync(device)
seconds = (time.perf_counter() - start) / repeats
return seconds, 2 * n ** 3 / seconds / 1e12 # each multiply-add is 2 operations; TFLOPS = trillions per second
devices = ["cpu"] + ["cuda"] * torch.cuda.is_available() + ["mps"] * torch.backends.mps.is_available()
for device in devices:
seconds, tflops = time_matmul(device)
print(f"{device:4}: {seconds * 1000:7.1f} ms per 4096x4096 multiply ({tflops:.1f} TFLOPS)")cpu : 67.3 ms per 4096x4096 multiply (2.0 TFLOPS)
mps : 37.8 ms per 4096x4096 multiply (3.6 TFLOPS)One run on an Apple M5 Mac. On a computer with an NVIDIA GPU you will see a cuda line instead of mps.
Explanation: TFLOPS means trillions of floating-point operations per second; one 4096 × 4096 multiply is about 137 billion operations. The laptop's GPU is about 1.8 times faster than its CPU here, a modest gain, because this CPU also has fast matrix hardware. The sync() calls matter: GPUs work in the background, so timing without waiting for them to finish would measure nothing. Data-center GPUs and AI chips are built for this one job, reach far higher speeds, especially with the lower-precision numbers AI uses, and large models are trained on thousands of them at once.
Hardware Words in AI News
| Term | Description |
|---|---|
| GPU memory (VRAM) | It is used to hold the model's weights and data; limits the model size a chip can run |
| FLOPS | Floating-point operations per second, a measure of raw speed |
| Precision (FP32, BF16, FP8) | How many bits each number uses; fewer bits are faster and smaller, but less exact |
| Quantization | It is used to shrink a trained model by storing weights in fewer bits, often to run on laptops and phones |
| Cluster | Many accelerators linked together to train one large model |
| CUDA | NVIDIA's software for programming its GPUs, used by PyTorch |
| TPU | Google's AI chip, designed for neural networks |
How Much Memory a Model Needs
The weights alone take parameters × bytes per number. Training needs several times more, for gradients and optimizer state.
| Model size | 32-bit (4 bytes) | 16-bit (2 bytes) | 4-bit (0.5 bytes) |
|---|---|---|---|
| This chapter's digit network, 2,410 parameters | about 10 KB | about 5 KB | about 1 KB |
| 7 billion parameters | about 28 GB | about 14 GB | about 3.5 GB |
| 70 billion parameters | about 280 GB | about 140 GB | about 35 GB |
This is why quantized open models can run on a laptop, while the largest models need many data-center accelerators.
Common Mistakes
Timing a GPU without synchronizing. You measure only how long it took to queue the work.
Moving data back and forth. Copying between CPU and GPU every step can cost more than the math; keep data on the device.
Assuming a GPU always helps. Tiny networks like the digit reader can run faster on a CPU, because the setup overhead outweighs the parallel speed.
Forgetting memory. A model that doesn't fit in GPU memory won't run, however fast the chip.
Interview Corner
Why are GPUs used for deep learning?
Neural network training and inference are dominated by matrix multiplication, which is massively parallel, and GPUs have thousands of cores and high memory bandwidth built for parallel arithmetic.
What is quantization?
Storing a model's weights with fewer bits, such as 8 or 4 instead of 16 or 32, which cuts memory and speeds up inference at a small cost in accuracy.
Practice
Exercise: your own hardware. Run both programs on your computer, and the second with n set to 512 and 8192. At which size does the GPU, if you have one, start to beat the CPU clearly?
Check your understanding:
- Which operation dominates neural network work?
- Why must GPU timings call
sync()? - How much memory do the weights of a 7-billion-parameter model need in 16-bit numbers?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Pick a device | "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" |
| Put a model on it | model.to(device) |
| Put data on it | X.to(device) |
| Wait for the GPU | torch.cuda.synchronize(), torch.mps.synchronize() |
Was this tutorial helpful?