Skip to content

Project: GPU Image Filter

Image filters are the classic GPU job: the same small calculation for every pixel, and millions of pixels. In this project you’ll build two filters, invert and blur, on a tiny image that you can see right in the terminal. Then you’ll reshape the code the way a GPU wants it, one thread per pixel, and write the real GPU version with Modular’s max.gpu package.

You’ll practise lists, nested loops, functions, constants, comptime if and the ideas from Mojo GPU Basics and GPU threads and blocks.

A grayscale image is a grid of brightness values: 0 is black, 255 is white. We store it as one flat List[UInt8], row after row, so pixel (x, y) sits at position y * WIDTH + x. UInt8 is an unsigned 8-bit number, exactly the 0 to 255 range a pixel needs.

To see the image in a terminal, we print one character per pixel, from ' ' (dark) to '@' (bright). Our test image is a bright ring and a grey bar, drawn with a little math:

comptime WIDTH = 32
comptime HEIGHT = 16
comptime SHADES = " .:-=+*#%@"
def make_image() -> List[UInt8]:
var pixels = List[UInt8](length=WIDTH * HEIGHT, fill=0)
for y in range(HEIGHT):
for x in range(WIDTH):
# A bright ring. Rows count double: terminal characters are tall.
var dx = x - 11
var dy = (y - 8) * 2
var d2 = dx * dx + dy * dy
if 36 <= d2 <= 100:
pixels[y * WIDTH + x] = 255
# A grey bar on the right.
if 24 <= x <= 27 and 2 <= y <= 13:
pixels[y * WIDTH + x] = 140
return pixels^
def show(pixels: List[UInt8]):
for y in range(HEIGHT):
var line = String()
for x in range(WIDTH):
var v = Int(pixels[y * WIDTH + x])
line += SHADES[byte=v * 10 // 256]
print("|" + line + "|")
def main():
show(make_image())

Output:

| |
| |
| ++++ |
| @ ++++ |
| @@@@@@@@@@@@@ ++++ |
| @@@@@@@@@@@@@@@@@ ++++ |
| @@@@@ @@@@@ ++++ |
| @@@@ @@@@ ++++ |
| @@@@@ @@@@@ ++++ |
| @@@@ @@@@ ++++ |
| @@@@@ @@@@@ ++++ |
| @@@@@@@@@@@@@@@@@ ++++ |
| @@@@@@@@@@@@@ ++++ |
| @ ++++ |
| |
| |

How it works:

  • The ring: a pixel is bright when its squared distance from the center (11, 8) is between 36 and 100, that is, between 6 and 10 away. We double the vertical distance because terminal characters are about twice as tall as they’re wide.
  • v * 10 // 256 turns 0 to 255 into a position from 0 to 9 in SHADES. 255 gives 9 (@), and the grey 140 gives 5 (+).
  • The | at both ends of each line just makes the edges of the image visible.

A real program would load a PNG or JPEG with a library. The filters below work the same way on any grid of numbers, so a hand-made image is enough to learn with.

Inverting turns black into white and the other way round: every pixel v becomes 255 - v. Each pixel only needs its own value, which makes this the simplest filter there is.

comptime WIDTH = 32
comptime HEIGHT = 16
comptime SHADES = " .:-=+*#%@"
def make_image() -> List[UInt8]:
var pixels = List[UInt8](length=WIDTH * HEIGHT, fill=0)
for y in range(HEIGHT):
for x in range(WIDTH):
var dx = x - 11
var dy = (y - 8) * 2
var d2 = dx * dx + dy * dy
if 36 <= d2 <= 100:
pixels[y * WIDTH + x] = 255
if 24 <= x <= 27 and 2 <= y <= 13:
pixels[y * WIDTH + x] = 140
return pixels^
def show(pixels: List[UInt8]):
for y in range(HEIGHT):
var line = String()
for x in range(WIDTH):
var v = Int(pixels[y * WIDTH + x])
line += SHADES[byte=v * 10 // 256]
print("|" + line + "|")
def invert(pixels: List[UInt8]) -> List[UInt8]:
var result = List[UInt8](capacity=len(pixels))
for v in pixels:
result.append(255 - v)
return result^
def main():
show(invert(make_image()))

Output:

|@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@|
|@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@|
|@@@@@@@@@@@@@@@@@@@@@@@@====@@@@|
|@@@@@@@@@@@ @@@@@@@@@@@@====@@@@|
|@@@@@ @@@@@@====@@@@|
|@@@ @@@@====@@@@|
|@@ @@@@@@@@@ @@@====@@@@|
|@@ @@@@@@@@@@@ @@@====@@@@|
|@ @@@@@@@@@@@ @@====@@@@|
|@@ @@@@@@@@@@@ @@@====@@@@|
|@@ @@@@@@@@@ @@@====@@@@|
|@@@ @@@@====@@@@|
|@@@@@ @@@@@@====@@@@|
|@@@@@@@@@@@ @@@@@@@@@@@@====@@@@|
|@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@|
|@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@|

255 - v can never go below 0, because v is at most 255. That matters: UInt8 math wraps around silently, so 10 - 20 in UInt8 would give 246, not -10. For filters that can go out of range, do the math in Int and clamp it before converting back. The Mojo Integer Overflow lesson has the details.

A box blur replaces each pixel with the average of itself and its 8 neighbours. Hard edges turn into soft slopes. Pixels on the border have fewer neighbours, so we only count the ones that are inside the image.

The blur needs its own output list. If we wrote into the input while reading it, a pixel would see neighbours that were already blurred. We put the work for one pixel in its own function; you’ll see why in the next step.

comptime WIDTH = 32
comptime HEIGHT = 16
comptime SHADES = " .:-=+*#%@"
def make_image() -> List[UInt8]:
var pixels = List[UInt8](length=WIDTH * HEIGHT, fill=0)
for y in range(HEIGHT):
for x in range(WIDTH):
var dx = x - 11
var dy = (y - 8) * 2
var d2 = dx * dx + dy * dy
if 36 <= d2 <= 100:
pixels[y * WIDTH + x] = 255
if 24 <= x <= 27 and 2 <= y <= 13:
pixels[y * WIDTH + x] = 140
return pixels^
def show(pixels: List[UInt8]):
for y in range(HEIGHT):
var line = String()
for x in range(WIDTH):
var v = Int(pixels[y * WIDTH + x])
line += SHADES[byte=v * 10 // 256]
print("|" + line + "|")
def blur_pixel(src: List[UInt8], mut dst: List[UInt8], x: Int, y: Int):
var total = 0
var count = 0
for dy in range(-1, 2):
for dx in range(-1, 2):
var nx = x + dx
var ny = y + dy
if 0 <= nx < WIDTH and 0 <= ny < HEIGHT:
total += Int(src[ny * WIDTH + nx])
count += 1
dst[y * WIDTH + x] = UInt8(total // count)
def blur(src: List[UInt8]) -> List[UInt8]:
var dst = List[UInt8](length=len(src), fill=0)
for y in range(HEIGHT):
for x in range(WIDTH):
blur_pixel(src, dst, x, y)
return dst^
def main():
show(blur(make_image()))

Output:

| |
| .... |
| ... .:--:. |
| .:----===----:. .-++-. |
| .:=+****###****+=:. .-++-. |
| .-+#%%#*******#%%#+-. .-++-. |
| :+%@%*=-------=*%@%+: .-++-. |
|.=#@@#=. .=#@@#=..-++-. |
|.=#@@*- -*@@#=..-++-. |
|.=#@@#=. .=#@@#=..-++-. |
| :+%@%*=-------=*%@%+: .-++-. |
| .-+#%%#*******#%%#+-. .-++-. |
| .:=+****###****+=:. .-++-. |
| .:----===----:. .:--:. |
| ... .... |
| |

The ring and the bar now fade out at their edges. Notice two details in blur_pixel:

  • total is an Int, not a UInt8. Nine pixels of 255 add up to 2,295, which doesn’t fit in a UInt8. We only convert back with UInt8(...) after dividing, when the average is between 0 and 255 again.
  • 0 <= nx < WIDTH is a chained comparison, the same as in Python. It keeps us inside the image at the borders.

On a CPU, blur walks through the pixels one after another. A GPU works differently: it starts thousands of threads, and every thread runs the same function on a different piece of data. For an image, the natural choice is one thread per pixel. blur_pixel(x, y) is already exactly that function: it only needs to know which pixel it’s responsible for.

GPU threads are grouped into blocks (for example 16 by 16 threads), and the blocks form a grid that covers the whole image. Each thread works out its pixel from its block number and its position inside the block:

x = block_idx.x * block_dim.x + thread_idx.x
y = block_idx.y * block_dim.y + thread_idx.y

Our image is 32 by 16, so with 16 by 16 blocks we need a grid of 2 by 1 blocks. If the image were 33 pixels wide we’d need 3 blocks across, and the threads in the third block that land past the edge must do nothing. That’s the bounds check every GPU kernel starts with.

Here’s that whole scheme simulated on the CPU, with plain loops standing in for blocks and threads. It prints how the work was split, and the same blurred image as Step 3:

from std.math import ceildiv
comptime WIDTH = 32
comptime HEIGHT = 16
comptime BLOCK = 16
comptime SHADES = " .:-=+*#%@"
def make_image() -> List[UInt8]:
var pixels = List[UInt8](length=WIDTH * HEIGHT, fill=0)
for y in range(HEIGHT):
for x in range(WIDTH):
var dx = x - 11
var dy = (y - 8) * 2
var d2 = dx * dx + dy * dy
if 36 <= d2 <= 100:
pixels[y * WIDTH + x] = 255
if 24 <= x <= 27 and 2 <= y <= 13:
pixels[y * WIDTH + x] = 140
return pixels^
def show(pixels: List[UInt8]):
for y in range(HEIGHT):
var line = String()
for x in range(WIDTH):
var v = Int(pixels[y * WIDTH + x])
line += SHADES[byte=v * 10 // 256]
print("|" + line + "|")
# What one GPU thread would do.
def blur_thread(src: List[UInt8], mut dst: List[UInt8], x: Int, y: Int):
if x >= WIDTH or y >= HEIGHT:
return # this thread is past the edge of the image
var total = 0
var count = 0
for dy in range(-1, 2):
for dx in range(-1, 2):
var nx = x + dx
var ny = y + dy
if 0 <= nx < WIDTH and 0 <= ny < HEIGHT:
total += Int(src[ny * WIDTH + nx])
count += 1
dst[y * WIDTH + x] = UInt8(total // count)
def main():
var src = make_image()
var dst = List[UInt8](length=len(src), fill=0)
var grid_x = ceildiv(WIDTH, BLOCK)
var grid_y = ceildiv(HEIGHT, BLOCK)
print(t"grid: {grid_x} x {grid_y} blocks of {BLOCK} x {BLOCK} threads")
# On a GPU, all of these run at the same time. Here we loop.
for block_y in range(grid_y):
for block_x in range(grid_x):
for thread_y in range(BLOCK):
for thread_x in range(BLOCK):
var x = block_x * BLOCK + thread_x
var y = block_y * BLOCK + thread_y
blur_thread(src, dst, x, y)
show(dst)

Output:

grid: 2 x 1 blocks of 16 x 16 threads
| |
| .... |
| ... .:--:. |
| .:----===----:. .-++-. |
| .:=+****###****+=:. .-++-. |
| .-+#%%#*******#%%#+-. .-++-. |
| :+%@%*=-------=*%@%+: .-++-. |
|.=#@@#=. .=#@@#=..-++-. |
|.=#@@*- -*@@#=..-++-. |
|.=#@@#=. .=#@@#=..-++-. |
| :+%@%*=-------=*%@%+: .-++-. |
| .-+#%%#*******#%%#+-. .-++-. |
| .:=+****###****+=:. .-++-. |
| .:----===----:. .:--:. |
| ... .... |
| |

ceildiv(a, b) from std.math divides and rounds up, so a partly filled block still gets counted. The four nested loops are what the GPU does for you in hardware: you write only the body, blur_thread, and say how big the grid and blocks are.

Here’s the same blur as a real GPU program. It follows the patterns from Modular’s Get started with GPU programming tutorial. In Mojo 1.2 the GPU APIs live in the max package, not in the standard library, so add it to your project first:

Terminal window
uv add max

Then gpu_blur.mojo:

from std.math import ceildiv
from std.sys import has_accelerator
from max.gpu import global_idx
from max.gpu.host import DeviceContext
comptime WIDTH = 32
comptime HEIGHT = 16
comptime BLOCK = 16
comptime SHADES = " .:-=+*#%@"
def blur_kernel(
src: Pointer[UInt8, MutAnyOrigin],
dst: Pointer[UInt8, MutAnyOrigin],
width: Int32,
height: Int32,
):
var x = global_idx.x
var y = global_idx.y
if x >= Int(width) or y >= Int(height):
return
var total = 0
var count = 0
for dy in range(-1, 2):
for dx in range(-1, 2):
var nx = x + dx
var ny = y + dy
if 0 <= nx < Int(width) and 0 <= ny < Int(height):
total += Int(src[unsafe_offset=ny * Int(width) + nx])
count += 1
dst[unsafe_offset=y * Int(width) + x] = UInt8(total // count)
def make_image() -> List[UInt8]:
var pixels = List[UInt8](length=WIDTH * HEIGHT, fill=0)
for y in range(HEIGHT):
for x in range(WIDTH):
var dx = x - 11
var dy = (y - 8) * 2
var d2 = dx * dx + dy * dy
if 36 <= d2 <= 100:
pixels[y * WIDTH + x] = 255
if 24 <= x <= 27 and 2 <= y <= 13:
pixels[y * WIDTH + x] = 140
return pixels^
def main() raises:
comptime if not has_accelerator():
print("No compatible GPU found")
else:
var ctx = DeviceContext()
print("Running on:", ctx.name())
var image = make_image()
# 1. Put the image in a host buffer, then copy it to the GPU.
var host = ctx.enqueue_create_host_buffer[DType.uint8](WIDTH * HEIGHT)
ctx.synchronize()
for i in range(WIDTH * HEIGHT):
host[i] = image[i]
var src = ctx.enqueue_create_buffer[DType.uint8](WIDTH * HEIGHT)
var dst = ctx.enqueue_create_buffer[DType.uint8](WIDTH * HEIGHT)
ctx.enqueue_copy(dst_buf=src, src_buf=host)
# 2. One thread per pixel, in 16 x 16 blocks.
ctx.enqueue_function[blur_kernel](
src,
dst,
Int32(WIDTH),
Int32(HEIGHT),
grid_dim=(ceildiv(WIDTH, BLOCK), ceildiv(HEIGHT, BLOCK)),
block_dim=(BLOCK, BLOCK),
)
# 3. Copy the result back and wait for the GPU to finish.
ctx.enqueue_copy(dst_buf=host, src_buf=dst)
ctx.synchronize()
for y in range(HEIGHT):
var line = String()
for x in range(WIDTH):
line += SHADES[byte=Int(host[y * WIDTH + x]) * 10 // 256]
print("|" + line + "|")

The kernel, blur_kernel, is blur_thread from Step 4 with three changes:

  • global_idx.x and global_idx.y give the thread its pixel. They’re the block_idx * block_dim + thread_idx formula from Step 4, worked out for you.
  • The image arrives as a Pointer, not a List. You can’t pass a List to a GPU. Instead you copy the pixels into a DeviceBuffer in the GPU’s memory, and the kernel receives a pointer to it. src[unsafe_offset=i] reads the i-th value, with no bounds check, which is why the if at the top matters.
  • width and height are Int32, not Int. Int’s size depends on the machine, and the GPU docs say it can’t be passed to a kernel. We tried: passing WIDTH as an Int fails to compile with “Int and UInt do not conform to DevicePassable; use a fixed-width type such as Int32 or Int64 instead”.

And main does the GPU housekeeping:

  • comptime if not has_accelerator() checks at compile time whether there’s a GPU Mojo can use. Without one, the GPU branch isn’t even compiled, and the program just prints a message. has_accelerator is in the standard library.
  • DeviceContext() connects to the GPU. Everything that starts with enqueue_ is put in a queue and runs later, in order, on the GPU. ctx.synchronize() waits until the queue is done.
  • Host buffer to device buffer and back: the CPU and the GPU have separate memory, so data is copied over before the kernel runs and copied back after. For a tiny image the copies cost more than the blur itself; GPUs pay off when there’s a lot of work per copy.
  • enqueue_function[blur_kernel](..., grid_dim=..., block_dim=...) compiles the kernel for your GPU and launches it with a 2 by 1 grid of 16 by 16 blocks, the same numbers as our simulation.

On a supported GPU this should print the name of the GPU and then the same blurred picture as Step 3. We couldn’t check that: on our machine, without a GPU, it prints:

No compatible GPU found

Step 6: Check that the kernel compiles, without a GPU

Section titled “Step 6: Check that the kernel compiles, without a GPU”

On a machine without a GPU, comptime if skips the GPU branch, so a mistake in your kernel goes unnoticed. You can still ask the compiler to build for a specific GPU with --target-accelerator and the GPU’s architecture name from the hardware compatibility page, for example sm_80 for an NVIDIA A100 or gfx942 for an AMD MI300X:

Terminal window
mojo build --target-accelerator sm_80 gpu_blur.mojo -o gpu_blur

On our machine this built without errors, and so did gfx942. The built program really contains the compiled kernel, but running it here fails at DeviceContext(), because there’s no NVIDIA driver:

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 the honest limit of what we could test: the GPU code compiles for both NVIDIA and AMD targets, and the CPU version of the same algorithm gives the picture you saw above. Mistakes in kernels do show up this way. When we passed WIDTH as an Int instead of Int32, the normal mojo run still printed “No compatible GPU found”, but the --target-accelerator build failed with the DevicePassable error from Step 5.

  • Threshold. Make every pixel either 0 or 255 depending on whether it’s above 128. (Practice 1.)
  • A bigger blur. Average a 5 by 5 square instead of 3 by 3, with the size as a comptime parameter.
  • Edge detection. Subtract each pixel’s left neighbor from its right neighbor and show where the result is large. Do the math in Int, because UInt8 would wrap.
  • Load a real image with Pillow through Python interop, turn it into a List[UInt8], filter it, and save it back.
  • Time it. On a GPU, try a 4000 by 4000 image and compare with the CPU version from Step 3, as in Mojo Benchmarking.

Write def threshold(pixels: List[UInt8], level: UInt8) -> List[UInt8] that turns every pixel above level into 255 and every other pixel into 0. Test it on the pixels [0, 100, 128, 129, 200, 255] with level 128. Then try it on the blurred image from Step 3.

Hint: it’s invert with an if inside.

Show solution
def threshold(pixels: List[UInt8], level: UInt8) -> List[UInt8]:
var result = List[UInt8](capacity=len(pixels))
for v in pixels:
result.append(UInt8(255) if v > level else UInt8(0))
return result^
def main():
var pixels: List[UInt8] = [0, 100, 128, 129, 200, 255]
print(threshold(pixels, 128))

Output:

[0, 0, 0, 255, 255, 255]

UInt8(255) if ... else UInt8(0) spells out the type on purpose: with plain 255 and 0, the conditional expression is an Int, and append on a List[UInt8] refuses it (“cannot be converted from ‘Int’ to ‘UInt8’”). 128 itself becomes 0, because the test is “above”, not “at least”. On the blurred image, threshold keeps the middle of the ring and of the grey bar and drops the soft edges: a common way to clean up a noisy picture.

A full HD image is 1920 by 1080 pixels. With 16 by 16 blocks, how many blocks does the grid need in each direction, how many in total, and how many threads end up past the bottom edge?

Hint: ceildiv from std.math for the grid; the threads past the edge are the extra rows in the last row of blocks.

Show solution
from std.math import ceildiv
def main():
var width = 1920
var height = 1080
var block = 16
var grid_x = ceildiv(width, block)
var grid_y = ceildiv(height, block)
print("grid:", grid_x, "x", grid_y, "=", grid_x * grid_y, "blocks")
print("threads:", grid_x * block * grid_y * block)
print("past the edge:", (grid_y * block - height) * grid_x * block)

Output:

grid: 120 x 68 = 8160 blocks
threads: 2088960
past the edge: 15360

1080 isn’t a multiple of 16, so the last row of blocks sticks out by 8 rows. Those 15,360 threads start, see they’re past the edge, and return right away. That’s why every kernel starts with a bounds check.

  • An image is a flat list of brightness values; pixel (x, y) is at y * WIDTH + x. UInt8 fits 0 to 255 but wraps on overflow, so do sums in Int.
  • Filters that write a new output and read each pixel’s neighbours, like blur, are a perfect fit for one thread per pixel.
  • A GPU thread finds its pixel with block_idx * block_dim + thread_idx (or global_idx), and must check the bounds, because the grid is rounded up with ceildiv.
  • In Mojo 1.2 the GPU APIs are in the max package (uv add max): DeviceContext, buffers, enqueue_copy, enqueue_function and synchronize. Pass Int32, not Int, to a kernel.
  • comptime if has_accelerator() keeps the program running without a GPU, and mojo build --target-accelerator checks that the kernel compiles. We could only do that; running it needs a supported GPU.

Next up: Mojo Exercises, a collection of small practice problems for everything you’ve learned.

Quick check

1. Why does blur write into a new list instead of changing the image in place?
2. A kernel runs with 16 by 16 blocks on an image 33 pixels wide. What must the kernel do first?
3. Why are width and height passed to the kernel as Int32?
4. On a machine without a GPU, how can you check that your kernel compiles?