This document is relevant for: Trn2, Trn3

nki.language.while_loop#

nki.language.while_loop(init, body_fun)[source]#

Structured while loop with a register condition.

Loops while the condition register is nonzero, checking the condition before each iteration (a true while, not do-while: if init is zero the body never runs).

The loop is roughly equivalent to the following Python code:

r = init
while r != 0:
    r = body_fun(r)

init may be a compile-time int or an nl.int32 NkiScalar, including a value from nki.isa.scalar_load() or a scalar comparison. The body receives the current condition, r, as a NkiScalar, and returns the next condition, as in return r - 1 or return r > 1. The loop updates its own condition value; init retains its original value. Carry any other loop state through SBUF/HBM.

Both the initial and returned conditions must be signed 32-bit values and available on all engines. nl.uint32, 64-bit scalars and Python bool values are rejected. To use an unsigned value, compare it with zero (value != 0) to produce an nl.int32 condition. A 64-bit scalar can still be computed inside the body and used as an offset there.

Parameters:
  • init – Initial condition, an int or a NkiScalar.

  • body_fun – function (r) -> r called each iteration with the current condition value; returns the next condition, a NkiScalar or an int.

Returns:

None. Side effects in body_fun persist after the loop.

Examples:

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

# nki.language.while_loop -- count down a trip count read at run time
val = nl.ndarray((1, 1), dtype=nl.float32, buffer=nl.sbuf)
nisa.dma_copy(dst=val, src=data)
acc = nl.zeros((1, 1), dtype=nl.float32, buffer=nl.sbuf)

count_sb = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.sbuf)
nisa.dma_copy(dst=count_sb, src=count_input)
count = nisa.scalar_load(count_sb)

def body(r):
    nisa.tensor_tensor(dst=acc, data1=acc, data2=val, op=nl.add)
    return r - 1

nl.while_loop(count, body)

This document is relevant for: Trn2, Trn3