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, notdo-while: ifinitis zero the body never runs).The loop is roughly equivalent to the following Python code:
r = init while r != 0: r = body_fun(r)
initmay be a compile-timeintor annl.int32NkiScalar, including a value fromnki.isa.scalar_load()or a scalar comparison. The body receives the current condition,r, as aNkiScalar, and returns the next condition, as inreturn r - 1orreturn r > 1. The loop updates its own condition value;initretains 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 Pythonboolvalues are rejected. To use an unsigned value, compare it with zero (value != 0) to produce annl.int32condition. A 64-bit scalar can still be computed inside the body and used as an offset there.- Parameters:
init – Initial condition, an
intor aNkiScalar.body_fun – function
(r) -> rcalled each iteration with the current condition value; returns the next condition, aNkiScalaror anint.
- Returns:
None. Side effects in
body_funpersist 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