Mojo GPU Memory
The biggest difference between GPU code and normal code isn’t the kernel, it’s the memory. A discrete GPU has its own RAM, separate from the CPU’s. The CPU can’t simply read a number the GPU just wrote, and the GPU can’t read your List. Every GPU program has to move data across on purpose, and most beginner GPU bugs are about forgetting a copy or reading too early. This page shows how memory works in Mojo’s GPU API, and the rules that keep you out of trouble.
Two memories
Section titled “Two memories”In GPU programs you’ll see two words all the time:
- Host is the CPU side. Host memory is your computer’s normal RAM, where your variables and lists live.
- Device is the GPU side. Device memory (also called global memory) is the GPU’s own RAM. Every thread of every kernel can read and write it.
A kernel can only work on device memory, and your main can only look at host memory. So data makes a round trip: host, copy to device, kernel, copy back to host. Here’s that round trip acted out on the CPU, with a second list standing in for the GPU’s memory:
def main(): # 1. Data starts in host (CPU) memory. var host: List[Float32] = [0, 1, 2, 3, 4]
# 2. Copy it to "device" memory (here just a second list). var device = host.copy()
# 3. The "kernel" works on the device copy only. for i in range(len(device)): device[i] += 20
print("host before copy back:", host)
# 4. Copy the result back to the host. host = device.copy() print("host after copy back: ", host)Output:
host before copy back: [0.0, 1.0, 2.0, 3.0, 4.0]host after copy back: [20.0, 21.0, 22.0, 23.0, 24.0]The first line is the classic GPU bug: the kernel ran fine, but you looked at the host copy before copying the result back. Nothing warns you; you just see old data.
HostBuffer and DeviceBuffer
Section titled “HostBuffer and DeviceBuffer”Mojo’s GPU API (in max.gpu.host) has one type for each side. Both are made by a DeviceContext:
| Type | Lives in | Made with | Who can read it |
|---|---|---|---|
HostBuffer[dtype] |
Host memory | ctx.enqueue_create_host_buffer[dtype](n) |
Your main (buf[i], print(buf)) |
DeviceBuffer[dtype] |
Device (global) memory | ctx.enqueue_create_buffer[dtype](n) |
Kernels |
Both are normal Mojo values: you never free them by hand, Mojo frees them after their last use. To move data between them, use ctx.enqueue_copy(dst_buf=..., src_buf=...). It works in both directions, and the keyword names make the direction obvious. There are also shortcuts on the buffers themselves: host_buffer.enqueue_copy_to(dst=device_buffer) does the same as the enqueue_copy call.
A complete example: add 20 to every element
Section titled “A complete example: add 20 to every element”This program is from Modular’s GPU programming fundamentals page. It uses a DeviceBuffer directly instead of a TileTensor, and changes the data in place:
from std.math import iotafrom std.sys import exit, has_accelerator
from max.gpu.host import DeviceContextfrom max.gpu import block_dim, block_idx, thread_idx
comptime num_elements = 20
def scalar_add( vector: Pointer[Float32, MutAnyOrigin], size: Int32, scalar: Float32): var idx = block_idx.x * block_dim.x + thread_idx.x if idx < Int(size): vector[unsafe_offset=idx] += scalar
def main() raises: comptime if not has_accelerator(): print("No GPUs detected") exit(0) else: var ctx = DeviceContext()
var host_buffer = ctx.enqueue_create_host_buffer[.float32]( num_elements ) ctx.synchronize()
iota(host_buffer.as_span()) print("Original host buffer:", host_buffer)
var device_buffer = ctx.enqueue_create_buffer[.float32]( num_elements ) ctx.enqueue_copy(src_buf=host_buffer, dst_buf=device_buffer)
var scalar_add_kernel = ctx.compile_function[scalar_add]() ctx.enqueue_function( scalar_add_kernel, device_buffer, Int32(num_elements), Float32(20.0), grid_dim=1, block_dim=num_elements, )
ctx.enqueue_copy(src_buf=device_buffer, dst_buf=host_buffer) ctx.synchronize()
print("Modified host buffer:", host_buffer)Output on a supported GPU, from the official docs:
Original host buffer: HostBuffer([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0])Modified host buffer: HostBuffer([20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0])(We removed the long comments from the official version; the code is the same.) The memory parts, step by step:
iota(host_buffer.as_span())fills the host buffer with 0, 1, 2 and so on.iotais instd.math.- The kernel’s first argument is a
Pointer[Float32, MutAnyOrigin], butmainpasses theDeviceBuffer. That’s on purpose: when aDeviceBuffergoes into a kernel, the kernel receives a pointer to its memory. Inside the kernel,vector[unsafe_offset=idx]reads and writes the element at that position. There’s no bounds check on a pointer, which is why theif idx < Int(size)line matters. - The kernel writes into the same buffer it reads (in place), so the program copies the result back into the original
host_buffer. If you want to keep the input, make a second device buffer for the output, like the vector addition on the previous page. ctx.compile_function[scalar_add]()compiles the kernel once, andenqueue_function(scalar_add_kernel, ...)runs it. That’s handy when you launch the same kernel many times.enqueue_function[scalar_add](...)does both in one step.
Always synchronize before reading
Section titled “Always synchronize before reading”Copies are queued like everything else. enqueue_copy returns at once, long before the data has arrived. The GPU runs the queue in order (copy in, kernel, copy out), but the CPU doesn’t wait unless you tell it to. So the rule is simple:
Call ctx.synchronize() before your CPU code touches a buffer that queued work writes to.
That’s also why the example calls synchronize() right after enqueue_create_host_buffer: even creating the buffer is queued, and the loop that fills it must wait for it to exist.
A shortcut for tests: map_to_host
Section titled “A shortcut for tests: map_to_host”For small tests, a DeviceBuffer can give you a temporary host copy with map_to_host(), used in a with block. Inside the block you read and write it like a host buffer; when the block ends, your changes are copied back to the device:
from std.sys import has_accelerator
from max.gpu import global_idxfrom max.gpu.host import DeviceContext
comptime length = 8
def times_ten(data: Pointer[Float32, MutAnyOrigin], size: Int32): if global_idx.x < Int(size): data[unsafe_offset=global_idx.x] *= 10
def main() raises: comptime if not has_accelerator(): print("No compatible GPU found") else: var ctx = DeviceContext() var buf = ctx.enqueue_create_buffer[DType.float32](length)
# Write the input through a host view of the device buffer. with buf.map_to_host() as host: for i in range(length): host[i] = Float32(i)
ctx.enqueue_function[times_ten]( buf, Int32(length), grid_dim=1, block_dim=length )
# Read the result the same way. with buf.map_to_host() as host: print(host)We compiled this one for NVIDIA and AMD but couldn’t run it, so there’s no output to show. global_idx.x is a shortcut for block_idx.x * block_dim.x + thread_idx.x. The official docs warn against map_to_host in most production code, because each with block copies in both directions and waits for the GPU. For real programs, use explicit host buffers and enqueue_copy.
What a kernel can receive
Section titled “What a kernel can receive”Kernel arguments are copied to the GPU when the kernel starts, so their type has to say how. That’s the DevicePassable trait. The common ones:
| You pass (host) | The kernel receives |
|---|---|
Float32, Int32, Int64 and other fixed-size numbers |
The same number |
DeviceBuffer[dtype] |
A Pointer to its elements |
TileTensor |
A TileTensor |
The one that surprises everybody is Int. Its size depends on the machine, so you can’t pass one to a kernel. Here the kernel takes size: Int and main passes 8:
from std.sys import has_accelerator
from max.gpu.host import DeviceContextfrom max.gpu import global_idx
def add_one(data: Pointer[Float32, MutAnyOrigin], size: Int): if global_idx.x < size: data[unsafe_offset=global_idx.x] += 1
def main() raises: comptime if has_accelerator(): var ctx = DeviceContext() var buf = ctx.enqueue_create_buffer[DType.float32](8) ctx.enqueue_function[add_one](buf, 8, grid_dim=1, block_dim=8) ctx.synchronize()Building it for an NVIDIA GPU (mojo build --target-accelerator=nvidia:sm_80 add_one.mojo) fails. Shortened, the important lines are:
add_one.mojo:10:5: error: function instantiation faileddef main() raises: ^add_one.mojo:14:38: note: call expansion failed with parameter value(s): (..., "target": 0, ..., ..., ..., ..., ..., ..., ..., "_ptxas_info_verbose": False) ctx.enqueue_function[add_one](buf, 8, grid_dim=1, block_dim=8) ^...Mojo/stdlib/std/simd.mojo:662:9: note: constraint failed: Int and UInt do not conform to DevicePassable; use a fixed-width type such as Int32 or Int64 insteadmojo: error: failed to run the pass managerThe useful part is the last note: line. On a machine without a GPU, plain mojo run doesn’t show this error at all, because the comptime if skips the GPU code. Building with --target-accelerator does. Using Int inside a kernel is fine; only the arguments need a fixed size.
Other kinds of GPU memory
Section titled “Other kinds of GPU memory”Device (global) memory is the big one, but it’s also the slowest memory on the GPU. Kernels can use two faster, much smaller kinds:
- Shared memory: a small, fast area per block. All threads in a block see the same shared memory, so they can load data once and reuse it. You’ll use it in the matrix multiply lesson.
- Local memory and registers: private to one thread. Small
vars inside a kernel are normally kept in registers by the compiler.
You don’t copy to these from the host. A kernel fills them itself, from global memory. Modular’s GPU block and warp guide explains how threads coordinate when they share memory.
Practice
Section titled “Practice”1. Simulate scalar_add on the CPU
Section titled “1. Simulate scalar_add on the CPU”Write a CPU program that does what the scalar_add example does with 5 elements: copy the host list to a “device” list, run the kernel logic once per thread index, copy back and print.
Hint: one loop over idx in range(num_elements) plays the role of the threads.
Show solution
comptime num_elements = 5
def main(): var host: List[Float32] = [0, 1, 2, 3, 4] var device = host.copy() # enqueue_copy: host -> device
# The kernel, run once per thread: grid_dim=1, block_dim=num_elements. for idx in range(num_elements): if idx < num_elements: device[idx] += 20.0
host = device.copy() # enqueue_copy: device -> host print(host)Output:
[20.0, 21.0, 22.0, 23.0, 24.0]Same values as the first five elements of the official GPU output. The bounds check never fails here, because there are exactly as many “threads” as elements, but it’s good to keep the kernel’s shape.
2. Fix the Int argument
Section titled “2. Fix the Int argument”Fix the add_one program above so it compiles for a GPU.
Hint: change the kernel’s size argument to a fixed-size type, then convert where you compare and where you call it.
Show solution
def add_one(data: Pointer[Float32, MutAnyOrigin], size: Int32): if global_idx.x < Int(size): data[unsafe_offset=global_idx.x] += 1And in main: ctx.enqueue_function[add_one](buf, Int32(8), grid_dim=1, block_dim=8). The kernel now takes an Int32, and converts it to Int inside to compare with global_idx.x. This version builds for both NVIDIA and AMD targets.
- Host memory is the CPU’s RAM, device memory is the GPU’s. Kernels only see device memory,
mainonly sees host memory. HostBuffer(enqueue_create_host_buffer) andDeviceBuffer(enqueue_create_buffer) are the two sides;enqueue_copy(dst_buf=..., src_buf=...)moves data in either direction.- Everything is queued: call
ctx.synchronize()before the CPU reads a buffer. Reading too early gives old data, not an error. - A
DeviceBufferpassed to a kernel arrives as aPointer; there’s no bounds check, so keep theif idx < sizetest. - Kernel arguments must be
DevicePassable: useInt32/Int64, notInt. map_to_host()is a handy shortcut for tests; GPUs also have faster shared and local memory that kernels manage themselves.
Next up: Mojo GPU Threads & Blocks, how grids and blocks work in two and three dimensions, and how to pick their sizes.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- GPU programming fundamentals: the official guide to
DeviceContext, buffers, copies andDevicePassable. DeviceBufferreference: every method, includingenqueue_copy_toandmap_to_host.HostBufferreference: the host-side buffer and its methods.- GPU block and warp operations: shared memory,
barrier()and how threads in a block work together.