.. meta::
   :description: Learn NKI block grids, block-level indexing and movement, partial blocks, ownership, transpose, and blocked matrix multiplication.
   :keywords: NKI, tiled grids, blocks, indexing, matrix multiplication
   :date-modified: 2026-10-09

.. _nki-tiled-grid-blocks:

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

Block-grid fundamentals
=======================

Tile grids give NKI kernels a compute-sized view of a tensor: ``tile_shape``
describes the data presented to an :mod:`nki.isa` instruction. Moving every
tile separately, however, is not always the most efficient way to bring that
data into SBUF. As documented in the :ref:`DMA bandwidth guide
<nki-dma-bandwidth-guide>`, a transfer should carry at least 2 KiB per
partition — 512 float32 elements along the free dimension — with 4 KiB needed
to saturate the engines. A ``(128, 512)`` float32 tile meets that minimum
exactly, but a ``(128, 128)`` tile carries only 512 bytes, so moving those
one at a time spends most of the available bandwidth on per-transfer
overhead.

Adjacent tiles can often be transferred more efficiently as one larger
region: four ``(128, 128)`` tiles reach 2 KiB per partition, and eight reach
4 KiB. The best unit to transfer is therefore larger than the best unit to
compute on.

:func:`nl.blocks() <nki.language.blocks>` separates the two. A block is a
rectangular group of tiles that moves in one coalesced DMA, so ``tile_shape``
still describes the compute operand, while ``block_shape`` decides how many
of those tiles travel together. :func:`nl.tiles() <nki.language.tiles>`
converts a block grid or block selection back to tile granularity, and
``.data`` exposes a selected blocked region as the ``NkiTensor`` operand that
DMA and ISA instructions accept.

This separation makes ``block_shape`` a practical tuning knob. The useful DMA
grain and available SBUF capacity can change with tensor shape, batch or
sequence length, and the number of logical NeuronCores. A larger block
amortizes DMA overhead when capacity permits; a smaller block reduces the live
SBUF footprint. A kernel can therefore retune data movement by changing
``block_shape`` rather than reshaping the compute or rewriting its inner tile
loop. The kernel keeps an outer loop that selects and moves blocks and an
inner loop that computes over the tiles each loaded block exposes.

This tutorial builds on the static selection and movement model in
:ref:`nki-tiled-grid-fundamentals` and the runtime indexing, sharding, and
transpose patterns in :ref:`nki-tiled-grid-selection`. Here, those shared
concepts are summarized at block granularity.

In this tutorial, you will:

* define a block hierarchy over HBM and SBUF tensors;
* select, allocate, and move complete or partial block regions;
* apply runtime indexing, sharding, and transpose at block granularity; and
* build a blocked matmul and hoist a reusable LHS block column.

Build the block hierarchy
-------------------------

Create and inspect a block grid
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:func:`nl.blocks() <nki.language.blocks>` preserves tile geometry and adds
block coordinates above it. ``block_shape`` is expressed in tile counts, not
elements.

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

   # src.shape == (512, 512)
   src_blocks = nl.blocks(
       src,
       tile_shape=(128, 128),
       block_shape=(2, 2),
   )

   src_blocks.shape          # (2, 2) block coordinates
   src_blocks.tile_shape     # (128, 128) elements per tile
   src_blocks.block_shape    # (2, 2) tiles per block
   src_blocks.element_shape  # (512, 512) represented elements

.. list-table::
   :header-rows: 1
   :widths: 30 30 40

   * - Property
     - Unit
     - Meaning
   * - ``tile_shape``
     - source elements
     - Nominal compute tile
   * - ``block_shape``
     - tiles
     - Tiles grouped into one block
   * - ``shape``
     - block coordinates
     - Currently indexable block extents
   * - ``element_shape``
     - source elements
     - Exact selected source extent

.. figure:: ../../img/tiled-grids/block-grid.svg
   :alt: A tile grid grouped into two by two tile blocks.
   :align: center
   :width: 100%

   Thin boundaries separate compute tiles; heavy boundaries separate blocks.

Choose tile and block shapes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

``block_shape`` must have the same rank as ``tile_shape``. It groups the tiled
dimensions and leaves any leading dimensions untouched, so a ``(8, 512, 512)``
tensor with ``tile_shape=(128, 128)`` and ``block_shape=(2, 2)`` yields a
``(8, 2, 2)`` block grid. The tile-shape considerations from
:ref:`nki-tiled-grid-fundamentals` continue to apply.

SBUF and PSUM capacity limits all simultaneously live block allocations, so
the largest useful ``block_shape`` depends on how many blocks a kernel keeps
resident at once.

Relate block and tile coordinates
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A block coordinate identifies one grouped region. Applying
:func:`nl.tiles() <nki.language.tiles>` to a block view exposes the tile
coordinates inside that region. A kernel can also retile a selected block view
when a later operation requires a different interior compute grain.

.. code-block:: python
   :name: block-interior

   block_view = src_blocks[0, 1]
   block_view.element_shape  # (256, 256)

   block_tiles = nl.tiles(block_view)
   block_tiles.shape         # (2, 2) interior tile coordinates
   block_tiles.tile_shape    # (128, 128)

Use leading and higher-rank dimensions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Leading dimensions omitted from ``tile_shape`` remain outside each tile and
block. For higher-rank tiled regions, ``tile_shape`` defines the element extent
of each interior tile and ``block_shape`` groups those tile coordinates. This is
the same dimension model introduced for tile grids; only the additional block
coordinate level is new.

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

   # weights.shape == (8, 512, 1024)
   weight_blocks = nl.blocks(
       weights,
       tile_shape=(128, 128),
       block_shape=(2, 4),
   )

   weight_blocks.shape  # (8, 2, 2)

Select a leading coordinate when processing one batch at a time. It can
remain in the view if the complete selection is representable; see
:ref:`nki-tiled-grid-fundamentals`.

Select and move block regions
-----------------------------

Index and slice block grids
~~~~~~~~~~~~~~~~~~~~~~~~~~~

Block grids support the same coordinate model as tile grids. The expressions
now count blocks.

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

   Static indexing keeps the tile-grid syntax and changes its unit from tiles
   to blocks.

Allocate and move a block region
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Copying a block from HBM to SBUF uses the same select, allocate, and move
sequence as a tile grid. Calling :func:`nl.tiles() <nki.language.tiles>` on
the SBUF block then exposes the compute-tile coordinates that ISA
instructions consume. For a ``(2, 3)`` block, the load is one DMA instruction
rather than six.

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

   block_view = src_blocks[i, j]
   block_sbuf = nl.empty_like(block_view, buffer=nl.sbuf)
   nisa.dma_copy(dst=block_sbuf.data, src=block_view.data)

   tiles_sbuf = nl.tiles(block_sbuf)
   for tile_i in range(tiles_sbuf.shape[0]):
       for tile_j in range(tiles_sbuf.shape[1]):
           tile_sbuf = tiles_sbuf[tile_i, tile_j]
           # Use tile_sbuf.data as an ISA operand.

   nisa.dma_copy(dst=out_blocks[i, j].data, src=block_sbuf.data)

.. figure:: ../../img/tiled-grids/block-interior.svg
   :alt: Six per-tile DMA instructions compared with one coalesced block-view DMA, followed by a view-only conversion to a tile grid.
   :align: center
   :width: 100%

   Block-view movement changes the DMA grain, not the compute grain: six tiles
   move with one coalesced DMA and remain six tile-level ISA operands.

Allocate a block grid directly
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:func:`nl.empty_like() <nki.language.empty_like>` mirrors the geometry of a
selected block region. :func:`nl.alloc_blocks() <nki.language.alloc_blocks>`
creates an explicitly sized block grid when no source selection should define
the allocation. Both forms can be indexed as blocks and exposed as interior
tile grids with :func:`nl.tiles() <nki.language.tiles>`.

The following kernel allocates a ``(128, 500)`` SBUF region as ``(1, 2)`` tile
blocks, initializes it, and copies the complete block grid to HBM:

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

Index and transform block grids
-------------------------------

The runtime scalar keys, ownership slices, and transpose operations introduced
in :ref:`nki-tiled-grid-selection` also apply to block grids. The selection rules
remain the same; logical coordinates and steps are now measured at block
granularity.

Use runtime keys with block grids
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

An SBUF scalar can supply a logical block coordinate at runtime. Vector keys
apply to tile grids, not block coordinates. The same OOB modes and
partial-index rules apply to the instruction that consumes the resulting view.

.. code-block:: python
   :name: block-runtime

   block_i_src = ...  # Runtime block-column coordinate in HBM.
   block_i_sbuf = nl.ndarray(
       (1, 1),
       dtype=block_i_src.dtype,
       buffer=nl.sbuf,
   )
   nisa.dma_copy(dst=block_i_sbuf, src=block_i_src)

   block_view = src_blocks[1, block_i_sbuf]
   block_sbuf = nl.empty_like(block_view, buffer=nl.sbuf)
   nisa.dma_copy(dst=block_sbuf.data, src=block_view.data)

.. figure:: ../../img/tiled-grids/runtime-block-selection.svg
   :alt: A runtime scalar selecting block column two from block row one.
   :align: center
   :width: 100%

   The runtime value supplies a logical block coordinate; the static first
   coordinate still selects block row 1.

``index_step_elements`` reports the source-element step between adjacent block
coordinates. :func:`~nki.language.grid_element_offset` remains the narrow
alternative for a kernel that already maintains an aligned element offset.

Shard blocks via slicing
~~~~~~~~~~~~~~~~~~~~~~~~

Contiguous, interleaved, and custom Python slices can select core-owned block
coordinates. After the ownership slice is applied, allocation, movement,
interior-tile compute, and storage operate on the local block view without
calculating global block offsets.

.. code-block:: python
   :name: block-ownership

   core_id = nl.program_id(0)
   core_count = nl.num_programs(0)
   owned_cols = nl.contiguous_indices(
       src_blocks.shape[1],
       shard_id=core_id,
       num_shards=core_count,
   )

   local_src_blocks = src_blocks[:, owned_cols]
   local_out_blocks = out_blocks[:, owned_cols]

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

   Sharding changes the selected block columns, not the downstream block
   movement or interior-tile compute.

Transpose block regions
~~~~~~~~~~~~~~~~~~~~~~~

A block transpose follows the same allocation and movement split as a tile
transpose:

1. Select the source block region.
2. Allocate a matching SBUF region with ``transpose_axes``.
3. Move it with :func:`~nki.isa.dma_transpose`.

The selected region can be one block, a block row, or a higher-rank block
view. ``nl.empty_like()`` prepares the transformed block geometry;
``dma_transpose`` performs the movement.

.. figure:: ../../img/tiled-grids/transpose-block-row.svg
   :alt: One source block row transposed into one destination block column.
   :align: center
   :width: 100%

   A source block row becomes a destination block column, and each block's
   interior tile axes are transposed with it.

``transpose_block_row`` implements this operation for ``(2, 2)`` tile blocks:

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

The store needs one extra step. :func:`~nki.isa.dma_transpose` always writes
to SBUF, so returning the result to HBM is an ordinary :func:`~nki.isa.dma_copy`
that moves data without reordering it — and the two sides do not agree on
order. The transposed SBUF operand traverses tile columns before tile rows,
while the HBM output operand traverses tile rows before tile columns. Calling
``permute()`` on the ``NkiTensor`` that ``.data`` returns swaps those two
axes, so one copy walks both sides in the same order. It rearranges the
access pattern only; no data moves.

The store uses the complete output block column.
``permute((0, 2, 1, 3))`` reorders the SBUF operand's free dimensions to match
the output traversal. This changes only the view, so the kernel uses one
``dma_transpose`` and one ``dma_copy``.

Compose block-grid operations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Block-grid operations can be chained because indexing and slicing produce
views without moving data. A kernel can first select the blocks owned by one
core, then pass that local view to ``nl.empty_like()`` and
:func:`~nki.isa.dma_transpose`. The allocation and movement code stays the
same whether its input represents the complete grid or one shard.

.. figure:: ../../img/tiled-grids/transpose-block-sharded.svg
   :alt: An interleaved core-owned block selection transposed through SBUF.
   :align: center
   :width: 100%

   One core's interleaved block selection and its transposed SBUF
   destination. Only the selection differs from the whole-grid case.

Promote sharded tiles to blocks
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Interleaved sharding balances work when the cost per tile varies, but it
leaves each core's tiles non-contiguous in HBM. Promoting those tiles to
blocks recovers the coalesced transfer anyway: since ``nl.blocks()`` accepts a
tile-grid view, a kernel can select tile coordinates first and then group each
core's selected tiles in local grid order.

For two cores, Core 0 selects global tile rows ``0, 2, ...`` and Core 1 selects
rows ``1, 3, ...``. Those rows become consecutive coordinates within each
local view, so ``block_shape=(2, 1)`` groups two interleaved global tile rows
into one logical block. Creating this block view does not allocate storage or
rearrange HBM.

.. figure:: ../../img/tiled-grids/interleaved-tiles-to-blocks.svg
   :alt: A global HBM tile grid with alternating rows owned by two cores, followed by aggregate DMA into one dense SBUF block per core.
   :align: center
   :width: 100%

   Tile slicing and block promotion leave the HBM grid unchanged. Separate
   boxes appear only after ``nl.empty_like()`` allocates dense SBUF blocks;
   their labels retain the source tiles' global coordinates.

The following LNC=2 kernel applies this pattern to every tile column:

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

Each :func:`~nki.isa.dma_copy` handles one complete logical block. This is an
aggregate block DMA rather than a contiguous HBM transfer: the source tiles
remain separated in HBM, but their regular interleaved stride is representable
by one ``.data`` operand. A selection that cannot be expressed as one native
access pattern must still be split into representable regions.

Blocked matrix multiplication kernel
------------------------------------

The blocked matmul applies one transfer hierarchy above the tile matmul from
:ref:`nki-tiled-grid-fundamentals`:

1. LHS and RHS blocks move from HBM to SBUF.
2. :func:`nl.tiles() <nki.language.tiles>` exposes their interior compute
   tiles.
3. Interior products accumulate into a PSUM tile grid.
4. The completed output block moves to HBM with one DMA.

The example uses instruction-compatible tile shapes and groups them into
larger movement regions:

.. list-table::
   :header-rows: 1
   :widths: 20 25 25 30

   * - Operand
     - Tile shape
     - Block shape
     - Block-grid coordinates
   * - ``lhs_t``
     - ``(128, 128)``
     - ``(4, 4)`` tiles
     - ``(k, m)``
   * - ``rhs``
     - ``(128, 512)``
     - ``(4, 2)`` tiles
     - ``(k, n)``
   * - ``out``
     - ``(128, 512)``
     - ``(4, 2)`` tiles
     - ``(m, n)``

Each output block remains live in PSUM throughout the reduction. One
``(128, 512)`` FP32 output tile occupies one of the eight PSUM banks, so the
kernel requires ``block_m * block_n <= 8``. The default ``(4, 2)`` output
block uses all eight banks. ``block_k`` controls the LHS and RHS transfer
grain and their SBUF usage without changing the PSUM footprint.

.. figure:: ../../img/tiled-grids/blocked-matmul-hierarchy.svg
   :alt: Selected LHS transpose and RHS blocks feeding the interior tile loops for one output block.
   :align: center
   :width: 100%

   The outer loops select block coordinates; the inner loops address the tiles
   participating in each block contraction.

``matmul_blocked`` implements this mapping. It creates block grids over the
HBM inputs and output, loads one pair of input blocks at a time, exposes their
interior tiles for :func:`~nki.isa.nc_matmul`, and stores each completed
output block with one DMA:

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

For this example, use multiples of 128 for the output-row (``M``) and
reduction (``K``) dimensions. Boundary blocks may contain fewer full tiles.
Mixed full and partial partition tiles require splitting the aggregate
transfers, which this kernel does not implement.

The ``m``, ``n``, and ``k`` loops walk block coordinates. Within each selected
block pair, the ``i``, ``j``, and ``p`` loops perform the same tile-level
contraction used by a tiled matmul.

The baseline reloads an LHS block for every output block column. The validated
``matmul_blocked_hoisted`` variant instead loads ``lhs_blocks[:, m]`` before
the ``n`` loop, reducing LHS loads from one per ``(m, n, k)`` to one
aggregate DMA per ``m``, covering all ``k`` blocks. The complete LHS column
must fit in SBUF, so its footprint grows with the reduction dimension.
:ref:`nki-tiled-grid-streaming` keeps that LHS column resident
while rotating RHS blocks through fixed stream slots.

.. _nki-tiled-grid-partial-blocks:

Handle partial blocks
---------------------

A full block spans ``tile_shape[d] * block_shape[d]`` elements along tiled
dimension ``d``. Tensor extents that are not multiples of this span leave
partial boundary blocks. Whether a partial block still moves in one DMA
depends on which dimension ends early.

Consider a ``(500, 500)`` source tiled by ``(128, 128)`` and grouped into
``(2, 2)`` tile blocks. The tile extents are 128, 128, 128, and 116 along both
dimensions, which produces all four cases at once:

.. figure:: ../../img/tiled-grids/partial-block.svg
   :alt: A four by four tile grid grouped into two by two tile blocks, with a trailing 116-element tile along each dimension, and a panel listing which blocks move in one DMA.
   :align: center
   :width: 100%

   A remainder along F leaves one partition extent per block. A remainder
   along P mixes 128 and 116, which no single operand can express.

For this dense two-dimensional layout, a block is representable when all
of its tiles share the same partition extent:

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

   # src.shape == (500, 500)
   src_blocks = nl.blocks(src, tile_shape=(128, 128), block_shape=(2, 2))

   src_blocks[0, 0].is_data_representable   # True: no remainder
   src_blocks[0, 1].is_data_representable   # True: F remainder only
   src_blocks[1, 0].is_data_representable   # False: spans 128 and 116
   src_blocks[1, 1].is_data_representable   # False: spans 128 and 116

For this layout, expose the block's interior tiles and split mixed partition
extents into the full tile rows and the final partial tile row. Each region
is representable, so the move uses two DMA instructions:

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

Other layouts can require further subdivision, for example when a
free-dimension remainder follows a gap. Check ``.is_data_representable``
for each proposed region.

This is the block-level form of the rule in
:ref:`nki-tiled-grid-data-representability`. ``block_shape`` does not change
it, because a block inherits the partition extents of the tiles it groups.


The complete implementation is available in
:download:`matmul.py <../../examples/tiled_grid/canonical/matmul.py>`, and
additional block operations are in
:download:`tile_block_grids.py <../../examples/tiled_grid/canonical/tile_block_grids.py>`.
The block-row transpose is in
:download:`transpose.py <../../examples/tiled_grid/canonical/transpose.py>`.
