.. meta::
   :description: Reference for the AWS Neuron NKI nki.compiler.CompileConfig options: defaults, the allocation and scheduling modes each option needs, OptLevel behavior, cost, limits, and examples.
   :keywords: NKI, CompileConfig, compile options, allocation, scheduling, opt_level, OptLevel, prefetch_auto, NKI_PREFETCH_RING_SIZE, split_reused_buffers, non_ssa_legalization, tensor_copy_elim, address_rotation, dma_copy_elim, element_widening, engine_balancing, register_load_reuse, dead_code_elim, remove_unused_instructions, remove_overwritten_writes, nki_alloc_fallback, sbuf_allocation_fallback, AllocationMode, SchedulingHeuristic, AWS Neuron, Trainium
   :date-modified: 2026-11-13

.. _nki-compile-config-ref:

=======================================
Reference: NKI CompileConfig options
=======================================

This topic provides reference for the per-kernel compile options of
:class:`nki.compiler.CompileConfig` in the AWS Neuron SDK. Use this page to
look up the default of an option, the allocation and scheduling modes in which
it acts, what it costs, and how to confirm that it took effect.

.. contents:: On this page
   :local:
   :depth: 2

Overview
========

Pass a :class:`nki.compiler.CompileConfig` to :func:`nki.jit` to select the
allocation and scheduling modes of a kernel and its optimizations. The
following kernel uses NKI allocation and enables ``prefetch_auto``:

.. nki_example:: ../examples/compile_config/intro.py
   :language: python
   :marker: NKI_EXAMPLE_COMPILE_CONFIG_INTRO

The API reference of :class:`~nki.compiler.CompileConfig` lists every option.
This page covers the options that need more than a few sentences. For how each
optimization works, see :ref:`nki-compile-config`. This page uses the
terminology of that topic: *NKI allocation* is ``allocation=Allocation.LINEAR``,
*NKI scheduling* is ``scheduling=True`` with NKI allocation, and *neuronx-cc
allocation* is the default or ``allocation=Allocation.COLORING``.

Usage
=====

Use this reference to look up one option. Each option section starts with a
field list:

Default
   The value of the option when the kernel does not set it.
At ``OptLevel.O2``
   Whether ``opt_level=OptLevel.O2`` turns the option on.
Acts with
   The allocation and scheduling modes in which the option has an effect. See
   :ref:`nki-compile-config-nki-flow-options` for what happens in other modes.

To select options for a kernel, see
:ref:`nki-compile-config-tuning-how-to`.

.. _nki-compile-config-compile-flow:

Allocation and scheduling modes
===============================

``allocation`` and ``scheduling`` select which compiler allocates and
schedules the kernel. ``opt_level`` selects how many optimizations NKI applies
(see :ref:`nki-compile-config-opt-levels`). The following kernel sets all
three. It uses NKI allocation and NKI scheduling at ``OptLevel.O2``. NKI
scheduling is experimental (see :ref:`nki-compile-config-availability`), so
start without ``scheduling=True``.

.. nki_example:: ../examples/compile_config/compile_flow.py
   :language: python
   :marker: NKI_EXAMPLE_COMPILE_FLOW

.. list-table::
   :header-rows: 1
   :widths: 25 25 50

   * - ``allocation``
     - ``scheduling``
     - Mode
   * - ``None`` (default)
     - ``None`` or ``False``
     - neuronx-cc allocation and scheduling.
   * - ``Allocation.COLORING``
     - ``None`` or ``False``
     - neuronx-cc allocation and scheduling.
   * - ``Allocation.LINEAR``
     - ``None`` or ``False``
     - NKI allocation, neuronx-cc scheduling.
   * - ``Allocation.LINEAR``
     - ``True``
     - NKI allocation and NKI scheduling (experimental).

Any other combination raises ``ValueError`` when you create the
``CompileConfig``, because ``scheduling=True`` needs ``Allocation.LINEAR``.

``None`` and ``Allocation.COLORING`` compile the kernel the same way in this
release. Use ``None`` to follow the default, which can change in a future
release. Use ``Allocation.COLORING`` to keep neuronx-cc allocation for the
kernel when the default changes, or when a framework integration selects
another mode for kernels that set no ``allocation``.

.. _nki-compile-config-nki-flow-options:

Options by mode
---------------

Most options change NKI allocation or NKI scheduling, so they act only in
those modes. In the following table, "Error" means that ``CompileConfig``
raises ``ValueError`` when you set the option to a value other than its
default. For ``register_load_reuse``, that value is ``False``.

.. list-table::
   :header-rows: 1
   :widths: 28 18 18 18 18

   * - Options
     - ``allocation`` not set
     - ``Allocation.COLORING``
     - ``Allocation.LINEAR``, ``scheduling`` not ``True``
     - ``Allocation.LINEAR``, ``scheduling=True``
   * - Allocation options: ``split_reused_buffers``, ``tensor_copy_elim``,
       ``remove_unused_instructions``, ``remove_overwritten_writes``,
       ``sbuf_allocation_fallback``, ``experimental_allocation_mode`` and the
       ``experimental_*_allocation_mode`` options
     - No effect
     - Error
     - Act
     - Act
   * - ``prefetch_auto``, ``dma_copy_elim`` and ``element_widening``
     - No effect
     - No effect, no error
     - Act
     - Act
   * - Scheduling options: ``engine_balancing``, ``register_load_reuse`` and
       ``experimental_scheduling_heuristic``
     - No effect. Error with ``scheduling=False``.
     - Error
     - Error
     - Act

A kernel that sets no ``allocation`` uses the default mode, which is
neuronx-cc allocation, so these options have no effect. A framework
integration can select NKI allocation for kernels that set no
``allocation``. In that case, the allocation options act as with NKI
allocation. The scheduling options act only when the framework also selects
NKI scheduling. Otherwise, they have no effect, and no ``ValueError`` occurs.

The other options follow these rules:

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

   * - Option
     - Acts with
   * - ``barrier_check``, ``dead_code_elim``, ``address_rotation``
     - Every mode.
   * - ``non_ssa_legalization``
     - neuronx-cc allocation only. With ``Allocation.LINEAR``, no error and no
       benefit; use ``split_reused_buffers``.
   * - ``nki_alloc_fallback``
     - NKI allocation only. With ``Allocation.COLORING``, no error and no
       effect.
   * - ``opt_level``
     - NKI allocation only. With neuronx-cc allocation, no error and no
       effect.

With ``nki_alloc_fallback=True``, a kernel that runs out of memory in NKI
allocation compiles with neuronx-cc allocation, and the options that need NKI
allocation have no effect for it (see
:ref:`nki-compile-config-nki-alloc-fallback`).

The following rules apply to every option on this page:

* An optimization can make one kernel faster and another kernel slower.
  Compare the runtime with and without the option, and check its effect in a
  profile.
* The option is part of the compiled kernel. A kernel compiled with the option
  does not reuse a cached compilation without it.

.. _nki-compile-config-opt-levels:

Optimization levels
-------------------

.. list-table::
   :header-rows: 1
   :widths: 20 80

   * - ``opt_level``
     - Effect
   * - ``OptLevel.O0``
     - A predictable baseline. Each instruction that has no ``engine=`` and
       that more than one engine can run, including ``nisa.tensor_copy``,
       runs on its default engine. ``engine_balancing`` has no effect.
   * - ``OptLevel.O1`` (default)
     - The compiler chooses the engine of each ``nisa.tensor_copy`` that has
       no ``engine=``. Other instructions that have no ``engine=`` run on
       their default engine, unless ``engine_balancing`` is on.
   * - ``OptLevel.O2``
     - ``O1``, plus these options:
       :ref:`prefetch_auto <nki-compile-config-prefetch-auto>`,
       :ref:`split_reused_buffers <nki-compile-config-split-reused-buffers>`,
       :ref:`tensor_copy_elim <nki-compile-config-tensor-copy-elim>`,
       :ref:`dma_copy_elim <nki-compile-config-dma-copy-elim>`,
       :ref:`element_widening <nki-compile-config-element-widening>`,
       ``remove_unused_instructions`` and ``remove_overwritten_writes`` (see
       :ref:`nki-compile-config-dead-code-elim`), and
       ``address_rotation=AddressRotation.ENABLE`` when
       :ref:`address_rotation <nki-compile-config-address-rotation>` is
       ``AUTO``. With ``scheduling=True``, also
       :ref:`engine_balancing <nki-compile-config-engine-balancing>`.

An option that you set explicitly works as follows at every level:

* ``prefetch_auto``, ``split_reused_buffers``, ``dma_copy_elim``,
  ``element_widening``, ``engine_balancing``, ``tensor_copy_elim``,
  ``remove_unused_instructions`` and ``remove_overwritten_writes`` default to
  ``None``. ``None`` follows the level: off at ``O0`` and ``O1``, on at
  ``O2``. ``True`` turns the option on at every level. The exception is
  ``engine_balancing``: at ``O0``, every instruction runs on its default
  engine. ``False`` keeps the option off, even at ``O2``.
* ``address_rotation`` defaults to ``AUTO``, which ``O2`` changes to
  ``ENABLE``. An explicit ``ENABLE`` or ``DISABLE`` stays at every level.

``O2`` does not change the other options, such as ``register_load_reuse``,
``non_ssa_legalization`` and ``dead_code_elim``. ``opt_level`` acts only with
NKI allocation. With neuronx-cc allocation, every level compiles the same
kernel. An explicit ``engine=`` on an instruction applies at every level.

Nested kernels
--------------

A nested ``@nki.jit`` kernel runs inline in the top-level kernel and uses the
configuration of the top-level kernel. The call raises ``NkiValidationError``
when both of these conditions are true:

* The nested kernel sets a ``CompileConfig`` option, or ``lnc``, to a value
  other than its default.
* That value is different from the value of the top-level kernel.

The error occurs even when both kernels would compile in the same mode. The
compiler does not check an option that the nested kernel leaves at its
default or sets to its default. For such an option, the value of the
top-level kernel applies. To apply the configuration of the top-level kernel
to the nested kernel with a warning instead of the error, set
``SpecializationConfig(allow_nested_config_override=True)`` on the top-level
kernel.

.. _nki-compile-config-prefetch-auto:

prefetch_auto
=============

``prefetch_auto`` places DMA prefetch tensors apart from compute tensors in
SBUF, so that a DMA that loads the next tile does not wait for compute that
still reads the current tile. It reduces the waits in
:ref:`nki-compile-config-load-waits` when the load and the compute use
different tensors. For the placement rules, see
:ref:`nki-compile-config-prefetch-how`.

:Default: ``None`` (off at ``O0`` and ``O1``)
:At ``OptLevel.O2``: On
:Acts with: NKI allocation

When to use it
--------------

Enable ``prefetch_auto`` when the profile shows loads that wait for compute,
and the load writes a different tensor than the tensor that compute reads. If
the waits are a small part of the kernel's runtime, the option cannot help
much.

Cost
----

The split of SBUF into a prefetch part and a compute part constrains
placement:

* Compute tensors cannot reuse memory that a prefetch tensor holds. With
  ``NKI_PREFETCH_RING_SIZE``, compute tensors cannot use the prefetch region
  at all. The peak SBUF use of the kernel can increase, and a kernel that fits
  in SBUF with mixed placement can stop fitting.
* The stricter placement can add new waits, for example between compute
  tensors that now share a smaller part of SBUF.
* With the default layout, the SBUF allocation strategy does not apply (see
  :ref:`nki-compile-config-prefetch-strategy`).

When anti-dependencies were not the bottleneck, these costs can make the
kernel slower.

.. _nki-compile-config-prefetch-auto-ring-size:

Sizing the prefetch region
--------------------------

Set the ``NKI_PREFETCH_RING_SIZE`` environment variable to a number of bytes
per SBUF partition to give prefetch tensors a fixed region of that size at the
top of SBUF. The variable is not a per-kernel option. It applies to every
kernel that the process compiles. For example:

.. code-block:: bash

   $ NKI_PREFETCH_RING_SIZE=65536 python my_script.py

The bounds of this region are hard (see
:ref:`nki-compile-config-prefetch-how`). A prefetch tensor that does not fit
makes NKI allocation fail with an error that names the prefetch region:

.. code-block:: text

   error: Out of DMA prefetch region in sbuf while allocating 16384 bytes for a
   prefetch buffer (prefetch region 8192 bytes/partition, 0 bytes live)

To fit the tensor, increase ``NKI_PREFETCH_RING_SIZE``. Use the variable when
you know how much SBUF the prefetch tensors of the kernel need: reserve that
amount and leave the rest to compute.

Marking tensors with prefetch=True
----------------------------------

NKI allocation recognizes only DMA loads from HBM as prefetch tensors on its
own. Mark a tensor with ``prefetch=True`` when the kernel fills it ahead of
the compute that reads it, but it is not the destination of a DMA load. For
example, mark the destination of an SBUF-to-SBUF DMA, or a compute output that
the kernel writes well before the compute that reads it. NKI allocation then
places the marked tensor with the prefetch tensors.

``prefetch=True`` changes only where a tensor goes. It does not give the
tensor a second buffer. When a loop writes the same tensor in each iteration,
the write for the next iteration waits until the current iteration has read
the tensor, wherever the tensor is. To overlap the two, use a separate tensor
for each iteration, or
:ref:`split_reused_buffers <nki-compile-config-split-reused-buffers>`.

Where the marked tensor goes depends on ``prefetch_auto`` and
``NKI_PREFETCH_RING_SIZE``:

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

   * - Setting
     - ``NKI_PREFETCH_RING_SIZE`` not set
     - ``NKI_PREFETCH_RING_SIZE`` above ``0``
   * - ``prefetch_auto`` enabled
     - With the prefetch tensors.
     - In the prefetch region, with the DMA load destinations.
   * - ``prefetch_auto`` disabled
     - The mark is ignored.
     - In the prefetch region. DMA load destinations are not in the region.

With ``NKI_PREFETCH_RING_SIZE=0``, there is no prefetch region. Prefetch
tensors then go where compute tensors go, and the mark has no effect.

.. _nki-compile-config-prefetch-auto-limits:

Limits
------

* ``prefetch=True`` is accepted only for SBUF tensors, and cannot be combined
  with an explicit ``address``.
* NKI allocation recognizes only DMA loads from HBM as prefetch tensors on its
  own.
* The compiler does not move a tensor allocated with ``prefetch=True`` during
  address rotation, with any value of ``address_rotation``.

How to check it
---------------

In the instruction timeline of Neuron Explorer, find a DMA load into a tile
and the compute instruction that reads the previous tile. Without the option,
the load starts only after that compute instruction ends. With the option in
effect, the load starts while that compute instruction still runs.

Example
-------

The following kernel loads ``x`` into SBUF, computes ``1 / x`` into
``computed``, and then adds one. ``loaded`` is a DMA load destination, so
``prefetch_auto`` treats it as a prefetch tensor on its own. ``computed`` is a
compute output, and ``prefetch=True`` places it with the prefetch tensors as
well. ``result`` stays a compute tensor, at the bottom of SBUF.

.. nki_example:: ../examples/compile_config/prefetch_auto.py
   :language: python
   :marker: NKI_EXAMPLE_PREFETCH_AUTO

Example: the next load overlaps compute
---------------------------------------

The following kernel doubles ``x`` one tile at a time, and keeps each tile in
a separate tensor. It uses the ``FAST`` strategy, which reuses freed memory
early (see :ref:`nki-compile-config-sbuf-strategies`).

* Without ``prefetch_auto``, each ``tile`` takes the address that the previous
  ``tile`` freed. The load of tile *i+1* then waits until the compute on tile
  *i* has read it, and the kernel loads, computes and stores one tile at a
  time.
* With ``prefetch_auto``, the tiles are prefetch tensors, at different
  addresses above the ``doubled`` tensors. NKI scheduling issues the load of
  tile *i+1* before the compute on tile *i*, so the two can run at the same
  time.

Under ``RING``, the default strategy, the tiles of this small kernel are at
different addresses with or without the option. The option then does not
change the order of loads and compute.

.. nki_example:: ../examples/compile_config/prefetch_auto_overlap.py
   :language: python
   :marker: NKI_EXAMPLE_PREFETCH_AUTO_OVERLAP

.. _nki-compile-config-split-reused-buffers:

split_reused_buffers
====================

``split_reused_buffers`` splits the live ranges of a reused SBUF tensor into
separate tensors. Instructions that use different live ranges then no longer
depend on each other through the memory that they share. You do not need to
change the kernel. For how the split works, see
:ref:`nki-compile-config-split-how`.

A *reused tensor* is one ``nl.ndarray`` that the kernel fills, reads, and then
fills again with new data that does not depend on the old data. Each fill and
the reads of that fill are one *live range* of the tensor.

:Default: ``None`` (off at ``O0`` and ``O1``)
:At ``OptLevel.O2``: On
:Acts with: NKI allocation

When to use it
--------------

Enable ``split_reused_buffers`` when the profile timeline shows loads into one
tensor and the compute that reads it alternating: the load for the next
iteration starts only after the compute on the previous iteration ends. The
largest gains are in DMA-bound kernels that reload a weight or activation tile
into the same tensor many times. Compute-bound kernels seldom get faster.

Cost
----

The split does not increase the amount of SBUF that is live at any time.
Under ``FAST`` and ``MAX_REUSE``, the clones can share an address, and the
option does not help (see :ref:`nki-compile-config-split-how`). With
``sbuf_allocation_fallback=True``, NKI allocation can change to these
strategies when SBUF runs short. When the waits on the reused tensor were not
the bottleneck, the option does not help.

.. _nki-compile-config-split-reused-buffers-limits:

Limits
------

The compiler does not split a tensor when any of the following conditions is
true:

* The tensor is not in SBUF, or it has only one live range.
* The tensor has an explicit ``address``.
* The kernel uses the tensor inside a loop that stays rolled, such as an
  ``nl.fori_loop`` without ``unroll=True``, and did not allocate the tensor in
  that loop.
* A write to the tensor can leave some of the bytes that it addresses
  unchanged, such as a predicated copy, a stream shuffle, or a DMA with a
  dynamic or out-of-bounds-skipping access pattern. Such a write does not show
  which data the later reads see, so the split is not safe.
* The reuse is not regular: the first write that recurs does not recur after a
  read of the tensor, as a write that loop iterations repeat would.

On an LNC=2 kernel, each core holds its own copy of the tensor, so a write on
one core never ends a live range on the other core.

How to check it
---------------

In the instruction timeline of Neuron Explorer, find the load for the next
iteration. Without the option, it starts only after the compute of the current
iteration ends. With the option in effect, it starts while that compute still
runs.

.. _nki-compile-config-split-reused-buffers-example:

Example
-------

The following kernel streams ``x`` through SBUF 128 rows at a time. The kernel
allocates ``tile`` and ``res`` once and overwrites both in every iteration.
With ``split_reused_buffers``, each iteration gets its own clone of both, so
the load for the next iteration can run while the current iteration computes.

.. nki_example:: ../examples/compile_config/split_reused_buffers.py
   :language: python
   :marker: NKI_EXAMPLE_SPLIT_REUSED_BUFFERS

.. _nki-compile-config-non-ssa-legalization:

non_ssa_legalization
====================

``non_ssa_legalization`` lets the compiler split a reused tensor into one
clone per live range with neuronx-cc allocation. It removes the same waits
that ``split_reused_buffers`` removes with NKI allocation (see
:ref:`nki-compile-config-split-how`).

:Default: ``False``
:At ``OptLevel.O2``: Not changed
:Acts with: neuronx-cc allocation (``allocation=Allocation.COLORING``, or no
            ``allocation``)

With ``non_ssa_legalization=True``, the compiler replaces each reused tensor
with one clone per live range. neuronx-cc allocation then places each clone
separately, so it can place the clones at different addresses. The load for
the next use can then overlap with the compute that still reads the previous
use.

When to use it
--------------

Enable ``non_ssa_legalization`` with neuronx-cc allocation in the same
conditions as ``split_reused_buffers`` with NKI allocation: the profile shows
that the load into a reused tensor waits for the compute that reads the
previous use, and these waits are on the critical path.

Cost
----

Each clone has the full size of the original tensor. neuronx-cc allocation
decides where the clones go and how much SBUF they take together. When the
waits on the reused tensor were not the bottleneck, the option does not help.

.. _nki-compile-config-non-ssa-legalization-limits:

Limits
------

The compiler does not split a tensor when any of the following conditions is
true:

* The tensor is an input or output of the kernel, or the cores share it.
* The tensor has only one live range, or its reuse is not regular: the same
  write does not recur after a read of the tensor, as a write that loop
  iterations repeat would.
* A write to the tensor can leave some of the bytes that it addresses
  unchanged, such as a predicated copy or a DMA with a dynamic access pattern.
* The tensor is a PSUM tensor that a matrix multiplication accumulates into.
* The kernel accesses the tensor from more than one block of control flow, for
  example inside and outside a loop that stays rolled.

With ``allocation=Allocation.LINEAR``, NKI allocation has already placed every
tensor when the compiler splits them. Every clone keeps the address that NKI
allocation selected for the original tensor, so the option does not help.
The exception is when ``nki_alloc_fallback`` compiles the kernel again with
neuronx-cc allocation. With NKI allocation, use
:ref:`split_reused_buffers <nki-compile-config-split-reused-buffers>`
instead.

How to check it
---------------

Compare a profile with the option and a profile without it. With the option in
effect, the load into the reused tensor for the next iteration starts while
compute still reads the tensor of the current iteration.

.. _nki-compile-config-tensor-copy-elim:

tensor_copy_elim
================

``tensor_copy_elim`` removes an ``nisa.tensor_copy`` whose readers can read
the source of the copy directly. The readers then read the source, and the
compiler does not allocate the destination of the copy. For the conditions
that a copy must meet, see :ref:`nki-compile-config-tensor-copy-elim-how`.

:Default: ``None`` (off at ``O0`` and ``O1``)
:At ``OptLevel.O2``: On
:Acts with: NKI allocation

When to use it
--------------

Enable ``tensor_copy_elim`` when a profile shows ``tensor_copy`` instructions
that only move a tile that the next instruction could read in place, and the
engines that run those copies (Vector, Scalar or GpSimd) are busy. The option
matters most with NKI scheduling. Without NKI scheduling, a later removal
in compilation removes many of these copies (see
:ref:`nki-compile-config-copy-elim-later`).

Cost
----

* The source tensor stays allocated until its last reader, instead of until
  the copy. For a PSUM source, this holds its PSUM bank longer, which can
  leave less room for other PSUM tensors.
* A reader that read SBUF now reads PSUM, which can change how long the reader
  takes.

.. _nki-compile-config-tensor-copy-elim-limits:

Limits
------

* The allocation strategy, such as ``experimental_sbuf_allocation_mode``, does
  not change which copies the option removes, because the option runs before
  NKI allocation assigns any address.
* A copy that does not meet every condition in
  :ref:`nki-compile-config-tensor-copy-elim-how` stays, and the kernel
  compiles as written.

How to check it
---------------

Search the instruction timeline of Neuron Explorer for ``tensor_copy``
instructions in a profile with the option and in a profile without it. With
the option in effect, the removed copies are not on the Vector, Scalar or
GpSimd engine, and their readers start without waiting for them.

Example
-------

The following kernel multiplies two tiles into PSUM, copies the result to SBUF,
and applies ``exp``. The activation can read PSUM, so ``tensor_copy_elim``
removes the copy, and the activation reads ``product`` in PSUM directly. The
compiler does not allocate ``product_sbuf``.

.. nki_example:: ../examples/compile_config/tensor_copy_elim.py
   :language: python
   :marker: NKI_EXAMPLE_TENSOR_COPY_ELIM

.. _nki-compile-config-address-rotation:

address_rotation
================

``address_rotation`` lets the compiler move a tensor to a different SBUF
address or PSUM bank after allocation, so that a write no longer waits for a
read of a different tensor that shares its memory. It takes an
:class:`nki.compiler.AddressRotation`. For how rotation works, see
:ref:`nki-compile-config-address-rotation-how`.

:Default: ``AddressRotation.AUTO``
:At ``OptLevel.O2``: ``AUTO`` becomes ``ENABLE`` with NKI allocation
:Acts with: Every mode

.. list-table::
   :header-rows: 1
   :widths: 20 80

   * - Value
     - Tensors that the compiler can move
   * - ``AUTO`` (default)
     - Only the tensors that neuronx-cc allocation places. A tensor whose
       address is already fixed keeps it. Fixed tensors are tensors allocated
       with ``nl.ndarray(..., address=...)`` and, with
       ``allocation=Allocation.LINEAR``, every tensor that NKI allocation
       places.
   * - ``ENABLE``
     - Every tensor, including tensors whose address is fixed.
   * - ``DISABLE``
     - None.

When to use it
--------------

Keep ``AUTO`` unless a profile shows a reason to change it.

* Set ``ENABLE`` when the kernel uses NKI allocation and the profile shows a
  write that waits for a read of a different tensor that shares its memory.
  ``OptLevel.O2`` does this for you.
* Set ``DISABLE`` to keep every tensor where the kernel or the compiler placed
  it, for example to compare a profile with a profile without rotation.

Cost
----

Rotation uses no additional memory. When the waits that it removes are not on
the critical path, a change of the value does not make the kernel faster.

Limits
------

* Rotation does not separate the live ranges of one tensor that the kernel
  reloads in every iteration. Use ``split_reused_buffers`` or
  ``non_ssa_legalization`` for that case.
* With ``ENABLE``, a tensor placed with ``nl.ndarray(..., address=...)``
  might not be at that address in the compiled kernel.
* The compiler does not move a tensor allocated with
  ``nl.ndarray(..., prefetch=True)``, with any value of ``address_rotation``.
* With ``allocation=Allocation.LINEAR`` at ``OptLevel.O2``, ``AUTO`` and
  ``ENABLE`` compile the same kernel and share one cached compilation.

How to check it
---------------

Compare a profile with each value. Find the write that waited and the read of
the other tensor that it overlapped. Where rotation moved the tensor, the write
starts before that read ends.

.. _nki-compile-config-dma-copy-elim:

dma_copy_elim
=============

``dma_copy_elim`` removes an ``nisa.dma_copy`` that loads data that an earlier
``nisa.dma_copy`` already loaded into SBUF. Instructions that read the
destination of the removed ``dma_copy`` read the destination of the earlier
``dma_copy`` instead, so the data moves into SBUF only once. You do not need
to change the kernel. For the conditions that a load must meet, see
:ref:`nki-compile-config-copy-elim-how`.

:Default: ``None`` (off at ``O0`` and ``O1``)
:At ``OptLevel.O2``: On
:Acts with: NKI allocation

When to use it
--------------

Enable ``dma_copy_elim`` when the profile shows the same HBM data loaded into
SBUF more than once while the first copy is still in SBUF. The largest gains
are in DMA-bound kernels that reload a weight or activation tile for each use
instead of keeping it.

Cost
----

The earlier destination now stays in use until the last redirected read, so a
later write to its address waits for that read. When the kernel reuses that
address soon after, the removal of a load can add a wait elsewhere.

.. _nki-compile-config-dma-copy-elim-limits:

Limits
------

The compiler keeps a ``dma_copy`` when any of the following conditions is
true:

* Its source has a dynamic access pattern, such as an index computed at run
  time.
* Its destination is not in SBUF.
* It fills only part of its destination, such as ``dst=b[:, 0:256]``.
* It waits on another instruction or core, or another instruction waits on
  it, such as through ``depends_on``.
* It is inside a rolled loop, such as an ``nl.fori_loop`` without
  ``unroll=True``.
* A rolled loop or a runtime branch, such as ``nl.if_else``, runs between it
  and the earlier ``dma_copy``, or reads its destination.

NKI unrolls a Python ``for`` loop when it traces the kernel, so the compiler
checks the iterations of such a loop like straight-line code.

How to check it
---------------

Compare a profile with the option and a profile without it. With the option in
effect, the DMA rows of the instruction timeline show fewer loads of the same
HBM data.

Example
-------

The following kernel reads ``w`` in two stages, and each stage loads it into
its own tensor. With ``dma_copy_elim``, the compiler removes the second load,
and the second stage reads the tensor of the first stage. The second stage
writes its result into ``inv`` in place. If the second stage wrote a new
result tensor instead, that tensor could take the memory that ``a`` frees after
the first stage, and the second load would stay.

.. nki_example:: ../examples/compile_config/dma_copy_elim.py
   :language: python
   :marker: NKI_EXAMPLE_DMA_COPY_ELIM

.. _nki-compile-config-element-widening:

element_widening
================

``element_widening`` runs an ``nisa.tensor_copy`` or a zero ``nisa.memset`` of
1-byte or 2-byte elements on fewer, wider elements. The instruction moves the
same bytes, so the result is bit-exact, and it takes less time. You do not need
to change the kernel. For how the rewrite works, see
:ref:`nki-compile-config-element-widening-how`.

:Default: ``None`` (off at ``O0`` and ``O1``)
:At ``OptLevel.O2``: On
:Acts with: NKI allocation
:Cost: None known. The option does not change where tensors go, how much
       memory the kernel uses, or the results.

When to use it
--------------

Enable ``element_widening`` when the profile shows ``tensor_copy`` or
``memset`` instructions on 1-byte or 2-byte data types, such as ``bfloat16``,
``float16``, ``float8`` or ``int8``, that take a noticeable part of engine
time.

.. _nki-compile-config-element-widening-limits:

Limits
------

The compiler does not rewrite an instruction when any of the following
conditions is true:

* For a ``tensor_copy``: its source and destination data types are
  different, so it converts each element.
* For a ``memset``: its value is not zero. ``-0.0`` is not zero for this
  purpose, because its sign bit is set.
* Its elements are 4 bytes or wider, such as ``float32``.
* An access is not aligned to a wider element: its start or its size is not a
  multiple of twice the element size, such as ``dst=padded[:, 1:513]`` or
  ``dst=padded[:, 0:511]``.
* An access is strided in its innermost dimension, such as
  ``src=tile[:, ::2]``.
* An access is indirect or has an address known only at run time, such as an
  index computed at run time.

How to check it
---------------

Compare a profile with the option and a profile without it. With the option in
effect, the ``tensor_copy`` and ``memset`` instructions that the option
rewrites take less time.

Example
-------

The following kernel pads a ``float16`` tile with zero columns. With
``element_widening``, the ``memset`` that zeroes ``padded`` runs on 512 4-byte
elements per partition instead of 1024 2-byte elements. The ``tensor_copy``
into the left half of ``padded`` runs on 256 elements instead of 512.

.. nki_example:: ../examples/compile_config/element_widening.py
   :language: python
   :marker: NKI_EXAMPLE_ELEMENT_WIDENING

.. _nki-compile-config-engine-balancing:

engine_balancing
================

``engine_balancing`` lets NKI scheduling choose the engine of each instruction
that has no ``engine=`` and that more than one engine can run. For the
instructions that can move and how NKI scheduling chooses, see
:ref:`nki-compile-config-engine-balancing-how`.

:Default: ``None`` (off at ``O0`` and ``O1``)
:At ``OptLevel.O2``: On, with ``scheduling=True``
:Acts with: NKI scheduling (``allocation=Allocation.LINEAR`` and
            ``scheduling=True``)

When to use it
--------------

Enable ``engine_balancing`` when the kernel uses NKI scheduling and a profile
shows one engine, usually Vector, busy for most of the kernel. Another engine
that can run the same instructions must be idle, and those instructions must
have no ``engine=``. The option cannot help when the busy engine runs
instructions that cannot move, or when the kernel waits for DMAs. To move a
few known instructions, set ``engine=`` on them instead, which gives a
predictable result.

Cost
----

* Scheduling takes longer, more for kernels with many instructions that can
  move.
* The choice comes from an estimate of NKI scheduling, not from a measurement.
* Work moved to GpSimd can delay DMAs that use software DGE
  (``nisa.dge_mode.swdge``), because GpSimd generates their descriptors.

Limits
------

* ``OptLevel.O0`` keeps every instruction on its default engine, even with
  ``engine_balancing=True``.
* On an LNC=2 kernel, inside an ``nl.no_reorder`` block, both cores use the
  engine choice of the first core.

How to check it
---------------

Compare a profile with the option and a profile without it. With the option in
effect, some instructions that ran on the busy engine run on another engine,
at the same time as the instructions that remain.

Example
-------

The following kernel multiplies one tile by four constants with independent
``nisa.tensor_scalar`` instructions. Without ``engine_balancing``, all four
instructions run on Vector, one after the other. With ``engine_balancing``,
NKI scheduling moves some of them to another engine, such as Scalar, so they
run at the same time.

.. nki_example:: ../examples/compile_config/engine_balancing.py
   :language: python
   :marker: NKI_EXAMPLE_ENGINE_BALANCING

.. _nki-compile-config-register-load-reuse:

register_load_reuse
===================

``register_load_reuse`` lets instructions that take the same runtime index
from the same SBUF tensor share one register load of that index, instead of
each instruction loading it again. For how the reuse works, see
:ref:`nki-compile-config-register-load-reuse-how`.

:Default: ``True``
:At ``OptLevel.O2``: Not changed. The option is on at every level.
:Acts with: NKI scheduling (``allocation=Allocation.LINEAR`` and
            ``scheduling=True``)

When to use it
--------------

Keep the default. Set ``register_load_reuse=False`` when the kernel fails to
compile because too many registers are live at the same time, or to measure
what the reuse saves. To control the register yourself, load the index once
with :func:`nki.isa.scalar_load` and pass the scalar as the offset.

Cost
----

A reused register stays live from its load to the last instruction that reads
it, on every engine that the load runs on. The compiler keeps at most four
loads available for reuse at a time. The option uses no SBUF or PSUM.

.. _nki-compile-config-register-load-reuse-limits:

Limits
------

An instruction loads the index into its own register, as without the option,
when any of the following conditions is true:

* No earlier load reads the same element of the same tensor, or the compiler
  dropped that load at the limit of four loads.
* An instruction between the two can write or free the index tensor, or any
  other tensor that a load still available for reuse reads. A write to a
  kernel input or output, or to a tensor at an explicit ``address``, also ends
  the reuse. Keep stores to the outputs after the instructions that share an
  index.
* The two instructions are at different loop levels, or a rolled loop (such as
  ``nl.fori_loop`` without ``unroll=True``) or an ``nl.if_else`` is between
  them. NKI unrolls a Python ``for`` loop when it traces the kernel, so its
  iterations are at one level.

How to check it
---------------

Compare the register loads of the kernel in a profile with the default and a
profile with ``register_load_reuse=False``. With the reuse in effect, the
instructions that share an index share one register load.

Example
-------

The following kernel applies ``exp`` to the table entry at a runtime index in
four column blocks. The kernel stores the result only after the last
activation, so the four activations share one register load of ``index``.
With ``register_load_reuse=False``, the kernel loads ``index`` into a register
four times, once for each activation.

.. nki_example:: ../examples/compile_config/register_load_reuse.py
   :language: python
   :marker: NKI_EXAMPLE_REGISTER_LOAD_REUSE

.. _nki-compile-config-dead-code-elim:

dead_code_elim, remove_unused_instructions and remove_overwritten_writes
========================================================================

Three options control the removal of instructions whose results the kernel
does not use:

.. list-table::
   :header-rows: 1
   :widths: 30 20 50

   * - Option
     - Acts with
     - Effect
   * - ``dead_code_elim``
     - Every mode
     - ``True`` (the default) lets the compiler remove, later in compilation,
       an instruction whose output no instruction reads, and an
       ``nisa.tensor_copy`` whose readers can read the source directly.
       ``False`` keeps these instructions.
   * - ``remove_unused_instructions``
     - NKI allocation
     - Before NKI allocation, removes an instruction whose output no other
       instruction reads. The instruction then takes no engine time, and its
       tensor takes no memory.
   * - ``remove_overwritten_writes``
     - NKI allocation
     - Before NKI allocation, removes a write that a later write fully
       replaces before any instruction reads it, and a write that no
       instruction reads before the kernel ends.

``dead_code_elim`` does not affect the two options that act before NKI
allocation. ``remove_unused_instructions`` and ``remove_overwritten_writes``
default to ``None``, which follows the level: off at ``OptLevel.O0`` and
``OptLevel.O1``, on at ``OptLevel.O2``. ``True`` turns an option on, and
``False`` keeps it off, even at ``OptLevel.O2``.

``tensor_copy_elim`` is a different removal of copies (see
:ref:`nki-compile-config-copy-elim-later`). ``dead_code_elim=False`` does not
keep a copy that ``tensor_copy_elim`` removes.

When to use it
--------------

Keep an instruction whose result the kernel does not use, for example a copy
that moves data out of PSUM early so that a PSUM bank becomes free sooner, or
a section of the kernel that you time on its own:

* With neuronx-cc allocation, set ``dead_code_elim=False``.
* With NKI allocation, also set ``remove_unused_instructions=False`` and
  ``remove_overwritten_writes=False``. You need both, because
  ``remove_overwritten_writes`` also removes a write that no instruction
  reads.

Cost
----

Every instruction that the compiler keeps takes engine time, and every tensor
that it writes takes memory.

Limits
------

* The compiler always keeps writes to kernel outputs. With NKI allocation, it
  also keeps writes to kernel arguments and to ``nl.shared_hbm`` tensors, and
  collective operations.
* ``remove_overwritten_writes`` has no effect on a kernel with ``nl.if_else``,
  ``nl.while_loop``, or an ``nl.fori_loop`` that is not fully unrolled.
* An accumulating write, such as a matmul into PSUM that adds to the earlier
  value, is not an overwrite.

A removed instruction does not appear in the profile.

Example
-------

In the following kernel, no instruction reads ``unused``. At ``OptLevel.O2``,
NKI allocation removes the ``reciprocal`` and the tensor, so the compiled
kernel has only the two DMA copies. With
``remove_unused_instructions=False``, ``remove_overwritten_writes=False`` and
``dead_code_elim=False`` added to the ``CompileConfig``, the compiled kernel
keeps the ``reciprocal``.

.. nki_example:: ../examples/compile_config/dead_code_elim.py
   :language: python
   :marker: NKI_EXAMPLE_DEAD_CODE_ELIM

.. _nki-compile-config-nki-alloc-fallback:

nki_alloc_fallback
==================

``nki_alloc_fallback`` compiles a kernel with neuronx-cc allocation when NKI
allocation runs out of memory.

:Default: ``False``
:At ``OptLevel.O2``: Not changed
:Acts with: NKI allocation

With ``nki_alloc_fallback=True``, when NKI allocation runs out of SBUF, PSUM
or HBM, the compiler compiles the kernel again with neuronx-cc allocation
instead of raising the out-of-memory error, and a warning names the failure.
The prefetch region error (see
:ref:`nki-compile-config-prefetch-auto-ring-size`) also triggers the fallback.
Allocation failures that are not a memory shortage always raise an error.

When to use it
--------------

Turn on ``nki_alloc_fallback`` when a kernel must compile even if NKI
allocation cannot place it, for example in a model that compiles many
kernels. We recommend that you change the kernel to fit instead (see
:ref:`nki-compile-config-out-of-memory`), because the fallback gives up NKI
allocation for that kernel.

Cost
----

After the fallback, the kernel uses neuronx-cc allocation and scheduling, and
the options that need NKI allocation have no effect for it (see
:ref:`nki-compile-config-nki-flow-options`). Its performance can be different
from its performance with NKI allocation.

How to check it
---------------

The fallback emits a warning that starts with ``Kernel '<name>': NKI memory
allocation ran out of memory``. In this warning, "NKI allocation" is NKI
allocation, "neuronx-cc allocation" is neuronx-cc allocation, and an
"NKI-allocated build" is a compilation with NKI allocation.

.. _nki-compile-config-sbuf-allocation-fallback:

sbuf_allocation_fallback
========================

``sbuf_allocation_fallback`` lets NKI allocation try a more compact strategy
when the requested strategy runs out of memory. Without the option, a kernel
keeps the strategy that it requested, and the out-of-memory error names the
strategies to try (see :ref:`nki-compile-config-out-of-memory`).

:Default: ``False``
:At ``OptLevel.O2``: Not changed
:Acts with: NKI allocation

The SBUF strategy is ``experimental_sbuf_allocation_mode`` when it is set, and
``experimental_allocation_mode`` otherwise. The default is
``AllocationMode.RING``. With ``sbuf_allocation_fallback=True``, when the
strategy runs out of SBUF, NKI allocation tries the next strategy and uses the
first one that fits:

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

   * - Requested strategy
     - Strategies tried, in order
   * - ``RING``
     - ``FAST``, then ``MAX_REUSE``
   * - ``FAST``
     - ``MAX_REUSE``
   * - ``MAX_REUSE``
     - None

An HBM shortage causes one more attempt, under ``MAX_REUSE``. NKI allocation
does not retry a PSUM shortage. If every attempt fails, the out-of-memory
error occurs as without the option. With ``prefetch_auto`` and no
``NKI_PREFETCH_RING_SIZE``, as at ``OptLevel.O2``, the SBUF retries place SBUF
tensors the same way (see :ref:`nki-compile-config-prefetch-strategy`).

When to use it
--------------

Turn on ``sbuf_allocation_fallback`` when a kernel runs out of memory under
its requested strategy, and you prefer a compiled kernel with less overlap of
loads and compute to an error. To keep control of the strategy, set
``experimental_sbuf_allocation_mode`` yourself instead.

Cost
----

A kernel that fits only after a retry can be slower than under ``RING`` (see
:ref:`nki-compile-config-sbuf-strategies`), and each retry adds compile time.

How to check it
---------------

When you compile through :func:`nki.jit`, the compiler does not report a
retry. Compile the kernel without the option. If compilation fails with an
out-of-memory error, the kernel fits only with a more compact strategy.

Example
-------

In the following kernel, the kernel frees ``a`` before it allocates ``d`` and
``e``, and ``b`` stays live until the end. ``RING`` places ``d`` after ``b``
instead of in the memory of ``a``. No free part of SBUF is then large enough
for ``e``, although the three live tensors fit in SBUF together. ``FAST``
places ``d`` in the memory of ``a``, and ``e`` fits. With its configuration,
the kernel fails to compile with an SBUF out-of-memory error. With
``sbuf_allocation_fallback=True``, NKI allocation tries ``FAST``, and the
kernel compiles. The widths are for trn2. On a target with more SBUF, scale
them to its SBUF size.

.. nki_example:: ../examples/compile_config/sbuf_allocation_fallback.py
   :language: python
   :marker: NKI_EXAMPLE_SBUF_ALLOCATION_FALLBACK

.. _nki-compile-config-experimental:

Experimental options
====================

The options in this section are experimental. Their names, values, defaults
and behavior can change in a future release. Use them to investigate a kernel,
and do not depend on them in production code. They act only with NKI
allocation (see :ref:`nki-compile-config-nki-flow-options`).

Allocation strategy options
---------------------------

These options select the allocation strategy of NKI allocation, an
:class:`~nki.compiler.AllocationMode`. For what each strategy does, see
:ref:`nki-compile-config-sbuf-strategies`.

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

   * - Option
     - Effect
   * - ``experimental_allocation_mode``
     - The strategy for SBUF, HBM and PSUM together. Default ``None``,
       which is ``RING``.
   * - ``experimental_sbuf_allocation_mode``
     - The strategy for SBUF. Overrides ``experimental_allocation_mode``
       for SBUF.
   * - ``experimental_hbm_allocation_mode``
     - The strategy for HBM. Overrides ``experimental_allocation_mode`` for
       HBM.
   * - ``experimental_psum_allocation_mode``
     - The strategy for PSUM. Overrides ``experimental_allocation_mode``
       for PSUM.

With ``prefetch_auto`` and no ``NKI_PREFETCH_RING_SIZE``, as at
``OptLevel.O2``, the SBUF strategy does not apply (see
:ref:`nki-compile-config-prefetch-strategy`).

.. _nki-compile-config-scheduling-heuristic:

experimental_scheduling_heuristic
---------------------------------

``experimental_scheduling_heuristic`` selects how NKI scheduling chooses the
next instruction from the instructions that are ready, a
:class:`~nki.compiler.SchedulingHeuristic`.

:Default: ``None`` (``ASAP``)
:Acts with: NKI scheduling (``allocation=Allocation.LINEAR`` and
            ``scheduling=True``)

.. list-table::
   :header-rows: 1
   :widths: 25 75

   * - Value
     - Next instruction
   * - ``ASAP`` (default, ``None``)
     - The instruction that can start first.
   * - ``CRITICAL_PATH``
     - The instruction on the longest path to the outputs of the kernel.
   * - ``DMA_PREFETCH``
     - A DMA before an instruction that is not a DMA.
   * - ``TRIVIAL``
     - The program order of the kernel.

``ASAP`` suits most kernels. Another value can make a kernel slower, so
compare the runtime with and without it.

Related reference
=================

* :class:`nki.compiler.CompileConfig`: the API reference.
* :ref:`Troubleshooting NKI compile configuration <nki-compile-config-tshoot>`:
  the errors that these options raise, and what to do.

Learn more
==========

* :ref:`Deep dive: NKI compile configuration <nki-compile-config>`: how NKI
  allocation and scheduling work, and how each optimization changes the
  kernel.
* :ref:`How to tune a NKI kernel with CompileConfig <nki-compile-config-tuning-how-to>`:
  the steps to select options for a kernel.
