Mojo First GPU Kernel
Time to write a real kernel. This page follows Modular’s official GPU tutorial almost line by line: first a kernel that just prints which thread it is, then one that adds two vectors of 1,000 numbers. Along the way you’ll meet every piece a GPU program needs: a device context, buffers, copies, a kernel launch and a sync.
The shape of every GPU program
Section titled “The shape of every GPU program”Almost every GPU program does the same four things:
- Put the input data in host memory (the CPU’s normal RAM).
- Copy it to device memory (the GPU’s own RAM).
- Launch a kernel that works on the device copy.
- Copy the result back to host memory, so the CPU can use it.
The CPU is in charge the whole time. It tells the GPU what to do through a DeviceContext, and the GPU does the heavy lifting. Keep these four steps in mind; the code below is just these steps written out.
Step 1: a kernel that prints its index
Section titled “Step 1: a kernel that prints its index”A kernel is a normal def function. This one has no arguments and just prints the two numbers that make each thread unique:
from std.sys import has_accelerator
from max.gpu.host import DeviceContextfrom max.gpu import block_idx, thread_idx
def print_threads(): """Print thread IDs."""
print(block_idx.x, thread_idx.x, sep="\t")
def main() raises: comptime if not has_accelerator(): print("No compatible GPU found") else: var ctx = DeviceContext() print("block\tthread") ctx.enqueue_function[print_threads]( grid_dim=2, block_dim=64 ) ctx.synchronize() print("Program finished")Output on a supported GPU, from the official docs (shortened there, and the order changes from run to run):
block thread1 321 331 34...0 300 31Program finishedHere’s what’s new:
block_idxandthread_idxcome frommax.gpu. They’re only meaningful inside a kernel..xis the first dimension (there are also.yand.z, covered on the threads and blocks page).ctx.enqueue_function[print_threads](grid_dim=2, block_dim=64)compiles the kernel for your GPU and queues it to run with 2 blocks of 64 threads: 128 threads in total, so 128 lines. The kernel goes in square brackets, because it’s a compile-time parameter.ctx.synchronize()makes the CPU wait until the GPU has finished everything in the queue. Without it,maincould end before the kernel has even started.- The lines come out in no particular order. All 128 threads run at once, and whichever prints first wins.
Step 2: the vector addition kernel
Section titled “Step 2: the vector addition kernel”Now a kernel that does real work: add two vectors of 1,000 Float32 numbers, one element per thread. Here’s the kernel on its own (the full program follows):
comptime float_dtype = DType.float32comptime vector_size = 1000comptime layout = row_major[vector_size]()
comptime block_size = 256comptime num_blocks = ceildiv(vector_size, block_size)
def vector_addition( lhs_tensor: TileTensor[float_dtype, type_of(layout), ImmutAnyOrigin], rhs_tensor: TileTensor[float_dtype, type_of(layout), ImmutAnyOrigin], out_tensor: TileTensor[float_dtype, type_of(layout), MutAnyOrigin],): """Calculate the element-wise sum of two vectors on the GPU."""
# Calculate the index of the vector element for the thread to process var tid = block_idx.x * block_dim.x + thread_idx.x
# Don't process out of bounds elements if tid < vector_size: out_tensor[tid] = lhs_tensor[tid] + rhs_tensor[tid]Line by line:
- The three arguments are
TileTensors: views of GPU memory that know their element type (float32) and shape (layout, a row of 1,000). The first two are read-only (ImmutAnyOrigin), the last one is written to (MutAnyOrigin). You’ll learnTileTensorproperly on the LayoutTensor page; here you only needtensor[i]. tidis the thread’s global index, the formula from the GPU basics page.block_dim.xis the number of threads per block (256 here).- 1,000 isn’t a multiple of 256, so 4 blocks give 1,024 threads, and the last 24 must do nothing. The
if tid < vector_sizecheck makes sure of that. - The kernel returns nothing. Kernels can’t return values; they write results into memory you passed in.
There’s no loop. On a CPU you’d write for i in range(1000). On the GPU, the loop is replaced by 1,024 threads, each doing one step of it.
Step 3: the whole program
Section titled “Step 3: the whole program”Here’s the complete program from the official tutorial:
from std.math import ceildivfrom std.sys import has_accelerator
from max.gpu.host import DeviceContextfrom max.gpu import block_dim, block_idx, thread_idxfrom layout import TileTensor, row_major
# Vector data type and sizecomptime float_dtype = DType.float32comptime vector_size = 1000comptime layout = row_major[vector_size]()
# Calculate the number of thread blocks needed by dividing the vector size# by the block size and rounding up.comptime block_size = 256comptime num_blocks = ceildiv(vector_size, block_size)
def vector_addition( lhs_tensor: TileTensor[float_dtype, type_of(layout), ImmutAnyOrigin], rhs_tensor: TileTensor[float_dtype, type_of(layout), ImmutAnyOrigin], out_tensor: TileTensor[float_dtype, type_of(layout), MutAnyOrigin],): """Calculate the element-wise sum of two vectors on the GPU."""
# Calculate the index of the vector element for the thread to process var tid = block_idx.x * block_dim.x + thread_idx.x
# Don't process out of bounds elements if tid < vector_size: out_tensor[tid] = lhs_tensor[tid] + rhs_tensor[tid]
def main() raises: comptime if not has_accelerator(): print("No compatible GPU found") else: # Get the context for the attached GPU var ctx = DeviceContext()
# Create HostBuffers for input vectors var lhs_host_buffer = ctx.enqueue_create_host_buffer[float_dtype]( vector_size ) var rhs_host_buffer = ctx.enqueue_create_host_buffer[float_dtype]( vector_size ) ctx.synchronize()
# Initialize the input vectors for i in range(vector_size): lhs_host_buffer[i] = Float32(i) rhs_host_buffer[i] = Float32(Float64(i) * 0.5)
print("LHS buffer: ", lhs_host_buffer) print("RHS buffer: ", rhs_host_buffer)
# Create DeviceBuffers for the input vectors var lhs_device_buffer = ctx.enqueue_create_buffer[float_dtype]( vector_size ) var rhs_device_buffer = ctx.enqueue_create_buffer[float_dtype]( vector_size )
# Copy the input vectors from the HostBuffers to the DeviceBuffers ctx.enqueue_copy(dst_buf=lhs_device_buffer, src_buf=lhs_host_buffer) ctx.enqueue_copy(dst_buf=rhs_device_buffer, src_buf=rhs_host_buffer)
# Create a DeviceBuffer for the result vector var result_device_buffer = ctx.enqueue_create_buffer[float_dtype]( vector_size )
# Wrap the DeviceBuffers in TileTensors var lhs_tensor = TileTensor(lhs_device_buffer, layout) var rhs_tensor = TileTensor(rhs_device_buffer, layout) var result_tensor = TileTensor(result_device_buffer, layout)
# Compile and enqueue the kernel ctx.enqueue_function[vector_addition]( lhs_tensor, rhs_tensor, result_tensor, grid_dim=num_blocks, block_dim=block_size, )
# Create a HostBuffer for the result vector var result_host_buffer = ctx.enqueue_create_host_buffer[float_dtype]( vector_size )
# Copy the result vector from the DeviceBuffer to the HostBuffer ctx.enqueue_copy( dst_buf=result_host_buffer, src_buf=result_device_buffer )
# Finally, synchronize the DeviceContext to run all enqueued operations ctx.synchronize()
print("Result vector:", result_host_buffer)Output on a supported GPU, from the official docs:
LHS buffer: HostBuffer([0.0, 1.0, 2.0, ..., 997.0, 998.0, 999.0])RHS buffer: HostBuffer([0.0, 0.5, 1.0, ..., 498.5, 499.0, 499.5])Result vector: HostBuffer([0.0, 1.5, 3.0, ..., 1495.5, 1497.0, 1498.5])Match the code to the four steps:
- Host data.
enqueue_create_host_buffer[float_dtype](vector_size)makes aHostBuffer: a block of CPU memory that belongs to thisDeviceContextand can be copied to and from the GPU. Thesynchronize()right after waits until it exists, before the loop fills it. - Copy to the device.
enqueue_create_buffermakes aDeviceBufferin GPU memory, andenqueue_copy(dst_buf=..., src_buf=...)queues the copy. A third device buffer will hold the result. - Run the kernel. The device buffers are wrapped in
TileTensors and passed toenqueue_function, together with the grid size (num_blocks, which is 4) and the block size (256). - Copy back. The result is copied into a new
HostBuffer, and the finalsynchronize()waits for the whole queue: copies, kernel and copy back. Only then is it safe to print.
You never free any of the buffers. They’re normal Mojo values, so Mojo destroys them after their last use, like a List (see Mojo Destructors).
The same work on the CPU
Section titled “The same work on the CPU”If you don’t have a GPU, you can still check the logic. This program turns the kernel into a normal function that gets block_idx and thread_idx as arguments, and calls it for every thread the GPU would start:
from std.math import ceildiv
comptime vector_size = 1000comptime block_size = 256comptime num_blocks = ceildiv(vector_size, block_size)
# What ONE GPU thread would do, as a normal CPU function.def vector_addition( block_idx: Int, thread_idx: Int, lhs: List[Float32], rhs: List[Float32], mut result: List[Float32],): var tid = block_idx * block_size + thread_idx if tid < vector_size: result[tid] = lhs[tid] + rhs[tid]
def main(): var lhs = List[Float32](length=vector_size, fill=0) var rhs = List[Float32](length=vector_size, fill=0) for i in range(vector_size): lhs[i] = Float32(i) rhs[i] = Float32(Float64(i) * 0.5)
var result = List[Float32](length=vector_size, fill=0) # The GPU runs all of these at once. The CPU runs them one by one. for block in range(num_blocks): for thread in range(block_size): vector_addition(block, thread, lhs, rhs, result)
print("threads:", num_blocks * block_size) print(result[0], result[1], result[2], "...", result[997], result[998], result[999])Output:
threads: 10240.0 1.5 3.0 ... 1495.5 1497.0 1498.5Same numbers as the GPU result in the official docs. Of course this version is just a slow loop: the point is that one kernel call is one step of a loop, and the GPU runs all the steps at the same time.
Rules for kernel functions
Section titled “Rules for kernel functions”A kernel looks like any def, but it has to follow a few rules (from Modular’s GPU programming fundamentals):
- It can’t raise. Don’t mark it
raises. - It can’t return a value. Write results into a buffer or tensor argument.
- Every argument must be a type the GPU understands (the trait is called
DevicePassable).Float32,Int32and other fixed-size numbers,DeviceBuffers (they arrive as pointers) andTileTensors work. PlainIntdoesn’t: its size depends on the machine, so passing one is a compile error. The GPU memory page shows that error.
enqueue_function checks the argument types against the kernel when the program compiles, so a wrong argument is a compile error, not a crash on the GPU.
Practice
Section titled “Practice”1. Multiply instead of add
Section titled “1. Multiply instead of add”Change the vector program so the kernel multiplies the two vectors element by element instead of adding them. Rename the kernel to vector_multiply.
Hint: only the kernel’s last line and the name inside enqueue_function[...] change.
Show solution
def vector_multiply( lhs_tensor: TileTensor[float_dtype, type_of(layout), ImmutAnyOrigin], rhs_tensor: TileTensor[float_dtype, type_of(layout), ImmutAnyOrigin], out_tensor: TileTensor[float_dtype, type_of(layout), MutAnyOrigin],): var tid = block_idx.x * block_dim.x + thread_idx.x if tid < vector_size: out_tensor[tid] = lhs_tensor[tid] * rhs_tensor[tid]And in main, launch it with ctx.enqueue_function[vector_multiply](...), with the same arguments as before. We compiled this version for NVIDIA and AMD targets; the next exercise checks the numbers on the CPU.
2. Predict the result on the CPU
Section titled “2. Predict the result on the CPU”Use the CPU version from this page to work out what vector_multiply produces. Print elements 0, 1, 2, 998 and 999.
Hint: copy the CPU program and change + to * in the per-thread function.
Show solution
from std.math import ceildiv
comptime vector_size = 1000comptime block_size = 256comptime num_blocks = ceildiv(vector_size, block_size)
def vector_multiply( block_idx: Int, thread_idx: Int, lhs: List[Float32], rhs: List[Float32], mut result: List[Float32],): var tid = block_idx * block_size + thread_idx if tid < vector_size: result[tid] = lhs[tid] * rhs[tid]
def main(): var lhs = List[Float32](length=vector_size, fill=0) var rhs = List[Float32](length=vector_size, fill=0) for i in range(vector_size): lhs[i] = Float32(i) rhs[i] = Float32(Float64(i) * 0.5)
var result = List[Float32](length=vector_size, fill=0) for block in range(num_blocks): for thread in range(block_size): vector_multiply(block, thread, lhs, rhs, result) print(result[0], result[1], result[2], "...", result[998], result[999])Output:
0.0 0.5 2.0 ... 498002.0 499000.5Element i is i * (i * 0.5), so element 999 is 999 * 499.5 = 499000.5. If the kernel is right, a GPU run gives the same values. Keeping a CPU version around like this is a cheap way to test a kernel.
- A GPU program follows four steps: host data, copy to device, run the kernel, copy back.
DeviceContext()is your handle to the GPU. Itsenqueue_...methods only queue work;synchronize()waits for it.enqueue_create_host_bufferandenqueue_create_buffermake CPU-side and GPU-side buffers;enqueue_copymoves data between them.enqueue_function[kernel](args..., grid_dim=..., block_dim=...)compiles and launches a kernel.- A kernel finds its element with
block_idx.x * block_dim.x + thread_idx.x, checks the bounds, and writes its result (no return value, noraises). - A CPU loop that calls the per-thread logic for every index is a simple way to test a kernel’s logic without a GPU.
Next up: Mojo GPU Memory, host and device memory, copying data and the mistakes to avoid.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Get started with GPU programming: the official tutorial this page follows, with more on streaming multiprocessors and warps.
- GPU programming fundamentals:
DeviceContext, buffers, kernel rules andcompile_function. - Vector addition example on GitHub: the finished program from the tutorial, for
max26.7. max.gpuAPI reference:block_idx,thread_idx,block_dim,global_idxand the rest.