.. meta::
   :description: Stream NKI tensors, tile grids, and block grids through bounded SBUF storage and build explicit software pipelines.
   :keywords: NKI, tiled grids, streaming, stream buffers, software pipeline, blocks, matmul
   :date-modified: 2026-10-12

.. _nki-tiled-grid-streaming:

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

Software pipelining
===================

A conventional tiled loop brings one region into SBUF and then computes on
it. When every iteration waits for its DMA to finish before starting compute,
data movement and compute happen one after the other, exposing the latency of
each transfer:

.. figure:: ../../img/tiled-grids/pipeline-sequential.svg
   :alt: Sequential DMA load and compute operations alternating on one slot.
   :align: center
   :width: 100%

   With one slot, each load and compute pair executes in sequence.

Software pipelining overlaps the two. While compute consumes the current step
from one SBUF slot, DMA loads the next step into another, hiding memory
latency behind useful work:

.. figure:: ../../img/tiled-grids/pipeline-two-stage.svg
   :alt: A double-buffered timeline overlapping load-next with compute-current.
   :align: center
   :width: 100%

   Double buffering exposes independent DMA and compute work in the steady
   state.

The compiler schedules this overlap: DMA and compute run on separate queues,
and it enforces the ordering between operations that share storage. What the
kernel controls is the storage itself. A *stream pool* is a fixed set of SBUF
slots reused in rotation as the kernel walks an operand consumed in order,
such as the K dimension of a matrix multiplication or a sequence of weight
blocks. The number of slots bounds the SBUF footprint, however large the
operand, and sets how many steps can be in flight at once.

In this tutorial, you will:

* allocate a stream pool and index its rotating slots;
* write two-stage and three-stage software pipelines;
* choose the tensor, tile, or block region represented by one stream step;
* combine a resident ``lhsT`` block column with a streamed ``rhs`` block
  column; and
* stream partial final steps.

This tutorial assumes familiarity with HBM, SBUF, PSUM, NKI ISA instructions,
tile grids, and block grids.

Allocate a stream pool
----------------------

:func:`nl.alloc_stream_buffers() <nki.language.alloc_stream_buffers>` takes
the complete region the kernel will walk and the dimension it advances along:

* ``view`` identifies the complete region being traversed;
* ``dim`` identifies the dimension that advances between iterations;
* ``num_slots`` sets how many physical allocations rotate.

Step ``k`` is ``view[:, ..., k, ..., :]``, the iteration count is
``view.shape[dim]``, and indexing the pool with ``buffers[k]`` returns
physical slot ``k % num_slots``. The returned slot has the same abstraction
as the selected step: streaming an ``NkiTensor`` produces ``NkiTensor``
slots, a tile grid produces tile-grid slots, and a block grid produces
block-grid slots.

``k`` must be a compile-time Python integer satisfying
``0 <= k < view.shape[dim]``. Use ``range(...)`` for static traversal;
runtime indices and compiled loop variables cannot select stream slots.

Compared with :func:`nl.empty_like() <nki.language.empty_like>`, a stream
pool changes how many allocations exist, not what they look like:

.. list-table::
   :header-rows: 1
   :widths: 34 66

   * - Allocation
     - Storage
   * - ``nl.empty_like(view, ...)``
     - One allocation shaped like ``view``
   * - ``nl.alloc_stream_buffers(view, dim=..., num_slots=...)``
     - ``num_slots`` allocations, each shaped like one step of ``view``,
       reused in rotation

Suppose ``src`` has shape ``(128, 8, 128)``. Streaming along ``dim=1`` makes
one ``(128, 128)`` slice the unit of movement, and two slots serve all eight
slices:

.. figure:: ../../img/tiled-grids/stream-tensor-step.svg
   :alt: Eight slices of a rank-three NkiTensor rotating through two SBUF slots.
   :align: center
   :width: 100%

   Advancing dimension 1 selects one ``(128, 128)`` ``NkiTensor`` per step.

.. nki_example:: ../../examples/tiled_grid/canonical/streaming.py
   :language: python
   :marker: NKI_EXAMPLE_TILED_GRID_SCALE_CHUNKS
   :linenos:

Allocating and indexing the pool select storage; neither moves data or
schedules instructions. Steps ``k`` and ``k + num_slots`` alias the same
physical slot, so place every read of the earlier step before writes for the
later one. The compiler preserves that order when it schedules slot reuse.

.. figure:: ../../img/tiled-grids/stream-buffers.svg
   :alt: Six logical iterations alternating between two physical stream slots.
   :align: center
   :width: 100%

   Logical iterations advance while the two physical allocations are reused.

Build pipelines
---------------

.. _nki-tiled-grid-two-stage-pipeline:

Build a two-stage pipeline
~~~~~~~~~~~~~~~~~~~~~~~~~~

A two-stage pipeline overlaps the load for the next iteration with compute
for the current iteration. Two slots remove the false dependency that would
arise if both operations used one physical allocation. The first load fills
the pipeline, and the final compute drains it.

A matmul reduction naturally uses this schedule because the output remains in
PSUM until all reduction coordinates have been processed. The following
kernel hoists each LHS tile column and streams the RHS column through two
slots:

.. nki_example:: ../../examples/tiled_grid/canonical/streaming.py
   :language: python
   :marker: NKI_EXAMPLE_TILED_GRID_PREFETCH_MATMUL
   :linenos:

This example uses full ``(128, 128)`` output tiles, so ``M`` and ``N`` must
be multiples of 128. The hoisted LHS column must have a uniform partition
extent: full ``K`` tiles or one partial ``K`` tile. That complete column must
fit in SBUF alongside the stream slots and output buffer.

The source order exposes independent DMA and Tensor Engine work. The
stream-buffer pool guarantees that load-next does not overwrite the moving
operand used by compute-current.

Build a three-stage pipeline
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

An elementwise pass usually has three operations for each logical item:

1. load from HBM into SBUF;
2. compute in SBUF;
3. store the result back to HBM.

If compute updates the slot in place, three physical slots allow three
consecutive items to occupy the load, compute, and store stages.

.. figure:: ../../img/tiled-grids/pipeline-three-stage.svg
   :alt: A triple-buffered load, compute, and store pipeline timeline.
   :align: center
   :width: 100%

   In the steady state, load, compute, and store use three different physical
   slots.

The following kernel applies this schedule to each tile column, with at
least two stream steps per column:

.. nki_example:: ../../examples/tiled_grid/canonical/streaming.py
   :language: python
   :marker: NKI_EXAMPLE_TILED_GRID_TRIPLE_BUFFER_PIPELINE
   :linenos:

Three stages do not universally imply three slots. Slot count follows storage
lifetime. This example needs three because load, in-place compute, and store
all use the same rotating pool. A pipeline with separate input and output
pools can have different slot counts for the two lifetimes. Use the smallest
slot count that safely expresses the intended overlap; additional slots
consume SBUF. Increasing the prefetch distance can also increase the work
needed to fill and drain the pipeline.

Choose the stream step
----------------------

The ``view`` and ``dim`` passed to the pool decide how much data one step
moves. In the table, ``src_tiles = nl.tiles(src, tile_shape=...)`` and
``src_blocks = nl.blocks(src, tile_shape=..., block_shape=...)``:

.. list-table::
   :header-rows: 1
   :widths: 40 15 45

   * - Source view
     - ``dim``
     - One slot holds
   * - ``NkiTensor`` with shape ``(128, 8, 128)``
     - ``1``
     - One ``(128, 128)`` ``NkiTensor``
   * - ``src_tiles[:, j]``
     - ``0``
     - One tile
   * - ``src_tiles[i]``
     - ``0``
     - One tile
   * - ``src_tiles``
     - ``1``
     - One complete tile column
   * - ``src_tiles``
     - ``0``
     - One complete tile row
   * - ``src_blocks[i]``
     - ``0``
     - One block
   * - ``src_blocks``
     - ``1``
     - One block column

Narrowing the view first changes the grain. Streaming ``src_tiles[:, 2]``
along ``dim=0`` moves one tile per step, while streaming the complete
``src_tiles`` along ``dim=1`` moves one complete tile column per step:

.. figure:: ../../img/tiled-grids/stream-tile-column-step.svg
   :alt: One complete tile column loaded into a column-shaped SBUF slot.
   :align: center
   :width: 100%

   Streaming the full grid along dimension 1 makes one complete column the
   movement grain.

The SBUF capacity scales with ``num_slots`` times the capacity of one full
stream step. A wider step, such as a complete column or a block, moves with
fewer coalesced DMAs, but every physical slot must hold that wider region.

.. _nki-streamed-blocked-matmul-kernel:

Streamed blocked matmul kernel
------------------------------

This kernel combines the tile and view model from
:ref:`nki-tiled-grid-fundamentals`, the compute-tile and movement-block
hierarchy from :ref:`nki-tiled-grid-blocks`, and the load-compute schedule
from :ref:`nki-tiled-grid-two-stage-pipeline`. Hoisting keeps one ``lhsT``
block column in SBUF for reuse across output columns, each ``rhs`` block
moves with one coalesced DMA, and two stream slots bound the streamed ``rhs``
footprint while the next block load overlaps the current block contraction.

For each output block ``(m, n)``, the kernel contracts
``lhsT_blocks[:, m]`` with ``rhs_blocks[:, n]`` over the block reduction
coordinate ``k``. The compute and movement geometry is:

.. list-table::
   :header-rows: 1
   :widths: 20 24 24 32

   * - View
     - Tile size (elements)
     - Block or region shape (tiles)
     - Nominal region extent (elements)
   * - ``lhsT``
     - ``(128, 128)``
     - ``(4, 4)``
     - ``(512, 512)``
   * - ``rhs``
     - ``(128, 512)``
     - ``(4, 2)``
     - ``(512, 1024)``
   * - PSUM, SBUF, and output
     - ``(128, 512)``
     - ``(4, 2)``
     - ``(512, 1024)``

The ``lhsT`` and ``rhs`` blocks share four reduction tiles along ``p``.
Their remaining dimensions provide four ``i`` tiles and two ``j`` tiles, so
each contraction contributes to a ``4 x 2`` output region. This shape uses
the eight-tile PSUM budget discussed in :ref:`nki-tiled-grid-blocks`.

.. figure:: ../../img/tiled-grids/streamed-blocked-matmul.svg
   :alt: Hoisted lhsT and streamed RHS block columns expanding into interior tile grids, accumulating in PSUM, and writing one HBM output block.
   :align: center
   :width: 100%

   The blue ``4 x 4`` ``lhsT`` block and green ``4 x 2`` ``rhs`` block expose
   their interior tiles for the current contraction. Dark purple marks the
   active ``4 x 2`` PSUM grid; light purple carries the completed result
   through SBUF to HBM.

The figure follows one ``(m, n)`` iteration. The complete kernel is included
below:

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

The aggregate transfers require a uniform partition extent in the hoisted
LHS column and each output block. A column that mixes full and partial
``K`` tiles, or an output block that mixes full and partial ``M`` tiles,
requires splitting those transfers. Partial ``N`` tiles and blocks containing
fewer full partition tiles are supported. The complete hoisted LHS column
must fit in SBUF alongside the RHS stream slots and output buffer.

Stream transposed data
----------------------

A stream pool can give every rotating slot the destination layout required
by a transpose. The stream ``dim`` still identifies the source-view
coordinate that advances, while ``transpose_axes`` defines the layout and
geometry of each SBUF slot. Allocating the pool does not move data or perform
the transpose.

The following kernel streams across one source tile row. Each
:func:`~nki.isa.dma_transpose` writes the current tile into a transposed SBUF
slot, and the following DMA stores it at the swapped output coordinate:

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

.. figure:: ../../img/tiled-grids/transpose-streamed.svg
   :alt: A source tile row transposed through two rotating SBUF slots into an output tile column.
   :align: center
   :width: 100%

   ``transposed_sbufs[j]`` rotates through two physical slots while preserving
   the transposed geometry of the logical step.

The same pattern applies to a ``NkiTensor`` step or a selected block-grid
region. Use separate stream pools when a kernel needs both normal and
transposed destinations, because every slot in one pool has the same layout.

Handle final partial steps
--------------------------

Every physical slot has the capacity required by the first stream step. If
the final tensor slice, tile, or block is partial, indexing its logical
iteration returns a clamped view over the corresponding full-capacity
physical slot.

.. figure:: ../../img/tiled-grids/stream-partial-step.svg
   :alt: A final partial stream view clamped over a full-capacity physical slot.
   :align: center
   :width: 100%

   The final logical view excludes reserved tail capacity from its DMA operand.

The DMA uses the final view's exact valid extent. The unused capacity remains
reserved in SBUF so that every physical slot can be reused with the same
allocation geometry.

The first step must provide enough capacity for every later step. Standard tile
grids and block grids satisfy this because only the final coordinate can be
smaller.

A clamped step behaves like any other partial view, so the rules from
:ref:`nki-tiled-grid-partial-blocks` decide how it moves. The following kernel
streams each block row of a ``(500, 500)`` source through two slots. The final
step of the first row is clamped along F and still moves with one DMA. Every
block in the last row spans a partition remainder, so ``_move_block`` splits
it into one transfer per partition extent:

.. nki_example:: ../../examples/tiled_grid/canonical/streaming.py
   :language: python
   :marker: NKI_EXAMPLE_TILED_GRID_STREAM_PARTIAL_BLOCKS
   :linenos:

The loop body is the same for full and partial steps. ``_move_block`` checks
``is_data_representable`` on both sides, so the kernel never inspects the
remainder itself.

The complete synchronized sources are available in
:download:`streaming.py <../../examples/tiled_grid/canonical/streaming.py>`
and
:download:`matmul.py <../../examples/tiled_grid/canonical/matmul.py>`.
