This document is relevant for: Trn2, Trn3
nki.language.if_else#
- nki.language.if_else(cond, then_fn, else_fn=None)[source]#
Run one callback according to a scalar condition.
Runs
then_fn()whencondis nonzero, otherwiseelse_fn()if provided. Scalar comparisons such asa < bcan be passed directly. Any nonzero value, including a negative value, selects then_fn. The callbacks take no arguments and do not return anything.A Python
boolorintcondition is resolved at compile time. Only the selected callback is called, and no conditional control flow is emitted.- Parameters:
cond – A Python
boolorint, or a 32-bitNkiScalar. Arithmetic expressions and scalar comparison results are accepted. It must be available on all engines: every sequencer runs the branch, so a value bound to one sequencer is rejected.then_fn – Function
() -> Noneexecuted whencondis nonzero.else_fn – Optional function
() -> Noneexecuted whencondis zero.
- Returns:
None.
Examples:
import nki import nki.isa as nisa import nki.language as nl @nki.jit def if_else_kernel(flag, data): flag_sb = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.sbuf) nisa.dma_copy(dst=flag_sb, src=flag) condition = nisa.scalar_load(flag_sb) > 0 result = nl.ndarray(data.shape, dtype=data.dtype, buffer=nl.sbuf) nisa.dma_copy(dst=result, src=data) def then_branch(): nisa.tensor_scalar(result, result, op0=nl.add, operand0=10.0) def else_branch(): nisa.tensor_scalar(result, result, op0=nl.add, operand0=-1.0) nl.if_else(condition, then_branch, else_branch) out = nl.ndarray(data.shape, dtype=data.dtype, buffer=nl.shared_hbm) nisa.dma_copy(dst=out, src=result) return out
This document is relevant for: Trn2, Trn3