GPUs and Hardware for AI

Updated · 7 min read
mediumPython 3.13aideep-learninggpuhardwarepytorch

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

ProcessorBuilt forCoresStrength
CPUGeneral tasks, one step after anotherA few to dozens of powerful coresComplicated, branching logic
GPUGraphics, then AIThousands of simple coresThe same math on huge arrays at once
TPU and other AI chipsNeural networks onlyLarge matrix-multiply unitsEven more math per watt

Example: Loops vs Vectorized Math

This program multiplies two 200 × 200 matrices with plain Python loops, then with NumPy.

Python
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))
Output
200x200 matrix multiply = 8,000,000 multiply-adds
Python loops: 0.80 s
NumPy:        0.08 ms  (10,243x faster)
Same answer: True

One 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.

Neural networks are matrix multiplication; hardware that multiplies in parallel wins

Example: CPU vs GPU in PyTorch

This program times a much bigger multiplication, 4096 × 4096, on every device PyTorch finds.

Python
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)")
Output
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

TermDescription
GPU memory (VRAM)It is used to hold the model's weights and data; limits the model size a chip can run
FLOPSFloating-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
QuantizationIt is used to shrink a trained model by storing weights in fewer bits, often to run on laptops and phones
ClusterMany accelerators linked together to train one large model
CUDANVIDIA's software for programming its GPUs, used by PyTorch
TPUGoogle'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 size32-bit (4 bytes)16-bit (2 bytes)4-bit (0.5 bytes)
This chapter's digit network, 2,410 parametersabout 10 KBabout 5 KBabout 1 KB
7 billion parametersabout 28 GBabout 14 GBabout 3.5 GB
70 billion parametersabout 280 GBabout 140 GBabout 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:

  1. Which operation dominates neural network work?
  2. Why must GPU timings call sync()?
  3. How much memory do the weights of a 7-billion-parameter model need in 16-bit numbers?

Quick check: AI hardware

4 questions
1Why do GPUs suit neural networks?
2How much faster was NumPy than Python loops here?
3What does quantization do?
4About how much memory do 7 billion 16-bit weights need?

Key Takeaways

Quick reference

NeedCode
Pick a device"cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
Put a model on itmodel.to(device)
Put data on itX.to(device)
Wait for the GPUtorch.cuda.synchronize(), torch.mps.synchronize()

Was this tutorial helpful?

Lesson 139 of 186