This document is relevant for: Trn2, Trn3

nki.isa.scalar_alu#

nki.isa.scalar_alu(data1: nki.isa.NkiScalar | int, data2: nki.isa.NkiScalar | int, op, name=None)[source]#

Apply a binary integer operation to two scalar values.

Each operand is a NkiScalar or a Python int. Arithmetic preserves the scalar’s dtype. When both operands are Python ints, the operation is evaluated at compile time and returns a Python int for arithmetic or bool for a comparison, without emitting an instruction.

Overloaded Python operators on NkiScalars are equivalent to this API and are preferred when available. For example, a + b is equivalent to nisa.scalar_alu(a, b, op=nl.add).

Supported arithmetic operations are nl.add, nl.subtract, nl.multiply, nl.divide, nl.fmod, nl.maximum and nl.minimum. nl.divide performs integer division rounded toward zero; nl.fmod returns the remainder with the sign of data1. For example, dividing -17 by 4 gives -4, with remainder -1.

Comparison operations are nl.less, nl.less_equal, nl.greater, nl.greater_equal, nl.equal and nl.not_equal. A comparison involving a NkiScalar returns a nl.int32 NkiScalar containing 1 when true or 0 when false. The result supports scalar arithmetic, stores, loop bounds and access pattern offsets. It cannot be used as a Python if or while condition.

Data types.

Scalars must have the same width and signedness. nl.int32 and nl.uint32 support every operation; nl.int64 supports only add, subtract and multiply. A Python int combined with a NkiScalar must fit the scalar’s dtype. Add, subtract and multiply wrap at the scalar’s width; arithmetic on two Python ints is unbounded.

Constraints.

Tensor operands are not supported. Division and remainder require a nonzero divisor; signed division overflow is unsupported for NkiScalar operands. Operands are evaluated in the order data1 op data2. This API is available with the tracer frontend and nki.simulate().

Engines.

The result is bound to the sequencer an operand is bound to, if any (see NkiScalar). Operands bound to two different sequencers are an error.

Parameters:
  • data1 – Left operand, a NkiScalar or Python int.

  • data2 – Right operand, a NkiScalar or Python int.

  • op – One of the supported nki.language binary operations.

  • name – Optional instruction name. Ignored when both operands are Python ints.

Returns:

A new NkiScalar, or a Python int or bool when both operands are ints.

Examples:

value = nisa.scalar_load(buf, engine=nisa.engine.sync)
# Prefer overloaded Python operators when available.
incremented = value + 1
scaled = incremented * 3
# Equivalent explicit ISA calls:
# incremented = nisa.scalar_alu(value, 1, op=nl.add)
# scaled = nisa.scalar_alu(incremented, 3, op=nl.multiply)
out_buf = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.sbuf)
# scaled is bound to sync, like value.
nisa.scalar_store(out_buf, scaled, engine=nisa.engine.sync)

This document is relevant for: Trn2, Trn3