This document is relevant for: Trn2, Trn3

Tile-grid fundamentals#

NKI instructions operate on tiles, while kernel inputs and outputs are usually larger tensors in HBM. nl.tiles() gives those tensors a grid of tile coordinates, so a kernel can work with one tile, a row or column of tiles, or a larger region without calculating element offsets by hand.

Once you select a region, the grid view carries the geometry needed to allocate matching storage in SBUF and form operands for NKI instructions. A typical kernel therefore follows the same sequence:

  1. Organize a tensor as a grid of tiles.

  2. Select the region needed for the next computation.

  3. Allocate matching or explicitly shaped on-chip storage.

  4. Move the region into that storage.

  5. Compute with existing NKI instructions.

This avoids describing the same region separately for HBM access, SBUF allocation, and each instruction operand. Tile grids preserve NKI’s explicit execution model: you still choose the tile sizes, memory locations, transfers, loops, and instructions. The grid simply keeps those choices tied to the same logical region.

In this tutorial, you will:

  • create a tile grid over an HBM tensor;

  • organize higher-rank tensors with leading batch dimensions;

  • select tiles with static indices and slices;

  • expose a selection as an ISA-compatible NkiTensor with .data;

  • recognize when a selection can be exposed as one NkiTensor;

  • allocate matching or explicitly shaped tile-grid storage in SBUF;

  • move selected regions between HBM and SBUF; and

  • progress from a simple tiled matmul to one that hoists a reusable LHS region.

This tutorial assumes familiarity with HBM, SBUF, PSUM, and NKI ISA instructions.

Create a tile grid#

Calling nl.tiles() gives an existing tensor a grid of tile coordinates, where each coordinate names one region of the backing tensor. The view is immutable and zero-copy, so creating it neither allocates storage nor moves data; both remain explicit steps.

src_tiles = nl.tiles(src, tile_shape=(128, 512))

src_tiles.shape                # Number of tile coordinates.
src_tiles.tile_shape           # Nominal elements in one tile.
src_tiles.element_shape        # Exact elements represented by the view.
src_tiles.index_step_elements  # Element step per grid coordinate.
src_tiles.data                 # NkiTensor operand for nisa.* calls.

Choose tile_shape for the instruction that will consume the data. For example, nc_matmul() commonly uses (128, 128) tiles for its stationary operand and (128, 512) tiles for its moving operand.

A tensor decomposed into a four by four tile grid.

Fig. 18 Each coordinate identifies one tile-sized region of the source tensor.#

Index and slice static regions#

Tile-grid indexing follows the same rules as a NumPy array: an integer picks one coordinate and consumes that grid dimension, while a slice preserves it. You can use the same syntax to select individual tiles, rows, columns, and rectangular regions, written with negative indices or steps where useful.

Six grids showing scalar, row, column, rectangular, negative-index, and stepped tile selections.

Fig. 19 Integers consume a grid dimension; slices preserve it. Negative indices and stepped slices use normal Python indexing semantics.#

Use .data with ISA instructions#

Indexing and slicing return grid views so that you can continue selecting regions or allocate storage with the same geometry. Even selecting src_tiles[1, 2] (a single tile) is still a grid view rather than a NkiTensor.

ISA instructions accept NkiTensor operands. When you are ready to pass a selected region to an instruction, access data:

Expression

Value

Typical use

src_tiles[key]

Tile-grid view

Index, slice, or allocate matching storage

src_tiles[key].data

HBM NkiTensor

Source operand for nisa.dma_copy

src_sbuf.data

SBUF NkiTensor

Destination or compute operand for nisa.*

Calling .data changes how you address the region, not where the data lives. A view backed by HBM yields an HBM NkiTensor; a view backed by SBUF yields an SBUF NkiTensor. Data moves only when the kernel issues an instruction such as nisa.dma_copy.

Most individual tiles and regular regions can be exposed as one NkiTensor. A later section, Know when .data is representable, shows why a selection that mixes different partition extents must be split first.

Select, allocate, and move#

To bring a region into SBUF, first index the HBM tile grid with key. Pass the resulting view to nl.empty_like() to allocate SBUF storage with matching geometry, then use the two .data operands in nisa.dma_copy:

src_view = src_tiles[key]                            # select HBM memory region
src_sbuf = nl.empty_like(src_view, buffer=nl.sbuf)   # allocate SBUF memory
nisa.dma_copy(dst=src_sbuf.data, src=src_view.data)  # copy data from HBM to SBUF

nl.empty_like() derives the SBUF allocation from src_view, so you do not need to calculate its shape separately.

Allocate a tile grid directly#

nl.empty_like() is convenient when an existing grid view already describes the storage a kernel needs. Scratch space, initialized results, and accumulator grids may not have a source view to copy. Use nl.alloc_tiles() when the kernel should define the tile geometry and logical element extent directly.

Allocation

Geometry

Typical use

nl.empty_like(view, ...)

Derived from view

Stage a selected HBM or on-chip region

nl.alloc_tiles(...)

Supplied with tile_shape, element_shape, and dtype

Allocate new independent storage

nl.alloc_tiles() creates one independent, uninitialized backing allocation and returns an indexable NkiTileGrid; it does not create a separate allocation for every tile. The buffer argument places that allocation in SBUF, PSUM, or shared HBM, subject to the constraints of the selected memory region. The returned grid supports the same metadata, indexing, and .data access as a view created by nl.tiles().

A complete tiled kernel#

scale_kernel puts this sequence inside a complete kernel. It creates tile grids over the HBM input and output, visits each coordinate, loads the input tile into SBUF, scales it, and writes the result back to HBM:

 1@nki.jit
 2def scale_kernel(src, factor=2.0):
 3    """Scale each tile independently."""
 4    # src is a 2D tensor, for example (512, 512).
 5    tile_shape = (128, 128)
 6    dst = nl.ndarray(src.shape, dtype=src.dtype, buffer=nl.shared_hbm)
 7    src_tiles = nl.tiles(src, tile_shape=tile_shape)
 8    dst_tiles = nl.tiles(dst, tile_shape=tile_shape)
 9
10    for i in range(src_tiles.shape[0]):
11        for j in range(src_tiles.shape[1]):
12            tile_sbuf = nl.empty_like(src_tiles[i, j], buffer=nl.sbuf)
13            nisa.dma_copy(tile_sbuf.data, src_tiles[i, j].data)
14            nisa.tensor_scalar(tile_sbuf.data, tile_sbuf.data, nl.multiply, factor)
15            nisa.dma_copy(dst_tiles[i, j].data, tile_sbuf.data)
16    return dst
17
18

Build a simple tiled matmul#

Matrix multiplication follows the same workflow, but each output tile depends on several pairs of input tiles. To compute out_tiles[m, n] for out = lhs_t.T @ rhs, the kernel walks across k, loads lhs_tiles[k, m] and rhs_tiles[k, n] into SBUF, and accumulates each product in PSUM. Here, K is the reduction dimension and maps to the partition dimension of both Tensor Engine inputs. After the final k step, the kernel copies the completed tile through SBUF to out_tiles[m, n] in HBM.

Operand

Element shape

Tile shape

Role

lhs_t

(K, M)

(128, 128)

Stationary

rhs

(K, N)

(128, 512)

Moving

out

(M, N)

(128, 512)

PSUM destination

Three tile grids showing fixed lhsT and rhs tile columns paired across k to compute one output tile.

Fig. 20 Fixing (m, n) selects one output tile. The k loop walks corresponding tiles from the lhsT and rhs grids.#

 1@nki.jit
 2def matmul_simple(lhs_t, rhs):
 3    """Compute ``lhs_t.T @ rhs`` one output tile at a time."""
 4    out = nl.ndarray(
 5        (lhs_t.shape[1], rhs.shape[1]), dtype=lhs_t.dtype, buffer=nl.shared_hbm
 6    )
 7    # Define tile-grid views over the HBM inputs and output.
 8    lhs_tiles = nl.tiles(lhs_t, tile_shape=(128, 128))
 9    rhs_tiles = nl.tiles(rhs, tile_shape=(128, 512))
10    out_tiles = nl.tiles(out, tile_shape=(128, 512))
11
12    for m in range(out_tiles.shape[0]):
13        for n in range(out_tiles.shape[1]):
14            # Accumulate one output tile across K in PSUM.
15            out_psum = nl.ndarray((128, 512), dtype=nl.float32, buffer=nl.psum)
16            for k in nl.affine_range(lhs_tiles.shape[0]):
17                # Load the current lhsT and rhs tiles from HBM into SBUF.
18                lhs_sbuf = nl.empty_like(lhs_tiles[k, m], buffer=nl.sbuf)
19                rhs_sbuf = nl.empty_like(rhs_tiles[k, n], buffer=nl.sbuf)
20                nisa.dma_copy(dst=lhs_sbuf.data, src=lhs_tiles[k, m].data)
21                nisa.dma_copy(dst=rhs_sbuf.data, src=rhs_tiles[k, n].data)
22                nisa.nc_matmul(
23                    dst=out_psum,
24                    stationary=lhs_sbuf.data,
25                    moving=rhs_sbuf.data,
26                    accumulate=k > 0,
27                )
28            # Move the completed tile from PSUM through SBUF to HBM.
29            out_sbuf = nl.ndarray((128, 512), dtype=nl.float32, buffer=nl.sbuf)
30            nisa.tensor_copy(dst=out_sbuf, src=out_psum)
31            nisa.dma_copy(dst=out_tiles[m, n].data, src=out_sbuf)
32    return out
33
34

This first version loads both input tiles inside the k loop. When n changes, it loads the same lhs_tiles[k, m] tile again even though m and k have not changed.

Hoist the reusable LHS column#

For a fixed m, the column lhs_tiles[:, m] does not change as n advances. Load that column into SBUF before entering the n loop, then index the loaded grid from the inner k loop:

for m in range(out_tiles.shape[0]):
    lhs_col_view = lhs_tiles[:, m]
    lhs_sbuf = nl.empty_like(lhs_col_view, buffer=nl.sbuf)
    nisa.dma_copy(dst=lhs_sbuf.data, src=lhs_col_view.data)

    for n in range(out_tiles.shape[1]):
        for k in range(lhs_col_view.shape[0]):
            lhs_tile_sbuf = lhs_sbuf[k].data
            rhs_view = rhs_tiles[k, n]
            # Load rhs_view into SBUF and accumulate with lhs_tile_sbuf.

The original kernel reads one LHS tile from HBM for every (m, n, k) iteration. After hoisting, it reads one for every (m, k) and reuses that SBUF tile across all n coordinates. See matmul_hoist_lhs in matmul.py for the complete implementation.

Tile higher-rank tensors#

nl.tiles() also supports tensors and tiles with more than two dimensions. The rank of tile_shape determines whether a source dimension belongs to each tile or remains a leading grid coordinate.

For a source with rank N and a tile_shape with rank T, the first N - T source dimensions remain leading coordinates. The final T dimensions are divided into tiles. The first dimension covered by tile_shape becomes the partition dimension.

Tile every source dimension#

When tile_shape has the same rank as the source, every source dimension is tiled:

# src.shape == (256, 4, 1024)
src_tiles = nl.tiles(src, tile_shape=(128, 2, 512))

src_tiles.shape       # (2, 2, 2)
src_tiles.tile_shape  # (128, 2, 512)

tile_view = src_tiles[0, 1, 0]
tile_view.data.shape  # (128, 2, 512)

The first tile extent, 128, is the partition extent. The remaining tile dimensions belong to the free-dimension traversal.

Preserve leading batch dimensions#

When tile_shape has fewer dimensions than the source, the unmatched leading dimensions remain grid coordinates:

# src.shape == (8, 256, 1024)
src_tiles = nl.tiles(src, tile_shape=(128, 512))

src_tiles.shape       # (8, 2, 2)
src_tiles.tile_shape  # (128, 512)

Here, dimension 0 is a leading batch coordinate. Dimensions 1 and 2 are tiled, and dimension 1 supplies the partition extent.

batch_tiles = src_tiles[batch]
tile_view = batch_tiles[0, 1]

batch_tiles.shape     # (2, 2)
tile_view.data.shape  # (128, 512)

For ordinary per-batch computation, consume the leading coordinates before accessing .data. This produces the expected 128 x 512 operand for DMA and compute instructions.

Retain a leading dimension intentionally#

A leading dimension does not have to be consumed before .data. For example, this selection keeps all eight batch coordinates while choosing one tile coordinate:

batch_view = src_tiles[:, 0, 0]

batch_view.element_shape  # (8, 128, 512)
batch_view.data.shape     # (128, 8, 512)

The native operand moves the partition dimension first. If matching SBUF storage is allocated, the batch entries are packed as slots along the free dimension:

batch_sbuf = nl.empty_like(batch_view, buffer=nl.sbuf)
nisa.dma_copy(dst=batch_sbuf.data, src=batch_view.data)

Conceptually, the SBUF allocation is packed as:

             free dimension
P=0       [ batch 0 ][ batch 1 ] ... [ batch 7 ]
P=1       [ batch 0 ][ batch 1 ] ... [ batch 7 ]
...
P=127     [ batch 0 ][ batch 1 ] ... [ batch 7 ]

All 128 partitions remain active. Keeping the batch dimension selected only adds batch slots to the free-dimension traversal.

Choose which dimensions belong to each tile#

The following grid has the same navigation shape, but different tile semantics:

# src.shape == (8, 256, 1024)
src_tiles = nl.tiles(src, tile_shape=(1, 128, 512))

src_tiles.shape       # (8, 2, 2)
src_tiles.tile_shape  # (1, 128, 512)
src_tiles[0, 0, 0].data.shape  # (1, 128, 512)

Because tile_shape now has the same rank as src, dimension 0 is no longer a leading batch coordinate. It is the tile’s partition dimension, with extent 1. The 128 x 512 region is traversed through the free dimensions and the operand uses only one partition.

Omit batch, head, or expert dimensions from tile_shape when they should remain leading coordinates. Include them only when they are intentionally part of the tile layout.

Understand partial tiles#

A tensor dimension can end partway through the requested tile size. For 500 rows divided into 128-row tiles, nl.tiles() creates three full tiles and one 116-row boundary tile. That boundary tile refers only to the valid rows in HBM, so the tensor needs no padding.

Use is_remainder to check whether a grid view contains a partial tile:

# src.shape == (500, 512)
src_tiles = nl.tiles(src, tile_shape=(128, 128))

src_tiles[0, 0].is_remainder     # False: one full tile
src_tiles[-1, 0].is_remainder    # True: one partial boundary tile
src_tiles[:-1, :].is_remainder   # False: every selected tile is full
src_tiles[-1:, :].is_remainder   # True: this view contains partial tiles

The result describes the complete selection, not just its first tile. It is True when any selected tile is partial along any tensor dimension. Because the grid geometry is known while the kernel is traced, this Python boolean can choose between a full-tile path and a boundary path.

True does not mean that the view is invalid or that its .data cannot be used. A partial tile can usually be represented as a NkiTensor on its own. The following section explains the case that does require splitting a view: selected tiles with different partition extents.

A tile grid with partial tiles along its final row and column.

Fig. 21 Boundary tiles contain only the valid elements that remain in the source tensor.#

Know when .data is representable#

Tensor dimensions may not be exact multiples of tile_shape. A kernel written for general shapes therefore has to handle boundary tiles, and in one case a selection that spans them cannot be passed to an instruction as a single operand.

Use is_data_representable to check a selected view before accessing .data. This boolean attribute is True when the complete selected region can be represented exactly by a single NkiTensor, which you can obtain through .data. If it is False, narrow the view or split it into smaller representable regions before accessing their .data.

For an individual tile or a regular rectangular slice, .data can usually expose the selected region as one NkiTensor. A problem arises whenever the region cannot be described by one native NkiTensor access pattern. The following example shows a common case: a selection that combines tiles with different valid partition extents. Consider one column from a (500, 512) tensor tiled by (128, 128):

# src.shape == (500, 512)
src_tiles = nl.tiles(src, tile_shape=(128, 128))
col_view = src_tiles[:, 2]

src_tiles[0, 0].is_data_representable   # True: one full tile
src_tiles[-1, 0].is_data_representable  # True: one partial tile alone
col_view.is_data_representable          # False: [128, 128, 128, 116]

This column contains three (128, 128) tiles followed by one (116, 128) tile, because only 116 partition elements remain at the end of the tensor.

nl.empty_like() can allocate SBUF for the complete column, including its smaller final tile:

col_sbuf = nl.empty_like(col_view, buffer=nl.sbuf)

As described in NKI tile layout, SBUF is physically two-dimensional. This allocation places the four tile slots along the free dimension and reserves the nominal P=128 capacity for each one. The final slot therefore has 12 unused partition lanes.

Four tiles from one selected grid column packed side by side along the SBUF free dimension, with reserved partition capacity behind the final partial tile.

Fig. 22 The SBUF allocation has capacity for all four tiles. Reserved capacity behind the partial tile is not valid tensor data.#

The allocation itself is valid: an allocation may reserve more capacity than the tensor data uses. The problem appears only when col_view.data tries to describe the whole column as one operand. A NkiTensor has one partition extent across its free dimension. Choosing P=128 would include the unused lanes in the final slot, while choosing P=116 would omit valid data from the first three tiles. One regular NkiTensor cannot encode the required partition extents [128, 128, 128, 116].

As a result, accessing col_view.data raises during tracing:

ValueError: Cannot represent grid.data as one exact NkiTensor: source
dimension 0 has nonuniform partition extents: the nominal tile extent is
128, the trailing extent is 116, and the selection contains 4 partition
cells. Select the full partition tiles and trailing partial tile
separately.

A Grid context: line follows, reporting the tensor shape, grid shape, tile shape, and partition dimension of the selection that failed.

Branch on the attribute so that one code path handles either case, splitting the column only where the partition extent changes:

col_view = src_tiles[:, 2]
col_sbuf = nl.empty_like(col_view, buffer=nl.sbuf)

if col_view.is_data_representable:
    nisa.dma_copy(dst=col_sbuf.data, src=col_view.data)
else:
    nisa.dma_copy(dst=col_sbuf[:-1].data, src=col_view[:-1].data)
    nisa.dma_copy(dst=col_sbuf[-1:].data, src=col_view[-1:].data)

In the else branch, both destination views refer to the same col_sbuf allocation. The first DMA uses a uniform P=128 extent, and the second uses P=116. A partial tile is therefore representable on its own; only a selection that mixes partition extents needs to be split in this example.

The split is necessary because one NkiTensor partition extent must apply across the complete free dimension. A contiguous free-dimension tail can instead be compacted to its exact valid length. For the regular layout used here, a contiguous free-dimension remainder stays representable. Every selected tile keeps the same partition extent, so one DMA still moves the whole region. Only a remainder on the partition dimension forces the split shown above. Other free-dimension selections may still require splitting when their addresses cannot be described by one native access pattern, such as a partial extent behind a gapped selection.

You can also download the complete synchronized tile examples from tile_block_grids.py.

This document is relevant for: Trn2, Trn3