This document is relevant for: Trn2, Trn3
NKI Scalar Values#
Most of NKI moves tiles: rectangles of data in SBUF, PSUM and HBM. Alongside
that, a kernel needs a few plain integers — an index to gather from, a trip
count read at run time, an offset computed on device. A
nki.isa.NkiScalar holds one such value.
This page covers where scalars come from, which engines hold them, what arithmetic they support, how their dtype decides both range and available operations, and the two places a kernel puts them to work: dynamic addressing and a loop bound.
Note
The examples below run under nki.simulate().
Loading and Storing#
nki.isa.scalar_load(src) reads one element of a tile
into a scalar, and
nki.isa.scalar_store(dst, value) writes one back.
Which Tiles a Scalar Can Be Loaded From and Stored To covers which tiles either one accepts.
Always pass engine= to scalar_store to name the sequencer that writes
the tile; storing without it is discouraged. Without engine= the store is
replicated onto every sequencer the kernel uses: each one writes the same
value, the next instruction that reads the tile waits for all of those writes,
and the value must be available on all engines.
Arithmetic on a scalar is traced rather than evaluated. i * 4 + 1 computes
nothing at compile time — it records the operations and yields a new scalar.
import nki
import nki.isa as nisa
import nki.language as nl
import numpy as np
@nki.jit
def scalar_arithmetic(index: nl.NkiTensor):
index_tile = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.sbuf)
nisa.dma_copy(dst=index_tile, src=index)
i = nisa.scalar_load(index_tile) # a NkiScalar
i = i * 4 + 1 # evaluated at run time
result = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.sbuf)
nisa.scalar_store(result, i, engine=nisa.engine.sync)
out = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.shared_hbm)
nisa.dma_copy(dst=out, src=result)
return out
nki.simulate(scalar_arithmetic)(np.array([[10]], dtype=np.int32)) # [[41]]
The source tile must be nl.int32, nl.uint32 or nl.int64.
scalar_store takes a destination tensor and a NkiScalar value of
matching width and signedness.
One Engine’s Register File#
Each engine’s sequencer has its own register file. Without engine=,
scalar_load runs on every sequencer and each one ends up with its own copy,
so the scalar is available on all engines. That is what makes it usable as
a scalar_offset, as a nki.language.fori_loop() bound, or as an
nki.language.if_else() condition.
scalar_load also takes an optional engine=, naming one sequencer such as
nisa.engine.sync. A load pinned that way runs only there, and its result is
bound to that engine: it can feed further scalar arithmetic and stores on
the same sequencer, but nothing else. Arithmetic propagates the binding, which
value.engine reports, and mixing two different engines is an error. A bound
value cannot be a loop bound, a loop-carried value or a condition, because
every sequencer runs the loop or branch, nor an access pattern’s
scalar_offset, stride or count, because whichever engine runs the
instruction reads them. NKI rejects each of these uses while tracing, and
nki.simulate() rejects them too.
The way out is to publish the value through SBUF: store it with the store
pinned to the owning engine, then load it back without engine=.
@nki.jit
def publish_to_all_engines(count: nl.NkiTensor):
count_tile = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.sbuf)
nisa.dma_copy(dst=count_tile, src=count)
# Bound to one sequencer: usable there, but not as a loop bound.
pinned = nisa.scalar_load(count_tile, engine=nisa.engine.sync) - 1
published = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.sbuf)
nisa.scalar_store(published, pinned, engine=nisa.engine.sync)
trip_count = nisa.scalar_load(published) # available on all engines
counter = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.sbuf)
nisa.memset(dst=counter, value=0)
def body(i):
n = nisa.scalar_load(counter, engine=nisa.engine.sync)
nisa.scalar_store(counter, n + 1, engine=nisa.engine.sync)
nl.fori_loop(0, trip_count, body)
out = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.shared_hbm)
nisa.dma_copy(dst=out, src=counter)
return out
nki.simulate(publish_to_all_engines)(np.array([[4]], dtype=np.int32)) # [[3]]
Which Tiles a Scalar Can Be Loaded From and Stored To#
Scalar loads and stores operate on internal tiles in SBUF and HBM. You cannot
use kernel input or output tensors with these APIs. For an input tile, use
nki.isa.dma_copy() to copy the value into an internal tile before loading
it. For an output tile, store the scalar in an internal tile and then copy the
result to the output tensor. Kernel arguments and returned tensors cannot be
used directly with either API; the same restriction applies to slices and
views on such tiles.
PSUM cannot be used with scalar_load and scalar_store either. Use
nki.isa.tensor_copy() to copy a value from PSUM to SBUF before loading it,
or to copy a stored value from SBUF to PSUM.
Both APIs read or write exactly one element. A 1x1 tile qualifies, and so does any view naming a single element of a larger tile.
v = nisa.scalar_load(tile) # a 1x1 tile
v = nisa.scalar_load(wide[0:1, 3:4]) # a 1x1 slice, at any offset
v = nisa.scalar_load(grid[1:2, 5:6]) # offset on both axes
v = nisa.scalar_load(wide.ap([[8, 1], [1, 1]])) # an ap() with counts of 1
nisa.scalar_store(wide[0:1, 2:3], v, engine=nisa.engine.sync)
A view naming more elements will be rejected, and so will one spanning more than
one partition. The offset has to be known while the kernel is built, so a
scalar_offset on the tile being loaded is not supported — pass the offset to
the instruction that consumes the scalar instead, as
Dynamic Addressing shows.
Width and Range#
A scalar’s dtype is fixed when it is loaded and never changes. Nothing widens
automatically, so arithmetic that outgrows nl.int32 wraps:
@nki.jit
def scalar_wraps(value: nl.NkiTensor):
tile = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.sbuf)
nisa.dma_copy(dst=tile, src=value)
v = nisa.scalar_load(tile)
squared = v * v # 10**10 does not fit 32 bits
result = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.sbuf)
nisa.scalar_store(result, squared, engine=nisa.engine.sync)
out = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.shared_hbm)
nisa.dma_copy(dst=out, src=result)
return out
nki.simulate(scalar_wraps)(np.array([[100000]], dtype=np.int32)) # [[1410065408]]
Warning
Wrapping is silent, and identical on device and under nki.simulate(). A
scalar keeps the low bits of the true result and nothing else: overflow past
the largest value of its dtype continues from the smallest, and underflow the
other way. 100000 * 100000 is 10**10, whose low 32 bits are
1410065408. A value that needs more than 32 bits has to be loaded as
nl.int64 from the start.
For a wider value, load from an nl.int64 tile. Arithmetic then keeps all 64
bits, and a literal too large for 32 bits is added as written:
@nki.jit
def wide_scalar(value: nl.NkiTensor):
tile = nl.ndarray((1, 1), dtype=nl.int64, buffer=nl.sbuf)
nisa.dma_copy(dst=tile, src=value)
v = nisa.scalar_load(tile) # nl.int64 in, so a 64-bit scalar
v = (v + 12345) * 3
result = nl.ndarray((1, 1), dtype=nl.int64, buffer=nl.sbuf)
nisa.scalar_store(result, v, engine=nisa.engine.sync)
out = nl.ndarray((1, 1), dtype=nl.int64, buffer=nl.shared_hbm)
nisa.dma_copy(dst=out, src=result)
return out
nki.simulate(wide_scalar)(np.array([[1 << 40]], dtype=np.int64)) # [[3298534920363]]
Unsigned scalars support the same arithmetic and comparisons as nl.int32.
Arithmetic wraps modulo 2**32: 0xffffffff + 1 produces zero and
0 - 1 produces 0xffffffff. Comparisons, division, remainder and
minimum/maximum interpret values in the range 0 through 0xffffffff.
Comparison results are nl.int32 scalars containing zero or one.
You cannot use nl.uint32 scalars for loop bounds, address offsets,
strides or counts. Scalars used together in an operation must have the same
width and signedness, and a scalar must be stored into a tile of the same dtype.
When one operand in an arithmetic or comparison operation is a scalar and the
other is a Python integer, the integer must be within the range of the scalar’s
dtype. For nl.uint32, this range is 0 to 0xffffffff.
Supported Operations by Scalar Width#
nl.int32 and nl.uint32 support the same arithmetic and comparisons.
nl.int64 supports fewer operations:
Operation |
|
|
|
|---|---|---|---|
|
Supported |
Supported |
Supported |
|
Returns a |
Returns a |
Rejected at compile time |
|
Supported |
Supported |
Rejected at compile time |
Supported, including an arithmetic expression |
Not supported |
Not supported |
|
Condition of |
Supported, including an arithmetic expression |
Not supported |
Not supported |
|
Supported |
Not supported |
Supported, including offsets beyond 4GB |
|
Supported |
Not supported |
Not supported |
|
Supported |
Not supported |
Not supported |
Loop conditions and bounds use signed nl.int32 scalars. Compare an unsigned
scalar with zero to produce an nl.int32 condition, as in value != 0.
Every unsupported case above is reported at compile time.
Comparison Results#
Comparisons of nl.int32 or nl.uint32 scalars return a new nl.int32
scalar containing 1 when true and 0 when false. The Python operators and
nki.isa.scalar_alu() have the same behavior: i < 4 is equivalent to
nisa.scalar_alu(i, 4, op=nl.less). Prefer the Python operator when one exists.
The result can be stored with nki.isa.scalar_store(), used in arithmetic
or another comparison, or used as an offset, a supported dynamic access-pattern
stride or count, a nki.language.fori_loop() bound, or a
nki.language.while_loop() condition. For example,
1 + (i < 4) produces a scalar containing either 1 or 2:
@nki.jit
def comparison_count(index: nl.NkiTensor):
index_tile = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.sbuf)
nisa.dma_copy(dst=index_tile, src=index)
i = nisa.scalar_load(index_tile)
count = 1 + (i < 4)
result = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.sbuf)
nisa.scalar_store(result, count, engine=nisa.engine.sync)
out = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.shared_hbm)
nisa.dma_copy(dst=out, src=result)
return out
nki.simulate(comparison_count)(np.array([[3]], dtype=np.int32)) # [[2]]
nki.simulate(comparison_count)(np.array([[4]], dtype=np.int32)) # [[1]]
A comparison result is a runtime scalar, so it cannot be converted to a Python
bool. Python if, while, assert, and, or, and not still
reject it. Comparisons involving an nl.int64 scalar remain unsupported.
Dynamic Addressing#
An access pattern’s scalar_offset takes a scalar available on all engines,
which is how a kernel reads a location it cannot know until run time. The
offset counts elements of the dimension named by indirect_dim, so with
indirect_dim=0 a scalar selects a row:
ROWS, COLS = 4, 8
@nki.jit
def gather_at_scalar_offset(data: nl.NkiTensor, index: nl.NkiTensor):
index_tile = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.sbuf)
nisa.dma_copy(dst=index_tile, src=index)
row = nisa.scalar_load(index_tile)
tile = nl.ndarray((1, COLS), dtype=nl.float32, buffer=nl.sbuf)
nisa.dma_copy(
dst=tile,
src=data.ap(
pattern=[[COLS, 1], [1, COLS]], offset=0,
scalar_offset=row, indirect_dim=0,
),
)
out = nl.ndarray((1, COLS), dtype=nl.float32, buffer=nl.shared_hbm)
nisa.dma_copy(dst=out, src=tile)
return out
data = np.arange(32, dtype=np.float32).reshape(4, 8)
nki.simulate(gather_at_scalar_offset)(data, np.array([[2]], dtype=np.int32))
# [[16. 17. 18. 19. 20. 21. 22. 23.]]
Warning
A scalar_offset is not bounds-checked. An index computed on device that
falls outside the tensor still forms an address, and the DMA reads that
address: the kernel returns another tensor’s data, or uninitialized HBM,
without an error from the compiler or from nki.simulate(). Check the
arithmetic that produces an index as well as the kernel that consumes it.
Choosing a Width for an Offset#
The offset counts elements of the indirect dimension rather than bytes, and is
scaled by that dimension’s stride when the address is formed, so a 32-bit index
reaches well past 4GB. Rows of 512 nl.float32 values are 2KB apart, so
2**31 of them span roughly 4TB. An nl.int64 offset is needed when the
index value itself passes 2**31 — element-indexing a tensor of more than
2**31 elements, for instance.
An offset into SBUF or PSUM must be nl.int32. A 64-bit one is rejected:
SBUF and PSUM today are too small for an offset that needs 64 bits to encode.
Loop Bounds and the Loop Variable#
fori_loop(lower, upper, body_fun, step=1)
accepts a scalar available on all engines as a bound, which is how a kernel
loops a number of times it reads at run time. The loop variable handed to the
body is itself a scalar, usable in arithmetic and as an offset:
@nki.jit
def sum_rows_to_bound(data: nl.NkiTensor, count: nl.NkiTensor):
count_tile = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.sbuf)
nisa.dma_copy(dst=count_tile, src=count)
trip_count = nisa.scalar_load(count_tile)
total = nl.zeros((1, COLS), dtype=nl.float32, buffer=nl.sbuf)
def body(i): # i is a NkiScalar
row = nl.ndarray((1, COLS), dtype=nl.float32, buffer=nl.sbuf)
nisa.dma_copy(
dst=row,
src=data.ap(
pattern=[[COLS, 1], [1, COLS]], offset=0,
scalar_offset=i, indirect_dim=0,
),
)
nisa.tensor_tensor(dst=total, data1=total, data2=row, op=nl.add)
nl.fori_loop(0, trip_count, body)
out = nl.ndarray((1, COLS), dtype=nl.float32, buffer=nl.shared_hbm)
nisa.dma_copy(dst=out, src=total)
return out
nki.simulate(sum_rows_to_bound)(data, np.array([[3]], dtype=np.int32))
# [[24. 27. 30. 33. 36. 39. 42. 45.]]
The loop variable is always 32-bit. A 64-bit scalar can be loaded inside the body and used as an offset there, but it cannot be combined with the loop variable: mixing widths is refused, so a wide offset stays the same on every iteration unless the loop carries it.
This document is relevant for: Trn2, Trn3