This document is relevant for: Trn2, Trn3

Tiled MLP CTE kernel#

Context Encoding (CTE), also called prefill, processes a sequence of input tokens in parallel. The MLP in this phase applies gate and up projections, combines them with a SwiGLU activation, and projects the intermediate back to the model’s hidden size:

\[y = \left(\operatorname{silu}(x \cdot gate) * (x \cdot up)\right) \cdot down\]

A direct implementation can materialize the three projection results in HBM. This tutorial instead keeps one activation block on chip while it streams the weights needed by each projection. Intermediate results move between SBUF and PSUM, but do not return to HBM before the final output store.

The kernel combines the main techniques developed in the preceding tutorials:

  • block grids move several compute tiles with each coalesced DMA;

  • contiguous slices assign independent activation blocks to NeuronCores;

  • rotating SBUF slots bound the footprint of streamed blocks;

  • tile views expose the compute grain inside each resident or streamed block;

  • PSUM tile groups hold matrix-multiplication accumulators; and

  • retiling and transposing prepare one resident allocation for the next stage.

All coordinates in this kernel are known at compile time, so it does not need the indirect-indexing patterns from Tile-grid indexing and transformations.

This tutorial assumes familiarity with HBM, SBUF, PSUM, and NKI ISA instructions, as well as Tile-grid fundamentals, Block-grid fundamentals, and Software pipelining.

Map the computation to grids#

The input has shape [B, S, K]. The kernel flattens the batch and sequence dimensions into M = B * S, performs the MLP on [M, K], and restores [B, S, H] before returning. The weight matrices are shared by every activation block.

At block-grid granularity, let m, k, i, and h identify block coordinates along those four dimensions. The MLP then becomes:

\[\begin{split}\begin{aligned} G_{m,i} &= \sum_k X_{m,k} \cdot gate_{k,i} \\ U_{m,i} &= \sum_k X_{m,k} \cdot up_{k,i} \\ A_{m,i} &= \operatorname{silu}(G_{m,i}) \odot U_{m,i} \\ Y_{m,h} &= \sum_i A_{m,i} \cdot down_{i,h} \end{aligned}\end{split}\]

Each product in these equations expands into tile-level nc_matmul() calls after the selected blocks reach SBUF. The block coordinates expose the larger execution structure:

  • m identifies independent activation blocks and can be sharded across NeuronCores.

  • k is the reduction dimension of the gate and up projections.

  • i is first the SwiGLU output dimension, then the reduction dimension of the down projection.

  • h is the final output dimension.

Input, gate, up, intermediate, down, and output block grids connected according to the two MLP contractions.

Fig. 52 Gate and up reduce the same resident X[m, :] block row over k. Their [m, i] results form A, which becomes the resident operand for the down projection’s reduction over i.#

Value

Element shape

Tile shape

Role

x

(M, K)

(128, 128)

Activation blocks sharded along M

gate and up

(K, I)

(128, 512)

Weight blocks streamed along K

gated_sbuf

(M_block, I)

(128, 512)

On-chip SwiGLU intermediate

down

(I, H)

(128, 512)

Weight blocks streamed along I

out

(M, H)

(128, 512)

Output blocks stored along M

M_block is the current activation block’s row count, at most block_m * tile_m.

tile_shape follows the ISA operation that consumes a tile. block_shape is the tunable movement grain: block_m controls how many activation tiles are processed together, while block_k, block_i, and block_h group the reduction and output tiles used by the projections.

The corresponding block-level loop is:

for m in owned_m_blocks:
    x_m = load(x_blocks[m, :])

    for i_group in i_groups:
        gate_psum = sum_k(x_m[k] @ gate[k, i_group])
        gated_sbuf[i_group] = silu(gate_psum)
        up_psum = sum_k(x_m[k] @ up[k, i_group])
        gated_sbuf[i_group] *= up_psum

    for h in h_blocks:
        out_sbuf[h] = sum_i(gated_sbuf[i] @ down[i, h])

    store(out_blocks[m, :], out_sbuf)

The kernel materializes only the current gated_sbuf block row, not a complete [M, I] tensor.

Start with the top-level kernel#

Read the top-level function before the helpers. It establishes the complete execution structure:

  1. Flatten B and S and define matching input and output block grids.

  2. Slice both grids with the same contiguous M-axis ownership range.

  3. Define gate, up, and down weight block grids shared by every owned activation block.

  4. Allocate two activation stream slots and load the first block.

  5. Prefetch the next activation block, run the three compute stages, and store one complete output block on each loop iteration.

The input and output grids use identical global M coordinates. The same owned_m slice therefore determines both what a NeuronCore reads and where it writes:

Matching input and output M-axis block ranges assigned to NeuronCore zero and NeuronCore one.

Fig. 53 Slicing changes which coordinates a core visits. The downstream stream and compute code remains the same for either ownership range.#

Each core may own more activation blocks than can remain in SBUF at once. x_sbufs provides two physical slots while preserving a logical view for every block in x_view:

Core-owned HBM activation blocks mapped in order to two rotating SBUF slots.

Fig. 54 Within each core-owned view, local stream step s uses physical slot s % 2. Global m coordinates show that the cores read disjoint HBM blocks; each core owns a separate two-slot SBUF pool.#

Loading the first block before the loop fills the pipeline. In each iteration, the load for block m + 1 appears before compute on block m:

Two-stage activation timeline overlapping the next HBM-to-SBUF load with projection work on the current block.

Fig. 55 After the prologue, the compiler can overlap the next activation load with projection work on the current slot. The final iteration drains the pipeline without issuing another load.#

The complete method puts those pieces in one place. Its loop body makes the dataflow explicit: transpose the activation, compute SwiGLU, transpose the intermediate, and compute the down projection. The helper methods are developed in the sections that follow.

  1@nki.jit
  2def mlp_cte(
  3    x: nl.NkiTensor,
  4    gate_proj: nl.NkiTensor,
  5    up_proj: nl.NkiTensor,
  6    down_proj: nl.NkiTensor,
  7    config: MLPConfig,
  8) -> nl.NkiTensor:
  9    """Single-rank Context Encoding MLP using tiled grids.
 10
 11    Computes ``y = (silu(x @ gate_proj) * (x @ up_proj)) @ down_proj`` for a
 12    single rank with M-axis sharding across logical NeuronCores.
 13
 14    Dimensions:
 15        B: Batch size
 16        S: Sequence length
 17        K: Input hidden dimension and gate/up reduction dimension
 18        I: Intermediate dimension between gate/up and down
 19        H: Output hidden dimension
 20        M: Flattened B * S
 21
 22    Args:
 23        x (nl.NkiTensor): [B, S, K] input hidden states in HBM.
 24        gate_proj (nl.NkiTensor): [K, I] gate projection weights in HBM.
 25        up_proj (nl.NkiTensor): [K, I] up projection weights in HBM.
 26        down_proj (nl.NkiTensor): [I, H] down projection weights in HBM.
 27        config (MLPConfig): Kernel configuration (tile/block sizes, buffering).
 28
 29    Returns:
 30        out (nl.NkiTensor): [B, S, H] MLP result in HBM.
 31
 32    Notes:
 33        - LNC sharding partitions the M = B * S axis across cores; each core
 34          processes its slice of x_blocks and writes its slice of
 35          out_blocks.
 36        - Two activation slots allow the next owned block to load while the
 37          current block moves through the projection stages.
 38    """
 39    assert len(x.shape) == 3, "x must be [B, S, K]"
 40    batch, sequence, k_size = x.shape
 41    assert k_size == config.K, "x hidden size must equal config.K"
 42    assert gate_proj.shape == (config.K, config.I)
 43    assert up_proj.shape == (config.K, config.I)
 44    assert down_proj.shape == (config.I, config.H)
 45
 46    # Flatten batch and sequence, then define input and output block grids.
 47    m_size = batch * sequence
 48    assert m_size % config.tile_m == 0, (
 49        f"M={m_size} must be divisible by tile_m={config.tile_m}"
 50    )
 51    x = x.reshape((m_size, k_size))
 52    out = nl.ndarray(
 53        (m_size, config.H),
 54        dtype=x.dtype,
 55        buffer=nl.shared_hbm,
 56    )
 57
 58    x_blocks = nl.blocks(
 59        x,
 60        tile_shape=(config.tile_m, config.tile_k),
 61        block_shape=(config.block_m, config.block_k),
 62    )
 63    out_blocks = nl.blocks(
 64        out,
 65        tile_shape=(config.tile_m, config.tile_h),
 66        block_shape=(config.block_m, config.H // config.tile_h),
 67    )
 68
 69    # Define per-core sharding of input and output blocks.
 70    owned_m = nl.contiguous_indices(
 71        x_blocks.shape[0],
 72        shard_id=nl.program_id(0),
 73        num_shards=nl.num_programs(0),
 74    )
 75    x_view = x_blocks[owned_m]
 76    out_view = out_blocks[owned_m]
 77
 78    # Create block-grid views for weights shared by all owned x blocks.
 79    gate = nl.blocks(
 80        gate_proj,
 81        tile_shape=(config.tile_k, config.tile_i),
 82        block_shape=(config.block_k, 1),
 83    )
 84    up = nl.blocks(
 85        up_proj,
 86        tile_shape=(config.tile_k, config.tile_i),
 87        block_shape=(config.block_k, 1),
 88    )
 89    down = nl.blocks(
 90        down_proj,
 91        tile_shape=(config.tile_down_i, config.tile_h),
 92        block_shape=(config.block_i, config.block_h),
 93    )
 94
 95    # Allocate the SiLU bias once for all owned x blocks.
 96    bias_sbuf = nl.ndarray((config.tile_m, 1), dtype=nl.float32, buffer=nl.sbuf)
 97    nisa.memset(bias_sbuf, value=0.0)
 98
 99    # Allocate rotating SBUF slots for x and load the first block (prologue).
100    assert x_view.shape[0] > 0, "each program must own an activation block"
101    x_sbufs = nl.alloc_stream_buffers(
102        x_view,
103        buffer=nl.sbuf,
104        dim=0,
105        num_slots=2,
106    )
107    nisa.dma_copy(
108        dst=x_sbufs[0].data,
109        src=x_view[0].data,
110        dge_mode=config.dge_mode,
111    )
112
113    for m_block in range(x_view.shape[0]):
114        # Prefetch x block m_block + 1 while computing x block m_block.
115        if m_block + 1 < x_view.shape[0]:
116            nisa.dma_copy(
117                dst=x_sbufs[m_block + 1].data,
118                src=x_view[m_block + 1].data,
119                dge_mode=config.dge_mode,
120            )
121
122        # Run the fused MLP stages on the current resident x block.
123        x_sbuf = x_sbufs[m_block]
124        x_t_sbuf = transpose_in_place(x_sbuf)
125        gated_sbuf = compute_swiglu(x_t_sbuf, gate, up, bias_sbuf, config)
126        gated_t_sbuf = transpose_in_place(gated_sbuf)
127        out_sbuf = compute_down_matmul(gated_t_sbuf, down, config)
128
129        # Store the completed output block to this core's HBM view.
130        nisa.dma_copy(
131            dst=out_view[m_block].data,
132            src=out_sbuf.data,
133        )
134
135    return out.reshape((batch, sequence, config.H))
136
137

Transpose resident data#

This kernel uses square subtiles to prepare the Tensor Engine’s stationary operands. transpose_in_place transposes each subtile and copies it back to its original SBUF region.

For an input activation that already uses (128, 128) tiles, the first view change preserves the existing square grid. The SwiGLU intermediate uses (128, 512) tiles, so each wide tile becomes four square subtiles. The following figure uses that wider case to make the view change and grouping visible:

The same SBUF allocation viewed first as 128-by-512 tiles and then as 128-by-128 square tiles.

Fig. 56 nl.tiles() changes only the view. Each outlined 1 x 4 region is one sbuf_banks[i, k] block created by nl.blocks(); the physical SBUF allocation and element_shape do not change.#

For each square-tile row i, the helper transposes every tile from sbuf_banks[i, k] into transpose_psum[k, j]. It then copies each complete PSUM row back to the same sbuf_banks[i, k] region:

Square SBUF subtiles transposed across PSUM banks and copied back in bank-sized regions.

Fig. 57 nc_transpose() operates on one square tile at a time. One tensor_copy() then returns the complete bank-sized region to its original SBUF location.#

The top-level kernel calls the same helper twice: first for the input activation block and later for the SwiGLU intermediate.

 1def transpose_in_place(block_sbuf):
 2    """Transpose (tile_p x tile_p) subtiles in-place via PSUM bank pipelining.
 3
 4    Re-tiles the block into square subtiles, transposes each through PSUM,
 5    and writes back to the same SBUF location. Interleaves across PSUM banks
 6    for pipeline efficiency, then bulk-copies each whole bank back to SBUF
 7    (one tensor_copy per bank, not per subtile).
 8
 9    Args:
10        block_sbuf: NKI SBUF block or tile-grid view.
11
12    Returns:
13        The same allocation with each square subtile transposed.
14    """
15    PSUM_SLOT_SIZE = 512
16    NUM_HW_BANKS = 8
17
18    tile_p = block_sbuf.tile_shape[0]
19
20    # Retile the resident block into square Tensor Engine operands.
21    tiles_sbuf = nl.tiles(block_sbuf, tile_shape=(tile_p, tile_p))
22    tiles_per_bank = min(tiles_sbuf.shape[1], PSUM_SLOT_SIZE // tile_p)
23
24    # Group square tiles by PSUM bank for coalesced copyback.
25    sbuf_banks = nl.blocks(
26        tiles_sbuf,
27        block_shape=(1, tiles_per_bank),
28    )
29    num_rows, num_banks = sbuf_banks.shape
30    assert num_banks <= NUM_HW_BANKS
31
32    for i in range(num_rows):
33        # One PSUM tile per bank slot lets each completed bank copy back as
34        # one contiguous region.
35        transpose_psum = nl.alloc_tiles(
36            tile_shape=(tile_p, tile_p),
37            element_shape=(num_banks * tile_p, tiles_per_bank * tile_p),
38            buffer=nl.psum,
39            dtype=block_sbuf.dtype,
40        )
41
42        # Phase 1: SBUF -> PSUM transposes, fanned across banks (interleaved
43        # for pipelining).
44        for j in range(tiles_per_bank):
45            for k in range(num_banks):
46                bank_view = nl.tiles(sbuf_banks[i, k])
47                if j < bank_view.shape[1]:
48                    nisa.nc_transpose(
49                        transpose_psum[k, j].data,
50                        bank_view[0, j].data,
51                    )
52        # Phase 2: bulk PSUM -> SBUF copy-back -- one tensor_copy per bank
53        # with the whole bank addressed as a single contiguous F-slab on the
54        # SBUF side.
55        for k in range(num_banks):
56            bank_view = nl.tiles(sbuf_banks[i, k])
57            nisa.tensor_copy(
58                bank_view.data,
59                transpose_psum[k, : bank_view.shape[1]].data,
60            )
61
62    return block_sbuf
63
64

Compute gate, up, and SwiGLU#

compute_swiglu owns the complete gate, up, activation, and multiply sequence. It computes the parenthesized intermediate in the MLP:

\[gated = \operatorname{silu}(x \cdot gate) * (x \cdot up)\]

The down projection consumes gated in the next section. For each group of I columns, compute_swiglu:

  1. Narrows gated_sbuf, gate, and up to the same I group.

  2. Allocates gate_psum and rotating SBUF slots for the narrowed gate weights.

  3. Streams gate blocks along K and accumulates x @ gate.

  4. Applies SiLU while moving the gate result to gated_group in SBUF.

  5. Reuses the PSUM budget to stream the narrowed up weights and accumulate x @ up.

  6. Multiplies up_psum into the resident gated_group.

  7. Advances to the next I group and returns the complete SwiGLU intermediate.

One (m, i) output tile requires one live PSUM tile. NeuronCore has eight PSUM banks, so the function limits each I group to 8 // m_tiles columns. For example, two M tiles can accumulate four I tiles at once:

A two-by-four group of matrix multiplication accumulators occupying all eight PSUM tiles.

Fig. 58 The group size changes with m_tiles; the product of its two grid dimensions cannot exceed eight.#

The group bounds also narrow every value participating in the projection. gated_group selects the destination columns in SBUF, while gate_view and up_view select the same block columns from the complete weight grids:

  • gated_sbuf[:, i_start:i_start + i_count]

  • gate[:, i_start:i_start + i_count]

  • up[:, i_start:i_start + i_count]

These slices do not move data. Each narrowed weight view still spans all K block rows, but contains only the I block columns represented by the current PSUM group. nl.alloc_stream_buffers(..., dim=0) then advances through that narrowed view one K block row at a time. Each stream step loads all selected I block columns together:

Two columns selected from the complete gate block grid, streamed along K, and combined with resident activation tiles in a matching PSUM group.

Fig. 59 Gray blocks are outside the current I group. Light green marks the selected weight block columns, dark green marks the current streamed K row, blue is the matching resident xT block, and purple is the PSUM group with the same selected output columns. The up projection repeats this selection and streaming pattern with up_view.#

For each projection, the explicit accumulate condition is false only for the first interior k tile of the first streamed block. Every later tile adds to the same PSUM destination.

Both projections are matrix-multiplication reductions, so each needs a PSUM accumulator for every (m, i) tile. A group can already occupy all eight PSUM tiles, so keeping both accumulators live at once would require up to sixteen.

The dependency in the SwiGLU equation avoids that requirement. Once the gate projection is complete, the kernel applies SiLU and writes the result to gated_group in SBUF. gate_psum is no longer needed, so up_psum can reuse the same PSUM tiles to accumulate the up projection. The final multiply reads gated_group from SBUF and up_psum from PSUM, then writes the result back to gated_group:

gate_psum   = x @ gate_view
gated_group = silu(gate_psum)
up_psum     = x @ up_view       # reuses the PSUM budget
gated_group = gated_group * up_psum
Gate PSUM tiles passing through SiLU into SBUF before up PSUM tiles multiply into the same SBUF region.

Fig. 60 Materializing silu(G) in SBUF ends the gate_psum lifetime before up_psum begins. The SwiGLU intermediate remains on chip throughout; it is not written to HBM between projections.#

With the grouping, streaming, and intermediate lifetime established, the complete method reads as the same sequence:

  1def compute_swiglu(x_sbuf, gate, up, bias_sbuf, config: MLPConfig):
  2    """Compute ``silu(x @ gate) * (x @ up)`` one I group at a time.
  3
  4    Args:
  5        x_sbuf: SBUF block view of the input ``[M, K]`` for one shard.
  6        gate: NKI HBM block view of the gate weights ``[K, I]``.
  7        up: NKI HBM block view of the up weights ``[K, I]``.
  8        bias_sbuf: SBUF tile providing the SiLU bias, typically zeros.
  9        config: Kernel configuration carrying tile/block sizes and DGE mode.
 10
 11    Returns:
 12        SBUF tile grid containing the ``[M, I]`` SwiGLU result.
 13    """
 14    assert isinstance(x_sbuf, nl.NkiBlockGrid), (
 15        "x_sbuf must preserve the K-block dimension"
 16    )
 17    assert x_sbuf.element_shape[1] == config.K, (
 18        "x must span full K for correct accumulation"
 19    )
 20    assert x_sbuf.shape[0] == gate.shape[0]
 21    assert x_sbuf.shape[0] == up.shape[0]
 22
 23    tile_m = x_sbuf.tile_shape[0]
 24    m_tiles = nl.tiles(x_sbuf).shape[0]
 25    tile_i = gate.tile_shape[1]
 26    dtype = gate.dtype
 27    i_tiles = gate.shape[1]
 28
 29    # Each (M tile, I tile) pair needs one of the eight PSUM tiles.
 30    max_i_per_group = 8 // m_tiles
 31    assert max_i_per_group > 0, "activation block exceeds PSUM capacity"
 32    has_i_remainder = (config.I % tile_i) != 0
 33    if has_i_remainder and i_tiles > 1:
 34        max_i_per_group = min(max_i_per_group, i_tiles - 1)
 35    i_groups = _ceiling_div(i_tiles, max_i_per_group)
 36
 37    # Allocate SBUF for the complete SwiGLU result across all I groups.
 38    gated_sbuf = nl.alloc_tiles(
 39        tile_shape=(tile_m, tile_i),
 40        element_shape=(x_sbuf.element_shape[0], gate.element_shape[1]),
 41        buffer=nl.sbuf,
 42        dtype=dtype,
 43    )
 44
 45    for i_group in range(i_groups):
 46        # Select one I group that fits the eight-PSUM budget.
 47        i_start = i_group * max_i_per_group
 48        i_count = min(max_i_per_group, i_tiles - i_start)
 49        gated_group = gated_sbuf[:, i_start : i_start + i_count]
 50        gate_view = gate[:, i_start : i_start + i_count]
 51        up_view = up[:, i_start : i_start + i_count]
 52
 53        # Gate projection: stream gate weights and accumulate x @ gate.
 54        psum_element_shape = (
 55            x_sbuf.element_shape[0],
 56            gate_view.element_shape[1],
 57        )
 58        gate_psum = nl.alloc_tiles(
 59            tile_shape=(tile_m, tile_i),
 60            element_shape=psum_element_shape,
 61            buffer=nl.psum,
 62            dtype=nl.float32,
 63        )
 64        gate_sbufs = nl.alloc_stream_buffers(
 65            gate_view,
 66            buffer=nl.sbuf,
 67            dim=0,
 68            num_slots=config.projection_slots,
 69        )
 70
 71        # Gate prologue: load the first narrowed K-block row.
 72        nisa.dma_copy(
 73            dst=gate_sbufs[0].data,
 74            src=gate_view[0].data,
 75            dge_mode=config.dge_mode,
 76        )
 77
 78        for k_block in range(gate_view.shape[0]):
 79            # Prefetch the next gate row while computing the current row.
 80            if k_block + 1 < gate_view.shape[0]:
 81                nisa.dma_copy(
 82                    dst=gate_sbufs[k_block + 1].data,
 83                    src=gate_view[k_block + 1].data,
 84                    dge_mode=config.dge_mode,
 85                )
 86
 87            x_tiles = nl.tiles(x_sbuf[k_block])
 88            gate_tiles = nl.tiles(gate_sbufs[k_block])
 89            for m_tile in range(m_tiles):
 90                for k_tile in range(gate_tiles.shape[0]):
 91                    for i_tile in range(i_count):
 92                        nisa.nc_matmul(
 93                            dst=gate_psum[m_tile, i_tile].data,
 94                            stationary=x_tiles[m_tile, k_tile].data,
 95                            moving=gate_tiles[k_tile, i_tile].data,
 96                            accumulate=k_block > 0 or k_tile > 0,
 97                        )
 98
 99        # Move SiLU(gate) to SBUF before reusing PSUM for the up projection.
100        for m_tile in range(m_tiles):
101            for i_tile in range(i_count):
102                nisa.activation(
103                    gated_group[m_tile, i_tile].data,
104                    op=nl.silu,
105                    data=gate_psum[m_tile, i_tile].data,
106                    bias=bias_sbuf,
107                )
108
109        # Up projection: reuse the PSUM budget to accumulate x @ up.
110        up_psum = nl.alloc_tiles(
111            tile_shape=(tile_m, tile_i),
112            element_shape=psum_element_shape,
113            buffer=nl.psum,
114            dtype=nl.float32,
115        )
116        up_sbufs = nl.alloc_stream_buffers(
117            up_view,
118            buffer=nl.sbuf,
119            dim=0,
120            num_slots=config.projection_slots,
121        )
122
123        # Up prologue: load the first narrowed K-block row.
124        nisa.dma_copy(
125            dst=up_sbufs[0].data,
126            src=up_view[0].data,
127            dge_mode=config.dge_mode,
128        )
129
130        for k_block in range(up_view.shape[0]):
131            # Prefetch the next up row while computing the current row.
132            if k_block + 1 < up_view.shape[0]:
133                nisa.dma_copy(
134                    dst=up_sbufs[k_block + 1].data,
135                    src=up_view[k_block + 1].data,
136                    dge_mode=config.dge_mode,
137                )
138
139            x_tiles = nl.tiles(x_sbuf[k_block])
140            up_tiles = nl.tiles(up_sbufs[k_block])
141            for m_tile in range(m_tiles):
142                for k_tile in range(up_tiles.shape[0]):
143                    for i_tile in range(i_count):
144                        nisa.nc_matmul(
145                            dst=up_psum[m_tile, i_tile].data,
146                            stationary=x_tiles[m_tile, k_tile].data,
147                            moving=up_tiles[k_tile, i_tile].data,
148                            accumulate=k_block > 0 or k_tile > 0,
149                        )
150
151        # Multiply the up result into the resident SiLU(gate) SBUF tiles.
152        for m_tile in range(m_tiles):
153            for i_tile in range(i_count):
154                nisa.tensor_tensor(
155                    gated_group[m_tile, i_tile].data,
156                    gated_group[m_tile, i_tile].data,
157                    up_psum[m_tile, i_tile].data,
158                    op=nl.multiply,
159                )
160
161    return gated_sbuf
162
163

Compute the down projection#

compute_down_matmul applies the same streamed blocked-matmul structure along the intermediate I dimension. The transposed SwiGLU block remains stationary in SBUF while down-weight blocks stream through rotating slots.

The method follows this sequence:

  1. Retile the resident SwiGLU allocation for the down projection and allocate the complete SBUF output block.

  2. Select one H block and allocate at most eight [m, h] PSUM tiles.

  3. Stream the selected down-weight blocks along I.

  4. Select the matching resident SwiGLU columns and accumulate each [m, i] @ [i, h] contribution.

  5. Copy the completed PSUM region to its H block in out_sbuf.

  6. Repeat for the remaining H blocks and return the complete output.

Resident transposed SwiGLU tiles and streamed down-weight tiles accumulating into a PSUM output block.

Fig. 61 A resident [m, i] region and the current streamed [i, h] block update the [m, h] PSUM region. Light purple marks the completed SBUF block that is stored with one coalesced DMA.#

The complete method implements that outer H loop and inner streamed reduction:

 1def compute_down_matmul(gated_t_sbuf, down, config: MLPConfig):
 2    """Compute the down projection with a resident activation block.
 3
 4    Args:
 5        gated_t_sbuf: Transposed gated activations in SBUF.
 6        down: NKI HBM block view of the down weights ``[I, H]``.
 7        config: Kernel configuration carrying tile/block sizes and DGE mode.
 8
 9    Returns:
10        SBUF block grid containing the ``[M, H]`` result.
11    """
12    assert isinstance(down, nl.NkiBlockGrid), "down must be a block view"
13
14    tile_i_down, tile_h = down.tile_shape
15    block_i, block_h = down.block_shape
16    tile_m = gated_t_sbuf.tile_shape[0]
17    h_blocks = down.shape[1]
18
19    # Retile the resident SwiGLU block for the down projection.
20    gated_t_tiles = nl.tiles(gated_t_sbuf, tile_shape=(tile_i_down, tile_m))
21    m_tiles = gated_t_tiles.shape[0]
22
23    # Allocate SBUF for the complete output block.
24    out_sbuf = nl.alloc_blocks(
25        tile_shape=(tile_m, tile_h),
26        block_shape=(m_tiles, block_h),
27        element_shape=(gated_t_sbuf.element_shape[0], down.element_shape[1]),
28        buffer=nl.sbuf,
29        dtype=nl.bfloat16,
30    )
31
32    for h_block in range(h_blocks):
33        # Accumulate one H block while streaming down weights over I.
34        down_view = down[:, h_block]
35        out_psum = nl.alloc_tiles(
36            tile_shape=(tile_m, tile_h),
37            element_shape=(m_tiles * tile_m, block_h * tile_h),
38            buffer=nl.psum,
39            dtype=nl.float32,
40        )
41
42        # Allocate rotating SBUF slots and load the first weight block.
43        down_sbufs = nl.alloc_stream_buffers(
44            down_view,
45            buffer=nl.sbuf,
46            dim=0,
47            num_slots=config.down_slots,
48        )
49        nisa.dma_copy(
50            dst=down_sbufs[0].data,
51            src=down_view[0].data,
52            dge_mode=config.dge_mode,
53        )
54
55        for i_block in range(down_view.shape[0]):
56            # Prefetch I block i_block + 1 while computing I block i_block.
57            if i_block + 1 < down_view.shape[0]:
58                nisa.dma_copy(
59                    dst=down_sbufs[i_block + 1].data,
60                    src=down_view[i_block + 1].data,
61                    dge_mode=config.dge_mode,
62                )
63
64            down_tiles = nl.tiles(down_sbufs[i_block])
65            i_tile_count = down_tiles.shape[0]
66            i_start = i_block * block_i
67            gated_view = gated_t_tiles[:, i_start : i_start + i_tile_count]
68
69            for m_tile in range(m_tiles):
70                for i_tile in range(i_tile_count):
71                    for h_tile in nl.affine_range(block_h):
72                        nisa.nc_matmul(
73                            dst=out_psum[m_tile, h_tile].data,
74                            stationary=gated_view[m_tile, i_tile].data,
75                            moving=down_tiles[i_tile, h_tile].data,
76                            accumulate=i_block > 0 or i_tile > 0,
77                        )
78
79        # Move completed PSUM tiles into the SBUF output block.
80        out_tiles = nl.tiles(out_sbuf[0, h_block])
81        for m_tile in range(m_tiles):
82            for h_tile in nl.affine_range(block_h):
83                nisa.tensor_copy(
84                    dst=out_tiles[m_tile, h_tile].data,
85                    src=out_psum[m_tile, h_tile].data,
86                )
87
88    return out_sbuf
89
90

Tie the stages together#

With every helper in place, the top-level loop shown first moves one activation block through all three projections:

MLP activations moving from HBM through streamed gate, up, and down projections with SBUF and PSUM intermediates.

Fig. 62 One activation block remains on chip through both SwiGLU projections and the down projection. Input activations and completed outputs cross the HBM boundary; projection weights stream from HBM separately.#

This organization creates two levels of reuse. An activation block stays in SBUF across the gate, up, and down stages, while each projection reuses its PSUM output tiles across all streamed reduction blocks. Block-level DMAs amortize transfer overhead, and the stream pools keep the SBUF footprint bounded while making adjacent loads and compute available for overlap.

Handle boundaries and constraints#

This discussion assumes BF16 inputs and weights and the default tile sizes. The implementation checks the assumptions that determine its grid geometry:

  • M = B * S must be divisible by tile_m (128). The final activation block may contain fewer than block_m full tiles.

  • Both K and I must be at most 4096 with these tile sizes, because the transpose helper uses at most eight PSUM banks for an entire row.

  • K must be divisible by tile_k so every gate and up reduction block has a complete reduction extent.

  • I must be divisible by tile_down_i because the current square transpose path does not handle a non-square final subtile.

  • H must be divisible by tile_h so every down-projection output tile has the expected free-dimension extent.

  • projection_slots and down_slots must each be at least two for the load-next, compute-current schedule.

  • block_m is limited to eight tiles, and each live PSUM region also satisfies m_tiles * output_tiles <= 8.

  • Every launched program must own at least one activation block.

Gate and up may still have a final partial (128, 512) tile when I is not divisible by tile_i. An I group can contain both full and partial tiles. Its element_shape and per-tile accesses preserve each tile’s valid extent.

These constraints describe this tutorial implementation, not general limitations of tile grids or block grids. Different model dimensions can use different block configurations as long as the consuming ISA instructions, SBUF capacity, and eight-PSUM budget remain valid.

The complete source for this tutorial is available in mlp_cte.py.

This document is relevant for: Trn2, Trn3