.. meta::
   :description: Build a fused NKI Context Encoding MLP from block grids, sharding, streams, transposes, and PSUM accumulation.
   :keywords: NKI, tile grid, block grid, MLP, SwiGLU, CTE, software pipelining
   :date-modified: 2026-10-09

.. _nki-tiled-grid-mlp-cte:

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

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:

.. math::

   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 :ref:`nki-tiled-grid-selection`.

This tutorial assumes familiarity with HBM, SBUF, PSUM, and NKI ISA
instructions, as well as :ref:`nki-tiled-grid-fundamentals`,
:ref:`nki-tiled-grid-blocks`, and :ref:`nki-tiled-grid-streaming`.

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:

.. math::

   \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}

Each product in these equations expands into tile-level
:func:`~nki.isa.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.

.. figure:: ../../img/tiled-grids/mlp-block-grid-mapping.svg
   :alt: Input, gate, up, intermediate, down, and output block grids connected according to the two MLP contractions.
   :align: center
   :width: 100%

   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``.

.. list-table::
   :header-rows: 1
   :widths: 20 19 19 42

   * - 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:

.. code-block:: text

   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:

.. figure:: ../../img/tiled-grids/mlp-core-ownership.svg
   :alt: Matching input and output M-axis block ranges assigned to NeuronCore zero and NeuronCore one.
   :align: center
   :width: 100%

   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``:

.. figure:: ../../img/tiled-grids/mlp-activation-stream.svg
   :alt: Core-owned HBM activation blocks mapped in order to two rotating SBUF slots.
   :align: center
   :width: 100%

   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``:

.. figure:: ../../img/tiled-grids/mlp-activation-pipeline.svg
   :alt: Two-stage activation timeline overlapping the next HBM-to-SBUF load with projection work on the current block.
   :align: center
   :width: 100%

   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.

.. nki_example:: ../../examples/tiled_grid/canonical/kernels/mlp_cte.py
   :language: python
   :marker: NKI_EXAMPLE_TILED_GRID_MLP_CTE
   :linenos:

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:

.. figure:: ../../img/tiled-grids/mlp-retile-intermediate.svg
   :alt: The same SBUF allocation viewed first as 128-by-512 tiles and then as 128-by-128 square tiles.
   :align: center
   :width: 100%

   ``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:

.. figure:: ../../img/tiled-grids/mlp-psum-transpose.svg
   :alt: Square SBUF subtiles transposed across PSUM banks and copied back in bank-sized regions.
   :align: center
   :width: 100%

   :func:`~nki.isa.nc_transpose` operates on one square tile at a time. One
   :func:`~nki.isa.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.

.. nki_example:: ../../examples/tiled_grid/canonical/kernels/mlp_cte.py
   :language: python
   :marker: NKI_EXAMPLE_TILED_GRID_TRANSPOSE_IN_PLACE
   :linenos:

Compute gate, up, and SwiGLU
----------------------------

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

.. math::

   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:

.. figure:: ../../img/tiled-grids/mlp-psum-group.svg
   :alt: A two-by-four group of matrix multiplication accumulators occupying all eight PSUM tiles.
   :align: center
   :width: 100%

   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:

.. figure:: ../../img/tiled-grids/mlp-projection-stream.svg
   :alt: Two columns selected from the complete gate block grid, streamed along K, and combined with resident activation tiles in a matching PSUM group.
   :align: center
   :width: 100%

   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``:

.. code-block:: text

   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

.. figure:: ../../img/tiled-grids/mlp-gate-up.svg
   :alt: Gate PSUM tiles passing through SiLU into SBUF before up PSUM tiles multiply into the same SBUF region.
   :align: center
   :width: 100%

   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:

.. nki_example:: ../../examples/tiled_grid/canonical/kernels/mlp_cte.py
   :language: python
   :marker: NKI_EXAMPLE_TILED_GRID_COMPUTE_SWIGLU
   :linenos:

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.

.. figure:: ../../img/tiled-grids/mlp-down-projection.svg
   :alt: Resident transposed SwiGLU tiles and streamed down-weight tiles accumulating into a PSUM output block.
   :align: center
   :width: 100%

   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:

.. nki_example:: ../../examples/tiled_grid/canonical/kernels/mlp_cte.py
   :language: python
   :marker: NKI_EXAMPLE_TILED_GRID_COMPUTE_DOWN_MATMUL
   :linenos:

Tie the stages together
-----------------------

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

.. figure:: ../../img/tiled-grids/mlp-dataflow.svg
   :alt: MLP activations moving from HBM through streamed gate, up, and down projections with SBUF and PSUM intermediates.
   :align: center
   :width: 100%

   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
:download:`mlp_cte.py <../../examples/tiled_grid/canonical/kernels/mlp_cte.py>`.
