IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /get-started.md). For the complete documentation index, see llms.txt.
Skip to main content
For the complete documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /get-started.md).

GPU buffers and data movement

Before a kernel can run, its input has to be in memory that the GPU can reach, and after it runs, your program has to get the results back. This page shows you how to do that from your host code: how to allocate and initialize GPU memory, move data between the host and one or more devices, keep buffers alive while the GPU uses them, and work with systems that have unified memory.

To understand this page, it helps to be familiar with the GPU memory hierarchy and the TileTensor struct.

Host and device memory​

The host is the CPU and the device is the GPU. On most systems each has its own memory, so you have to copy data to the device before a kernel can use it and copy it back before the host can read the results.

Your host code manages that memory through three kinds of objects:

  • A DeviceContext represents one device. It allocates memory, copies data, and launches kernels by adding operations to a queue.
  • A DeviceBuffer owns memory on the device, and a HostBuffer owns memory on the host.
  • A TileTensor is a view. It gives a kernel shaped access to a buffer's memory, but it doesn't own that memory. See Buffers own memory, tensors view it.

Queued work and synchronization​

Each call whose name starts with enqueue_, on a DeviceContext or on a buffer, adds an operation to the context's queue and returns right away, before the device runs it. The host keeps running while the device works through the queue. The device runs the operations in the order that you queued them, so each one sees the results of the ones before it: a kernel launched after a copy reads the copied data.

To wait for the device, call synchronize(). It returns once every queued operation has finished. Call it before the host reads anything the device wrote, and before the host changes or gives up anything that queued work still uses. This code from host_device_movement.mojo copies an input to the device, runs a kernel on it, and copies the result back:

host_device_movement.mojo
    # Copies and the kernel run in order on the context's stream.
    ctx.enqueue_copy(dev_in, host_in)
    ctx.enqueue_function[scale](
        TileTensor(dev_in, layout).as_imm(),
        TileTensor(dev_out, layout),
        grid_dim=ceildiv(SIZE, BLOCK_SIZE),
        block_dim=BLOCK_SIZE,
    )
    ctx.enqueue_copy(host_out, dev_out)
    # The host must wait before it reads what the device wrote.
    ctx.synchronize()

A timeline with a host row and a device row. The host makes three quick enqueue calls, then waits in synchronize until the device finishes, then reads the result. The device runs the copy in, the kernel, and the copy out one after another, each starting after the host queued it. A timeline with a host row and a device row. The host makes three quick enqueue calls, then waits in synchronize until the device finishes, then reads the result. The device runs the copy in, the kernel, and the copy out one after another, each starting after the host queued it.

Figure 1. Each enqueue_ call returns right away, and the device runs the queued operations in order. synchronize() returns when the last one finishes.

The rest of this page covers each step: how to allocate and fill buffers, how to move data, and how tensors view buffers and keep them alive.

Allocate and initialize buffers​

Three kinds of objects can own the memory that you work with when programming for a GPU:

  • A DeviceBuffer owns an allocation in device memory.
  • A HostBuffer owns an allocation in pinned host memory.
  • A shared-memory allocation, made inside a kernel, belongs to the thread block that runs it. GPU memory hierarchy covers its lifetime.

enqueue_create_buffer() allocates a DeviceBuffer, and enqueue_create_host_buffer() allocates a HostBuffer. Each takes the element type as a parameter and the number of elements as an argument:

var device_buffer = ctx.enqueue_create_buffer[.float32](1024)
var host_buffer = ctx.enqueue_create_host_buffer[.float32](1024)

Both calls are queued operations, so a copy or kernel queued after the allocation can use the buffer right away. The host can't: call synchronize() before your host code writes to or reads from a new HostBuffer:

ctx.synchronize()
for i in range(1024):
    host_buffer[i] = Float32(i * i)

A new buffer's contents are undefined. To set every element of a device buffer to one value, call its enqueue_fill() method, or pass the buffer and the value to enqueue_memset(). The fill is a queued operation too. This line from buffer_management.mojo, a program that computes a * x + y with its inputs and output packed into one device allocation, fills the y input:

buffer_management.mojo
    y_dev.enqueue_fill(Y_VALUE)

Split one allocation into several buffers​

create_sub_buffer() returns a DeviceBuffer that views part of an existing buffer, without copying. Use it to make one allocation and divide it among several tensors. The example packs its two inputs and its output into one allocation:

buffer_management.mojo
    # One allocation holds x, y and the output, back to back.
    var storage = ctx.enqueue_create_buffer[dtype](3 * SIZE)
    # Offsets and sizes count elements, not bytes. Each view shares the
    # allocation and keeps it alive.
    var x_dev = storage.create_sub_buffer[dtype](0, SIZE)
    var y_dev = storage.create_sub_buffer[dtype](SIZE, SIZE)
    var out_dev = storage.create_sub_buffer[dtype](2 * SIZE, SIZE)

One device allocation of three times SIZE elements, divided into x, y, and the output, starting at offsets 0, SIZE, and 2 times SIZE One device allocation of three times SIZE elements, divided into x, y, and the output, starting at offsets 0, SIZE, and 2 times SIZE

Figure 2. One allocation divided into three sub-buffers. Offsets and sizes count elements, not bytes.

The parameter sets the element type of the new buffer, which can differ from the parent's. The two arguments are the offset and the size, both counted in elements of that type. The call raises an error if the range doesn't fit inside the parent buffer.

A sub-buffer is a DeviceBuffer like any other: you can build tensors from it, fill it, and copy to and from it. It also keeps the parent allocation alive, so the memory stays allocated while any sub-buffer still refers to it.

Check available memory​

get_memory_info() returns the free and total device memory, in bytes. Some devices can't measure their free memory, and the call raises an error on them, so call it in a try block:

buffer_management.mojo
    # Some backends can't measure free memory and raise instead.
    try:
        var info = ctx.get_memory_info()
        print("Free device memory (MiB):", Int(info[0]) // (1 << 20))
        print("Total device memory (MiB):", Int(info[1]) // (1 << 20))
    except e:
        print("Device memory info unavailable:", e)

Treat the free value as an estimate: other processes can allocate memory on the same device between the call and your allocation. On a system with unified memory, the total is the memory the GPU can map, which can be less than the machine has. See Unified memory.

Move data​

You can move data between the host and a device, or between two devices.

Copy between host and device buffers​

enqueue_copy() copies from a HostBuffer to a DeviceBuffer or back. The usual pattern is to stage the input in a HostBuffer, copy it to a DeviceBuffer before the kernel runs, and copy the result back after:

ctx.enqueue_copy(dst_buf=device_buffer, src_buf=host_buffer)
# Launch kernels that read and write device_buffer.
ctx.enqueue_copy(dst_buf=host_buffer, src_buf=device_buffer)
ctx.synchronize()

The buffers also have enqueue_copy_to() and enqueue_copy_from() methods, which call enqueue_copy() on their context. These two lines do the same thing:

ctx.enqueue_copy(dst_buf=device_buffer, src_buf=host_buffer)
host_buffer.enqueue_copy_to(dst=device_buffer)

Copy from and to Mojo collections​

enqueue_copy() accepts a Span as the host side of a copy. A Span views the elements of a List or another contiguous collection, so you can copy data that your program already holds without staging it in a HostBuffer or passing a raw pointer:

buffer_management.mojo
    # The copy length comes from the device buffer, so the span must hold
    # at least that many elements.
    ctx.enqueue_copy(x_dev, Span(x_host))

The device buffer sets the number of elements copied, in either direction. Copying to the host works the same way, with a span over a mutable list:

buffer_management.mojo
    ctx.enqueue_copy(Span(out_host), out_dev)

The buffer methods enqueue_copy_from() and enqueue_copy_to() also accept a Span.

A List lives in ordinary host memory, not pinned memory. For small inputs and results, copying a Span is the simplest choice. For large or repeated transfers, stage the data in a HostBuffer, which the device can copy without an extra step.

Each copy is a queued operation, so the host must not read the destination, or change the source, until it calls synchronize(). See Queued work and synchronization.

Copy between device buffers​

enqueue_copy() also copies one DeviceBuffer to another. The destination's size sets the number of elements copied.

The two buffers can also be on different devices that use the same driver, such as two NVIDIA GPUs that use the same CUDA driver. Call enqueue_copy() on the destination buffer's DeviceContext; calling it on another context raises an error. The copy waits for work already queued on the source's context, so it reads the data that work wrote, and it doesn't need peer access between the devices.

Peer access is a separate feature. With it on, a kernel on one device can read and write a buffer on the other device directly, through the buffer's pointer. On NVIDIA and AMD GPUs, a copy between the two devices can also be faster, because it no longer goes through host memory. To check for peer access, call can_access_peer() on one Device with the other as the argument, and turn it on with enable_peer_access().

Map a device buffer for quick access​

map_to_host() gives the host a copy of a device buffer inside a with block, and copies any changes back when the block exits. It's convenient for inspecting a small result or initializing a buffer in a test. It always copies the whole buffer in both directions and synchronizes the context, even on a system with unified memory, so avoid it in code where performance matters:

var input_device = ctx.enqueue_create_buffer[.float32](1024)

with input_device.map_to_host() as input_host:
    for i in range(1024):
        input_host[i] = Float32(i)

Buffers own memory, tensors view it​

A TileTensor owns nothing. It's a view that pairs a pointer into one of the allocations described in Allocate and initialize buffers with a layout that describes the data's shape. You build one from a buffer and a layout.

When a kernel only reads a tensor, pass it an immutable view, which as_imm() returns. The compiler then rejects any write through the view. On a GPU, it also assumes the memory doesn't change while the kernel runs, so it can hoist and cache loads from global memory. For that reason, use an immutable view only for data that nothing writes during the kernel.

The axpy() kernel reads x and y and writes the result, so its launch passes two immutable views and one mutable view:

buffer_management.mojo
    ctx.enqueue_function[axpy](
        TileTensor(x_dev, layout).as_imm(),
        TileTensor(y_dev, layout).as_imm(),
        TileTensor(out_dev, layout),
        grid_dim=ceildiv(SIZE, BLOCK_SIZE),
        block_dim=BLOCK_SIZE,
    )

Assigning one DeviceBuffer variable to another, as in new_buf = old_buf, doesn't copy device memory. Both variables refer to the same allocation, which stays alive until the last value that refers to it is gone. To get a second copy of the data, allocate a second buffer and copy into it, as in old_buf.enqueue_copy_to(dst=new_buf). The two buffers then have separate allocations.

Keep a buffer alive until the work finishes​

Mojo destroys a value right after its last use, not at the end of the scope. For a buffer, the last use in your code is often an enqueue_ call, which returns before the device runs the work. If Mojo destroys the buffer there, the queued work can still be using its memory.

Keep each buffer alive until the queued work that uses it has finished. Some backends free a buffer's memory as soon as Mojo destroys it, even if queued work still uses it. The simplest way is to use the buffer after the synchronize() call that follows its last queued use. To end the buffer's lifetime at that point, assign it to the discard pattern, _, as described in Explicit lifetime extension in the Mojo Manual. The example keeps its one allocation alive this way:

buffer_management.mojo
    ctx.synchronize()
    # Mojo destroys a value after its last use. Using `storage` here keeps
    # the allocation alive until the queued work no longer needs it.
    _ = storage^

A TileTensor that you build from a buffer keeps the buffer alive until the tensor's own last use. That last use is usually an enqueue_ call too, so the same rule applies when you reach the memory only through a tensor.

For more on how Mojo decides when to destroy a value, see Death of a value in the Mojo Manual.

Unified memory​

On some systems the CPU and GPU share one physical pool of memory. Apple silicon works this way, and so do AMD Ryzen AI Max processors such as Strix Halo, whose CPU and GPU memory is physically shared, and NVIDIA DGX Spark.

Sharing physical memory and letting the host access device memory are two separate properties, and a system can have the first without the second:

  • To check whether a device shares physical memory with the host, call is_host_unified() on its Device, as in ctx.device().is_host_unified(). It returns True on the systems above, and False on GPUs with their own memory, such as the NVIDIA B200 and AMD MI355X.
  • Shared physical memory doesn't mean that the host can read or write a DeviceBuffer directly. Today that works only on Apple silicon. On NVIDIA and AMD GPUs, device buffers aren't reachable from the host, even on systems where is_host_unified() returns True.

To move data between the host and the device on every system, use a HostBuffer and enqueue_copy(), as shown in Host and device memory. The calls on this page behave the same everywhere, so the same program runs whether or not the memory is unified.

Unified memory also doesn't mean the GPU can use all of the host's memory. get_memory_info() reports the memory the GPU can map, which can be less than the machine has. On Strix Halo, for example, Linux lets the GPU map about half of system RAM by default.

A kernel that reads ordinary host memory is a third, separate case. Some Linux systems with NVIDIA GPUs support heterogeneous memory management (HMM), which lets a kernel read ordinary host memory. HMM needs a Turing or newer GPU, NVIDIA's open kernel modules with driver 535 or later, and a recent Linux kernel. To see whether a system has it, run nvidia-smi -q and look for Addressing Mode : HMM. On those systems a kernel that mistakenly reads a host address can appear to work, and then fail on a GPU without HMM. Make sure your tests check results, and test on more than one system when you can.

Next steps​

Was this page helpful?