This document is relevant for: Trn2, Trn3
NKI Tensor Indirection#
Tensor indirection lets one compute instruction read or write a set of columns of an on-chip tensor. The columns can be any columns, in any order. An SBUF tensor gives their positions, so the kernel can choose them at run time. Tensor indirection is available on NeuronCore-v4+ (Trainium3).
This page uses these terms:
Data tensor: the SBUF or PSUM tensor that the instruction reads from or writes to.
Index tensor: an SBUF tensor of
uint16values that tells the engine which columns of the data tensor to use.Offset: one value in the index tensor. An offset is the position of one element along the free dimension of the data tensor. The same offset applies to every partition of a partition group.
Partition group: a set of 16 adjacent partitions that read their offsets from the same rows of the index tensor.
Gather: an indirect read. The instruction reads the columns at the offsets and uses them as a dense input.
Scatter: an indirect write. The instruction writes its dense output to the columns at the offsets.
When to Use Tensor Indirection#
An access pattern selects evenly spaced elements: one start and one step for each dimension. The start, the step, and the count can be fixed or read from a register at run time (see NKI Scalar Values). Tensor indirection selects columns from a list of offsets in SBUF, so the columns do not have to be evenly spaced or in increasing order. Use tensor indirection when the columns that you need are not evenly spaced. For example, after a top-k step, one instruction can read the k selected columns of a score tile.
Fig. 144 The same four columns of one data tensor. An access pattern reads them with one step, in increasing order. Tensor indirection reads them in the order of the offsets: 5, 1, 7, 3.#
Tensor indirection is different from dynamic DMA access. Dynamic DMA access
uses vector_offset or vector_select() to move whole rows,
usually from HBM, with a DMA. Tensor indirection selects columns of an
on-chip tensor inside a compute instruction, with no DMA. See
Dynamic Access with scalar_offset and vector_offset for dynamic DMA access.
The API#
indirect() makes an indirect view of a data tensor:
def indirect(self, index: NkiTensor, num_elem: int | None = None) -> NkiTensor
self: the data tensor. It must be a 2D SBUF or PSUM tensor with contiguous storage, shape(P, F).index: the index tensor. It must be a 2Dnl.uint16SBUF tensor with contiguous storage, shape(P, K).Pmust be the partition count of the data tensor, and a multiple of 16.num_elem: the number of offsets to use. The maximum and the default are16 * K, every cell of the index rows of one partition group.
The return value is a view of shape (P, num_elem). Making the view does
not move data. The engine reads or writes the columns when you give the view
to a nki.isa instruction. Use the view as an input to gather, and as the
dst to scatter.
An offset counts elements from the first element of each partition of the
data tensor. If the data tensor is a slice such as t[:, 4:10], offset 0
is column 4 of t.
Fig. 145 t[:, 4:10].indirect(index, num_elem=3) with offsets 3, 0, and 5 reads
columns 7, 4, and 9 of t.#
Each offset must be less than F. The device does not check the offsets,
and nki.simulate() does not check them for a sliced data tensor. An
offset that is out of range gives undefined results.
Gather#
A gather reads num_elem columns. For each partition p and each
i in range(num_elem):
gathered[p, i] = data[p, offset(p, i)]
offset(p, i) comes from the index tensor. See Index Tensor Layout.
The offsets can be in any order, and the same offset can occur more than
once.
Fig. 146 A gather of 4 columns. Rows 0 to 3 of the index tensor hold the offsets.
Column i of the gathered view is column offset[i] of the data
tensor, in every partition.#
In this example, data is (128, 512) and the index holds 64 offsets.
The instruction copies the 64 columns into a dense (128, 64) tile:
@nki.jit
def gather_columns(data_hbm, index_hbm):
data = nl.load(data_hbm) # (128, 512) float32
index = nl.load(index_hbm) # (128, 4) uint16
result = nl.ndarray((P, NUM_ELEM), dtype=nl.float32, buffer=nl.sbuf)
# Gather: column i of `cols` is column offset[i] of `data`.
cols = data.indirect(index, num_elem=NUM_ELEM)
nisa.tensor_copy(dst=result, src=cols, engine=nisa.engine.vector)
out = nl.ndarray((P, NUM_ELEM), dtype=nl.float32, buffer=nl.shared_hbm)
nl.store(out, value=result)
return out
Scatter#
A scatter writes the dense output of an instruction to num_elem columns:
data[p, offset(p, i)] = values[p, i]
The other columns of data do not change. The input of a scatter
instruction must be contiguous along the free dimension. A strided input,
such as values[:, ::2], does not compile.
Fig. 147 A scatter of 4 columns. The columns that are not in the index keep their values.#
In this example, the instruction writes the 64 columns of values into
data:
@nki.jit
def scatter_columns(data_hbm, index_hbm, values_hbm):
data = nl.load(data_hbm) # (128, 512) float32
index = nl.load(index_hbm) # (128, 4) uint16
values = nl.load(values_hbm) # (128, 64) float32
# Scatter: column i of `values` goes to column offset[i] of `data`.
# The other columns of `data` do not change.
cols = data.indirect(index, num_elem=NUM_ELEM)
nisa.tensor_copy(dst=cols, src=values, engine=nisa.engine.vector)
out = nl.ndarray((P, F), dtype=nl.float32, buffer=nl.shared_hbm)
nl.store(out, value=data)
return out
Do not put the same offset twice in one partition group of a scatter index. The result for that column depends on the write order.
Gather and Scatter in One Instruction#
An instruction can gather its input and scatter its output. In this
example, the same view cols is the input and the output, so the
instruction multiplies the 64 columns by 2 in place:
@nki.jit
def scale_columns(data_hbm, index_hbm):
data = nl.load(data_hbm) # (128, 512) float32
index = nl.load(index_hbm) # (128, 4) uint16
# Gather and scatter: read columns offset[i] of `data`, multiply them
# by 2, and write them back to the same columns.
cols = data.indirect(index, num_elem=NUM_ELEM)
nisa.tensor_scalar(dst=cols, data=cols, op0=nl.multiply, operand0=2.0,
engine=nisa.engine.vector)
out = nl.ndarray((P, F), dtype=nl.float32, buffer=nl.shared_hbm)
nl.store(out, value=data)
return out
Index Tensor Layout#
The offsets are in the index tensor in column order. Offset i of a
partition group is at row i % 16 of the group and at column i // 16.
The engine reads down column 0, then down column 1, and so on. It reads
only the first num_elem cells, so the other cells can hold any value.
Fig. 148 The location of each offset in a (16, 3) index tensor for
num_elem = 40.#
This host-side function makes an index tensor that gives every partition the same offsets:
def make_index(offsets, num_partitions):
"""Build a (num_partitions, K) uint16 index that gives every partition
the same offsets. Offset i goes to row i % 16 and column i // 16 of
each group of 16 partitions."""
offsets = np.asarray(offsets, dtype=np.uint16)
k = (len(offsets) + 15) // 16
group = np.zeros((16, k), dtype=np.uint16)
for i, offset in enumerate(offsets):
group[i % 16, i // 16] = offset
return np.tile(group, (num_partitions // 16, 1))
rng = np.random.default_rng(0)
offsets = rng.permutation(F)[:NUM_ELEM] # 64 different columns, any order
index = make_index(offsets, P) # shape (128, 4)
data = rng.standard_normal((P, F)).astype(np.float32)
gathered = nki.simulate(gather_columns)(data, index)
assert np.array_equal(gathered, data[:, offsets])
Partition Groups#
Each partition group reads its offsets from its own 16 rows of the index
tensor. Partitions 0 to 15 use index rows 0 to 15, partitions 16 to 31 use
index rows 16 to 31, and so on. So the full rule for group g is:
offset(p, i) = index[16 * g + i % 16, i // 16] # g = p // 16
Fig. 149 Two partition groups with different offsets. Group 0 gathers columns 6, 1, and 8. Group 1 gathers columns 4, 9, and 0.#
On the Vector, Scalar, and GpSimd Engines, each partition group can use different offsets. On the Tensor Engine, every partition group must use the same offsets. See Tensor Engine.
Supported Instructions#
The table shows the instructions that accept an indirect view, the operands
that can be indirect, and the engines that support it. All other nki.isa
instructions reject indirect views. An instruction can have more than one
indirect operand.
Instruction |
Operands that can be indirect |
Engines |
|---|---|---|
|
Vector, Scalar |
|
|
Vector, Scalar, GpSimd |
|
|
Vector |
|
|
Vector |
|
|
Vector |
|
|
Vector |
|
|
Vector |
|
|
Vector |
|
|
Scalar; GpSimd for |
|
|
Scalar |
|
|
Tensor |
|
|
Tensor |
The operands that are not in the table, such as data2 of
nki.isa.tensor_tensor() or bias of nki.isa.activation(),
cannot be indirect.
With tensor indirection, pass an explicit engine= from the table to
nki.isa.tensor_copy(), nki.isa.tensor_scalar(), and
nki.isa.tensor_tensor().
Tensor Engine#
nki.isa.nc_matmul() can gather stationary and moving along
their free dimension, and scatter dst along the free dimension of PSUM.
This example multiplies a stationary tile by 64 gathered columns of a moving
tile:
@nki.jit
def matmul_gathered_moving(stationary_hbm, moving_hbm, index_hbm):
stationary = nl.load(stationary_hbm) # (128, 128) float16, [K, M]
moving = nl.load(moving_hbm) # (128, 512) float16, [K, F]
index = nl.load(index_hbm) # (128, 4) uint16
# The Tensor Engine needs index rows that repeat every 16 partitions,
# which make_index gives.
moving_cols = moving.indirect(index, num_elem=NUM_ELEM) # [K, N=64]
result_psum = nl.ndarray((P, NUM_ELEM), dtype=nl.float32, buffer=nl.psum)
nisa.nc_matmul(dst=result_psum, stationary=stationary, moving=moving_cols)
result = nl.ndarray((P, NUM_ELEM), dtype=nl.float32, buffer=nl.sbuf)
nisa.tensor_copy(dst=result, src=result_psum)
out = nl.ndarray((P, NUM_ELEM), dtype=nl.float32, buffer=nl.shared_hbm)
nl.store(out, value=result)
return out
The Tensor Engine has these rules:
Every partition group must use the same offsets. Rows 16 to 31 of the index tensor must be equal to rows 0 to 15, and so on for each group of 16 rows.
nki.simulate()rejects an index tensor that breaks this rule. The compiler cannot check the index values, so on the device the result is incorrect.The Tensor Engine reads a gathered
stationaryoperand in the opposite order. WithMoffsets, rowmofdstuses columnoffset[M - 1 - m]ofstationary. To get rowmfrom columnc[m], put the offsets in the index tensor in the opposite order:make_index(c[::-1], P). See the figure below.The data tensor of an indirect
stationaryoperand can have at most 128 elements per partition.For
nki.isa.nc_matmul(), an indirectstationaryormovingoperand must have afloat16,bfloat16, or FP8 dtype.With
is_transpose=True,movingcannot be indirect.tile_positionmust be(0, 0).For
nki.isa.nc_matmul_mx(), a data operand and its scale must use the same index tensor, or neither can be indirect.
Fig. 150 A gathered stationary operand. With offsets 5, 1, 7, 3, the rows of
dst come from columns 3, 7, 1, 5. With the reversed list, they come
from columns 5, 1, 7, 3.#
Rules and Limits#
The data tensor:
It is a 2D SBUF or PSUM tensor with contiguous storage. A slice along the partition or free dimension is permitted. A strided or permuted view is not.
It uses a static access pattern. A view that uses
scalar_offset,vector_offset, or a dynamic step or count cannot be indirect.An indirect view cannot be made indirect again.
The index tensor:
It is a 2D
nl.uint16SBUF tensor with contiguous storage.It uses a static access pattern. Its step and count cannot come from a register.
Its partition count is a multiple of 16 and is equal to the partition count of the data tensor.
Its first partition is a multiple of 32.
Its first element starts at a multiple of 4 bytes within each partition. Each offset is a 2-byte
uint16, so a slice of the index tensor must start at an even column. For example,index[:, 2:]is allowed, andindex[:, 1:]is not. The same rule applies to the byte offset that you give inaddress=.For a gather, its first partition is the same as the first partition of the data tensor.
For a scatter, its first partition is the same as the first partition of the first data input of the instruction (for example
data1ofnki.isa.tensor_tensor()), when that input is in SBUF. When an input is an indirect view of a PSUM tensor, the scatter index starts on the same partition as the index of that input.
Data types:
The index tensor is
nl.uint16.The data tensor and the other operands can have any dtype that the instruction supports without tensor indirection. Offsets count elements, not bytes, for every dtype. For example,
nki.isa.tensor_copy()can gatherbfloat16columns into afloat32tile.The Tensor Engine has its own dtype rule. See Tensor Engine.
NKI checks the partition rules at trace time only for tensors that set
address=. For a gather from PSUM, set address= on both the data tensor
and the index tensor so that they start at the same partition. Otherwise
neuronx-cc can reject the kernel because the two base partitions differ.
The other operands of the instruction can use a dynamic step, which the
kernel reads from a register at run time. A dynamic count is not supported,
because an indirect view always has a fixed count of num_elem. The input
of a scatter must be contiguous. The compiler cannot check a dynamic step, so
a dynamic step on the input of a scatter must be 1 at run time.
Other limits:
num_elemis at most16 * K, whereKis the number of columns of the index tensor.The Scalar Engine cannot scatter to PSUM.