Level 3 In-Depth AI · Programming and Tools
GPUs and Why AI Needs Them
Neural networks are mostly giant matrix multiplications, and a GPU does thousands of multiply-adds at once. Cores, memory bandwidth and VRAM, CUDA in one page, and how to work out whether a model will fit on your GPU.
- Level
- ●●●●● Easy
- Reading
- 13 min
- To learn it well
- 1 hour to read, 30 minutes to try
- Builds on
- 2 concepts →
- Quiz
- 5 questions ↓
Read first
Matrices and Matrix MultiplicationThe full path from zero — 2 concepts before this one
- Vectors
- Matrices and Matrix Multiplication
- GPUs and Why AI Needs Them
Read them roughly in this order. See it on the concept map →
Why it matters
Deep learning exploded in 2012, when a network called AlexNet won the ImageNet image-recognition competition by a wide margin (Convolutional Neural Networks, A Short History of AI). The ideas behind it were decades old. What was new was that it was trained on two consumer GPUs (graphics processing units), NVIDIA GTX 580 gaming cards, which made training feasible in about a week instead of many months.
Since then, the size of AI models has been limited mainly by how much GPU computing people can afford. As of late 2026, frontier language models are trained on clusters of tens to hundreds of thousands of data-centre GPUs, and NVIDIA's market value has grown on the back of that demand. At the small end, whether you can run an open model on your laptop or fine-tune one on Colab is a question of GPU memory.
You do not need to program GPUs directly to do AI. PyTorch does that for you. But you do need to understand what a GPU is good at, why your code is sometimes not faster on one, and how to estimate whether a model will fit. That is what this chapter covers.
The intuition
A CPU (central processing unit), the main chip in every computer, is like a handful of brilliant professors. Each one can do any task, follow complicated instructions with lots of decisions, and switch jobs quickly. A modern laptop CPU has around 8 to 16 such cores.
A GPU is like a stadium full of thousands of school pupils with calculators. Each one is slower and simpler than a professor, and they all have to follow the same instruction at the same time on different numbers. For most tasks that would be useless. For one task it is perfect: doing millions of identical, independent multiply-and-add operations.
That task is exactly what neural networks need. A layer computes : every entry of the output is a dot product of one row and one column, and none of them depends on any other. Hand each pupil a few entries and they can all work at once. GPUs were built for graphics, where the same calculation runs for each of millions of pixels, and it turned out that matrix multiplication has the same shape of problem.
Key idea A GPU is fast at AI because neural networks are mostly matrix multiplications, and every entry of a matrix product can be computed independently and in parallel. The GPU's job is to keep thousands of simple arithmetic units busy at once.
How it works
Three numbers that describe a GPU
1. Compute: how many operations per second. Measured in FLOPS, floating-point operations per second. One TFLOPS (teraFLOPS) is a trillion per second. Since 2017, NVIDIA GPUs have included tensor cores, special units that multiply small blocks of matrices in one step, at reduced precision such as 16-bit numbers. As published by NVIDIA, an H100 data-centre GPU (2022) reaches about 990 TFLOPS on dense 16-bit (BF16) matrix maths. A laptop CPU manages a few TFLOPS at best.
2. Memory: how much fits. A GPU has its own memory, called VRAM (video RAM), separate from the computer's main memory. Everything the GPU works on, including model weights, inputs, intermediate results and gradients, must be in VRAM. Typical sizes for common cards:
| GPU | VRAM | Memory bandwidth | Typical use |
|---|---|---|---|
| NVIDIA T4 (Colab free tier) | 16 GB | 320 GB/s | learning, small models |
| NVIDIA RTX 4090 (gaming) | 24 GB | about 1,000 GB/s | home fine-tuning and inference |
| NVIDIA A100 | 40 or 80 GB | up to about 2,000 GB/s | training, serving |
| NVIDIA H100 (SXM) | 80 GB | about 3,350 GB/s | large-scale training |
3. Memory bandwidth: how fast data moves. Memory bandwidth is how many bytes per second can travel between VRAM and the arithmetic units. It matters as much as raw compute, because a calculation cannot start until its numbers arrive. Data-centre GPUs use stacked HBM (high-bandwidth memory) for this reason. For comparison, a typical desktop CPU's main memory delivers somewhere around 50 to 100 GB/s.
Compute-bound or memory-bound?
Every operation either waits mostly on arithmetic or mostly on memory.
- Compute-bound operations do many calculations per number loaded. Multiplying two large matrices takes about operations on only numbers, so each number is reused about times. This is where GPUs shine.
- Memory-bound operations do little work per number: adding two arrays, applying an activation function, normalising. They run at the speed memory can deliver data, and the arithmetic units sit idle much of the time.
A worked example. Adding two vectors of a billion 32-bit numbers means reading 8 GB and writing 4 GB, but only a billion additions. On an H100 the arithmetic takes only microseconds, but moving 12 GB at 3,350 GB/s takes about 3.6 milliseconds. Memory wins by a factor of hundreds. Generating text with an LLM is like this too: to produce each new token, the GPU must read every weight of the model once. An 8-billion-parameter model in 16-bit numbers is 16 GB, so at about 1,000 GB/s on an RTX 4090 you get at most roughly 60 tokens per second for one user, however many TFLOPS the card has. That is why Quantization (smaller numbers) makes local models faster, and why caching and batching matter so much in Serving LLMs at Scale.
CUDA in one page
CUDA is NVIDIA's platform for programming its GPUs, released in 2007. Before it, using a GPU for non-graphics work meant disguising your numbers as pixels. CUDA lets you write ordinary-looking C++ functions, called kernels, that run on the GPU.
The model is simple:
- The CPU (the "host") copies data into GPU memory (the "device").
- The CPU launches a kernel: one small function, run by thousands of threads at once. Each thread uses its own index number to decide which piece of data to work on. Thread 0 adds element 0, thread 1 adds element 1, and so on.
- Threads are organised into blocks, and blocks into a grid. Threads in a block can share a small, very fast scratch memory, which is how fast matrix multiplication reuses data.
- The CPU copies results back when it needs them.
You will almost never write a CUDA kernel yourself. NVIDIA's libraries (cuBLAS for matrix maths, cuDNN for neural-network operations) and PyTorch already contain highly tuned kernels for everything common. When you write a @ b on a CUDA tensor in PyTorch, it launches a cuBLAS kernel. Researchers who write custom kernels today often use Triton, a Python-like language from OpenAI, instead of raw CUDA. FlashAttention (2022) is a famous example of a hand-written kernel: it made Attention much faster by being smarter about memory traffic, not by doing less arithmetic.
Alternatives. AMD GPUs use a similar platform called ROCm, which PyTorch supports. Apple-silicon Macs have a built-in GPU that PyTorch reaches through MPS. Google designs its own AI chips, TPUs. AI Hardware: GPUs, TPUs and Accelerators compares them. CUDA's head start and software ecosystem are a large part of why NVIDIA dominates AI hardware.
Using a GPU from PyTorch
In PyTorch you choose a device and move both the model and the data to it:
device = "cuda" if torch.cuda.is_available() else "cpu"
model = model.to(device)
x = x.to(device) # inputs must be on the same device as the model
Two things surprise beginners. First, GPU calls are asynchronous: Python asks the GPU to start work and carries on immediately, so naive timing measures nothing. Second, copying data between CPU and GPU is slow compared with computing on the GPU, so you move data once and keep it there.
Will it fit? Estimating memory
The most practical GPU skill is estimating memory before you start. Each number takes a fixed number of bytes:
| Format | Bytes per number |
|---|---|
| 32-bit float (fp32) | 4 |
| 16-bit float (fp16, bf16) | 2 |
| 8-bit integer (int8) | 1 |
| 4-bit (int4) | 0.5 |
Running a model (inference) needs the weights plus some room for activations and the The KV Cache and Fast Inference:
The factor 1.2 is a rough allowance for short prompts. Long contexts need much more. An 8-billion-parameter model in bf16 needs about GB. It fits on a 24 GB card, not on a 16 GB T4. Quantised to 4 bits it needs about 5 GB and fits almost anywhere.
Training needs far more. With the Adam optimizer and Mixed Precision Training training, each parameter needs its 16-bit weight (2 bytes), its 16-bit gradient (2 bytes), a 32-bit master copy of the weight (4 bytes) and Adam's two 32-bit running averages (8 bytes): about 16 bytes per parameter, before counting activations. Fully training or fine-tuning an 8B model therefore needs about 128 GB, more than a single 80 GB H100. That is why LoRA, which trains only a tiny fraction of the weights, and Distributed Training, which splits the job across many GPUs, exist.
In code
The first script measures how fast your hardware multiplies matrices, on the CPU and on a GPU if you have one. It picks CUDA, Apple's MPS or nothing, and it waits for the GPU to finish before stopping the clock.
import time
import torch
def pick_device():
if torch.cuda.is_available():
return torch.device("cuda") # NVIDIA GPU
if torch.backends.mps.is_available():
return torch.device("mps") # Apple-silicon GPU
return torch.device("cpu")
def sync(device):
# GPU calls return immediately; wait for the work to really finish.
if device.type == "cuda":
torch.cuda.synchronize()
elif device.type == "mps":
torch.mps.synchronize()
def tflops(device, n=4096, repeats=10):
a = torch.randn(n, n, device=device)
b = torch.randn(n, n, device=device)
a @ b; sync(device) # warm-up run
start = time.perf_counter()
for _ in range(repeats):
c = a @ b
sync(device)
seconds = (time.perf_counter() - start) / repeats
return 2 * n**3 / seconds / 1e12 # a matmul costs 2·n³ operations
print(f"cpu: {tflops(torch.device('cpu')):.2f} TFLOP/s")
gpu = pick_device()
if gpu.type != "cpu":
print(f"{gpu.type}: {tflops(gpu):.2f} TFLOP/s")
# On an Apple M1 Pro laptop:
# cpu: 1.39 TFLOP/s
# mps: 4.18 TFLOP/s
On this laptop the built-in GPU is only about three times faster than the CPU, because Apple's CPU has its own matrix accelerator and a laptop GPU is small. Run the same script on a Colab GPU, or better a data-centre GPU, and the gap is far larger. Try n=512 too. Small matrices cannot keep thousands of cores busy, and the GPU's advantage shrinks or vanishes.
The second script turns the memory rules of thumb into numbers:
BYTES = {"fp32": 4, "bf16": 2, "int8": 1, "int4": 0.5}
def inference_gb(params_billion, dtype="bf16", overhead=1.2):
"""Weights, plus ~20% for activations and the KV cache (short prompts)."""
return params_billion * BYTES[dtype] * overhead
def full_training_gb(params_billion):
"""Adam with mixed precision: about 16 bytes per parameter, before activations."""
return params_billion * 16
for name, p in [("GPT-2 small", 0.124), ("Llama-style 8B", 8), ("70B", 70)]:
print(f"{name:15s} inference bf16 {inference_gb(p):6.1f} GB | "
f"int4 {inference_gb(p, 'int4'):5.1f} GB | full training {full_training_gb(p):7.1f} GB")
# GPT-2 small inference bf16 0.3 GB | int4 0.1 GB | full training 2.0 GB
# Llama-style 8B inference bf16 19.2 GB | int4 4.8 GB | full training 128.0 GB
# 70B inference bf16 168.0 GB | int4 42.0 GB | full training 1120.0 GB
These are estimates, not guarantees. Activation memory during training grows with batch size and sequence length and can exceed the weights. The tools in The Hugging Face Ecosystem and Fine-Tuning an Open Model in Practice report actual memory use.
Common pitfalls
- "Expected all tensors to be on the same device". The model is on the GPU and the data on the CPU, or the other way round. Move both with
.to(device). CUDA out of memory. Reduce the batch size first. Then consider Mixed Precision Training, gradient checkpointing, a smaller model, quantisation or LoRA. In notebooks, old tensors from earlier cells may still occupy memory: restart the kernel.- The GPU is idle. If GPU utilisation (shown by
nvidia-smi) is low, the bottleneck is usually loading data on the CPU. Use severalDataLoaderworkers (see PyTorch) and keep data on the GPU. - Calling
.item()orprintevery step. Each forces the CPU to wait for the GPU, which stalls the pipeline. Log every hundred steps instead. - Timing without synchronising. Because of asynchronous execution, timing GPU code without
torch.cuda.synchronize()measures only how long it took to queue the work.
Watch out Out-of-memory crashes often come after hours of training, on the one batch with the longest sequences. Test your largest possible batch first, for a few steps, before launching a long run.
Where it leads
- PyTorch shows the full training loop with
.to(device). - Mixed Precision Training and Quantization shrink numbers to save memory and time.
- Distributed Training splits training across many GPUs. Serving LLMs at Scale covers serving models efficiently.
- AI Hardware: GPUs, TPUs and Accelerators compares GPUs, TPUs and other accelerators, and The Energy Cost of AI the electricity they use.
- Running Models Locally applies the memory arithmetic above to choosing a model for your own computer.
A bit of history
GPUs began as fixed-function chips for 3-D games. NVIDIA marketed its GeForce 256 in 1999 as the first "GPU". In the early 2000s, researchers found they could abuse programmable graphics hardware for scientific computing, an approach called GPGPU (general-purpose computing on GPUs), by pretending their data were textures. CUDA, released by NVIDIA in 2007, made this a normal kind of programming. In 2009, Rajat Raina, Anand Madhavan and Andrew Ng showed that GPUs could speed up training of large neural networks dramatically. In 2012, Alex Krizhevsky, Ilya Sutskever and Geoffrey Hinton trained AlexNet on two GTX 580s with 3 GB of memory each and changed the field. NVIDIA added tensor cores with its Volta V100 in 2017, and every generation since has been designed with AI as its main purpose.
Try it
- Run the matrix-multiplication script on your computer and on a Colab GPU runtime. How many times faster is the GPU? Repeat with
n=256. What happens, and why?- Using the memory rules above, which of these fits on a 16 GB T4: a 3B model in bf16 for inference, a 13B model in 4-bit for inference, or full training of a 1B model with Adam?
- An RTX 4090 has about 1,000 GB/s of memory bandwidth. Estimate the maximum tokens per second for generating text with a 4-bit 8B model on it.
Hint for 3: a 4-bit 8B model is about 4 GB of weights, and each new token needs one full read of the weights.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Making Deep Learning Go Brrrr From First Principles
A clear explanation of compute-bound, memory-bound and overhead-bound work on GPUs, and what to do about each.
Which GPU(s) to Get for Deep Learning
A long, practical guide to how GPUs work for deep learning and how to choose one, including memory and tensor cores.
CUDA Programming Guide
The official reference for the CUDA programming model: kernels, threads, blocks, grids and the memory hierarchy.
PyTorch: CUDA semantics
How PyTorch uses GPUs: devices, asynchronous execution, memory management and best practices.
Machine Learning Engineering Open Book
A practitioner's open book on the hardware and software of training and serving large models: GPUs, networking, storage and debugging.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/programming/gpus-and-cuda.md