This document is relevant for: Trn2, Trn3

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:

Sequential DMA load and compute operations alternating on one slot.

Fig. 43 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:

A double-buffered timeline overlapping load-next with compute-current.

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

nl.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 nl.empty_like(), a stream pool changes how many allocations exist, not what they look like:

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:

Eight slices of a rank-three NkiTensor rotating through two SBUF slots.

Fig. 45 Advancing dimension 1 selects one (128, 128) NkiTensor per step.#

 1@nki.jit
 2def scale_chunks(src):
 3    """Scale rank-three tensor slices through two reusable SBUF slots."""
 4    # src.shape == (128, 8, 128)
 5    out = nl.ndarray(src.shape, dtype=src.dtype, buffer=nl.shared_hbm)
 6    src_sbufs = nl.alloc_stream_buffers(src, buffer=nl.sbuf, dim=1, num_slots=2)
 7
 8    for m in range(src.shape[1]):
 9        src_chunk = src[:, m, :]
10        chunk_sbuf = src_sbufs[m]
11        nisa.dma_copy(dst=chunk_sbuf, src=src_chunk)
12        nisa.tensor_scalar(
13            dst=chunk_sbuf,
14            data=chunk_sbuf,
15            op0=nl.multiply,
16            operand0=2.0,
17        )
18        nisa.dma_copy(dst=out[:, m, :], src=chunk_sbuf)
19    return out
20
21

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.

Six logical iterations alternating between two physical stream slots.

Fig. 46 Logical iterations advance while the two physical allocations are reused.#

Build pipelines#

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:

 1@nki.jit
 2def explicit_prefetch_matmul(lhs_t, rhs):
 3    """Prefetch the next RHS tile while multiplying the current tile."""
 4    # lhs_t and rhs are 2D tensors, for example (256, 256).
 5    tile_shape = (128, 128)
 6    _, out_rows = lhs_t.shape
 7    _, out_cols = rhs.shape
 8    assert lhs_t.shape[0] == rhs.shape[0], "Inputs must have the same K dimension"
 9    assert out_rows % tile_shape[0] == 0, (
10        f"This example requires M to be a multiple of {tile_shape[0]}"
11    )
12    assert out_cols % tile_shape[1] == 0, (
13        f"This example requires N to be a multiple of {tile_shape[1]}"
14    )
15    out = nl.ndarray((out_rows, out_cols), dtype=lhs_t.dtype, buffer=nl.shared_hbm)
16
17    lhs_tiles = nl.tiles(lhs_t, tile_shape=tile_shape)
18    rhs_tiles = nl.tiles(rhs, tile_shape=tile_shape)
19    out_tiles = nl.tiles(out, tile_shape=tile_shape)
20    reduction_tiles = lhs_tiles.shape[0]
21
22    for m in range(out_tiles.shape[0]):
23        # Hoist the LHS column.
24        lhs_col_view = lhs_tiles[:, m]
25        lhs_sbuf = nl.empty_like(lhs_col_view, buffer=nl.sbuf)
26        assert lhs_col_view.is_data_representable and lhs_sbuf.is_data_representable, (
27            "Split full and partial K tiles before hoisting the LHS column"
28        )
29        nisa.dma_copy(dst=lhs_sbuf.data, src=lhs_col_view.data)
30
31        for n in range(out_tiles.shape[1]):
32            rhs_col_view = rhs_tiles[:, n]
33            # Stream the RHS column through two physical slots.
34            rhs_sbufs = nl.alloc_stream_buffers(
35                rhs_col_view, buffer=nl.sbuf, dim=0, num_slots=2
36            )
37
38            out_psum = nl.ndarray(tile_shape, dtype=nl.float32, buffer=nl.psum)
39
40            # Prologue.
41            nisa.dma_copy(dst=rhs_sbufs[0].data, src=rhs_col_view[0].data)
42
43            # Steady state.
44            for k in range(reduction_tiles - 1):
45                nisa.dma_copy(
46                    dst=rhs_sbufs[k + 1].data,
47                    src=rhs_col_view[k + 1].data,
48                )
49                nisa.nc_matmul(
50                    dst=out_psum,
51                    stationary=lhs_sbuf[k].data,
52                    moving=rhs_sbufs[k].data,
53                    accumulate=k > 0,
54                )
55
56            # Epilogue.
57            nisa.nc_matmul(
58                dst=out_psum,
59                stationary=lhs_sbuf[reduction_tiles - 1].data,
60                moving=rhs_sbufs[reduction_tiles - 1].data,
61                accumulate=reduction_tiles > 1,
62            )
63
64            # Copy the result from PSUM through SBUF to HBM.
65            out_sbuf = nl.ndarray(tile_shape, dtype=nl.float32, buffer=nl.sbuf)
66            nisa.tensor_copy(dst=out_sbuf, src=out_psum)
67            nisa.dma_copy(
68                dst=out_tiles[m, n].data,
69                src=out_sbuf,
70            )
71    return out
72
73

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.

A triple-buffered load, compute, and store pipeline timeline.

Fig. 47 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:

 1@nki.jit
 2def triple_buffer_pipeline(src):
 3    """Scale tiles in place through a three-stage pipeline."""
 4    # src is a 2D tensor, for example (512, 256).
 5    tile_shape = (128, 512)
 6    src_tiles = nl.tiles(src, tile_shape=tile_shape)
 7    out = nl.ndarray(src.shape, dtype=src.dtype, buffer=nl.shared_hbm)
 8    out_tiles = nl.tiles(out, tile_shape=tile_shape)
 9
10    def scale_in_place(slot):
11        nisa.tensor_scalar(dst=slot.data, data=slot.data, op0=nl.multiply, operand0=2.0)
12
13    for j in range(src_tiles.shape[1]):
14        src_view = src_tiles[:, j]
15        out_view = out_tiles[:, j]
16        src_sbufs = nl.alloc_stream_buffers(
17            src_view, buffer=nl.sbuf, dim=0, num_slots=3
18        )
19        count = src_view.shape[0]
20        assert count >= 2, "This pipeline requires at least two stream steps"
21
22        # Prologue: load two items and compute the first.
23        nisa.dma_copy(dst=src_sbufs[0].data, src=src_view[0].data)
24        nisa.dma_copy(dst=src_sbufs[1].data, src=src_view[1].data)
25        scale_in_place(src_sbufs[0])
26
27        # Steady state: load k, compute k - 1, and store k - 2.
28        for k in range(2, count):
29            nisa.dma_copy(dst=src_sbufs[k].data, src=src_view[k].data)
30            scale_in_place(src_sbufs[k - 1])
31            nisa.dma_copy(
32                dst=out_view[k - 2].data,
33                src=src_sbufs[k - 2].data,
34            )
35
36        # Epilogue: finish and store the remaining items.
37        scale_in_place(src_sbufs[count - 1])
38        nisa.dma_copy(
39            dst=out_view[count - 2].data,
40            src=src_sbufs[count - 2].data,
41        )
42        nisa.dma_copy(
43            dst=out_view[count - 1].data,
44            src=src_sbufs[count - 1].data,
45        )
46    return out
47
48

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=...):

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:

One complete tile column loaded into a column-shaped SBUF slot.

Fig. 48 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.

Streamed blocked matmul kernel#

This kernel combines the tile and view model from Tile-grid fundamentals, the compute-tile and movement-block hierarchy from Block-grid fundamentals, and the load-compute schedule from Build a 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:

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 Block-grid fundamentals.

Hoisted lhsT and streamed RHS block columns expanding into interior tile grids, accumulating in PSUM, and writing one HBM output block.

Fig. 49 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:

 1@nki.jit
 2def matmul_blocked_streamed(lhs_t, rhs, block_m=4, block_n=2, block_k=4):
 3    """Stream RHS reduction blocks while accumulating one output block."""
 4    assert block_m * block_n <= 8, "output block exceeds PSUM capacity"
 5    assert lhs_t.shape[0] == rhs.shape[0], "Inputs must have the same K dimension"
 6    tile_m = nl.tile_size.gemm_stationary_fmax
 7    tile_k = nl.tile_size.pmax
 8    tile_n = nl.tile_size.gemm_moving_fmax
 9    out = nl.ndarray(
10        (lhs_t.shape[1], rhs.shape[1]),
11        dtype=lhs_t.dtype,
12        buffer=nl.shared_hbm,
13    )
14
15    lhs_blocks = nl.blocks(
16        lhs_t,
17        tile_shape=(tile_k, tile_m),
18        block_shape=(block_k, block_m),
19    )
20    rhs_blocks = nl.blocks(
21        rhs,
22        tile_shape=(tile_k, tile_n),
23        block_shape=(block_k, block_n),
24    )
25    out_blocks = nl.blocks(
26        out,
27        tile_shape=(tile_m, tile_n),
28        block_shape=(block_m, block_n),
29    )
30
31    for m in range(lhs_blocks.shape[1]):
32        lhs_col = lhs_blocks[:, m]
33        lhs_sbuf = nl.empty_like(lhs_col, buffer=nl.sbuf)
34        assert lhs_col.is_data_representable and lhs_sbuf.is_data_representable, (
35            "Split full and partial K tiles before hoisting the LHS column"
36        )
37        nisa.dma_copy(dst=lhs_sbuf.data, src=lhs_col.data)
38
39        for n in range(rhs_blocks.shape[1]):
40            out_block = out_blocks[m, n]
41            out_psum = nl.alloc_tiles(
42                tile_shape=(tile_m, tile_n),
43                element_shape=out_block.element_shape,
44                buffer=nl.psum,
45                dtype=nl.float32,
46            )
47            out_sbuf = nl.alloc_tiles(
48                tile_shape=(tile_m, tile_n),
49                element_shape=out_block.element_shape,
50                buffer=nl.sbuf,
51                dtype=lhs_t.dtype,
52            )
53            assert (
54                out_block.is_data_representable
55                and out_psum.is_data_representable
56                and out_sbuf.is_data_representable
57            ), "Split full and partial M tiles into separate output blocks"
58            rhs_col = rhs_blocks[:, n]
59            rhs_stream = nl.alloc_stream_buffers(
60                rhs_col,
61                buffer=nl.sbuf,
62                dim=0,
63                num_slots=2,
64            )
65
66            # Prologue: make the first RHS block available.
67            nisa.dma_copy(dst=rhs_stream[0].data, src=rhs_col[0].data)
68
69            for k in range(rhs_col.shape[0]):
70                # Prefetch the next RHS block before computing the current one.
71                if k + 1 < rhs_col.shape[0]:
72                    nisa.dma_copy(
73                        dst=rhs_stream[k + 1].data,
74                        src=rhs_col[k + 1].data,
75                    )
76
77                lhs_tiles = nl.tiles(lhs_sbuf[k])
78                rhs_tiles = nl.tiles(rhs_stream[k])
79                for i in range(out_sbuf.shape[0]):
80                    for j in range(out_sbuf.shape[1]):
81                        for p in range(rhs_tiles.shape[0]):
82                            nisa.nc_matmul(
83                                dst=out_psum[i, j].data,
84                                stationary=lhs_tiles[p, i].data,
85                                moving=rhs_tiles[p, j].data,
86                                accumulate=None,
87                            )
88
89            nisa.tensor_copy(dst=out_sbuf.data, src=out_psum.data)
90            nisa.dma_copy(dst=out_block.data, src=out_sbuf.data)
91    return out
92
93

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 dma_transpose() writes the current tile into a transposed SBUF slot, and the following DMA stores it at the swapped output coordinate:

 1@nki.jit
 2def transpose_streamed(src):
 3    """Transpose each tile through a statically indexed double buffer."""
 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_sbufs = nl.alloc_stream_buffers(
12            src_row_view,
13            buffer=nl.sbuf,
14            dim=0,
15            num_slots=2,
16            transpose_axes=(1, 0),
17        )
18        for j in range(src_row_view.shape[0]):
19            nisa.dma_transpose(
20                dst=transposed_sbufs[j].data,
21                src=src_row_view[j].data,
22            )
23            nisa.dma_copy(
24                dst=out_tiles[j, i].data,
25                src=transposed_sbufs[j].data,
26            )
27    return out
28
29
A source tile row transposed through two rotating SBUF slots into an output tile column.

Fig. 50 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.

A final partial stream view clamped over a full-capacity physical slot.

Fig. 51 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 Handle 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:

 1def _move_block(dst_view, src_view):
 2    """Move one block, splitting it when its tiles have mixed partition extents."""
 3    if src_view.is_data_representable and dst_view.is_data_representable:
 4        nisa.dma_copy(dst=dst_view.data, src=src_view.data)
 5        return
 6
 7    # A block that spans a partition remainder needs one transfer per extent.
 8    dst_tiles = nl.tiles(dst_view)
 9    src_tiles = nl.tiles(src_view)
10    nisa.dma_copy(dst=dst_tiles[:-1].data, src=src_tiles[:-1].data)
11    nisa.dma_copy(dst=dst_tiles[-1:].data, src=src_tiles[-1:].data)
12
13
14@nki.jit
15def stream_2d_blocks(src):
16    """Stream one block at a time and process its interior tile grid."""
17    # src is a 2D tensor, for example (500, 500).
18    tile_shape = (128, 128)
19    block_shape = (2, 2)
20    src_blocks = nl.blocks(src, tile_shape=tile_shape, block_shape=block_shape)
21    out = nl.ndarray(src.shape, dtype=src.dtype, buffer=nl.shared_hbm)
22    out_blocks = nl.blocks(out, tile_shape=tile_shape, block_shape=block_shape)
23
24    for i in range(src_blocks.shape[0]):
25        src_row_view = src_blocks[i, :]
26        src_sbufs = nl.alloc_stream_buffers(
27            src_row_view, buffer=nl.sbuf, dim=0, num_slots=2
28        )
29        for j in range(src_row_view.shape[0]):
30            # The final step of a row returns a view clamped to its valid extent.
31            block_sbuf = src_sbufs[j]
32            _move_block(block_sbuf, src_row_view[j])
33            tiles_sbuf = nl.tiles(block_sbuf)
34            for k in range(tiles_sbuf.shape[0]):
35                for p in range(tiles_sbuf.shape[1]):
36                    tile_sbuf = tiles_sbuf[k, p].data
37                    nisa.tensor_scalar(
38                        dst=tile_sbuf, data=tile_sbuf, op0=nl.multiply, operand0=2.0
39                    )
40            _move_block(out_blocks[i, j], block_sbuf)
41    return out
42
43

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 streaming.py and matmul.py.

This document is relevant for: Trn2, Trn3