Mojo LayoutTensor and TileTensor
Writing grid[row * cols + col] works, but it gets messy fast: every kernel repeats the same index math, and one wrong stride gives silently wrong results. Mojo’s layout package solves this with two ideas: a layout describes how a shape is stored in memory, and a tensor combines a layout with a pointer to the data, so you can write m[row, col]. For a long time the tensor type was called LayoutTensor. Since max 26.7 it’s deprecated, and its replacement is TileTensor. This page teaches TileTensor, and the good news is that nearly all of it runs on the CPU too.
LayoutTensor is now TileTensor
Section titled “LayoutTensor is now TileTensor”You’ll find LayoutTensor in a lot of code written before max 26.7, including older versions of Modular’s own examples. It still compiles in max 26.7.0, but with a warning:
from layout import Layout, LayoutTensor
def main(): var storage = List[Float32](length=6, fill=0) var t = LayoutTensor[DType.float32, Layout.row_major(2, 3)](storage) t[1, 2] = 5 print(t[1, 2])hello.mojo:5:13: warning: Use TileTensor instead var t = LayoutTensor[DType.float32, Layout.row_major(2, 3)](storage) ^~~~~~~~~~~~Modular’s introduction to TileTensor says LayoutTensor is deprecated as of MAX 26.7 and calls TileTensor “essentially a new version” of it. The ideas are the same; one difference you’ll notice right away is how you write a layout (row_major[2, 3]() instead of Layout.row_major(2, 3)). Use TileTensor for new code.
Layouts: shape and stride
Section titled “Layouts: shape and stride”A layout is a small function: give it coordinates like (row, column) and it returns the position in a flat block of memory. It’s described by two lists of numbers:
- The shape: how big each dimension is, like 3 rows and 4 columns.
- The stride: how far to jump in memory when you move one step in that dimension.
A row-major layout stores row 0 first, then row 1, and so on (like C, and like NumPy by default). A column-major layout stores column 0 first. Here are both for a 3 by 4 matrix:
from layout import coord, row_major, col_major
def main(): var rm = row_major[3, 4]() var cm = col_major[3, 4]() print("row-major: ", rm) print("column-major:", cm) print("(1, 2) is at index", rm(coord[1, 2]), "in row-major") print("(1, 2) is at index", cm(coord[1, 2]), "in column-major") print("index 7 is", rm.idx2crd(7), "in row-major")Output:
row-major: ((3, 4):(4, 1))column-major: ((3, 4):(1, 3))(1, 2) is at index 6 in row-major(1, 2) is at index 7 in column-majorindex 7 is (1, 3) in row-majorA layout prints as (shape:stride). Row-major ((3, 4):(4, 1)) means: moving one row jumps 4 places, moving one column jumps 1. So (1, 2) is at 1 * 4 + 2 * 1 = 6. Column-major has strides (1, 3), so (1, 2) is at 1 * 1 + 2 * 3 = 7. coord[1, 2] makes a coordinate, calling the layout with it gives the index, and idx2crd goes the other way.
print_layout draws the whole mapping, which helps a lot when strides get confusing. It takes the older layout type, so you convert with .to_layout():
from layout import print_layout, row_major, col_major
def main(): print_layout(row_major[3, 4]().to_layout()) print_layout(col_major[3, 4]().to_layout())Output:
((3, 4):(4, 1)) 0 1 2 3 +----+----+----+----+ 0 | 0 | 1 | 2 | 3 | +----+----+----+----+ 1 | 4 | 5 | 6 | 7 | +----+----+----+----+ 2 | 8 | 9 | 10 | 11 | +----+----+----+----+((3, 4):(1, 3)) 0 1 2 3 +----+----+----+----+ 0 | 0 | 3 | 6 | 9 | +----+----+----+----+ 1 | 1 | 4 | 7 | 10 | +----+----+----+----+ 2 | 2 | 5 | 8 | 11 | +----+----+----+----+The numbers on the edges are the coordinates; the numbers in the cells are the memory positions.
A TileTensor on the CPU
Section titled “A TileTensor on the CPU”A TileTensor is a layout plus a pointer to memory that belongs to someone else. On the CPU, a List works as that memory:
from layout import TileTensor, row_major
comptime rows = 2comptime cols = 3
def main(): var storage = List[Float32](length=rows * cols, fill=0) var t = TileTensor(storage, row_major[rows, cols]()) for r in range(rows): for c in range(cols): t[r, c] = Float32(r * 10 + c) print(t) print(storage)Output:
[[0.0, 1.0, 2.0], [10.0, 11.0, 12.0]][0.0, 1.0, 2.0, 10.0, 11.0, 12.0]You read and write with t[r, c], and the layout does the r * 3 + c for you. Printing the tensor shows its shape; printing the list shows the same six numbers lying flat in memory, row by row.
Views share the same memory
Section titled “Views share the same memory”Because a tensor is just a view, you can put several views on the same memory. Here the same six numbers are read as rows and as columns:
from layout import TileTensor, row_major, col_major
def main(): var storage: List[Float32] = [1, 2, 3, 4, 5, 6] var by_rows = TileTensor(storage, row_major[2, 3]()) var by_cols = TileTensor(storage, col_major[2, 3]()) print(by_rows) print(by_cols) by_rows[0, 0] = 100 print(by_cols[0, 0])Output:
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]][[1.0, 3.0, 5.0], [2.0, 4.0, 6.0]]100.0Writing through by_rows changes what by_cols sees, because there’s only one copy of the data. Nothing was copied when the views were made.
Tiles: views of a smaller block
Section titled “Tiles: views of a smaller block”The tile method gives you a view of one rectangular piece of a tensor. You say how big the tiles are (as parameters), and which tile you want, counted in tiles, not in elements:
from layout import TileTensor, row_major
comptime rows = 4comptime cols = 6
def main(): var storage = List[Float32](length=rows * cols, fill=0) for i in range(rows * cols): storage[i] = Float32(i) var tensor = TileTensor(storage, row_major[rows, cols]()) print(tensor)
var tile = tensor.tile[2, 3](1, 0) # 2x3 tiles: tile row 1, tile column 0 print(tile) tile[0, 0] = -1 print(tensor[2, 0])Output:
[[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, 20.0, 21.0, 22.0, 23.0]][[12.0, 13.0, 14.0], [18.0, 19.0, 20.0]]-1.0The 4 by 6 tensor splits into 2 by 3 tiles: two tile rows and two tile columns. Tile (1, 0) is the bottom-left one, rows 2 and 3, columns 0 to 2. Inside the tile, indexes start at 0 again, so tile[0, 0] is the same element as tensor[2, 0]. This is the main reason TileTensor exists: on a GPU, each block of threads typically takes one tile and works on it, as you’ll see in GPU matrix multiply.
TileTensor in a kernel
Section titled “TileTensor in a kernel”On the GPU, you build the tensor on the host from a DeviceBuffer and pass it to the kernel, like the vector addition on the first kernel page. Here’s a 2D kernel like the one on the threads page, written with a tensor. It doubles every element of a 5 by 6 matrix:
from std.math import ceildivfrom std.sys import has_accelerator
from max.gpu import global_idxfrom max.gpu.host import DeviceContextfrom layout import TileTensor, row_major
comptime dtype = DType.float32comptime rows = 5comptime cols = 6comptime layout = row_major[rows, cols]()comptime block = 4
def double_it(m: TileTensor[dtype, type_of(layout), MutAnyOrigin]): var row = global_idx.y var col = global_idx.x if row < rows and col < cols: m[row, col] = m[row, col] * 2
def main() raises: comptime if not has_accelerator(): print("No compatible GPU found") else: var ctx = DeviceContext() var host = ctx.enqueue_create_host_buffer[dtype](rows * cols) var dev = ctx.enqueue_create_buffer[dtype](rows * cols) ctx.synchronize() for i in range(rows * cols): host[i] = Float32(i) ctx.enqueue_copy(dst_buf=dev, src_buf=host)
var m = TileTensor(dev, layout) ctx.enqueue_function[double_it]( m, grid_dim=(ceildiv(cols, block), ceildiv(rows, block)), block_dim=(block, block), ) ctx.enqueue_copy(dst_buf=host, src_buf=dev) ctx.synchronize() print(TileTensor(host, layout))What’s new compared with the pointer version:
comptime layout = row_major[rows, cols]()is defined once, at the top, and used for both the kernel’s argument type and the tensors inmain.- The kernel’s argument type is
TileTensor[dtype, type_of(layout), MutAnyOrigin]: element type, layout type, and an origin that says it may be written.type_of(layout)gives the type of the layout value. TileTensor(dev, layout)wraps the device buffer, andTileTensor(host, layout)wraps the host buffer for printing.- Inside the kernel,
m[row, col]replacesgrid[unsafe_offset=row * cols + col].
We compiled it for NVIDIA and AMD targets but couldn’t run it. Here’s the same work on the CPU, one “thread” per cell, using a tensor over a List:
from std.math import ceildivfrom layout import TileTensor, row_major
comptime rows = 5comptime cols = 6comptime layout = row_major[rows, cols]()comptime block = 4
def main(): var storage = List[Float32](length=rows * cols, fill=0) for i in range(rows * cols): storage[i] = Float32(i) var m = TileTensor(storage, layout)
# Visit every (row, col) a 2D grid of 4x4 blocks would cover. for row in range(ceildiv(rows, block) * block): for col in range(ceildiv(cols, block) * block): if row < rows and col < cols: m[row, col] = m[row, col] * 2 print(m)Output:
[[0.0, 2.0, 4.0, 6.0, 8.0, 10.0], [12.0, 14.0, 16.0, 18.0, 20.0, 22.0], [24.0, 26.0, 28.0, 30.0, 32.0, 34.0], [36.0, 38.0, 40.0, 42.0, 44.0, 46.0], [48.0, 50.0, 52.0, 54.0, 56.0, 58.0]]The loop body is word for word the kernel body. That’s a nice side effect of TileTensor working on both sides: you can test the indexing on the CPU first.
Practice
Section titled “Practice”1. Column-major by hand
Section titled “1. Column-major by hand”Put the numbers 1 to 6 in a list and view them as a 2 by 3 column-major tensor. Print it, and print the memory index of (1, 2).
Hint: col_major[2, 3](), and call the layout with coord[1, 2].
Show solution
from layout import TileTensor, coord, col_major
def main(): var storage: List[Float32] = [1, 2, 3, 4, 5, 6] var layout = col_major[2, 3]() var t = TileTensor(storage, layout) print(t) print("(1, 2) is at index", layout(coord[1, 2]))Output:
[[1.0, 3.0, 5.0], [2.0, 4.0, 6.0]](1, 2) is at index 5Column-major strides for 2 rows are (1, 2), so (1, 2) is at 1 * 1 + 2 * 2 = 5, the last element.
2. Clear one corner
Section titled “2. Clear one corner”Make a 4 by 4 row-major tensor holding 0 to 15. Take the bottom-right 2 by 2 tile, print it, then set all its elements to 0 and print the whole tensor.
Hint: with 2 by 2 tiles, the bottom-right one is tile (1, 1).
Show solution
from layout import TileTensor, row_major
def main(): var storage = List[Float32](length=16, fill=0) for i in range(16): storage[i] = Float32(i) var tensor = TileTensor(storage, row_major[4, 4]()) var corner = tensor.tile[2, 2](1, 1) print(corner) for r in range(2): for c in range(2): corner[r, c] = 0 print(tensor)Output:
[[10.0, 11.0], [14.0, 15.0]][[0.0, 1.0, 2.0, 3.0], [4.0, 5.0, 6.0, 7.0], [8.0, 9.0, 0.0, 0.0], [12.0, 13.0, 0.0, 0.0]]The tile is a view, so clearing it clears those four elements in the original tensor too.
LayoutTensoris deprecated sincemax26.7 (“Use TileTensor instead”). UseTileTensorfrom thelayoutpackage for new code.- A layout maps coordinates to memory positions with a shape and a stride:
row_major[3, 4]()prints as((3, 4):(4, 1)). - A
TileTensoris a layout plus borrowed memory: aListon the CPU, aDeviceBufferorHostBufferfor GPU work. Index it witht[row, col]. - Tensors are views: several can share the same data, and there’s no bounds checking.
tile[h, w](i, j)gives a view of one block of the tensor, counted in tiles.- In a kernel, take
TileTensor[dtype, type_of(layout), MutAnyOrigin]; the same indexing code works on the CPU for testing.
Next up: Mojo GPU Matrix Multiply, a classic GPU example built step by step.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Introduction to TileTensor: what
TileTensoris, how it relates toLayoutTensor, and the deprecation note. - TileTensor layouts: shapes, strides, nested and tiled layouts in depth.
- Using TileTensor: creating tensors on the CPU and GPU, tiling, vectorizing and copying.
TileTensorAPI reference: every method, includingtile,loadandstore.- Using LayoutTensor: the old type’s docs, useful when you read older code.