Skip to content

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.

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.x
global_idx.y = block_dim.y * block_idx.y + thread_idx.y
global_idx.z = block_dim.z * block_idx.z + thread_idx.z

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

When you launch a kernel, grid_dim and block_dim each take an Int or a tuple:

  • block_dim=256 means 256 threads in x (and 1 in y and z).
  • block_dim=(16, 16) means a 16 by 16 square of threads, 256 in total (z is 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 DeviceContext
from 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_idx
x y z x y z x y z x y z
-------------------- -------------------- -------------------- --------------------
0 1 0 0 0 0 0 4 0 0 4 0
0 1 0 1 0 0 1 4 0 1 4 0
...
1 1 0 2 3 1 6 7 1 6 7 1
1 1 0 3 3 1 7 7 1 7 7 1
Done

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

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 = 5
comptime cols = 6
comptime 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 threads
0 0 0 0 1 1
0 0 0 0 1 1
0 0 0 0 1 1
0 0 0 0 1 1
2 2 2 2 3 3
idle threads: 34

Two 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 ceildiv
from std.sys import has_accelerator
from max.gpu import global_idx
from max.gpu.host import DeviceContext
comptime rows = 5
comptime cols = 6
comptime block_x = 4
comptime 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.

Choosing sizes is partly an art, but these rules get you a working, reasonable start:

  1. 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.
  2. 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.
  3. Then compute the grid: ceildiv(size, block_size) in each dimension, so every element gets a thread.
  4. 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: 156
n = 1000 blocks: 4 threads: 1024 idle: 24
n = 1024 blocks: 4 threads: 1024 idle: 0
n = 5000 blocks: 20 threads: 5120 idle: 120

A 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 slots
block of 128 threads -> 4 warps, 0 unused slots
block of 256 threads -> 8 warps, 0 unused slots
block of 1000 threads -> 32 warps, 24 unused slots

A block of 100 threads still takes 4 full warps; 28 of their slots do nothing. That’s the example the official docs use too.

  • Threads in the same block can share fast shared memory and wait for each other with barrier() (from max.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.

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 = 1920
comptime height = 1080
comptime 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: 2073600
idle: 15360

1920 / 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.

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 = 16
comptime 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 = 32

So 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_idx and global_idx, each with x, y and z.
  • global_idx.x == block_dim.x * block_idx.x + thread_idx.x, and the same for y and z.
  • Launch sizes can be an Int or a tuple: block_dim=(16, 16) is a 2D block; missing dimensions are 1.
  • For 2D data, use x for columns and y for 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 ceildiv per 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

1. In a kernel launched with block_dim=(8, 8), what is global_idx.x for block_idx.x == 2 and thread_idx.x == 5?
2. You process a matrix with 100 rows and 50 columns using 16x16 blocks. Which launch is right?
3. Why are block sizes like 128 or 256 common?
4. Which statement is true?