Mojo GPU Basics
A GPU (graphics processing unit) is a chip with thousands of small, simple cores. It’s slow at the step-by-step logic a CPU is good at, but very fast when you need to do the same small job on a huge amount of data: add two arrays with millions of numbers, brighten every pixel of an image, multiply big matrices. Mojo lets you write the code that runs on the GPU yourself, in the same language as the rest of your program. This page explains the ideas you need before writing your first GPU function.
What a GPU is good at
Section titled “What a GPU is good at”A CPU has a handful of cores, and each one is clever: it predicts branches, runs instructions out of order and switches between very different tasks. A GPU has many more cores, but each one is simple. They work in groups that run the same instruction at the same time, each on its own piece of data.
| CPU | GPU | |
|---|---|---|
| Cores | A few, each fast and clever | Thousands, each simple |
| Best at | Branchy logic, one task after another | The same math on lots of data at once |
| Good fit | Parsing a file, a web server, game logic | Adding big arrays, image filters, matrix math, AI models |
| Bad fit | Huge, regular number crunching | Small jobs, lots of if/else, constant back-and-forth with the CPU |
There’s one more cost to keep in mind: the GPU usually has its own memory. Your data has to be copied to the GPU before it can work on it, and the results have to be copied back. For a small job, the copying takes longer than the work. GPUs pay off when there’s a lot of data and a lot of math per byte.
Kernels, threads, blocks and grids
Section titled “Kernels, threads, blocks and grids”A function that runs on the GPU is called a kernel. When you start a kernel, the GPU runs it many times at once. Each running copy is a thread, and every thread runs the same code. The only difference between threads is their index, a number the GPU gives each one. A thread uses its index to pick the piece of data it works on.
Threads come in groups:
- A block (thread block) is a group of threads, for example 256. Threads in the same block can share fast memory and wait for each other.
- A grid is all the blocks of one kernel launch.
When you start a kernel, you choose two numbers: how many blocks (grid_dim) and how many threads per block (block_dim). Inside the kernel, each thread can read block_idx.x (which block it’s in) and thread_idx.x (its position in that block). Together they give a unique number:
global index = block_idx.x * block_dim.x + thread_idx.xYou can’t run a kernel without a GPU, but you can run the same idea on the CPU. This program pretends to be a grid of 3 blocks with 4 threads each, working on a list of 10 elements. The two loops do what the GPU does all at once:
from std.math import ceildiv
comptime vector_size = 10comptime block_size = 4comptime num_blocks = ceildiv(vector_size, block_size)
def main(): print("blocks:", num_blocks, "threads per block:", block_size) for block in range(num_blocks): for thread in range(block_size): var tid = block * block_size + thread if tid < vector_size: print("block", block, "thread", thread, "-> element", tid) else: print("block", block, "thread", thread, "-> nothing to do")Output:
blocks: 3 threads per block: 4block 0 thread 0 -> element 0block 0 thread 1 -> element 1block 0 thread 2 -> element 2block 0 thread 3 -> element 3block 1 thread 0 -> element 4block 1 thread 1 -> element 5block 1 thread 2 -> element 6block 1 thread 3 -> element 7block 2 thread 0 -> element 8block 2 thread 1 -> element 9block 2 thread 2 -> nothing to doblock 2 thread 3 -> nothing to doA few things to notice, because every GPU kernel you write will have them:
ceildiv(fromstd.math) divides and rounds up: 10 elements in blocks of 4 need 3 blocks, not 2.- That gives 12 threads for 10 elements, so the last two threads have nothing to do. Every kernel needs a bounds check like
if tid < vector_size, or those threads read and write memory that isn’t yours. - On a real GPU there’s no order: threads run at the same time, and you can’t rely on block 0 finishing before block 2.
What you need to install
Section titled “What you need to install”GPU programming in Mojo uses Modular’s max package. In Mojo 1.2 the GPU APIs (DeviceContext, block_idx, thread_idx and friends) aren’t in the standard library; they come with max under max.gpu. Add it to your project next to mojo:
uv add maxThat’s the same package the parallelize lesson uses. Then, depending on your GPU:
| GPU | Software you need |
|---|---|
| NVIDIA | GPU driver 580 or later (check with nvidia-smi) |
| AMD | AMD GPU driver 6.3.3 or later (ROCm), on Linux or WSL |
| Apple silicon | macOS 15 or later and Xcode 16 or later |
This is a summary of the hardware compatibility page, which also has fixes for when Mojo doesn’t find a GPU that’s there. Older NVIDIA drivers can work with an extra setting described on that page.
Is there a GPU?
Section titled “Is there a GPU?”The standard library has one GPU-related function: has_accelerator() in std.sys. It tells you whether Mojo found a supported GPU. Use it with comptime if, so the GPU code is only compiled when there’s a GPU to compile it for:
from std.sys import has_accelerator
def main(): comptime if has_accelerator(): print("Found a supported GPU.") else: print("No supported GPU found, so the GPU code is left out.")Our test machine has no GPU, so it prints the second line.
Output:
No supported GPU found, so the GPU code is left out.comptime if is checked when the program is compiled, not when it runs (the comptime control flow lesson explains it). That matters: without a GPU, Mojo can’t compile kernels, so the GPU branch must be skipped at compile time, not just at run time. You’ll see this pattern at the top of every GPU program on the next pages.
Saying hello to the GPU
Section titled “Saying hello to the GPU”Here’s the first program from Modular’s GPU tutorial. It gets a DeviceContext, your handle to one GPU, and prints the GPU’s name:
from max.gpu.host import DeviceContextfrom std.sys import has_accelerator
def main() raises: comptime if not has_accelerator(): print("No compatible GPU found") else: var ctx = DeviceContext() print("Found GPU:", ctx.name())Output on a supported GPU, from the official docs (the name depends on your GPU):
Found GPU: NVIDIA A10GDeviceContext() raises an error if there’s no usable GPU, so main is marked raises. On our test machine, the else branch isn’t compiled at all, and the program prints No compatible GPU found.
Compiling GPU code without a GPU
Section titled “Compiling GPU code without a GPU”You don’t need a GPU to check that GPU code compiles. mojo build can compile the kernels for a GPU you name with --target-accelerator. To see the names it knows:
uv run mojo build --print-supported-acceleratorsHere are a few of the lines Mojo 1.2 printed on our machine:
NVIDIA (CUDA): sm_75 - Turing (RTX 2060) sm_80 - Ampere datacenter (A100) sm_86 - Ampere workstation (A10) sm_89 - Ada Lovelace (L4, RTX 4090) sm_90 - Hopper (H100)The full list also has AMD names (like gfx942 for the MI300X) and Apple ones (like apple-m1). To compile the program above for an A100:
uv run mojo build --target-accelerator=nvidia:sm_80 hello_gpu.mojoThat builds fine here, and it really compiles the GPU branch: running the result on our GPU-less machine fails when it looks for NVIDIA’s driver (shortened):
Unhandled exception caught during execution: At max/mojo/max/gpu/host/device_context.mojo:4636:17: Failed to open library "libnvidia-ml.so.1"That’s how every GPU program on this site was checked. It catches type errors and mistakes in kernels, but it can’t tell you whether the results are right. Only running on a real GPU does that. (Building for an Apple target failed on our Linux machine, because it needs Apple’s Metal tools from Xcode.)
Practice
Section titled “Practice”1. Count the idle threads
Section titled “1. Count the idle threads”A kernel works on 20 elements with blocks of 8 threads. Write a CPU program that works out how many blocks you need and how many threads have nothing to do.
Hint: use ceildiv(20, 8) for the blocks, then count the indices that are >= 20.
Show solution
from std.math import ceildiv
comptime n = 20comptime block_size = 8
def main(): var blocks = ceildiv(n, block_size) var idle = 0 for block in range(blocks): for thread in range(block_size): var tid = block * block_size + thread if tid >= n: idle += 1 print("blocks:", blocks, "idle threads:", idle)Output:
blocks: 3 idle threads: 43 blocks of 8 make 24 threads for 20 elements, so 4 threads only run the bounds check and stop.
2. Which thread handles element 700?
Section titled “2. Which thread handles element 700?”With 256 threads per block, which block and which thread inside it handle element 700?
Hint: go backwards from index = block * 256 + thread: use // and %.
Show solution
comptime block_size = 256
def main(): var element = 700 var block = element // block_size var thread = element % block_size print("block", block, "thread", thread) print("check:", block * block_size + thread)Output:
block 2 thread 188check: 700Blocks 0 and 1 cover elements 0 to 511, so element 700 is in block 2, at position 700 - 512 = 188.
- A GPU has thousands of simple cores that run the same instruction on different data. It shines on big, regular math and is a poor fit for small or branchy jobs.
- A kernel is a function that runs on the GPU as many threads. Threads are grouped into blocks, and all blocks form the grid.
- Each thread finds its element with
block_idx.x * block_dim.x + thread_idx.x, and needs a bounds check, because the grid is usually bigger than the data. - GPU APIs come from the
maxpackage (uv add max), undermax.gpu. You also need a supported GPU and its driver. - Guard GPU code with
comptime if has_accelerator(), so it still compiles on machines without a GPU. mojo build --target-accelerator=...compiles GPU code without a GPU, which catches compile errors but doesn’t run anything.
Next up: Mojo First GPU Kernel, adding two vectors on the GPU, step by step.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Intro to GPUs: Modular’s explanation of GPU hardware, streaming multiprocessors, warps and the execution model.
- GPU hardware compatibility: every supported GPU, the drivers each needs, and how to fix detection problems.
- Get started with GPU programming: the official step-by-step tutorial the next page follows.
- Compilation targets:
--target-acceleratorand the other flags for building for hardware you don’t have. - Mojo GPU Puzzles: Modular’s hands-on exercises for learning GPU programming in Mojo (needs a GPU to run).