.. meta::
   :description: Deep dive into NKI control flow with specialization-time or run-time bounds, and conditionals on AWS Neuron hardware.
   :keywords: NKI, loop, fori_loop, while_loop, if_else, compiled loop, compiled conditional, hardware loop, unroll, runtime bounds, NkiScalar, AWS Neuron, Trainium
   :date-modified: 11/13/2026

.. _nki-control-flow:

================
NKI Control Flow
================

This document explains NKI control flow: specialization-time Python loops, compiled loops, and the compiled conditional.

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

Choosing Control Flow
---------------------

Choosing the appropriate construct depends on when its loop bounds or condition become known: during specialization, at compile time, or only at run time. Recall that a NKI kernel goes through two stages before it runs on the device (see :ref:`nki-language-guide`):

* **Specialization**: NKI runs the kernel as Python, tracing and recording the ``nki.isa.*`` operations it calls. Python loops and conditionals are fully resolved during this stage.
* **Compilation**: The compiler lowers the recorded operations to machine code. A ``nki.language.fori_loop`` with ``unroll=True`` is unrolled during this stage.

Python ``for`` and ``while`` loops are unrolled during specialization, so their bounds and conditions must be Python values. A ``nki.language.fori_loop`` with ``unroll=True`` is traced once during specialization and unrolled during compilation, so its bounds must be known at compile time and it does not run as a loop on the device. The compiled loops ``nki.language.fori_loop`` and ``nki.language.while_loop`` and the compiled conditional ``nki.language.if_else`` run on the device, so their bounds or condition can be values known only at run time. The table below summarizes when each construct is resolved and when to use it:

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

   * - Construct
     - Behavior
     - When to Use
   * - Python ``for`` loops
     - Unrolled at specialization time
     - Small iteration count known at specialization time
   * - Python ``while`` loops
     - Unrolled at specialization time
     - Small iteration count, with a condition known at specialization time
   * - :func:`nki.language.fori_loop`
     - Compiled loop. With the default ``unroll=None``, the compiler decides whether to unroll it. ``unroll=False`` always keeps it rolled
     - Large iteration count, or iteration count unknown at specialization time
   * - :func:`nki.language.fori_loop` with ``unroll=True``
     - Traced once, unrolled by the compiler
     - Iteration count known at compile time, when tracing every iteration would be slow
   * - :func:`nki.language.while_loop`
     - Compiled loop
     - Stopping condition known only within the loop, or unknown at specialization time
   * - :func:`nki.language.if_else`
     - Compiled conditional
     - Run code only when a condition known at run time holds


Unrolled Loops
--------------

During specialization, Python ``for`` and ``while`` loops are fully unrolled, turning the loop bodies into straight-line code. Loop unrolling is a transformation technique designed to improve performance at the cost of code size. Unrolling loops helps the compiler eliminate redundant instructions, reducing overhead.

Consider an example using Python loops that print the values from 0 to 4:

.. code-block:: python

   # First loop, traditional Python for loop.
   for i in range(3):
       print(i)

   # Second loop, traditional Python while loop.
   j = 3
   while j < 5:
       print(j)
       j += 1


After specialization, the loops unroll to the following Python code:

.. code-block:: python

   print(0)
   print(1)
   print(2)
   print(3)
   print(4)


Implications of Loop Unrolling
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Although loop unrolling can reduce overhead by converting loop bodies into straight-line code, loops over a large number of iterations can greatly increase compile time --- each iteration inlines a copy of the loop body, which NKI must trace. For loops with many iterations, consider using compiled loops ``nki.language.fori_loop`` or ``nki.language.while_loop`` instead.

.. code-block:: python

   # Loop over a very large number of iterations.
   for i in range(1_000_000):
      nisa.tensor_scalar(dst=acc, data=acc, op0=nl.add, operand0=1.0)


Loop unrolling can also generate many instructions, which leads to larger NEFFs that take longer to load. For example, after specialization, the loop above unrolls into 1 million instructions in the NEFF:

.. code-block:: python

   nisa.tensor_scalar(dst=acc, data=acc, op0=nl.add, operand0=1.0)
   nisa.tensor_scalar(dst=acc, data=acc, op0=nl.add, operand0=1.0)
   # ... many nisa.tensor_scalar instructions
   nisa.tensor_scalar(dst=acc, data=acc, op0=nl.add, operand0=1.0)
   nisa.tensor_scalar(dst=acc, data=acc, op0=nl.add, operand0=1.0)


As a rule of thumb, use Python loops for small iteration counts, where straight-line code helps performance, and compiled loops for large or unknown iteration counts, where unrolling increases compile time and NEFF size.


Compiled Loops
--------------

The body of a compiled loop is traced once, during specialization, into a NKI IR loop. The compiler lowers the NKI IR loop to NeuronISA. NKI offers two types of compiled loops: ``nki.language.fori_loop`` and ``nki.language.while_loop``.


Using nki.language.fori_loop
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

``nki.language.fori_loop(lower, upper, body_fun, step=1, unroll=None)`` runs a counted loop, similar to ``for i in range(lower, upper, step)``. Instead of a loop body, you pass a function, ``body_fun``, that takes the loop variable ``i`` and returns nothing. NKI traces ``body_fun`` once. The following example uses ``nki.language.fori_loop``:

.. code-block:: python

   import numpy as np

   import nki
   import nki.isa as nisa
   import nki.language as nl


   @nki.jit
   def sum_rows_fori(data, count):
       ROWS, COLS = data.shape

       # Read the run-time row count into a scalar to use as the loop bound.
       count_sb = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.sbuf)
       nisa.dma_copy(dst=count_sb, src=count)
       n = nisa.scalar_load(count_sb)

       total = nl.zeros((1, COLS), dtype=nl.float32, buffer=nl.sbuf)
       row = nl.ndarray((1, COLS), dtype=nl.float32, buffer=nl.sbuf)

       def body(i):
           # The loop variable selects row i of data at run time.
           nisa.dma_copy(
               dst=row,
               src=data.ap([[COLS, 1], [1, COLS]], scalar_offset=i, indirect_dim=0),
           )
           nisa.tensor_tensor(dst=total, data1=total, data2=row, op=nl.add)

       nl.fori_loop(0, n, body)

       out = nl.ndarray((1, COLS), dtype=nl.float32, buffer=nl.shared_hbm)
       nisa.dma_copy(dst=out, src=total)
       return out


   data = np.arange(32, dtype=np.float32).reshape(4, 8)
   count = np.array([[3]], dtype=np.int32)
   sum_rows_fori(data, count)
   # [[24. 27. 30. 33. 36. 39. 42. 45.]]

Constraints
~~~~~~~~~~~

* A bound is a Python ``int`` or a signed 32-bit (``nl.int32``) ``NkiScalar`` that is available on all engines. A value loaded with ``nisa.scalar_load(..., engine=...)`` is rejected. See :ref:`nki-scalar`.
* The loop variable is a ``NkiScalar``, not a Python ``int``, so it can only be used where a ``NkiScalar`` is accepted, such as ``scalar_offset``.
* Writing to the loop variable doesn't change the loop. To keep state across iterations, use SBUF or HBM tensors.
* If existing code uses deprecated ``VirtualRegister`` bounds, migrate them to ``NkiScalar``.

See :func:`nki.language.fori_loop` for the full parameter reference.


.. _nki-control-flow-unroll:

Unrolling nki.language.fori_loop
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

With ``unroll=True``, NKI traces ``body_fun`` only once, as it does for a rolled loop, and the compiler then replicates the body once per iteration. The result is not a compiled loop: as with a Python ``for`` loop, the NEFF has no loop, but tracing does not repeat for each iteration.

.. code-block:: python

   @nki.jit
   def sum_rows_unrolled(data):
       ROWS, COLS = data.shape
       total = nl.zeros((1, COLS), dtype=nl.float32, buffer=nl.sbuf)
       row = nl.ndarray((1, COLS), dtype=nl.float32, buffer=nl.sbuf)

       def body(i):
           nisa.dma_copy(
               dst=row,
               src=data.ap([[COLS, 1], [1, COLS]], scalar_offset=i, indirect_dim=0),
           )
           nisa.tensor_tensor(dst=total, data1=total, data2=row, op=nl.add)

       # ROWS is a Python int, so the loop can be fully unrolled.
       nl.fori_loop(0, ROWS, body, unroll=True)

       out = nl.ndarray((1, COLS), dtype=nl.float32, buffer=nl.shared_hbm)
       nisa.dma_copy(dst=out, src=total)
       return out

Both bounds must be known at compile time. A loop whose trip count is known only at run time fails to compile with ``fori_loop unroll=True requires compile-time loop bounds``. :func:`nki.simulate` does not check this.

As with any ``nki.language.fori_loop``, the loop variable is a ``NkiScalar``, even when the loop is unrolled. Use a Python ``for`` loop when the body needs ``i`` as an ``int``.

To schedule the instructions of one iteration, see :ref:`nki-control-flow-scheduling`.


Using nki.language.while_loop
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

``nki.language.while_loop(init, body_fun)`` runs while a condition is not zero,
similar to ``while r != 0``. NKI checks the condition before each iteration.
If ``init`` is zero, the body does not run. The body receives the current
condition as a value and returns the condition for the next iteration.

.. code-block:: python

   count = nisa.scalar_load(count_tile)

   def body(remaining):
       # Perform one iteration of work.
       return remaining - 1

   nl.while_loop(count, body)

The loop updates its own condition value. ``count`` keeps its original value
and can be reused after the loop. Carry other loop state through SBUF or HBM.


Constraints
~~~~~~~~~~~

* The initial and returned conditions must be signed 32-bit and available on all engines.
* ``body_fun`` must return the next condition.
* If existing code uses a deprecated ``VirtualRegister`` condition, migrate it to ``NkiScalar``.

See :func:`nki.language.while_loop` for the full parameter reference.



Compiled Conditionals
---------------------

``nki.language.if_else(cond, then_fn, else_fn=None)`` runs ``then_fn`` when ``cond`` is nonzero, and otherwise runs ``else_fn`` if one is given. Any nonzero value, including a negative one, selects ``then_fn``. Both callbacks take no arguments and return ``None``. NKI traces each callback once, and the compiler emits a branch that is resolved at run time.

For a complete kernel that adds 10 when a flag is positive and otherwise subtracts 1, see the example in :func:`nki.language.if_else`.

Constraints
^^^^^^^^^^^

* A Python ``bool`` or ``int`` condition is resolved at specialization time: only the selected callback is traced, and no branch is emitted.
* A ``NkiScalar`` condition must be 32-bit and available on all engines. Unlike a loop bound, an ``nl.uint32`` condition is accepted.
* To pass results out of a callback, write to SBUF or HBM tensors.

See :func:`nki.language.if_else` for the full parameter reference.


Interaction with ``no_reorder``
-------------------------------

Compiled loops (``nki.language.fori_loop``, ``nki.language.while_loop``) and compiled conditionals (``nki.language.if_else``) inside :func:`nki.language.no_reorder` blocks are not supported, and fail to compile. :func:`nki.simulate` does not check this.

.. code-block:: python

   # Not supported: nl.fori_loop inside nl.no_reorder
   with nl.no_reorder():
       nl.fori_loop(0, n, body)

   # Not supported: nl.while_loop inside nl.no_reorder
   with nl.no_reorder():
       nl.while_loop(cond, body)

   # Not supported: nl.if_else inside nl.no_reorder
   with nl.no_reorder():
       nl.if_else(cond, then_fn)

A Python loop, or an ``nl.fori_loop`` with ``unroll=True``, can be used inside ``no_reorder``:

.. code-block:: python

   # Supported: a Python loop is unrolled at specialization time
   with nl.no_reorder():
       for i in range(4):
           body(i)

   # Supported: a fully unrolled nl.fori_loop has no loop left to compile
   with nl.no_reorder():
       nl.fori_loop(0, 4, body, unroll=True)


.. _nki-control-flow-scheduling:

Scheduling with Compiled Loops
------------------------------

You can reorder instructions with :meth:`~nki.isa.NkiInstruction.schedule_after` and :meth:`~nki.isa.NkiInstruction.schedule_before`, but only within one block. The body of a rolled compiled loop and each branch of a compiled conditional are separate blocks, so you can't move an instruction into or out of them. You also can't move an instruction past a rolled compiled loop or a compiled conditional, even when both instructions are outside it.

A rolled loop has a single copy of its body, which runs once per iteration. You can schedule instructions within that body using a fixed name or an instruction handle, but you can't select one particular iteration. With ``unroll=True``, each iteration has its own copy of the body, so :func:`nki.isa.instruction` with ``iterations=`` selects one iteration's instructions. See :ref:`how-to-scheduling-apis`.


Migrating from Parser Loops
---------------------------

The parser frontend has been removed. Migrate its loop constructs to the
tracing APIs described above.

The static range iterators :func:`nki.language.affine_range`,
:func:`nki.language.sequential_range`, and :func:`nki.language.static_range`
are deprecated and behave like Python ``range`` in the tracer. The tracer
does not support Python ``while`` loops with a ``VirtualRegister`` condition.

.. list-table::
   :header-rows: 1
   :widths: 45 30 25

   * - Parser loop
     - Tracer equivalent
     - Behavior
   * - Python ``for`` over :func:`nki.language.affine_range`,
       :func:`nki.language.sequential_range`, or :func:`nki.language.static_range`
     - Python ``for`` over ``range``
     - Unrolled at specialization time
   * - Python ``while`` with a specialization-time condition
     - Python ``while`` (unchanged)
     - Unrolled at specialization time
   * - Python ``while`` with a ``VirtualRegister`` condition
     - :func:`nki.language.while_loop`
     - Compiled loop

For more migration guidance, see :ref:`nki-migrate-0-6-to-0-7`.
