This document is relevant for: Trn2, Trn3
Block-grid fundamentals#
Tile grids give NKI kernels a compute-sized view of a tensor: tile_shape
describes the data presented to an 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 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.
nl.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. nl.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 Tile-grid fundamentals and the runtime indexing, sharding, and transpose patterns in Tile-grid indexing and transformations. 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#
nl.blocks() preserves tile geometry and adds
block coordinates above it. block_shape is expressed in tile counts, not
elements.
# 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
Property |
Unit |
Meaning |
|---|---|---|
|
source elements |
Nominal compute tile |
|
tiles |
Tiles grouped into one block |
|
block coordinates |
Currently indexable block extents |
|
source elements |
Exact selected source extent |
Fig. 33 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
Tile-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
nl.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.
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.
# 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 Tile-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.
Fig. 34 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 nl.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.
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)
Fig. 35 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#
nl.empty_like() mirrors the geometry of a
selected block region. nl.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 nl.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:
1@nki.jit
2def initialize_block_grid():
3 """Initialize an SBUF block grid with a partial final column."""
4 tile_shape = (128, 128)
5 block_shape = (1, 2)
6 element_shape = (128, 500)
7 out_sbuf = nl.alloc_blocks(
8 tile_shape=tile_shape,
9 block_shape=block_shape,
10 element_shape=element_shape,
11 buffer=nl.sbuf,
12 dtype=nl.float32,
13 )
14 out = nl.ndarray(element_shape, dtype=nl.float32, buffer=nl.shared_hbm)
15 out_blocks = nl.blocks(out, tile_shape=tile_shape, block_shape=block_shape)
16
17 assert out_sbuf[:, -1].is_remainder
18 nisa.memset(dst=out_sbuf.data, value=2.5)
19 nisa.dma_copy(dst=out_blocks.data, src=out_sbuf.data)
20 return out
21
22
Index and transform block grids#
The runtime scalar keys, ownership slices, and transpose operations introduced in Tile-grid indexing and transformations 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.
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)
Fig. 36 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. grid_element_offset() remains the narrow
alternative for a kernel that already maintains an aligned element offset.
Transpose block regions#
A block transpose follows the same allocation and movement split as a tile transpose:
Select the source block region.
Allocate a matching SBUF region with
transpose_axes.Move it with
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.
Fig. 38 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:
1@nki.jit
2def transpose_block_row(src):
3 """Transpose one complete row of ``(2, 2)`` tile blocks."""
4 src_blocks = nl.blocks(
5 src,
6 tile_shape=(128, 128),
7 block_shape=(2, 2),
8 )
9 src_row_view = src_blocks[0]
10 transposed_sbuf = nl.empty_like(
11 src_row_view,
12 buffer=nl.sbuf,
13 transpose_axes=(1, 0),
14 )
15 nisa.dma_transpose(
16 dst=transposed_sbuf.data,
17 src=src_row_view.data,
18 axes=(3, 1, 2, 0),
19 )
20
21 out = nl.ndarray(
22 (src.shape[1], 256),
23 dtype=src.dtype,
24 buffer=nl.shared_hbm,
25 )
26 out_blocks = nl.blocks(
27 out,
28 tile_shape=(128, 128),
29 block_shape=(2, 2),
30 )
31 # The SBUF allocation traverses blocks before their interior tiles, while
32 # the contiguous HBM output traverses tiles before blocks. permute swaps
33 # those levels so one copy walks both sides in the same order.
34 nisa.dma_copy(
35 dst=out_blocks[:, 0].data,
36 src=transposed_sbuf.data.permute((0, 2, 1, 3)),
37 )
38 return out
39
40
The store needs one extra step. dma_transpose() always writes
to SBUF, so returning the result to HBM is an ordinary 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
dma_transpose(). The allocation and movement code stays the
same whether its input represents the complete grid or one shard.
Fig. 39 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.
Fig. 40 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:
1@nki.jit
2def copy_interleaved_tile_blocks(src):
3 """Promote interleaved tile rows to aggregate DMA blocks."""
4 out = nl.ndarray(src.shape, dtype=src.dtype, buffer=nl.shared_hbm)
5 src_tiles = nl.tiles(src, tile_shape=(128, 128))
6 out_tiles = nl.tiles(out, tile_shape=(128, 128))
7 owned_rows = nl.interleaved_indices(
8 src_tiles.shape[0],
9 shard_id=nl.program_id(0),
10 num_shards=nl.num_programs(0),
11 )
12 src_blocks = nl.blocks(
13 src_tiles[owned_rows, :],
14 block_shape=(2, 1),
15 )
16 out_blocks = nl.blocks(
17 out_tiles[owned_rows, :],
18 block_shape=(2, 1),
19 )
20
21 for i in range(src_blocks.shape[0]):
22 for j in range(src_blocks.shape[1]):
23 block_sbuf = nl.empty_like(src_blocks[i, j], buffer=nl.sbuf)
24 nisa.dma_copy(dst=block_sbuf.data, src=src_blocks[i, j].data)
25 nisa.dma_copy(dst=out_blocks[i, j].data, src=block_sbuf.data)
26 return out
27
28
Each 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 Tile-grid fundamentals:
LHS and RHS blocks move from HBM to SBUF.
nl.tiles()exposes their interior compute tiles.Interior products accumulate into a PSUM tile grid.
The completed output block moves to HBM with one DMA.
The example uses instruction-compatible tile shapes and groups them into larger movement regions:
Operand |
Tile shape |
Block shape |
Block-grid coordinates |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
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.
Fig. 41 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 nc_matmul(), and stores each completed
output block with one DMA:
1@nki.jit
2def matmul_blocked(lhs_t, rhs, block_m=4, block_n=2, block_k=4):
3 """Compute ``lhs_t.T @ rhs`` with block-level DMA."""
4 assert block_m * block_n <= 8, "output block exceeds PSUM capacity"
5 tile_m = nl.tile_size.gemm_stationary_fmax
6 tile_k = nl.tile_size.pmax
7 tile_n = nl.tile_size.gemm_moving_fmax
8 # Keep M/K tiles full to avoid mixed partition extents in block transfers.
9 assert lhs_t.shape[1] % tile_m == 0, (
10 f"This example requires M to be a multiple of {tile_m}"
11 )
12 assert lhs_t.shape[0] % tile_k == 0 and rhs.shape[0] % tile_k == 0, (
13 f"This example requires K to be a multiple of {tile_k} in both inputs"
14 )
15 out = nl.ndarray(
16 (lhs_t.shape[1], rhs.shape[1]),
17 dtype=lhs_t.dtype,
18 buffer=nl.shared_hbm,
19 )
20
21 lhs_blocks = nl.blocks(
22 lhs_t,
23 tile_shape=(tile_k, tile_m),
24 block_shape=(block_k, block_m),
25 )
26 rhs_blocks = nl.blocks(
27 rhs,
28 tile_shape=(tile_k, tile_n),
29 block_shape=(block_k, block_n),
30 )
31 out_blocks = nl.blocks(
32 out,
33 tile_shape=(tile_m, tile_n),
34 block_shape=(block_m, block_n),
35 )
36
37 for m in range(lhs_blocks.shape[1]):
38 for n in range(rhs_blocks.shape[1]):
39 out_block = out_blocks[m, n]
40 out_psum = nl.alloc_tiles(
41 tile_shape=(tile_m, tile_n),
42 element_shape=out_block.element_shape,
43 buffer=nl.psum,
44 dtype=nl.float32,
45 )
46 out_sbuf = nl.alloc_tiles(
47 tile_shape=(tile_m, tile_n),
48 element_shape=out_block.element_shape,
49 buffer=nl.sbuf,
50 dtype=lhs_t.dtype,
51 )
52
53 for k in nl.sequential_range(rhs_blocks.shape[0]):
54 lhs_sbuf = nl.empty_like(lhs_blocks[k, m], buffer=nl.sbuf)
55 rhs_sbuf = nl.empty_like(rhs_blocks[k, n], buffer=nl.sbuf)
56 nisa.dma_copy(dst=lhs_sbuf.data, src=lhs_blocks[k, m].data)
57 nisa.dma_copy(dst=rhs_sbuf.data, src=rhs_blocks[k, n].data)
58 lhs_tiles_sbuf = nl.tiles(lhs_sbuf)
59 rhs_tiles_sbuf = nl.tiles(rhs_sbuf)
60 for i in range(out_sbuf.shape[0]):
61 for j in range(out_sbuf.shape[1]):
62 for p in range(rhs_tiles_sbuf.shape[0]):
63 is_first_contraction = k == 0 and p == 0
64 nisa.nc_matmul(
65 dst=out_psum[i, j].data,
66 stationary=lhs_tiles_sbuf[p, i].data,
67 moving=rhs_tiles_sbuf[p, j].data,
68 accumulate=not is_first_contraction,
69 )
70
71 nisa.tensor_copy(dst=out_sbuf.data, src=out_psum.data)
72 nisa.dma_copy(dst=out_block.data, src=out_sbuf.data)
73 return out
74
75
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.
Software pipelining keeps that LHS column resident
while rotating RHS blocks through fixed stream slots.
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:
Fig. 42 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:
# 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:
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 block_level_scale(src):
16 """Process full and partial boundary blocks one block at a time."""
17 # src is a 2D tensor, for example (500, 500).
18 tile_shape = (128, 128)
19 block_shape = (2, 2)
20 dst = nl.ndarray(src.shape, dtype=src.dtype, buffer=nl.shared_hbm)
21 src_blocks = nl.blocks(src, tile_shape=tile_shape, block_shape=block_shape)
22 dst_blocks = nl.blocks(dst, tile_shape=tile_shape, block_shape=block_shape)
23
24 for i in range(src_blocks.shape[0]):
25 for j in range(src_blocks.shape[1]):
26 block_view = src_blocks[i, j]
27 block_sbuf = nl.empty_like(block_view, buffer=nl.sbuf)
28 _move_block(block_sbuf, block_view)
29 # A partial boundary block exposes only the tiles it contains.
30 tiles_sbuf = nl.tiles(block_sbuf)
31 for k in range(tiles_sbuf.shape[0]):
32 for p in range(tiles_sbuf.shape[1]):
33 tile_sbuf = tiles_sbuf[k, p].data
34 nisa.tensor_scalar(tile_sbuf, tile_sbuf, nl.multiply, 2.0)
35 _move_block(dst_blocks[i, j], block_sbuf)
36 return dst
37
38
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
Know when .data is representable. block_shape does not change
it, because a block inherits the partition extents of the tiles it groups.
The complete implementation is available in
matmul.py, and
additional block operations are in
tile_block_grids.py.
The block-row transpose is in
transpose.py.
This document is relevant for: Trn2, Trn3