This document is relevant for: Trn2, Trn3

Tile-grid indexing and transformations#

Some kernels select data with values known only at runtime, such as an expert ID or a vector of gather row indices. NKI represents a runtime value as a NkiScalar, or as an SBUF NkiTensor shaped (1, 1) for one coordinate or (K, 1) for a vector of row indices. Tile grids accept these as indices, so the view drives SBUF allocation and DMA operands without address arithmetic.

Sharding and transpose are the other two topics in this tutorial. A shard slice narrows a grid to the coordinates assigned to one NeuronCore, and a transpose changes how a selected region moves into SBUF.

In this tutorial, you will:

  • select runtime scalar and vector coordinates, reason about the resulting geometry, and handle element offsets, partial indices, and out-of-bounds accesses;

  • divide tile columns between NeuronCores with standard or custom slices while keeping the downstream kernel body unchanged; and

  • change a selected region’s layout during data movement and compose transpose with an indirect gather.

This tutorial assumes familiarity with tile-grid creation, static indexing, .data, nl.empty_like(), and dma_copy() from Tile-grid fundamentals.

Indirect indexing#

Select and move a region with a runtime scalar#

To use a runtime value as a tile coordinate, load it into a (1, 1) SBUF tensor of int32 or uint32 and pass that tensor directly in a grid key:

# copy index tensor to SBUF
index_src = ... # runtime index on HBM
index_sbuf = nl.ndarray((1, 1), dtype=index_src.dtype, buffer=nl.sbuf)
nisa.dma_copy(dst=index_sbuf, src=index_src)

# use index tensor to copy corresponding tile to SBUF
src_view = src_tiles[index_sbuf, 0]
src_sbuf = nl.empty_like(src_view, buffer=nl.sbuf)
nisa.dma_copy(dst=src_sbuf.data, src=src_view.data)
A runtime scalar supplying the row coordinate for a tile-grid selection.

Fig. 23 The first coordinate is supplied at runtime; the second coordinate is fixed during compilation.#

A runtime scalar can consume any grid dimension, including a leading batch, head, or expert dimension. With weights.shape == (8, 128, 512) and tile_shape=(128, 512), expert_tiles[expert_id_sbuf, 0, 0] selects one expert’s (128, 512) tile rather than an aggregate view of all eight.

A key can mix static and runtime coordinates, but at most one entry can be runtime; the rest are static integers or slices.

Understand indirect selection shape#

The shape of an integer SBUF key changes what the key means. A scalar selects one tile coordinate. A vector does not select several tile coordinates; it gathers source rows and packs them into a new partition extent. For a grid with tile_shape=(128, 512):

Key

Interpretation

Result

Python integer

Static grid coordinate

Selects one tile and consumes that grid dimension

(1, 1) SBUF integer

Runtime grid coordinate

Selects one tile and consumes that grid dimension

(K, 1) SBUF integer, K > 1

Runtime vector of source rows

Gathers K rows and makes K the result’s partition extent

For a tile-aligned data tensor, the difference is visible in the selected element shapes:

# data.shape == (512, 512)
data_tiles = nl.tiles(data, tile_shape=(128, 512))

tile_view = data_tiles[scalar_sbuf, 0]
tile_view.element_shape                 # (128, 512)

rows_view = data_tiles[indices_sbuf, 0]
rows_view.element_shape                 # (K, 512)

The scalar can also be a NkiScalar. Omitted trailing grid dimensions remain available for later indexing.

A vector index supplies at most 128 rows, so K can be at most 128 for a (128, 512) tile. The partial-index example later in this tutorial shows how a final (72, 1) index tile naturally produces a 72-row selection.

Vector indices must begin at SBUF partition zero and apply only to tile-grid dimensions.

Gather and scatter with a vector#

An index tensor begins in HBM like the data it indexes. Tile it with tile_shape=(128, 1) so each grid coordinate contains at most one tile’s partition extent of row indices. The kernel loads one index tile into SBUF, then reuses that vector while moving each free-dimension data tile.

Runtime-selected source rows packed into an output tile.

Fig. 24 A source-side vector key gathers rows in the order stored in index_sbuf.#

The following gather kernel applies that complete pattern. index_sbuf determines both which source rows are read and their packed order in src_sbuf:

 1@nki.jit
 2def gather_kernel(data, indices):
 3    """Gather rows in index tiles, including a partial final index tile."""
 4    # data is a 2D tensor, for example (512, 1024).
 5    # indices is a 2D index tensor, for example (200, 1). Its final tile has
 6    # 72 indices when tile_shape is (128, 1).
 7    out = nl.ndarray(
 8        (indices.shape[0], data.shape[1]), dtype=data.dtype, buffer=nl.shared_hbm
 9    )
10    data_tiles = nl.tiles(data, tile_shape=(128, 512))
11    index_tiles = nl.tiles(indices, tile_shape=(128, 1))
12    out_tiles = nl.tiles(out, tile_shape=(128, 512))
13
14    for i in range(out_tiles.shape[0]):
15        index_view = index_tiles[i, 0]
16        index_sbuf = nl.empty_like(index_view.data, buffer=nl.sbuf)
17        nisa.dma_copy(dst=index_sbuf, src=index_view.data)
18        for j in range(out_tiles.shape[1]):
19            src_view = data_tiles[index_sbuf, j]
20            src_sbuf = nl.empty_like(src_view, buffer=nl.sbuf)
21            nisa.dma_copy(dst=src_sbuf.data, src=src_view.data)
22            nisa.dma_copy(dst=out_tiles[i, j].data, src=src_sbuf.data)
23    return out
24
25

Scatter uses the same tiled-index load. Applying index_sbuf to the destination grid writes each packed source row to its indexed destination:

# index_sbuf was loaded from index_tiles[i, 0].
src_view = src_tiles[i, j]
src_sbuf = nl.empty_like(src_view, buffer=nl.sbuf)
nisa.dma_copy(dst=src_sbuf.data, src=src_view.data)

out_view = out_tiles[index_sbuf, j]
nisa.dma_copy(dst=out_view.data, src=src_sbuf.data)
Packed source rows scattered to runtime-selected output rows.

Fig. 25 A destination-side vector key writes each packed row to its indexed destination row.#

Reuse a runtime element offset#

Most kernels do not need to calculate source offsets. They use a runtime tile coordinate and let the grid locate the corresponding source tile:

src_view = src_tiles[tile_i_sbuf, j]

For a runtime coordinate, the generated kernel scales tile_i_sbuf by src_tiles.index_step_elements[0]. This converts a tile-row coordinate into an offset measured in source elements.

grid_element_offset() is for the narrower case where the kernel already maintains that element offset, or where the same offset indexes more than one compatible grid. The marker tells the grid that the conversion has already been done:

row_step = lhs_tiles.index_step_elements[0]
row_offset = nl.grid_element_offset(row_offset_sbuf)

lhs_view = lhs_tiles[row_offset, j]
rhs_view = rhs_tiles[row_offset, j]

# Advance by one tile row in source-element units.
nisa.tensor_scalar(
    dst=row_offset_sbuf,
    data=row_offset_sbuf,
    op0=nl.add,
    operand0=row_step,
)

Its position inside the brackets identifies the indexed dimension, and the offset is relative to the current view rather than a flattened memory address.

An element offset must align with that dimension’s step:

row_offset % grid.index_step_elements[0] == 0

For runtime offsets, the kernel is responsible for keeping the value aligned and within the selected extent.

The same indexing form applies to HBM and SBUF grids. Their layouts can map the selection differently in memory while still identifying the same logical grid cell. Element-offset markers apply to scalar grid coordinates, not vector gather indices. NkiTensor indexing is already element-based; use ds() for dynamic sub-tile slicing.

Define out-of-bounds behavior#

An indirect grid view has a shape fixed at compile time, while its index values are resolved at runtime. Those values may fall outside the source or destination tensor. The DMA instruction that consumes view.data handles such accesses according to its oob_mode:

Mode

Behavior

nisa.oob_mode.error

Raise a runtime error for an out-of-bounds access. This is the default.

nisa.oob_mode.skip

Transfer in-bounds elements and skip out-of-bounds accesses without clamping or wrapping the index. Skipped destination elements remain unchanged.

For scalar indexing, consider a (512, 512) source tiled by (128, 512), which contains four full tile rows. A runtime scalar coordinate from 0 through 3 selects a valid tile row; a coordinate such as 7 is out of bounds. With nisa.oob_mode.skip, that copy leaves the destination unchanged.

Runtime scalar indexing requires every reachable coordinate along the indexed dimension to have the same valid element extent. A (500, 512) source tiled by (128, 512) mixes 128-row tiles with a final 116-row tile, so indexing that complete grid with grid[scalar, 0] is rejected during tracing. The OOB mode does not change this requirement.

Vector indexing selects individual source rows. For the same (500, 512) source, row indices from 0 through 499 are valid. A vector containing indices 384 through 511 requests 128 rows: with nisa.oob_mode.skip, 116 rows transfer and the remaining 12 destination rows stay unchanged. The selected view still has 128 rows.

Initialize the destination before the DMA so skipped rows have a defined value:

# data.shape == (500, 512)
# index_sbuf is a (K, 1) integer SBUF tensor, with 2 <= K <= 128.
data_tiles = nl.tiles(data, tile_shape=(128, 512))
src_view = data_tiles[index_sbuf, 0]
src_sbuf = nl.empty_like(src_view, buffer=nl.sbuf)

nisa.memset(dst=src_sbuf.data, value=sentinel)
nisa.dma_copy(
    dst=src_sbuf.data,
    src=src_view.data,
    oob_mode=nisa.oob_mode.skip,
)

For scatter, initialize any output rows that may receive no valid writes if the kernel requires defined values there.

A partial index tile is a separate concern. Its shape determines how many indices are loaded; their values determine whether the selected source or destination rows are in bounds.

Carry a partial index tile through gather#

The shape rule from indirect selection shape also applies to a partial index tile. Suppose indices has shape (200, 1) and is tiled by (128, 1). Its second tile contains 72 valid indices:

last_index_view = index_tiles[-1, 0]

last_index_view.is_remainder  # True
last_index_view.data.shape    # (72, 1)

After those 72 values are copied to SBUF, using the SBUF tensor as a vector key creates a 72-row data view. nl.empty_like() carries that exact extent into a matching SBUF allocation.

The loop does not need a separate remainder kernel:

for i in range(index_tiles.shape[0]):
    index_view = index_tiles[i, 0]
    index_sbuf = nl.empty_like(index_view.data, buffer=nl.sbuf)
    nisa.dma_copy(dst=index_sbuf, src=index_view.data)

    src_view = data_tiles[index_sbuf, j]
    src_sbuf = nl.empty_like(src_view, buffer=nl.sbuf)
    nisa.dma_copy(dst=src_sbuf.data, src=src_view.data)

The first iteration moves 128 indices and gathers 128 rows. The second moves 72 indices and gathers 72 rows through the same code. Each index value is still subject to the DMA OOB mode; a valid index tile can contain an invalid source row.

A full index tile and a partial 72-entry index tile producing matching full and partial gathered data regions.

Fig. 26 The final index tile’s 72 valid entries produce a 72-row gather and a matching SBUF view.#

Sharding#

A Trainium chip contains multiple NeuronCores that share access to HBM. An LNC=2 kernel divides its work between logical NeuronCore 0 and 1 while both cores address the same HBM tensors. With tile grids, this division is expressed through slicing: each core selects its assigned tile coordinates from the same HBM-backed grids. Sharding is confined to this view construction, so the downstream allocation, DMA, compute, and store code remains unchanged with or without sharding.

nl.program_id(0) identifies the current logical NeuronCore, and nl.num_programs(0) gives the number of participating cores. These values are compile-time integers specialized for each core.

Use standard sharding slices#

contiguous_indices() and interleaved_indices() are convenience functions that return built-in Python slice objects. They do not allocate storage, copy data, or emit an instruction.

For contiguous sharding, each core receives an adjacent range of tile columns:

column_count = lhs_tiles.shape[1]
core_id = nl.program_id(0)
core_count = nl.num_programs(0)

owned_cols = nl.contiguous_indices(
    column_count,
    shard_id=core_id,
    num_shards=core_count,
)

lhs_owned = lhs_tiles[:, owned_cols]
rhs_owned = rhs_tiles[:, owned_cols]
out_owned = out_tiles[:, owned_cols]

For eight tile columns and LNC=2, NeuronCore 0 receives slice(0, 4) and NeuronCore 1 receives slice(4, 8).

Contiguous tile-column sharding across NeuronCore zero and one.

Fig. 27 Contiguous slicing gives each core an adjacent range of tile columns.#

Round-robin sharding uses the same pattern with interleaved_indices():

owned_cols = nl.interleaved_indices(
    column_count,
    shard_id=core_id,
    num_shards=core_count,
)

For eight tile columns and LNC=2, NeuronCore 0 receives slice(0, 8, 2) and NeuronCore 1 receives slice(1, 8, 2).

Interleaved tile-column sharding across NeuronCore zero and one.

Fig. 28 Interleaved slicing alternates tile columns between the two cores.#

Apply the same slice to aligned inputs and outputs so each core operates on a consistent region.

Define a custom shard slice#

The helper APIs cover common balanced layouts, but they are optional. A kernel can construct a Python slice directly for an application-specific work distribution.

Suppose a causal-attention kernel uses a 60/40 split to account for its nonuniform work distribution. For ten tile columns, the split falls after column 5:

column_count = lhs_tiles.shape[1]
core_id = nl.program_id(0)

split_column = (3 * column_count) // 5
column_boundaries = (0, split_column, column_count)
owned_cols = slice(
    column_boundaries[core_id],
    column_boundaries[core_id + 1],
)

lhs_owned = lhs_tiles[:, owned_cols]
rhs_owned = rhs_tiles[:, owned_cols]
out_owned = out_tiles[:, owned_cols]

For ten tile columns, NeuronCore 0 receives slice(0, 6) and NeuronCore 1 receives slice(6, 10). Because core_id is specialized during compilation, each core constructs an ordinary static slice. Different boundary values can encode another known work distribution.

A single Python slice represents one regular start, stop, and step pattern. Use indirect indexing when ownership requires an arbitrary list of coordinates.

After slicing, lhs_owned.shape counts local coordinates. A loop index such as j is local to that view; the grid maps it back to the owned global tile column when .data is formed. The compute body therefore does not need to calculate global column offsets:

 1def _tensor_add_owned_region(lhs, rhs, row_indices, column_indices):
 2    """Add the tile region selected by one pair of ownership slices."""
 3    tile_shape = (128, 512)
 4    out = nl.ndarray(lhs.shape, dtype=lhs.dtype, buffer=nl.shared_hbm)
 5    lhs_tiles = nl.tiles(lhs, tile_shape=tile_shape)[row_indices, column_indices]
 6    rhs_tiles = nl.tiles(rhs, tile_shape=tile_shape)[row_indices, column_indices]
 7    out_tiles = nl.tiles(out, tile_shape=tile_shape)[row_indices, column_indices]
 8
 9    for i in range(lhs_tiles.shape[0]):
10        for j in range(lhs_tiles.shape[1]):
11            lhs_view = lhs_tiles[i, j]
12            rhs_view = rhs_tiles[i, j]
13            lhs_sbuf = nl.empty_like(lhs_view, buffer=nl.sbuf)
14            rhs_sbuf = nl.empty_like(rhs_view, buffer=nl.sbuf)
15            nisa.dma_copy(dst=lhs_sbuf.data, src=lhs_view.data)
16            nisa.dma_copy(dst=rhs_sbuf.data, src=rhs_view.data)
17            nisa.tensor_tensor(lhs_sbuf.data, lhs_sbuf.data, rhs_sbuf.data, op=nl.add)
18            nisa.dma_copy(
19                dst=out_tiles[i, j].data,
20                src=lhs_sbuf.data,
21            )
22    return out
23
24

The entry points differ only in the column slice passed to this body. Uneven tile counts are retained in the local grid shapes, so one core may execute more loop iterations than another.

Transpose#

Transpose uses the same select, allocate, and move workflow as other tile-grid operations. The selected source can be one tile, a row of tiles, or an entire grid. nl.empty_like() with transpose_axes prepares the destination geometry, and dma_transpose() performs the data movement.

Allocate a transposed grid#

When the input is a grid, transpose_axes applies to the entire selected grid. It permutes both the grid coordinates and the logical element shape:

# src.shape == (256, 384)
src_tiles = nl.tiles(src, tile_shape=(128, 128))

src_tiles.shape          # (2, 3)
src_tiles.element_shape  # (256, 384)

transposed_sbuf = nl.empty_like(
    src_tiles,
    buffer=nl.sbuf,
    transpose_axes=(1, 0),
)

transposed_sbuf.shape          # (3, 2)
transposed_sbuf.element_shape  # (384, 256)

The destination coordinate corresponding to source (i, j) is (j, i). Partial boundary extents move to their corresponding transposed boundaries. nl.empty_like() only allocates the SBUF layout; it does not read src_tiles or issue a transpose instruction.

A two-by-three HBM tile grid defining an uninitialized three-by-two transposed SBUF grid.

Fig. 29 Transpose-aware allocation changes the grid geometry without moving data.#

Transpose one tile#

For one (128, 128) tile, select the source, allocate the swapped destination layout, and then issue dma_transpose():

src_view = src_tiles[i, j]
transposed_sbuf = nl.empty_like(
    src_view,
    buffer=nl.sbuf,
    transpose_axes=(1, 0),
)
nisa.dma_transpose(dst=transposed_sbuf.data, src=src_view.data)
nisa.dma_copy(dst=out_tiles[j, i].data, src=transposed_sbuf.data)

dma_transpose moves the data, and the swapped output coordinate stores it in the transposed HBM tensor.

One source tile transposed into the output tile at its swapped grid coordinate.

Fig. 30 Transposing source tile (i, j) writes the result to output coordinate (j, i).#

Transpose a row of tiles#

A grid selection can combine adjacent tiles into one transpose operation. Selecting src_tiles[i] produces one complete tile row. Its aggregate source extent becomes one output tile column:

 1@nki.jit
 2def transpose_coalesced_single_store(src):
 3    """Transpose and write one complete tile row per DMA."""
 4    rows, cols = src.shape
 5    out = nl.ndarray((cols, rows), dtype=src.dtype, buffer=nl.shared_hbm)
 6    src_tiles = nl.tiles(src, tile_shape=(128, 128))
 7    out_tiles = nl.tiles(out, tile_shape=(128, 128))
 8
 9    for i in range(src_tiles.shape[0]):
10        src_row_view = src_tiles[i]
11        transposed_sbuf = nl.empty_like(
12            src_row_view,
13            buffer=nl.sbuf,
14            transpose_axes=(1, 0),
15        )
16        nisa.dma_transpose(dst=transposed_sbuf.data, src=src_row_view.data)
17        nisa.dma_copy(
18            dst=out_tiles[:, i].data,
19            src=transposed_sbuf.data,
20        )
21    return out
22
23

This replaces one transpose and store per tile with one transpose and one store per source tile row.

One source tile row transposed and stored as one output tile column.

Fig. 31 One transpose and one store move the selected source row into one output column.#

Transpose higher-rank grids#

Native DMA transpose supports these tiled-dimension permutations:

Rank

transpose_axes

Logical mapping

2

(1, 0)

(P, F) -> (F, P)

3

(2, 1, 0)

(P, M, F) -> (F, M, P)

4

(3, 1, 2, 0)

(P, A, B, F) -> (F, A, B, P)

For rank three, the grid shape changes with the same permutation:

# src3.shape == (256, 2, 384)
src3_tiles = nl.tiles(src3, tile_shape=(128, 2, 128))
dst3_sbuf = nl.empty_like(
    src3_tiles,
    buffer=nl.sbuf,
    transpose_axes=(2, 1, 0),
)

src3_tiles.shape  # (2, 1, 3)
dst3_sbuf.shape   # (3, 1, 2)

The rank-four form follows the same model:

# src4.shape == (256, 2, 3, 384)
src4_tiles = nl.tiles(src4, tile_shape=(128, 2, 3, 128))
dst4_sbuf = nl.empty_like(
    src4_tiles,
    buffer=nl.sbuf,
    transpose_axes=(3, 1, 2, 0),
)

src4_tiles.shape  # (2, 1, 1, 3)
dst4_sbuf.shape   # (3, 1, 1, 2)

The middle dimensions retain their order while the first and last tiled dimensions exchange roles. Leading dimensions omitted from tile_shape remain leading dimensions and are not included in transpose_axes. The source free extent that becomes the destination partition extent must not exceed 128.

Compose gather and transpose#

An indirect selection can feed the same transpose operation. The following kernel loads a (K, 1) index vector, gathers K source rows, allocates the transposed SBUF layout, and writes those rows as output columns:

Runtime-selected rows gathered and transposed into output columns.

Fig. 32 The vector controls the output-column order because the gathered rows are packed before dma_transpose.#

 1@nki.jit
 2def gather_transpose(data, indices):
 3    """Gather rows and transpose the result to ``(D, K)``."""
 4    index_sbuf = nl.ndarray(indices.shape, dtype=indices.dtype, buffer=nl.sbuf)
 5    nisa.dma_copy(dst=index_sbuf, src=indices)
 6    data_tiles = nl.tiles(data, tile_shape=(128, 128))
 7    src_view = data_tiles[index_sbuf]
 8    transposed_sbuf = nl.empty_like(
 9        src_view,
10        buffer=nl.sbuf,
11        transpose_axes=(1, 0),
12    )
13    out = nl.ndarray(
14        transposed_sbuf.element_shape,
15        dtype=data.dtype,
16        buffer=nl.shared_hbm,
17    )
18    nisa.dma_transpose(dst=transposed_sbuf.data, src=src_view.data)
19    nisa.dma_copy(dst=out, src=transposed_sbuf.data)
20    return out
21
22

The grid key performs the gather; transpose_axes=(1, 0) prepares the SBUF destination; and one dma_transpose composes both operations. No separate gather buffer or manual row-to-column address calculation is needed.

The same composition extends to rank-three and rank-four data through gather_transpose_3d and gather_transpose_4d in the complete example.

The complete synchronized examples are available in indirect_indexing.py, sharding.py, and transpose.py.

This document is relevant for: Trn2, Trn3