.. meta::
   :description: Learn the NKI tile-grid model, static indexing and slicing, explicit data movement, and tiled matrix multiplication.
   :keywords: NKI, tiled grids, indexing, slicing, matrix multiplication
   :date-modified: 2026-10-09

.. _nki-tiled-grid-fundamentals:

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

Tile-grid fundamentals
======================

NKI instructions operate on tiles, while kernel inputs and outputs are usually
larger tensors in HBM. :func:`nl.tiles() <nki.language.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:

#. Organize a tensor as a grid of tiles.
#. Select the region needed for the next computation.
#. Allocate matching or explicitly shaped on-chip storage.
#. Move the region into that storage.
#. 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 :func:`nl.tiles() <nki.language.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.

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

   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, :func:`~nki.isa.nc_matmul` commonly uses ``(128, 128)`` tiles for its
stationary operand and ``(128, 512)`` tiles for its moving operand.

.. figure:: ../../img/tiled-grids/tile-grid-anatomy.svg
   :alt: A tensor decomposed into a four by four tile grid.
   :align: center
   :width: 100%

   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.


.. figure:: ../../img/tiled-grids/tile-selection-indexing.svg
   :alt: Six grids showing scalar, row, column, rectangular, negative-index, and stepped tile selections.
   :align: center
   :width: 100%

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

ISA instructions accept :class:`~nki.language.NkiTensor` operands. When you
are ready to pass a selected region to an instruction, access
:attr:`~nki.language.NkiTileGrid.data`:

.. list-table::
   :header-rows: 1
   :widths: 32 28 40

   * - 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,
:ref:`nki-tiled-grid-data-representability`, 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 :func:`nl.empty_like() <nki.language.empty_like>` to
allocate SBUF storage with matching geometry, then use the two ``.data``
operands in ``nisa.dma_copy``:

.. code-block:: python
   :name: tile-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


:func:`nl.empty_like() <nki.language.empty_like>` derives the SBUF allocation
from ``src_view``, so you do not need to calculate its shape separately.


Allocate a tile grid directly
-----------------------------

:func:`nl.empty_like() <nki.language.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 :func:`nl.alloc_tiles() <nki.language.alloc_tiles>` when the
kernel should define the tile geometry and logical element extent directly.

.. list-table::
   :header-rows: 1
   :widths: 24 36 40

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


.. nki_example:: ../../examples/tiled_grid/canonical/tile_block_grids.py
   :language: python
   :marker: NKI_EXAMPLE_TILED_GRID_SCALE_KERNEL
   :linenos:

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.

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

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

.. figure:: ../../img/tiled-grids/tiled-matmul-grid-coordinates.svg
   :alt: Three tile grids showing fixed lhsT and rhs tile columns paired across k to compute one output tile.
   :align: center
   :width: 100%

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

.. nki_example:: ../../examples/tiled_grid/canonical/matmul.py
   :language: python
   :marker: NKI_EXAMPLE_TILED_GRID_MATMUL_SIMPLE
   :linenos:

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:

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

   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
:download:`matmul.py <../../examples/tiled_grid/canonical/matmul.py>` for the
complete implementation.

Tile higher-rank tensors
------------------------

:func:`nl.tiles() <nki.language.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:

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

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

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

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

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

   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:

.. code-block:: python
   :name: tile-batch-view

   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:

.. code-block:: python
   :name: tile-batch-copy

   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:

.. code-block:: text

                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:

.. code-block:: python
   :name: tile-explicit-batch

   # 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, :func:`nl.tiles() <nki.language.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 :attr:`~nki.language.NkiGrid.is_remainder` to check whether a grid view
contains a partial tile:

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

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

.. figure:: ../../img/tiled-grids/partial-tile-grid.svg
   :alt: A tile grid with partial tiles along its final row and column.
   :align: center
   :width: 100%

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

.. _nki-tiled-grid-data-representability:

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 :attr:`~nki.language.NkiGrid.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
:class:`~nki.language.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 :class:`~nki.language.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)``:

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

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

:func:`nl.empty_like() <nki.language.empty_like>` can allocate SBUF for the
complete column, including its smaller final tile:

.. code-block:: python
   :name: tile-column-allocate

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

As described in :ref:`NKI tile layout <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.

.. figure:: ../../img/tiled-grids/data-representability.svg
   :alt: 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.
   :align: center
   :width: 100%

   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:

.. code-block:: text

   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:

.. code-block:: python
   :name: tile-column-copy

   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
:download:`tile_block_grids.py <../../examples/tiled_grid/canonical/tile_block_grids.py>`.
