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)
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 |
|
Runtime grid coordinate |
Selects one tile and consumes that grid dimension |
|
Runtime vector of source rows |
Gathers |
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.
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)
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 |
|---|---|
|
Raise a runtime error for an out-of-bounds access. This is the default. |
|
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.
Fig. 26 The final index tile’s 72 valid entries produce a 72-row gather and a matching SBUF view.#
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.
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.
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.
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 |
|
Logical mapping |
|---|---|---|
2 |
|
|
3 |
|
|
4 |
|
|
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:
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