.. meta::
   :description: Deep dive into the NKI Library MXFP8 matmul kernel on Trainium3: blocking and tiling, wrapX and 1x32 swizzles, load paths, spill-reload, PSUM copy-in, LNC2 sharding, SBUF optimizations, how the fused backward and the composed MoE and MLP kernels reuse it, and how kernel configs are looked up.
   :keywords: MXFP8, NKI, NKI Library, matmul_mxfp8, matmul_mxfp8_backward, MoE, kernel, Trainium3, deep dive
   :date-modified: 2026-11-22

.. _nki-deep-dive-mxfp-matmul-kernel:

====================================================
Deep dive: the NKI Library MXFP8 matmul kernel
====================================================

This topic explains how the NKI Library MXFP8 matmul kernel runs on Trainium3: how it blocks, tiles,
loads and quantizes its operands, and the techniques it uses to keep the TensorEngine busy. The
same kernel powers the MXFP8 linears in TorchAO Neuron and TorchTitan Neuron, and its tuning knobs
are what the MXFP8 auto-tuning skill sweeps.

What you should know before reading
-----------------------------------

Before you start, you should be familiar with the following:

- **MXFP8 matrix multiplication in NKI:** data layout, quantization and scales. See
  :doc:`/nki/deep-dives/mxfp-matmul`.
- **Trainium3 engines and memory:** the TensorEngine (PE), Vector Engine (DVE), Scalar Engine
  (ACT), DMA, SBUF, PSUM and HBM. See :ref:`Trainium 3 Architecture Guide for NKI <trainium3_arch>`.

Overview
--------


MXFP8 lets the Trainium3 TensorEngine (PE) run matmuls up to 4x faster than BF16 at close to BF16
accuracy. Using it efficiently is harder than BF16 for three reasons:

1. **Vector engine load.** Not all data arrives in MXFP8, so BF16 operands are quantized on chip.
   That puts work on the Vector Engine (DVE) that a BF16 matmul doesn't have.
2. **Data swizzling.** MXFP8 quantization groups run along the contraction dimension, but the PE
   needs each group's 32 contraction values laid out as an 8 × 4 tile. That reordering isn't
   always free.
3. **Lower arithmetic intensity.** When BF16 data comes into the kernel, it needs as many DMA
   transfers as a BF16 matmul, but the compute runs 4x faster, so the kernel is much more likely to
   be DMA-bound.

The NKI Library MXFP8 kernels handle this with one generalized matmul that works for any shape.
Every part of how it runs is a configurable argument (see
:ref:`nki-deep-dive-mxfp-matmul-kernel-configs`), and larger kernels such as the fused backward and
the composed MoE and MLP kernels are built from it. API references:
:doc:`matmul_mxfp8 </nki/library/api/matmul-mxfp8-generic-kernel>`,
:doc:`matmul_mxfp8_backward </nki/library/api/matmul-mxfp8-generic-backward-kernel>`,
:doc:`MoE forward </nki/library/api/blockwise-mm-forward-mxfp8>`,
:doc:`MoE backward </nki/library/api/blockwise-mm-backward-mxfp8>`, and
:doc:`quantize_mxfp8 </nki/library/api/quantize-mxfp8>`.

.. _nki-deep-dive-mxfp-matmul-kernel-blocking:

Blocking and tiling
-------------------

The kernel uses the same blocking and tiling structure as a BF16 matmul. What matters for tuning
is that every level of the hierarchy is a parameter instead of a hard-coded choice, so each shape
can use the settings that run it fastest.

.. figure:: /nki/img/deep-dives/mxfp8-matmul-kernel-blocked-matmul.gif
   :alt: Animated walkthrough of the blocked, tiled and pipelined MXFP8 matmul: DMA tile loads, DVE quantize to MXFP8 data and scales, PE matmul accumulating in PSUM, PSUM to SBUF copy and output store
   :width: 100%

   The blocked, tiled and pipelined matmul: DMA loads tiles, DVE quantizes them to MXFP8 data and
   scales, the PE accumulates in PSUM, and the result is copied to SBUF and stored.

- **Block size** (``TILES_IN_BLOCK_M/N/K``): how much of each operand is staged in SBUF at once.
  Larger blocks reuse each loaded and quantized tile across more output tiles, which cuts HBM
  traffic and re-quantization, at the cost of SBUF capacity. With more than one K block, the output
  block stays in SBUF as an FP32 accumulator and is written to HBM only after the last K block.
- **Tile size** (``tile_m``, ``tile_k``, ``tile_n``): the unit the PE consumes. The LHS tile is
  stationary and the RHS tile is moving. Tile sizes don't need to be powers of two: for many model
  shapes, a tile that divides the dimension evenly beats a power-of-two tile that leaves a thin
  remainder tile, and the tuner searches those options.
- **Tiles per load** (``TILES_IN_LOAD_M/N``): how many tiles are combined into one DMA when the
  kernel fills a block. Larger loads mean fewer, bigger DMAs and better DMA throughput. Smaller
  loads let quantize and compute start on the first tile sooner.

Shapes don't have to be multiples of the block or tile size. The last block and tile in each
dimension run as partial blocks with masked loads, compute and stores, so uneven shapes run
without host-side padding. The contraction dimension must be a multiple of 32, and the free
dimensions a multiple of 8.

.. _nki-deep-dive-mxfp-matmul-kernel-swizzle:

Swizzle and quantization schemes
--------------------------------

The Tensor Engine multiplies two ``mxfp8_x4`` values at a time, one from each operand. Each packs
four FP8 numbers, and the Tensor Engine multiplies and sums all four in one step, which is why
MXFP8 runs 4x faster than BF16. That gives the right answer only if all four numbers come from the
contraction (K) dimension and sit next to each other along the free dimension. So the kernel
reorders the data to move four K values onto the free axis (the *swizzle*). Quantization then
works on 8 × 4 groups of swizzled values, and the 32 values in a group share one scale. The two
quantization schemes differ in which 32 values form a group.

Both schemes can use a K tile (``tile_k``) of 512, 256 or 128 values. Because the swizzle moves
four K values onto the free axis, these tiles use 128, 64 or 32 partitions respectively.

.. figure:: /nki/img/deep-dives/mxfp8-matmul-kernel-swizzle.png
   :alt: WrapX versus 1x32 swizzle: how 32 contraction values map to an 8 by 4 block and which values share a scale
   :width: 100%

   WrapX versus 1x32: how contraction values are packed for the PE, and which values share a
   scale.

- **WrapX** groups values spread across the whole K tile. One DMA transpose with the right access
  pattern produces the wrapX layout at no extra cost over a regular DMA transpose (the *fast DMA
  transpose*). WrapX is best when the kernel quantizes on chip. Because the grouping depends on
  how K was tiled, pre-quantized wrapX data can break once it is sliced or gathered.
- **1x32** groups 32 consecutive K values, the same scheme GPUs use. It is the right format for
  pre-quantized data, because you can quantize once and then shard, all-gather or slice. The cost
  is that a DMA can't produce the 1x32 swizzle for free.

.. _nki-deep-dive-mxfp-matmul-kernel-load-paths:

Load paths
----------

Every tile has to reach SBUF in the swizzled layout before it is quantized and multiplied. The
kernel offers several load paths, which differ in which engine pays for the swizzle.

.. figure:: /nki/img/deep-dives/mxfp8-matmul-kernel-load-paths.png
   :alt: Table of MXFP8 load paths and which engine performs the swizzle for each
   :width: 100%

   Load paths and which engine performs the swizzle. K is the contraction dimension and F the
   free dimension.

- **PE swizzle** is the default for 1x32: pairs of BF16 values are reinterpreted as FP32, which
  halves the partition count, the PE runs two strided transposes, and the result is copied out of
  PSUM.
- **Strided-copy swizzle** for 1x32 [K, F] inputs uses no PE: a strided DMA folds four
  consecutive K rows onto the free axis, and an engine copy interleaves them.
  ``strided_copy_swizzle_1x32_ratio`` sets the share of tiles that take this path. The PE is
  usually the busier engine, so moving swizzles off it helps most in PE-bound kernels: on Qwen3 32B
  backward shapes it gave up to 1.04x on a plain matmul (``5120 × 8192 × 6400`` down dW,
  1520.0 → 1463.4 µs), and more on fused kernels.
- **Pre-quantized** operands (FP8 data and scales already in HBM) load with two plain DMA copies:
  no swizzle, no quantize, and half the bytes of BF16. This is why pre-quantized weights help:
  each weight is quantized once per step, after the optimizer step or right before its FSDP
  all-gather, and every matmul that step reuses it. Because this data crosses kernel and device
  boundaries, it must be 1x32.

The kernel can mix paths within one call to balance the engines: ``strided_copy_swizzle_1x32_ratio``
sends a fraction of the tiles down the strided-copy path and the rest down the PE path, and
``psum_copy_in_ratio`` (see :ref:`nki-deep-dive-mxfp-matmul-kernel-psum-copy-in`) does the same for
the K-block accumulation. The tuner picks the split for each shape.

**Dense HBM scales.** In SBUF, the PE needs the scale tile to span the same contraction
partitions as the data, so only 4 of every 32 partitions hold real scales. Storing that
mostly empty layout in HBM would waste memory and DMA bandwidth, and would stop the scales from
being sliced or concatenated by collectives. So HBM keeps scales dense, as ``[K/32, F]`` with one
byte per 32 values, and the load scatters each row to the partition the PE expects, with one DMA
per 32-partition quadrant. In SBUF, scale packing then lets several tiles share one scale buffer
(see :ref:`nki-deep-dive-mxfp-matmul-kernel-sbuf`).

.. figure:: /nki/img/deep-dives/mxfp8-matmul-kernel-scales-dense.png
   :alt: Dense HBM scales scattered into the SBUF scale tile layout, one DMA per quadrant
   :width: 100%

   Dense HBM scales scattered into the SBUF scale layout, one DMA per quadrant.

.. _nki-deep-dive-mxfp-matmul-kernel-spill-reload:

Spill-reload
------------

The whole operand doesn't fit in SBUF, so blocks are reloaded: with M blocks of LHS and N blocks of
RHS, each LHS block is loaded N times and each RHS block M times. With ``spill_reload=True``, the
kernel quantizes each block once, writes the FP8 data and scales to an HBM scratch buffer, and every
later use reloads that copy through the pre-quantized path. That saves DVE quantize work, and the
reloads move about half the bytes of BF16, at the cost of one extra HBM write per tile. If a block
won't be reused, the kernel doesn't spill it, which saves DMA bandwidth. Whether spill-reload pays
off depends on the shape and the reuse count, so the tuner sets it per key.

.. figure:: /nki/img/deep-dives/mxfp8-matmul-kernel-spill-reload.gif
   :alt: Spill-reload walkthrough: blocks are quantized once, spilled to HBM as FP8, and later blocks reload the FP8 copy without quantizing
   :width: 100%

   Spill-reload: each block is quantized once and later uses reload the FP8 copy.

.. _nki-deep-dive-mxfp-matmul-kernel-psum-copy-in:

PSUM copy-in
------------

With more than one K block, each block's partial sum has to be added into the FP32 accumulator in
SBUF. By default that is a ``tensor_tensor`` add on the DVE, which is also busy quantizing. With
PSUM copy-in, the Scalar Engine (ACT) copies the running sum into PSUM, the PE accumulates on top
of it, and ACT copies the finished result back out, with no DVE work. ``psum_copy_in_ratio`` sets
the share of tiles accumulated this way and is tuned per key.

.. figure:: /nki/img/deep-dives/mxfp8-matmul-kernel-psum-copy-in.png
   :alt: PSUM copy-in versus default K-block accumulation
   :width: 100%

   Default K-block accumulation on the DVE (top) versus PSUM copy-in on ACT (bottom).

.. _nki-deep-dive-mxfp-matmul-kernel-lnc2:

LNC2 sharding
-------------

On two NeuronCores (LNC2), the kernel splits along one operand's free dimension (M or N) and never
along K, so the output doesn't need a cross-core sum. When exactly one operand is pre-quantized,
usually the weights, the kernel splits the BF16 activation. Each core then quantizes only its half,
and both read the cheap FP8 weights. Splitting the pre-quantized operand instead would make both
cores quantize the full activation.

.. _nki-deep-dive-mxfp-matmul-kernel-sbuf:

SBUF memory optimizations
-------------------------

SBUF space caps the block size, and bigger blocks mean more reuse, so saved bytes turn into speed.

- **Scale packing.** Only 1/8 of an SBUF scale tile holds real scales. With scale packing, up to
  four tiles share one scale buffer at partition offsets 0, 4, 8 and 12, so scales take 4x less
  SBUF. On ``matmul_mxfp8`` the argument is ``use_scale_packing`` (off by default). In a MoE
  tuning file the field is ``enable_scale_packing``, and it is on by default.
- **Output buffer dtype.** The output block needs FP32 only when partial sums from several K
  blocks are added together. With a single K block, PSUM drains straight into the BF16 output,
  which halves the buffer.

.. figure:: /nki/img/deep-dives/mxfp8-matmul-kernel-scale-packing.png
   :alt: Scale packing: four K tiles share one SBUF scale buffer at partition offsets 0, 4, 8 and 12
   :width: 100%

   Scale packing: four K tiles share one SBUF scale buffer.

.. _nki-deep-dive-mxfp-matmul-kernel-composability:

Composability: backward, MoE and MLP
------------------------------------

Inside the NKI Library, the matmul is built on a block-level routine that other kernels can call.
A caller can run any slice of the block grid, keep operands or outputs in SBUF, add into an
existing result, and pipeline its own work around the matmul. The standalone matmul, the fused
backward, MoE and MLP all use this same building block, which is why one set of tuning knobs
covers all of them.

.. figure:: /nki/img/deep-dives/mxfp8-matmul-kernel-composability.png
   :alt: Kernels built on the block-level MXFP8 matmul API and the features that make it composable
   :width: 100%

   One block-level API, many kernels.

- **Fused backward.** ``matmul_mxfp8_backward`` computes both gradients of a linear layer in one
  kernel: dX = dY · W and dW = dYᵀ · X. The kernel reads each input in whichever layout it already
  has, so no transposed copies are made. Each phase gets its own tuned config and LNC2 split. The
  fused backward runs faster than two separate matmul calls.
- **MoE.** The MoE kernels are composed from the same matmul; see
  :ref:`nki-deep-dive-mxfp-matmul-kernel-moe`.
- **MLP.** The dense MLP kernels run the MoE kernels in single-expert mode, which fuses gate, up,
  the activation and down into one kernel.

.. _nki-deep-dive-mxfp-matmul-kernel-moe:

MoE kernels
-----------

The MXFP8 MoE forward and backward kernels are composed kernels: each one chains several block-level
matmuls with the routing and activation work around them, in one kernel call per MoE layer.

- **Forward.** Tokens are processed in blocks, and each block belongs to one expert. A block's
  tokens are quantized once and used for both the gate and up projections. The activation result is
  written to a scratch buffer in HBM and read back as the input of the down projection, whose
  result is written to each token's row in the output. With routed experts (each rank holds every
  expert), the kernel adds a token's results from its several experts in that row.
- **Backward.** Four matmul phases per block: the gradients through the down and the gate and up
  projections, then the two weight gradients.
- **Independent configs.** Each matmul phase (gate/up and down in the forward, phases 1-4 in the
  backward) takes its own config, keyed by block size, so each can be tuned on its own. Kernel-wide
  options such as the backward transpose modes are set once per direction.
- **Weights in place.** With 1x32 or pre-quantized weights, each expert's weights are read in place
  from the full weight tensor, so they aren't copied. BF16 weights under wrapX are read in place
  when they are already stored in the layout the kernel reads; otherwise the kernel makes one
  transposed copy in HBM per kernel call.
- **Activations.** The MXFP8 MoE kernels support two activations today, SiLU and Swish; support
  for more is planned.

.. _nki-deep-dive-mxfp-matmul-kernel-configs:

Kernel configs and the tuning cache
-----------------------------------

Every knob on this page (tile sizes, block and load counts, spill-reload, the ratio knobs) is an
argument of the kernel. For each call, the kernel's configuration comes from the first of these
that applies:

1. **Arguments passed by the caller.** A framework or a user can pass any config explicitly.
2. **Tuned-config files.** Frameworks pass one or more JSON files of tuned configs through the NKI
   Library resolver (``resolve_matmul_mxfp8_configs``). If several files contain the same key, the
   later file wins; overlaps aren't reported. TorchTitan Neuron passes the file you give it with
   ``--mxfp8_matmul_configs``.
3. **The built-in cache.** The NKI Library ships tuned configs for common model shapes (about 540
   entries in 2.34).
4. **Heuristic defaults** for shapes with no entry.

An entry's key describes the call, not the model: the per-core M × K × N shape plus how each operand
is loaded, for example ``4096x2560x2432_pe_1x32_prequant``. Any run that makes the same call uses
the entry, so models that share shapes share tunings, and you can build one larger file from
several runs. The tuning skill's merge step refuses two entries for the same key that disagree; a
hand-merged file has no such check. A file tuned on your exact run gives the best performance, because a shape with no
entry falls back to the defaults. Set ``MXFP8_NKI_TUNED_CONFIGS_LOG=1`` to log each lookup and
whether it hit.

MoE tuning files work differently: they're keyed by block size per phase, not by shape (see
:ref:`torchtitan-neuron-tutorial-mxfp8-autotuning-moe-configs`).

You can tune by hand, by sweeping configs yourself, or with the Neuron Agentic Development tuning
skills, which capture your run's calls, search configs for each, and verify the result in
training. For that workflow, see :doc:`/training/torchtitan/tutorials/tutorial-mxfp8-autotuning`.

Further reading
---------------

- :doc:`/nki/library/api/matmul-mxfp8-generic-kernel`
- :doc:`/nki/library/api/matmul-mxfp8-generic-backward-kernel`
- :doc:`/nki/deep-dives/mxfp-matmul`
- :doc:`/training/torchtitan/tutorials/tutorial-mxfp8-autotuning`
