This document is relevant for: Trn2, Trn3
NKI Control Flow#
This document explains NKI control flow: specialization-time Python loops, compiled loops, and the compiled conditional.
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 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_loopwithunroll=Trueis 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:
Construct |
Behavior |
When to Use |
|---|---|---|
Python |
Unrolled at specialization time |
Small iteration count known at specialization time |
Python |
Unrolled at specialization time |
Small iteration count, with a condition known at specialization time |
Compiled loop. With the default |
Large iteration count, or iteration count unknown at specialization time |
|
|
Traced once, unrolled by the compiler |
Iteration count known at compile time, when tracing every iteration would be slow |
Compiled loop |
Stopping condition known only within the loop, or unknown at specialization time |
|
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:
# 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:
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.
# 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:
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:
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
intor a signed 32-bit (nl.int32)NkiScalarthat is available on all engines. A value loaded withnisa.scalar_load(..., engine=...)is rejected. See NKI Scalar Values.The loop variable is a
NkiScalar, not a Pythonint, so it can only be used where aNkiScalaris accepted, such asscalar_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
VirtualRegisterbounds, migrate them toNkiScalar.
See nki.language.fori_loop() for the full parameter reference.
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.
@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. 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 Scheduling with Compiled Loops.
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.
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_funmust return the next condition.If existing code uses a deprecated
VirtualRegistercondition, migrate it toNkiScalar.
See 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 nki.language.if_else().
Constraints#
A Python
boolorintcondition is resolved at specialization time: only the selected callback is traced, and no branch is emitted.A
NkiScalarcondition must be 32-bit and available on all engines. Unlike a loop bound, annl.uint32condition is accepted.To pass results out of a callback, write to SBUF or HBM tensors.
See 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 nki.language.no_reorder() blocks are not supported, and fail to compile. nki.simulate() does not check this.
# 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:
# 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)
Scheduling with Compiled Loops#
You can reorder instructions with schedule_after() and 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 nki.isa.instruction() with iterations= selects one iteration’s instructions. See How to Use the NKI 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 nki.language.affine_range(),
nki.language.sequential_range(), and 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.
Parser loop |
Tracer equivalent |
Behavior |
|---|---|---|
Python |
Python |
Unrolled at specialization time |
Python |
Python |
Unrolled at specialization time |
Python |
Compiled loop |
For more migration guidance, see Migrating from NKI 0.6.0 to NKI 0.7.0.
This document is relevant for: Trn2, Trn3