.. meta::
   :description: Use runtime scalar and vector indices, OOB handling, sharding, and transpose with NKI tile grids.
   :keywords: NKI, tiled grids, indirect indexing, gather, scatter, sharding, transpose
   :date-modified: 2026-10-09

.. _nki-tiled-grid-selection:

.. rst-class:: tiled-grid-doc

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
:class:`~nki.isa.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``, :func:`nl.empty_like() <nki.language.empty_like>`, and
:func:`~nki.isa.dma_copy` from :ref:`nki-tiled-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:

.. code-block:: python
   :name: index-scalar

   # 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)

.. figure:: ../../img/tiled-grids/runtime-scalar-selection.svg
   :alt: A runtime scalar supplying the row coordinate for a tile-grid selection.
   :align: center
   :width: 100%

   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.

.. _nki-tiled-grid-indirect-shape:

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)``:

.. list-table::
   :header-rows: 1
   :widths: 28 34 38

   * - 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:

.. code-block:: python
   :name: index-key-types

   # 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 :class:`~nki.isa.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.

.. figure:: ../../img/tiled-grids/gather-rows.svg
   :alt: Runtime-selected source rows packed into an output tile.
   :align: center
   :width: 100%

   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``:

.. nki_example:: ../../examples/tiled_grid/canonical/indirect_indexing.py
   :language: python
   :marker: NKI_EXAMPLE_TILED_GRID_GATHER_KERNEL
   :linenos:

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

.. code-block:: python
   :name: index-scatter

   # 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)

.. figure:: ../../img/tiled-grids/scatter-rows.svg
   :alt: Packed source rows scattered to runtime-selected output rows.
   :align: center
   :width: 100%

   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:

.. code-block:: python
   :name: index-tile-coordinate

   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.

:func:`~nki.language.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:

.. code-block:: python
   :name: index-element-offset

   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:

.. code-block:: text

   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
:func:`~nki.language.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``:

.. list-table::
   :header-rows: 1
   :widths: 28 72

   * - 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:

.. code-block:: python
   :name: index-oob

   # 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 :ref:`indirect selection shape
<nki-tiled-grid-indirect-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:

.. code-block:: python
   :name: index-tail

   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. :func:`nl.empty_like()
<nki.language.empty_like>` carries that exact extent into a matching SBUF
allocation.

The loop does not need a separate remainder kernel:

.. code-block:: python
   :name: index-gather-loop

   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.

.. figure:: ../../img/tiled-grids/partial-index-gather.svg
   :alt: A full index tile and a partial 72-entry index tile producing matching full and partial gathered data regions.
   :align: center
   :width: 100%

   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.

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

Use standard sharding slices
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:func:`~nki.language.contiguous_indices` and
:func:`~nki.language.interleaved_indices` are convenience functions that
return built-in Python :class:`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:

.. code-block:: python
   :name: shard-contiguous

   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)``.

.. figure:: ../../img/tiled-grids/sharding-contiguous.svg
   :alt: Contiguous tile-column sharding across NeuronCore zero and one.
   :align: center
   :width: 100%

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

Round-robin sharding uses the same pattern with
:func:`~nki.language.interleaved_indices`:

.. code-block:: python
   :name: shard-interleaved

   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)``.

.. figure:: ../../img/tiled-grids/sharding-interleaved.svg
   :alt: Interleaved tile-column sharding across NeuronCore zero and one.
   :align: center
   :width: 100%

   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 :class:`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:

.. code-block:: python
   :name: shard-custom

   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:

.. nki_example:: ../../examples/tiled_grid/canonical/sharding.py
   :language: python
   :marker: NKI_EXAMPLE_TILED_GRID_TENSOR_ADD_OWNED_REGION
   :linenos:

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. :func:`nl.empty_like() <nki.language.empty_like>` with
``transpose_axes`` prepares the destination geometry, and
:func:`~nki.isa.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:

.. code-block:: python
   :name: transpose-allocation

   # 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.

.. figure:: ../../img/tiled-grids/transpose-grid-allocation.svg
   :alt: A two-by-three HBM tile grid defining an uninitialized three-by-two transposed SBUF grid.
   :align: center
   :width: 100%

   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 :func:`~nki.isa.dma_transpose`:

.. code-block:: python
   :name: transpose-tile

   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.

.. figure:: ../../img/tiled-grids/transpose-tile.svg
   :alt: One source tile transposed into the output tile at its swapped grid coordinate.
   :align: center
   :width: 100%

   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:

.. nki_example:: ../../examples/tiled_grid/canonical/transpose.py
   :language: python
   :marker: NKI_EXAMPLE_TILED_GRID_TRANSPOSE_COALESCED
   :linenos:

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

.. figure:: ../../img/tiled-grids/transpose-coalesced-row.svg
   :alt: One source tile row transposed and stored as one output tile column.
   :align: center
   :width: 100%

   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:

.. list-table::
   :header-rows: 1
   :widths: 16 30 54

   * - 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:

.. code-block:: python
   :name: transpose-rank3

   # 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:

.. code-block:: python
   :name: transpose-rank4

   # 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:

.. figure:: ../../img/tiled-grids/gather-transpose.svg
   :alt: Runtime-selected rows gathered and transposed into output columns.
   :align: center
   :width: 100%

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

.. nki_example:: ../../examples/tiled_grid/canonical/transpose.py
   :language: python
   :marker: NKI_EXAMPLE_TILED_GRID_GATHER_TRANSPOSE
   :linenos:

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
:download:`indirect_indexing.py <../../examples/tiled_grid/canonical/indirect_indexing.py>`,
:download:`sharding.py <../../examples/tiled_grid/canonical/sharding.py>`, and
:download:`transpose.py <../../examples/tiled_grid/canonical/transpose.py>`.
