.. meta::
   :description: Auto-tune the MXFP8 matmul and MoE kernel configs for a TorchTitan Neuron training run on Trainium3 with the Neuron Agentic Development tuning skills, then train with the tuned JSON. Includes how the tuning search works and what a MoE tuning file contains.
   :keywords: TorchTitan, TorchNeuron, TorchAO, MXFP8, NKI, matmul_mxfp8, MoE, kernel tuning, auto-tuning, mxfp8_matmul_configs, tuning_path, Neuron Agentic Development, AWS Neuron, Trainium3, tutorial
   :date-modified: 2026-11-23
   :content-type-template: _content-types/procedural-tutorial.rst

.. _torchtitan-neuron-tutorial-mxfp8-autotuning:

=========================================================================
Tutorial: Auto-tune MXFP8 kernel configs for TorchTitan Neuron training
=========================================================================

This tutorial shows you how to tune the MXFP8 kernels for a TorchTitan Neuron training run on
AWS Trainium3, and then train with the result. You hand your training command to an agent that
runs a Neuron Agentic Development tuning skill on your Trn3 instance. The agent gives back your
training setup with the tuned config files added: for dense linears, one extra flag on your
command; for MoE experts, a short recipe that loads the tuned file. Before it hands them back, it
compares training step time with and without them, and keeps a tuned file only if it makes the
step faster. You don't change any kernel or model code.

When you finish, you will have:

- a tuned kernel config JSON for your model and training configuration;
- an updated training command or recipe that uses the tuned config;
- before and after step times, MFU and a loss check from your own instance.

Overview
--------

:doc:`/training/torchtitan/tutorials/tutorial-mxfp8-training` trains in MXFP8 on Trainium3. By
default, every MXFP8 linear in that run calls the NKI kernel
:doc:`matmul_mxfp8 </nki/library/api/matmul-mxfp8-generic-kernel>` from the
:doc:`NKI Library </nki/library/api/index>` in its forward pass, and
:doc:`matmul_mxfp8 </nki/library/api/matmul-mxfp8-generic-kernel>` or
:doc:`matmul_mxfp8_backward </nki/library/api/matmul-mxfp8-generic-backward-kernel>` in its
backward pass. MoE models also call the composed MXFP8 MoE kernels
(:doc:`forward </nki/library/api/blockwise-mm-forward-mxfp8>` and
:doc:`backward </nki/library/api/blockwise-mm-backward-mxfp8>`), which build each MoE layer from the
same matmul. Each kernel call can run with a **tuned config**: a set of input parameters that
define how the kernel runs, including its blocking, tiling and loading, and other performance
features such as spill-reload.
The kernel has defaults, but the best config depends on the shape and can be tuned for better
performance. You tune once, before training, for the kernel calls your run makes. Every training
step then uses the tuned configs, and so does any other run that makes the same calls.

**Auto-tuning** finds the fastest correct configuration for each call your run makes and writes
the winners to a JSON file. You pass that file to TorchTitan Neuron as follows:

- **Dense linears**: the trainer flag ``--mxfp8_matmul_configs <json>``. At run time each MXFP8
  matmul looks up its key in the JSON. On a **hit**, the tuned config is passed to the kernel
  explicitly. On a **miss**, the kernel uses its own defaults.
- **MoE experts**: the ``tuning_path=<json>`` setting of the MXFP8 experts converter, which you
  set in your recipe. It gives the configs that the MoE forward and backward kernels use. Some
  MoE recipes already point it to a tuned file that ships with TorchTitan Neuron.

A tuned JSON changes only how the kernels execute on the chip. It doesn't change the accuracy,
the quantization scheme or the model. Before it ships a JSON, the tuning skill checks that the
loss matches the baseline run (your run before tuning).

Two skills from :doc:`Neuron Agentic Development </tools/neuron-agentic-development/index>` do
the work:

.. list-table::
   :header-rows: 1
   :widths: 34 33 33

   * -
     - Dense linears
     - MoE experts
   * - Skill
     - `neuron-nki-mxfp8-matmul-config-tuning <https://github.com/aws-neuron/neuron-agentic-development/tree/main/skills/neuron-nki-mxfp8-matmul-config-tuning>`_
     - `neuron-nki-mxfp8-moe-config-tuning <https://github.com/aws-neuron/neuron-agentic-development/tree/main/skills/neuron-nki-mxfp8-moe-config-tuning>`_
   * - Kernels tuned
     - :doc:`matmul_mxfp8 </nki/library/api/matmul-mxfp8-generic-kernel>`,
       :doc:`matmul_mxfp8_backward </nki/library/api/matmul-mxfp8-generic-backward-kernel>`
     - :doc:`MXFP8 MoE forward </nki/library/api/blockwise-mm-forward-mxfp8>`,
       :doc:`MXFP8 MoE backward </nki/library/api/blockwise-mm-backward-mxfp8>`
   * - Output
     - ``--mxfp8_matmul_configs <tuned.json>`` trainer flag
     - ``tuning_path=<tuned.ntt.json>`` on the MoE experts converter

The agent ``neuron-training-mxfp8-kernel-tuning-agent`` loads both skills and picks the one that
applies. For a MoE model whose attention and dense linears are MXFP8 too, it tunes the experts
first (they are most of the MXFP8 time), then the linears, and then compares training step time
with both tuned files against the baseline run.

.. important::

   A tuned JSON applies to the kernel calls it has keys for, not to one model. How it's matched
   depends on the kind of file:

   - **Dense linears:** each key is a matmul's per-core shape plus how its operands are loaded.
     Any run that makes the same call uses the entry, and you can merge tunings from several runs
     into one file. Different models and training configurations (parallelism, local batch size,
     sequence length) usually produce different shapes, so their calls don't match and need their
     own tuning. A call with no entry uses the kernel's defaults, with no error. Re-tune when the
     shapes change, and after a compiler upgrade.
   - **MoE experts:** entries are keyed only by block size, not by shape. A file tuned for another
     model or TP degree is still used when its block size matches, so your run can be slower or
     fail to compile. Don't reuse a MoE file across models or setups.

   SAC and full AC runs of the same configuration can share one JSON. For how kernel configs are
   looked up, see :ref:`nki-deep-dive-mxfp-matmul-kernel-configs`.

Before you start
----------------

Make sure you have:

- An MXFP8 training command that already runs on your instance: the one you want to tune. For
  the examples here, complete :doc:`/training/torchtitan/tutorials/tutorial-mxfp8-training`
  first; it runs both recipes.
- Time on the instance. Per recipe and local batch size, expect about 35 minutes of kernel search
  plus 15-20 training runs for the A/B and in-graph checks, about 2.5-3 hours in total for a dense
  model. A MoE model takes longer: the kernel search for the experts can take a few hours, and the
  agent then needs about 8-10 training runs to compare the tuned files. If you also tune the MXFP8
  linears, as in the MoE example, add the dense time on top. Tuning pays off for long runs and for
  recipes you run often.

Model details
-------------

Both examples use recipes from the MXFP8 training tutorial. The dense example tunes **Qwen3 32B**
with ``simple_fsdp_qwen3_32b_tp4_fsdp16_fullac_mxfp8_wprequant``. The MoE example tunes
**Qwen3-30B-A3B** with ``qwen3_30b_a3b_nki_fullac_compile_mxfp8``, which runs its experts and its
attention projections in MXFP8. Any TorchTitan Neuron MXFP8 recipe that uses the NKI kernels can be
tuned the same way.

Prerequisites
-------------

- A Trn3 instance with the Neuron SDK installed and your MXFP8 training working in its Python
  environment. Tuning and training must run in the same environment: the same tiling can compile
  to very different code under another compiler version, so the skill checks that its compiler
  matches the one your training uses.
- ``neuron-explorer`` from ``aws-neuronx-tools``, which the skill uses to time kernels on the
  device.
- Claude Code or Kiro installed on the instance. The agent runs on the same machine as the
  hardware; see :doc:`/tools/neuron-agentic-development/getting-started`.
- Shared storage that every rank can read, for example an FSx for Lustre or EFS mount, for the
  tuned JSON. The examples below use ``/fsx/tuned``.

On first use, the skill checks your environment and installs any libraries it is missing. It
shows you what it would install and asks first, and it never changes the Neuron SDK packages.

Step 1: Install the tuning agent
--------------------------------

Install Neuron Agentic Development on the Trn3 instance and deploy it to your agent tool:

.. code-block:: bash

   pip install --upgrade neuron-agentic-development \
       --extra-index-url https://pip.repos.neuron.amazonaws.com
   deploy-neuron-agentic-development-to-claude    # or: deploy-neuron-agentic-development-to-kiro

Then open the agent in the Python environment that runs your training:

.. code-block:: bash

   # Kiro
   kiro-cli chat --agent neuron-training-mxfp8-kernel-tuning-agent

   # Claude Code: start the session in your training directory
   claude --agent neuron-training-mxfp8-kernel-tuning-agent

Step 2: Tune a dense model
--------------------------

Step 2a: Choose the training command to tune
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

You don't run anything yet. Pick the training command you want to tune, exactly as you run it,
including its environment variables. Use the local batch size and sequence length you will train
with, because the tuned configs are specific to them. This tutorial uses the Qwen3 32B run from the
MXFP8 training tutorial:

.. code-block:: bash

   NGPU=64 \
   MODULE=torchtitan_neuron.experiments.graph_trainer.qwen3 \
   CONFIG=simple_fsdp_qwen3_32b_tp4_fsdp16_fullac_mxfp8_wprequant \
   ./run_train.sh --training.steps 20 --dataloader.dataset c4_test \
     --hf_assets_path=./tests/assets/tokenizer

The agent runs the baseline itself as part of the A/B, so you don't need to. The NKI Library
already ships tuned configs for many Qwen3 32B shapes, so the baseline is partly tuned and the gain
from a new tuning can be small. The agent keeps a built-in config when it can't beat it.

Step 2b: Run the tuning agent
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Give the agent the command and the recipe it uses:

.. code-block:: text

   Tune the MXFP8 matmul kernels for my training run with the
   neuron-nki-mxfp8-matmul-config-tuning skill. This is the training command
   I run on this Trn3 instance:

     NGPU=64 MODULE=torchtitan_neuron.experiments.graph_trainer.qwen3 \
     CONFIG=simple_fsdp_qwen3_32b_tp4_fsdp16_fullac_mxfp8_wprequant \
     ./run_train.sh --training.steps 20 --dataloader.dataset c4_test \
       --hf_assets_path=./tests/assets/tokenizer

   The recipe is *_mxfp8_wprequant (1x32, pre-quantized weights, fused backward).
   Write the tuned JSON to /fsx/tuned/ and hand back my command with its
   --mxfp8_matmul_configs line.

To cover several configurations at once, list them: for example "wrapX and 1x32 with
pre-quantized weights, at local batch 1 and 2, SAC and full AC". The agent plans one campaign per
(recipe, local batch) pair and A/Bs every cell.

The agent then works through the procedure in
:ref:`torchtitan-neuron-tutorial-mxfp8-autotuning-how-it-works`:

1. Checks the environment and installs missing libraries after you agree.
2. Runs your command for 2-3 steps with the call dump on
   (``MXFP8_NKI_TUNED_CONFIGS_DUMP=<file>``) to record every matmul call.
3. Replays each call alone on a NeuronCore with many candidate configs, checks each against an
   FP32 CPU reference, and times it on the device.
4. Writes the winners to a tuned JSON.
5. Compares training step time with and without the tuned JSON. When needed, it also tests a
   few alternative configs inside the real training run, and keeps whichever gives the fastest step.

When it finishes, the agent gives you:

- the tuned JSON and ``tuned.provenance.json``, which records the compiler, library versions and,
  for each key, the default and tuned kernel times;
- your training command with the override added;
- step time and MFU from a baseline run, the tuned run and a second baseline run on your
  instance, plus the hit check and the loss check for steps 1-3;
- anything it skipped and why.

Step 2c: Train with the tuned config
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Add the flag the agent handed back to your command:

.. code-block:: bash

   NGPU=64 \
   MODULE=torchtitan_neuron.experiments.graph_trainer.qwen3 \
   CONFIG=simple_fsdp_qwen3_32b_tp4_fsdp16_fullac_mxfp8_wprequant \
   ./run_train.sh --training.steps 20 --dataloader.dataset c4_test \
     --hf_assets_path=./tests/assets/tokenizer \
     --mxfp8_matmul_configs /fsx/tuned/qwen3_32b_wprequant.json

``mxfp8_matmul_configs`` is a field on ``Trainer.Config``, so you can also set it in your own
recipe instead of on the command line:

.. code-block:: python

   from torchtitan_neuron.experiments.graph_trainer.qwen3.config_registry import (
       simple_fsdp_qwen3_32b_tp4_fsdp16_fullac_mxfp8_wprequant as _base,
   )

   def my_qwen3_32b_wprequant_tuned():
       config = _base()
       config.mxfp8_matmul_configs = "/fsx/tuned/qwen3_32b_wprequant.json"
       return config

After the model converters run and before the model is built, the trainer writes the path into
every MXFP8 linear's config and logs one line:

.. code-block:: text

   MXFP8 tuned matmul configs from /fsx/tuned/qwen3_32b_wprequant.json on <N> linears

To see each lookup, set ``MXFP8_NKI_TUNED_CONFIGS_LOG=1``. Each kernel key then logs one
``MXFP8_AUTOTUNE ... hit=True`` or ``hit=False`` line.

The tuned config is a kernel argument, so it becomes part of the compiled training graph. The first
step after you swap in a new JSON compiles again and takes longer. Set
``NKI_ENABLE_TRACE_CACHE=0`` when you A/B two JSONs yourself.

Step 3: Tune a MoE model
------------------------

Step 3a: Choose the training command to tune
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

As for a dense model, you don't run anything yet: pick the MoE training command you want to
tune, exactly as you run it, at the local batch size and sequence length you will train with.
This tutorial uses the Qwen3-30B-A3B recipe from the MoE step of the MXFP8 training tutorial:

.. code-block:: bash

   NGPU=64 \
   MODULE=torchtitan_neuron.models.qwen3 \
   CONFIG=qwen3_30b_a3b_nki_fullac_compile_mxfp8 \
   ./run_train.sh --training.steps 20 --dataloader.dataset c4_test \
     --hf_assets_path=./tests/assets/tokenizer

This recipe already loads a tuned MoE file that ships with TorchTitan Neuron
(``qwen3_30b_a3b_tp4_b512_1x32.json``), so your baseline is already tuned. The agent has to beat
that file, and keeps it if it can't. That's most likely when you run the recipe as shipped; a new
tuning pays off when you change the local batch size, sequence length or parallelism.

Step 3b: Run the tuning agent
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The MoE layers run with the MoE kernels, and the attention projections and other MXFP8 linears
run with the dense matmul kernels. Ask the agent to tune both: the MoE layers with the MoE skill
and the linears with the matmul skill. It tunes the MoE layers first, because they take most of
the MXFP8 time, then the linears. Finally, it runs training with both tuned files together and
compares the step time against the baseline run (your run before tuning).

.. code-block:: text

   Tune the MXFP8 kernels for my MoE training run: the experts with the
   neuron-nki-mxfp8-moe-config-tuning skill and the MXFP8 linears with the
   neuron-nki-mxfp8-matmul-config-tuning skill. This is the training command
   I run on this Trn3 instance:

     NGPU=64 MODULE=torchtitan_neuron.models.qwen3 \
     CONFIG=qwen3_30b_a3b_nki_fullac_compile_mxfp8 \
     ./run_train.sh --training.steps 20 --dataloader.dataset c4_test \
       --hf_assets_path=./tests/assets/tokenizer

   The experts use NeuronMXFP8GroupedExpertsConverter with quant_scheme="1x32",
   and the recipe already loads qwen3_30b_a3b_tp4_b512_1x32.json.
   Tune the experts first, then the linears, then A/B both together.
   Write the tuned files to /fsx/tuned/. Hand back my command with
   --mxfp8_matmul_configs, and a recipe that loads the tuned MoE file.

If the recipe keeps its linears in BF16 or uses the MLIR lowering for them, only the experts are
tuned.

The kernel search time depends on the model: in the skill's measured runs it ranged from about 70
minutes to a few hours. After the search, plan for about 8-10 training runs, and add the dense time
if you also tune the linears. The agent hands back the same results as for a dense model, with
``tuned.ntt.json`` for the experts. For how the MoE search differs from the dense one, see
:ref:`torchtitan-neuron-tutorial-mxfp8-autotuning-moe-differences`.

Step 3c: Train with the tuned configs
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The two tuned files are independent: the MoE layers read only ``tuning_path``, and the attention
projections and other MXFP8 linears read only ``mxfp8_matmul_configs``.

- **Experts:** set ``tuning_path`` on the experts converter
  (``NeuronMXFP8GroupedExpertsConverter.Config``) in your recipe. The file's layout is in
  :ref:`torchtitan-neuron-tutorial-mxfp8-autotuning-moe-configs`.
- **Linears:** add ``--mxfp8_matmul_configs <json>``, as for a dense model.

For the command in Step 3a as shown, the agent will most likely keep the shipped MoE file: in the
skill's own test of this recipe, a new search ran about as fast as the shipped file. Then you
don't need a new recipe. Run the command from Step 3a with only the linears flag added:

.. code-block:: bash

   NGPU=64 \
   MODULE=torchtitan_neuron.models.qwen3 \
   CONFIG=qwen3_30b_a3b_nki_fullac_compile_mxfp8 \
   ./run_train.sh --training.steps 20 --dataloader.dataset c4_test \
     --hf_assets_path=./tests/assets/tokenizer \
     --mxfp8_matmul_configs /fsx/tuned/qwen3_30b_a3b_linears.json

Any speedup over the baseline then comes from the tuned linears, and it can be small.

If the agent hands back a new MoE file, TorchTitan Neuron 2.34 has no flag for a custom MoE tuning
file, so a recipe is needed. The agent writes a recipe (for example ``my_recipes.py``) that loads
your MoE file. Put it on your ``PYTHONPATH`` and run it with the linears flag, with ``CONFIG`` set
to the recipe's function name:

.. code-block:: bash

   NGPU=64 \
   MODULE=my_recipes \
   CONFIG=my_qwen3_30b_a3b_mxfp8_tuned \
   ./run_train.sh --training.steps 20 --dataloader.dataset c4_test \
     --hf_assets_path=./tests/assets/tokenizer \
     --mxfp8_matmul_configs /fsx/tuned/qwen3_30b_a3b_linears.json

Check the log:

- At startup: ``Converted the NKI MoE experts to 1x32 MXFP8 kernels, tuned by
  /fsx/tuned/tuned.ntt.json``.
- During the first step, one line for each tuned phase, for example
  ``MXFP8 MoE backward.phase1_block_configs: blocks run [512] rows; tuned entries used: [512].``
  If a block size in your file is never used, a warning names it.

All complete! Now, let's confirm everything works.

Confirmation
------------

The run succeeded if all of the following hold:

- Dense linears: the ``MXFP8 tuned matmul configs from ... on <N> linears`` line appears at
  startup, with ``<N>`` equal to the number of MXFP8 linears, and every key in the JSON logs
  ``hit=True`` with ``MXFP8_NKI_TUNED_CONFIGS_LOG=1``.
- MoE: the startup log says ``Converted the NKI MoE experts to <scheme> MXFP8 kernels, tuned by
  <path>`` with the path of your file. During the first step, each tuned phase logs
  ``tuned entries used: [<block rows>]`` with every block size you tuned, and no warning says
  that tuned entries are never used.
- Loss for steps 1-3 matches the baseline run within about 5e-4 relative, when both runs use the
  same ``--debug.seed``. Later steps drift slightly because a new blocking reorders the FP32
  accumulation.
- Step time: if the agent shipped a tuned file, steady-state step time (mean of steps 10-20)
  beats the baseline by more than the step-to-step noise. If it kept the existing configs, step
  time matches the baseline. The baseline is the run before tuning; for both examples here it
  already uses built-in or shipped tuned configs.

Congratulations! You have tuned the MXFP8 kernels for a TorchTitan Neuron run and trained with the
result. If you hit a problem, see
:ref:`torchtitan-neuron-tutorial-mxfp8-autotuning-common-issues`.

----

.. _torchtitan-neuron-tutorial-mxfp8-autotuning-how-it-works:

How the tuning works
--------------------

The skill finds, for every kernel call a run makes, the configuration that is fastest **where it
runs**, checks that it is correct, and lets the training step decide what ships.

.. figure:: images/mxfp8-autotuning/mxfp8-tuning-overview.png
   :alt: MXFP8 kernel config tuning workflow: capture the training run's kernel calls, search configs for each kernel shape on the device, write tuned.json, verify with a training A/B, and refine inside the training graph
   :width: 100%

   The tuning workflow, with example numbers from a Qwen3 4B run.

A standalone version of this diagram is in
:download:`mxfp8-tuning-overview.html <images/mxfp8-autotuning/mxfp8-tuning-overview.html>`.

In short:

1. **Capture.** The agent runs your training command for 2-3 steps and records every MXFP8 kernel
   call: its shape, operand layout and arguments. Each distinct call gets a key in the JSON, for
   example ``4096x2560x2432_pe_1x32_prequant`` (the per-core M × K × N shape plus how each operand
   is loaded).
2. **Standalone search.** Each call is replayed alone on a NeuronCore with many candidate configs.
   Every candidate is checked against an FP32 reference and timed on the device. The search runs a
   broad sweep, refines around the best few, and re-measures the finalists several times.
3. **Write the JSON.** The winner for each key goes into ``tuned.json`` if it beats the default by
   at least 1%, and the skill predicts the saving per training step.
4. **Verify in training.** Baseline, tuned and baseline training runs check that every tuned key
   is used, the loss matches and the step is faster by more than the noise. If it isn't, the
   existing configs are kept.
5. **Refine in training (when needed).** A config that is fastest standalone isn't always fastest
   inside the training graph, where kernels share DMA queues with their neighbors. When the A/B
   realizes much less than the predicted saving, or the run has fused backward kernels, the skill
   profiles the top candidates inside a real training step and keeps whichever makes the step
   fastest. For MoE experts this step always runs (see below).

.. _torchtitan-neuron-tutorial-mxfp8-autotuning-moe-differences:

MoE differences
^^^^^^^^^^^^^^^

The MoE skill follows the same capture, search, write and verify steps, with these differences:

- **Routing.** The kernel's work depends on how many tokens each expert gets, so the capture also
  records those counts. When the skill replays a call to time it, it recreates the routing from
  the recorded counts (or splits the tokens evenly), because it can't reuse the exact routing from
  your run.
- **Routed experts** (such as Qwen3-30B-A3B) can take a long time to compile: up to 20-30 minutes
  for the backward of a 128-expert model. To search faster, the skill first tries candidates on a
  scaled-down copy of each call, with 1/8 of the experts and 1/8 of the tokens for a 128-expert
  model. Each expert still gets the same number of tokens, so the kernel does the same work per
  block. The best candidates are then timed again on the full-size call.
- **Dense experts** run with expert parallelism (``neuron_ep`` recipes), where each rank holds whole
  experts and the number of tokens it receives varies. The slowest rank sets the step time, so the
  skill tunes for both an average load and a full load, and tunes the shorter last block of each
  call (the *tail*) separately. This doesn't apply to Qwen3-30B-A3B, which uses routed experts.
- **Phases are tuned together.** The phases interact, so the search holds the other phases at the
  best configs found so far and measures combinations of the top phase entries.
- **The final choice is made in training.** The agent A/Bs the top three complete tuned files in
  real training runs. Then, starting from the fastest one, it changes one part at a time (for
  example, its forward configs or its tail entries) and keeps whichever gives the fastest step.

What is swept
^^^^^^^^^^^^^

.. figure:: images/mxfp8-autotuning/mxfp8-tuning-knobs.png
   :alt: The knobs the tuning sweeps for one matmul call: tile size, block size, load split, spill-reload and engine balance ratios
   :width: 100%

   The knobs of one matmul call. A config is a set of kernel arguments.

To understand what each knob does inside the kernel, and why the best value depends on the
shape, read :doc:`/nki/deep-dives/mxfp-matmul-kernel`. Each knob maps to a section there:

.. list-table::
   :header-rows: 1
   :widths: 40 60

   * - Knob
     - Explained in
   * - ``tile_m``, ``tile_k``, ``tile_n``, ``TILES_IN_BLOCK_M/N/K``
     - :ref:`Blocking and tiling <nki-deep-dive-mxfp-matmul-kernel-blocking>`
   * - ``TILES_IN_LOAD_M/N``
     - :ref:`Blocking and tiling <nki-deep-dive-mxfp-matmul-kernel-blocking>` and
       :ref:`Load paths <nki-deep-dive-mxfp-matmul-kernel-load-paths>`
   * - ``spill_reload``
     - :ref:`Spill-reload <nki-deep-dive-mxfp-matmul-kernel-spill-reload>`
   * - ``psum_copy_in_ratio``
     - :ref:`PSUM copy-in <nki-deep-dive-mxfp-matmul-kernel-psum-copy-in>`
   * - ``strided_copy_swizzle_1x32_ratio``
     - :ref:`Load paths <nki-deep-dive-mxfp-matmul-kernel-load-paths>` (strided-copy swizzle)

The deep dive also covers the quantization schemes (wrapX and 1x32), LNC2 sharding, SBUF
optimizations, and how the fused backward, MoE and MLP kernels reuse the same matmul, which is why
the MoE kernel configs below use the same fields.

For example, tuning Qwen3 4B (SAC, TP4 × FSDP16, local batch 2, 1x32 with pre-quantized weights)
produced these two entries in ``tuned.json``, one for the down projection's weight gradient and one
for its forward pass. Each key is the matmul's per-core M × K × N shape plus how its operands are
loaded:

.. code-block:: text

   "1280x8192x2432_pe_1x32_kbyf_pe_1x32_kbyf": {
     "tile_n": 512,
     "TILES_IN_BLOCK_M": 10, "TILES_IN_BLOCK_N": 5, "TILES_IN_BLOCK_K": 2,
     "TILES_IN_LOAD_M": 10, "TILES_IN_LOAD_N": 1,
     "spill_reload": true, ...
   },
   "4096x2432x2560_pe_1x32_prequant": {
     "tile_n": 512,
     "TILES_IN_BLOCK_M": 17, "TILES_IN_BLOCK_N": 5, "TILES_IN_BLOCK_K": 5,
     "TILES_IN_LOAD_M": 17, "TILES_IN_LOAD_N": 5,
     "spill_reload": true, ...
   }

.. list-table::
   :header-rows: 1
   :widths: 40 35 25

   * - Matmul
     - Kernel time per call, default → tuned
     - Speedup
   * - Down projection, weight gradient
     - 1218.5 µs → 558.0 µs
     - 2.18x
   * - Down projection, forward
     - 428.7 µs → 308.7 µs
     - 1.39x

.. _torchtitan-neuron-tutorial-mxfp8-autotuning-moe-configs:

What a MoE kernel config contains
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The MoE tuning file (``tuned.ntt.json``) has a ``forward`` and a ``backward`` section. Each
section has one ``<phase>_block_configs`` map per kernel phase. The keys of each map are **block
sizes**: the number of token rows the kernel processes in one block of one expert. The file
doesn't record the model's shapes. Every MoE layer in the run uses the same entries, so a file is
only right for the model and setup it was tuned for.

In the table, R is the block size, H is the hidden size, and I is each rank's share of the expert
FFN size. The MoE kernels run each rank on two physical NeuronCores
(:ref:`LNC=2 <logical-neuroncore-config>`). The shapes are for one of these two cores, and a "/2"
marks a dimension that is split between them.

.. list-table::
   :header-rows: 1
   :widths: 30 35 35

   * - JSON slot
     - Phase
     - Matmul on one physical core (M × K × N)
   * - ``forward.gate_up_block_configs``
     - Forward gate and up projections (one config for both)
     - R × H × I
   * - ``forward.down_block_configs``
     - Forward down projection
     - R × I × H
   * - ``backward.phase1_block_configs``
     - Backward phase 1: gradient through the down projection
     - R × H × I/2
   * - ``backward.phase2_block_configs``
     - Backward phase 2: gradient through the gate and up projections
     - R × 2I × H/2
   * - ``backward.phase3_block_configs``
     - Backward phase 3: gate and up weight gradient
     - H/2 × R × 2I
   * - ``backward.phase4_block_configs``
     - Backward phase 4: down weight gradient
     - I × R × H/2

One exception: for routed 1x32 experts where I is smaller than R, phase 1 splits the rows between
the two cores instead, so each core runs R/2 × H × I.

Each entry sets matmul fields, for example the tiling fields (``tile_m``, ``tile_k``, ``tile_n``,
``TILES_IN_BLOCK_M/N/K``, ``TILES_IN_LOAD_M/N/K``), ``spill_reload``, ``enable_scale_packing``,
and the ratio knobs ``psum_copy_in_ratio`` and ``strided_copy_swizzle_1x32_ratio``. Fields you
leave out get defaults: spill-reload and scale packing stay on, and the kernel picks the rest.
Each section can also set a few fields that apply to every block size, such as
``phase3_transpose_mode`` in ``backward``.

For example, this is the tuned file that ships with TorchTitan Neuron for the Qwen3-30B-A3B recipe
in Step 3 (``qwen3_30b_a3b_tp4_b512_1x32.json``: block size 512, H = 2048, I = 768 / 4 = 192,
1x32). Its forward pass kept the kernel defaults, so the file has only backward entries. The first
entry is shown in full:

.. code-block:: text

   {
     "forward": {},
     "backward": {
       "phase1_block_configs": {
         "512": {
           "tile_m": 128, "tile_k": 512, "tile_n": 192,
           "TILES_IN_BLOCK_M": 2, "TILES_IN_BLOCK_N": 1, "TILES_IN_BLOCK_K": 4,
           "TILES_IN_LOAD_M": 2, "TILES_IN_LOAD_N": 1
         }
       },
       "phase2_block_configs": {"512": {"tile_n": 512, "TILES_IN_BLOCK_M": 4, ...}},
       "phase3_block_configs": {"512": {"tile_n": 384, "strided_copy_swizzle_1x32_ratio": 0.75, ...}},
       "phase4_block_configs": {"512": {"tile_n": 512, "TILES_IN_BLOCK_M": 2, ...}}
     }
   }

Things to know about the block-size keys:

- **The block size comes from your run.** For routed experts, TorchTitan Neuron sets the block
  size to half the tokens one expert gets when routing is balanced, rounded to the nearest of 256,
  512, 1024, 2048 or 4096:

  .. code-block:: text

     block size ≈ tokens per rank × experts per token / number of experts / 2

  Tokens per rank is local batch size × sequence length. For Qwen3-30B-A3B at local batch size 4
  and sequence length 4096, that's 16384 × 8 / 128 / 2 = 512. If you change the local batch size or
  the sequence length, the block size can change, and entries for other sizes aren't used: the log
  shows ``tuned entries used: []`` and a warning that names the unused sizes. For dense experts,
  the expert-parallel degree also changes the block size. The skill doesn't tune the block size
  itself. If you know your trained model's token distribution, you can set it in the ``forward``
  section with ``"block_size"`` (a multiple of 128), then re-tune at that size, because the phase
  entries are keyed by it.
- **Dense experts have tail entries.** With dense (expert-parallel) experts, the number of tokens a
  rank receives changes from step to step, so the last block of a call is usually only partly
  full. Instead of running a full-size block that is mostly padding, the kernel runs that last
  block at a smaller size: a half or a quarter block, for example 2048 or 1024 rows for a
  4096-row block. Each of these smaller sizes has its own entry in the file. Under 1x32, the
  backward phase 1 and phase 2 tail entries must use the same weight layout as the full block
  (the same ``tile_k``, ``tile_n``, ``TILES_IN_BLOCK_K/N``, ``TILES_IN_LOAD_K/N`` and scale
  packing), or the graph fails to compile; the skill writes them that way. Routed experts, such
  as Qwen3-30B-A3B, pad each expert's last block to the full block size instead, so they have no
  tail entries.

----

.. _torchtitan-neuron-tutorial-mxfp8-autotuning-common-issues:

Common issues
-------------

- **MoE: the standalone kernel search fails on every candidate config with** ``AttributeError:
  module 'nkilib.experimental.moe_mxfp8.bwd.config' has no attribute '_default_matmul_config'``:
  this is a known issue in Neuron 2.34; ``kct.py doctor`` still passes. The MoE skill's plugin calls
  a helper that NKI Library 2.34 removed. Open the skill's
  `scripts/plugins/moe_mxfp8.py <https://github.com/aws-neuron/neuron-agentic-development/blob/main/skills/neuron-nki-mxfp8-moe-config-tuning/scripts/plugins/moe_mxfp8.py>`_
  in the copy your agent loads, for example
  ``~/.kiro/skills/neuron-nki-mxfp8-moe-config-tuning/scripts/plugins/moe_mxfp8.py``, and find
  these lines in ``_phase_default``:

  .. code-block:: python

     ph = {n: bc._default_matmul_config() for n in ("phase1_config", "phase2_config", "phase3_config", "phase4_config")}
     for p in ph.values():
         p.quant_scheme = s
     cfg = bc.MXFP8MOEBwdConfig(**ph)

  Replace them with the following, keeping the indentation, then run the search again. You can
  also ask the agent to make this change. The dense linears skill is not affected.

  .. code-block:: python

     cfg = bc.MXFP8MOEBwdConfig()
     cfg.resolve_phase_defaults()
     for n in ("phase1_config", "phase2_config", "phase3_config", "phase4_config"):
         getattr(cfg, n).quant_scheme = s
     cfg.quant_scheme = s

- **No speedup, and keys log** ``hit=False`` (dense linears): the JSON was tuned for a different
  model, recipe, local batch size, sequence length or TP degree, or for the other backward (fused
  versus two-GEMM). A miss is silent apart from the hit log. Re-tune on the current setup.
- **No dump file after the capture run, or every key misses**: there are two common causes.

  - The recipe sends the linears through the MLIR lowering (``*_mxfp8_mlir``), which doesn't call
    the NKI matmul kernels, so there are no linear calls to record. Use an NKI recipe. The MoE
    experts still run on the NKI kernels in these recipes, so this doesn't explain a missing MoE
    dump.
  - The run loaded its compiled graph from the PyTorch Dynamo precompile cache instead of tracing
    the model again, so no kernel calls were recorded. This happens when
    ``TORCH_CACHING_PRECOMPILE=1`` is set and an earlier run filled the cache. For the capture
    run, unset ``TORCH_CACHING_PRECOMPILE`` or delete ``TORCHINDUCTOR_CACHE_DIR`` (by default
    ``/tmp/torchinductor_<username>``), then capture again. Clearing only the NEFF cache doesn't
    help. See :ref:`torch-compile-ref`.
- ``FileNotFoundError: mxfp8_matmul_configs: <path> does not exist; it must be readable on every
  rank``: the JSON isn't on shared storage, or the mount path differs between nodes. Put the file
  where every rank can read it under the same path. For a MoE ``tuning_path`` that doesn't exist,
  you get a plain ``FileNotFoundError`` with the path when the recipe is built. The fix is the
  same.
- **MoE: a ValueError saying the MXFP8 MoE tuning "has unknown keys"**: first check that
  ``tuning_path`` points to ``tuned.ntt.json``. The MoE skill also writes a ``tuned.json`` next to
  it in its own working format, and the dense linears file is also called ``tuned.json``. Neither
  works as ``tuning_path``. If you edited the file by hand, check the key names against the ones
  the error lists. If the path and names are right, the file was probably written for another
  version of TorchTitan Neuron. Re-tune with your current version.
- **A warning that mxfp8_matmul_configs is set but the model has no MXFP8 linears; it has no
  effect**: you passed the flag with a BF16 recipe, or a recipe whose converter didn't swap any
  linears. Use an MXFP8 recipe.
- **A RuntimeError saying a variable "no longer select[s] the Neuron MXFP8 kernel"**: your shell
  exports one of the retired kernel-selecting variables (for example ``MXLINEAR_FUSED_NKI`` or
  ``MXFP8_NKI_1X32``). Unset it; the training config now selects the kernels. See
  :ref:`torchtitan-neuron-tutorial-mxfp8-common-issues` in the MXFP8 training tutorial.
- **The tuned run is no faster than an already-tuned baseline**: the kernels may already use
  built-in tuned entries or a checked-in JSON, so the campaign competes with an earlier campaign.
  For dense linears, ``tuned.provenance.json`` marks keys that had a built-in entry, and large
  gains come from keys without one. For MoE experts, check the baseline's startup log: if it
  says ``tuned by <path>``, the recipe already loads a tuned file (the Qwen3-30B-A3B recipe does),
  and your file has to beat it.
- **A slower first step only**: expected. The tuned configs are part of the compiled graph, so the
  first step compiles again. For MoE recipes, the whole forward and backward graphs compile again,
  and the first step can take tens of minutes.
- **MoE: the tuned run fails to compile with** ``NCC_IBIR251``: with dense (expert-parallel) 1x32
  experts, a backward phase 1 or phase 2 tail block uses a different weight layout from the full
  block. The layout fields are ``tile_k``, ``tile_n``, ``TILES_IN_BLOCK_K/N``,
  ``TILES_IN_LOAD_K/N`` and ``enable_scale_packing``. A tail size with no entry in the JSON uses
  the default layout. So this happens if you change these fields in the full-block entry by hand
  and don't give every tail size an entry with the same values, including when the file has no
  tail entries at all. Let the skill write the JSON; it adds the tail entries in the full block's
  layout.
- **MoE:** ``tuned entries used: []`` **in the log**, followed by a warning that tuned entries are
  never used: the JSON is keyed by a block size that the run doesn't use. The warning shows the
  block size the run uses. The block size follows the local batch size and sequence length (and,
  for dense experts, the expert-parallel degree), so re-tune for each setup.
- **Loss differs from the baseline run beyond 5e-4 at step 1**: a tiling changes only the order of
  FP32 accumulation, and the tuner rejects candidates that fail the reference check. Make sure both
  runs use the same seed (``--debug.seed``) and the same initialization, then report the JSON, its
  provenance file and both logs.

Clean up
--------

Stop the training processes (``Ctrl-C`` on the ``torchrun`` launcher). Keep the tuned JSON and its
provenance file if you will run this recipe again. Delete the tuning work directory (call dump,
manifest, results and profiles) if you no longer need it. Stop or terminate the instance, since it
bills while running.

Next steps
----------

- Re-run the tuning whenever you change the model, recipe, local batch size, sequence length,
  parallelism, or move to a new compiler build. Pass the previous JSON to the agent: it re-measures
  it as a warm start.
- If tuning gives little speedup, something other than the tuned kernels limits the step.
  Profile a training step and look at exposed collectives, layout copies around the NKI calls,
  attention and the loss. Compare against the BF16 version of the same recipe (same TP,
  activation checkpointing and batch size; for Qwen3-30B-A3B, ``qwen3_30b_a3b_nki_fullac_compile``).
  For a MoE model, you can also ask the agent for the MoE skill's step report: it profiles the
  tuned step and shows where the time goes. To look inside a single kernel, use
  the ``neuron-nki-profiling`` and ``neuron-nki-profile-querying`` skills.
- :doc:`/training/torchtitan/best-practices` for tuning beyond the kernels.

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

- :doc:`/training/torchtitan/tutorials/tutorial-mxfp8-training`
- :doc:`/tools/neuron-agentic-development/index`
- :doc:`/nki/library/api/matmul-mxfp8-generic-kernel` and
  :doc:`/nki/library/api/matmul-mxfp8-generic-backward-kernel`
- :doc:`/nki/deep-dives/mxfp-matmul-kernel`
- :doc:`/nki/deep-dives/mxfp-matmul`
- :doc:`/training/torchtitan/about-torchtitan-neuron`
- :doc:`/training/torchao-neuron/about-torchao-neuron`
