Mojo GPU Threads & Blocks
On the last two pages every kernel used a flat row of threads: grid_dim=4, block_dim=256. That fits a vector. But a lot of GPU work is shaped differently: an image has rows and columns, a video adds time. Mojo lets you arrange threads and blocks in up to three dimensions, so each thread’s index matches a position in your data. This page explains the index values a kernel can read, shows 2D and 3D launches, and gives you simple rules for picking sizes.
The five index values
Section titled “The five index values”Inside a kernel you can read five values from max.gpu. Each one has an x, y and z part, and they’re all Ints:
| Value | What it is |
|---|---|
grid_dim |
How many blocks the grid has, in each dimension |
block_dim |
How many threads each block has, in each dimension |
block_idx |
Which block this thread is in |
thread_idx |
This thread’s position inside its block |
global_idx |
This thread’s position in the whole grid |
global_idx is the one you’ll use most. It’s just a shortcut for the formula from the earlier pages, done for each dimension:
global_idx.x = block_dim.x * block_idx.x + thread_idx.xglobal_idx.y = block_dim.y * block_idx.y + thread_idx.yglobal_idx.z = block_dim.z * block_idx.z + thread_idx.zSo in a 1D kernel, var tid = global_idx.x does the same as var tid = block_idx.x * block_dim.x + thread_idx.x. The official tutorial writes the long form so you see where it comes from; after that, the short form is easier to read.
Grids and blocks in 2D and 3D
Section titled “Grids and blocks in 2D and 3D”When you launch a kernel, grid_dim and block_dim each take an Int or a tuple:
block_dim=256means 256 threads inx(and 1 inyandz).block_dim=(16, 16)means a 16 by 16 square of threads, 256 in total (zis 1).grid_dim=(2, 2, 1)means a 2 by 2 square of blocks.
This kernel from the GPU programming fundamentals page prints every index value, so you can see how they relate:
from std.sys import has_accelerator
from max.gpu.host import DeviceContextfrom max.gpu import block_dim, block_idx, global_idx, thread_idx
def print_threads(): """Print thread block and thread indices."""
print( block_idx.x, block_idx.y, block_idx.z, thread_idx.x, thread_idx.y, thread_idx.z, global_idx.x, global_idx.y, global_idx.z, block_dim.x * block_idx.x + thread_idx.x, block_dim.y * block_idx.y + thread_idx.y, block_dim.z * block_idx.z + thread_idx.z, sep="\t", )
def main() raises: comptime if not has_accelerator(): print("No compatible GPU found") else: # Initialize GPU context for device 0 (default GPU device). var ctx = DeviceContext()
print("block_idx\t\tthread_idx\t\tglobal_idx\t\tcalculated global_idx") print("x\ty\tz", "x\ty\tz", "x\ty\tz", "x\ty\tz", sep="\t") print("-" * 20, "-" * 20, "-" * 20, "-" * 20, sep="\t") ctx.enqueue_function[print_threads]( grid_dim=(2, 2, 1), # 2x2x1 blocks per grid block_dim=(4, 4, 2), # 4x4x2 threads per block )
ctx.synchronize() print("Done")Output on a supported GPU, from the official docs (shortened there; the order changes between runs):
block_idx thread_idx global_idx calculated global_idxx y z x y z x y z x y z-------------------- -------------------- -------------------- --------------------0 1 0 0 0 0 0 4 0 0 4 00 1 0 1 0 0 1 4 0 1 4 0...1 1 0 2 3 1 6 7 1 6 7 11 1 0 3 3 1 7 7 1 7 7 1DoneThe grid has 4 blocks and each block has 4 * 4 * 2 = 32 threads, so 128 lines in total. Look at the last line: block (1, 1, 0), thread (3, 3, 1). Its global_idx.x is 4 * 1 + 3 = 7, and the last two groups of three numbers show that the formula gives exactly what global_idx holds.
A 2D grid for 2D data
Section titled “A 2D grid for 2D data”For a matrix or an image, use x for columns and y for rows: col = global_idx.x, row = global_idx.y. Then threads next to each other in x touch elements next to each other in memory, which GPUs like (see GPU matrix multiply for why).
You work out the grid one dimension at a time, rounding up each time. This CPU program plays a grid of 4 by 4 blocks over a 5-row, 6-column matrix, and prints which block handles each cell:
from std.math import ceildiv
comptime rows = 5comptime cols = 6comptime block_x = 4 # threads per block across (columns)comptime block_y = 4 # threads per block down (rows)comptime grid_x = ceildiv(cols, block_x)comptime grid_y = ceildiv(rows, block_y)
def main(): print("grid:", grid_x, "x", grid_y, "blocks of", block_x, "x", block_y, "threads") # owner[row * cols + col] = number of the block that handles that cell var owner = List[Int](length=rows * cols, fill=-1) var idle = 0 for by in range(grid_y): for bx in range(grid_x): for ty in range(block_y): for tx in range(block_x): var row = by * block_y + ty # like global_idx.y var col = bx * block_x + tx # like global_idx.x if row < rows and col < cols: owner[row * cols + col] = by * grid_x + bx else: idle += 1 for row in range(rows): for col in range(cols): print(owner[row * cols + col], end=" " if col < cols - 1 else "\n") print("idle threads:", idle)Output:
grid: 2 x 2 blocks of 4 x 4 threads0 0 0 0 1 10 0 0 0 1 10 0 0 0 1 10 0 0 0 1 12 2 2 2 3 3idle threads: 34Two blocks across (6 columns need 2 blocks of 4) and two blocks down (5 rows need 2 blocks of 4): 64 threads for 30 cells. Blocks 1, 2 and 3 hang over the edge, so a 2D kernel needs a bounds check on both dimensions.
Here’s the real kernel for the same shape. Each thread writes row * 10 + col into its cell. The matrix is stored row by row in a flat buffer, so cell (row, col) is at row * cols + col:
from std.math import ceildivfrom std.sys import has_accelerator
from max.gpu import global_idxfrom max.gpu.host import DeviceContext
comptime rows = 5comptime cols = 6comptime block_x = 4comptime block_y = 4
def fill_cells(grid: Pointer[Int32, MutAnyOrigin]): var row = global_idx.y var col = global_idx.x if row < rows and col < cols: grid[unsafe_offset=row * cols + col] = Int32(row * 10 + col)
def main() raises: comptime if not has_accelerator(): print("No compatible GPU found") else: var ctx = DeviceContext() var dev = ctx.enqueue_create_buffer[DType.int32](rows * cols) var host = ctx.enqueue_create_host_buffer[DType.int32](rows * cols) ctx.enqueue_function[fill_cells]( dev, grid_dim=(ceildiv(cols, block_x), ceildiv(rows, block_y)), block_dim=(block_x, block_y), ) ctx.enqueue_copy(dst_buf=host, src_buf=dev) ctx.synchronize() print(host)We compiled it for NVIDIA and AMD but couldn’t run it, so there’s no output here. Note that the tuples are (x, y), so columns come first: grid_dim=(ceildiv(cols, ...), ceildiv(rows, ...)). Mixing up the order is an easy mistake that leaves part of the matrix untouched. The LayoutTensor page shows a tidier way to index 2D data than row * cols + col.
Picking block and grid sizes
Section titled “Picking block and grid sizes”Choosing sizes is partly an art, but these rules get you a working, reasonable start:
- Make the block size a multiple of 32, like 128 or 256 threads (or 16 by 16 = 256 for 2D). The GPU runs threads in warps of 32 (or 64 on some GPUs), and a block that isn’t a multiple wastes the rest of its last warp.
- Stay under the per-block limit. It depends on the GPU; the official docs give the NVIDIA A100 as an example, with at most 1,024 threads per block.
- Then compute the grid:
ceildiv(size, block_size)in each dimension, so every element gets a thread. - Measure if speed matters. The best size depends on the GPU and the kernel, so try a few and time them on your hardware.
Here’s rule 3 for a few vector sizes with 256 threads per block:
from std.math import ceildiv
comptime block_size = 256
def main(): var sizes: List[Int] = [100, 1000, 1024, 5000] for n in sizes: var blocks = ceildiv(n, block_size) var threads = blocks * block_size print("n =", n, " blocks:", blocks, " threads:", threads, " idle:", threads - n)Output:
n = 100 blocks: 1 threads: 256 idle: 156n = 1000 blocks: 4 threads: 1024 idle: 24n = 1024 blocks: 4 threads: 1024 idle: 0n = 5000 blocks: 20 threads: 5120 idle: 120A few idle threads in the last block are normal and cheap. And here’s rule 1, counting warps of 32:
from std.math import ceildiv
comptime warp_size = 32
def main(): var block_sizes: List[Int] = [100, 128, 256, 1000] for b in block_sizes: var warps = ceildiv(b, warp_size) var unused = warps * warp_size - b print("block of", b, "threads ->", warps, "warps,", unused, "unused slots")Output:
block of 100 threads -> 4 warps, 28 unused slotsblock of 128 threads -> 4 warps, 0 unused slotsblock of 256 threads -> 8 warps, 0 unused slotsblock of 1000 threads -> 32 warps, 24 unused slotsA block of 100 threads still takes 4 full warps; 28 of their slots do nothing. That’s the example the official docs use too.
What threads can and can’t do together
Section titled “What threads can and can’t do together”- Threads in the same block can share fast shared memory and wait for each other with
barrier()(frommax.gpu.sync). You’ll use both in the matrix multiply lesson. - Threads in different blocks don’t share that memory and can’t use
barrier()to wait for each other. Design kernels so blocks don’t depend on each other. - There’s no order. Don’t assume thread 0 runs before thread 1, or block 0 before block 1.
- If two threads write the same element, the result is unpredictable (a data race, like on the parallelize page). One output element per thread avoids that.
Practice
Section titled “Practice”1. A full HD image
Section titled “1. A full HD image”You want one thread per pixel of a 1920 by 1080 image, with 16 by 16 blocks. What’s the grid_dim, and how many threads are idle?
Hint: ceildiv for each dimension; 1080 isn’t a multiple of 16.
Show solution
from std.math import ceildiv
comptime width = 1920comptime height = 1080comptime block = 16
def main(): var grid_x = ceildiv(width, block) var grid_y = ceildiv(height, block) var threads = grid_x * grid_y * block * block print(t"grid_dim = ({grid_x}, {grid_y})") print("threads:", threads, "pixels:", width * height) print("idle:", threads - width * height)Output:
grid_dim = (120, 68)threads: 2088960 pixels: 2073600idle: 153601920 / 16 is exactly 120, but 1080 / 16 is 67.5, so you need 68 rows of blocks. The last row of blocks is half empty: 15,360 idle threads out of about 2 million, which is fine.
2. Find a thread’s position
Section titled “2. Find a thread’s position”With block_dim=(16, 16), a thread has block_idx (1, 2) and thread_idx (3, 0). What are its global_idx.x and global_idx.y?
Hint: apply the formula separately to x and y.
Show solution
comptime block_dim_x = 16comptime block_dim_y = 16
def main(): var block_idx_x = 1 var block_idx_y = 2 var thread_idx_x = 3 var thread_idx_y = 0 var col = block_idx_x * block_dim_x + thread_idx_x var row = block_idx_y * block_dim_y + thread_idx_y print("global_idx.x =", col, " global_idx.y =", row)Output:
global_idx.x = 19 global_idx.y = 32So this thread handles column 19, row 32. In a row-by-row buffer with cols columns, that’s index 32 * cols + 19.
- Kernels read
grid_dim,block_dim,block_idx,thread_idxandglobal_idx, each withx,yandz. global_idx.x == block_dim.x * block_idx.x + thread_idx.x, and the same foryandz.- Launch sizes can be an
Intor a tuple:block_dim=(16, 16)is a 2D block; missing dimensions are 1. - For 2D data, use
xfor columns andyfor rows, and bounds-check both. - Use block sizes that are a multiple of 32, stay under the GPU’s per-block limit, and compute the grid with
ceildivper dimension. - Threads in a block can cooperate through shared memory and
barrier(); no order is guaranteed between threads or blocks.
Next up: Mojo LayoutTensor and TileTensor, a cleaner way to work with 2D data on the GPU.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- GPU programming fundamentals: the official guide to grids, blocks,
global_idxand launching kernels. - Intro to GPUs: how blocks map to streaming multiprocessors and warps, and why partial warps waste resources.
- GPU block and warp operations:
barrier(), block reductions and warp-level operations. max.gpuAPI reference: the index values and other GPU primitives.