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() when cond is nonzero, otherwise else_fn() if provided. Scalar comparisons such as a < b can 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 bool or int condition is resolved at compile time. Only the selected callback is called, and no conditional control flow is emitted.

Parameters:
  • cond – A Python bool or int, or a 32-bit NkiScalar. 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 () -> None executed when cond is nonzero.

  • else_fn – Optional function () -> None executed when cond is 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