.. meta::
   :description: Deep dive into tensor indirection, which lets one compute instruction gather or scatter columns of an SBUF or PSUM tensor at offsets read at run time
   :keywords: NKI kernels, Neuron Kernel Interface, AWS Neuron SDK, Trainium3, tensor indirection, gather, scatter, NkiTensor.indirect
   :date-modified: 11/09/2026

.. _nki-tensor-indirection:

=======================
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 ``uint16`` values 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 :ref:`access pattern <nki-aps>` 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
:ref:`NKI Scalar Values <nki-scalar>`). 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.

.. figure:: ../img/tensor-indirection/ti-ap-vs-indirection.svg
   :align: center
   :width: 95%

   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 :meth:`~nki.language.NkiTensor.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
:ref:`nki-aps-dynamic-access` for dynamic DMA access.

The API
=======

:meth:`~nki.language.NkiTensor.indirect` makes an indirect view of a data tensor:

.. code-block:: python

   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 2D ``nl.uint16`` SBUF tensor with
  contiguous storage, shape ``(P, K)``. ``P`` must 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
  are ``16 * 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``.

.. figure:: ../img/tensor-indirection/ti-slice-offsets.svg
   :align: center
   :width: 95%

   ``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 :func:`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)``:

.. code-block:: python

   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.

.. figure:: ../img/tensor-indirection/ti-gather.svg
   :align: center
   :width: 95%

   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_example:: /nki/examples/tensor_indirection/ti_examples.py
   :language: python
   :marker: NKI_EXAMPLE_TI_GATHER

Scatter
=======

A scatter writes the dense output of an instruction to ``num_elem`` columns:

.. code-block:: python

   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.

.. figure:: ../img/tensor-indirection/ti-scatter.svg
   :align: center
   :width: 95%

   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_example:: /nki/examples/tensor_indirection/ti_examples.py
   :language: python
   :marker: NKI_EXAMPLE_TI_SCATTER

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_example:: /nki/examples/tensor_indirection/ti_examples.py
   :language: python
   :marker: NKI_EXAMPLE_TI_UPDATE

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.

.. figure:: ../img/tensor-indirection/ti-index-layout.svg
   :align: center
   :width: 95%

   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:

.. nki_example:: /nki/examples/tensor_indirection/ti_examples.py
   :language: python
   :marker: NKI_EXAMPLE_TI_INDEX

.. nki_example:: /nki/examples/tensor_indirection/ti_examples.py
   :language: python
   :marker: NKI_EXAMPLE_TI_RUN

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:

.. code-block:: python

   offset(p, i) = index[16 * g + i % 16, i // 16]    # g = p // 16

.. figure:: ../img/tensor-indirection/ti-partition-groups.svg
   :align: center
   :width: 95%

   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.

.. list-table::
   :header-rows: 1
   :widths: 30 40 30

   * - Instruction
     - Operands that can be indirect
     - Engines
   * - :func:`nki.isa.tensor_copy`
     - ``src``, ``dst``
     - Vector, Scalar
   * - :func:`nki.isa.tensor_scalar` [#ts]_
     - ``data``, ``dst``
     - Vector, Scalar, GpSimd
   * - :func:`nki.isa.tensor_tensor` [#tt]_
     - ``data1``, ``dst``
     - Vector
   * - :func:`nki.isa.tensor_scalar_reduce`
     - ``data``, ``dst``
     - Vector
   * - :func:`nki.isa.tensor_scalar_cumulative`
     - ``src``, ``dst``
     - Vector
   * - :func:`nki.isa.tensor_reduce`
     - ``data``, ``dst``
     - Vector
   * - :func:`nki.isa.tensor_copy_predicated`
     - ``predicate``, ``dst``
     - Vector
   * - :func:`nki.isa.exponential`
     - ``src``, ``dst``
     - Vector
   * - :func:`nki.isa.activation`
     - ``data``, ``dst``
     - Scalar; GpSimd for ``data`` only
   * - :func:`nki.isa.activate2`
     - ``data``, ``dst``
     - Scalar
   * - :func:`nki.isa.nc_matmul`
     - ``stationary``, ``moving``, ``dst``
     - Tensor
   * - :func:`nki.isa.nc_matmul_mx` [#mx]_
     - ``stationary`` and ``stationary_scale`` as a pair, ``moving`` and
       ``moving_scale`` as a pair, ``dst``
     - Tensor

.. [#ts] On the GpSimd Engine, :func:`nki.isa.tensor_scalar` is the only
   instruction that can scatter.
.. [#tt] With tensor indirection, the SBUF inputs of
   :func:`nki.isa.tensor_tensor` and the index tensor of ``data1`` must start
   at partition 0.
.. [#mx] ``stationary`` and ``stationary_scale`` are indirect together: give
   both the same index tensor, or make neither indirect. The same applies to
   ``moving`` and ``moving_scale``. ``dst`` can be indirect on its own.

The operands that are not in the table, such as ``data2`` of
:func:`nki.isa.tensor_tensor` or ``bias`` of :func:`nki.isa.activation`,
cannot be indirect.

With tensor indirection, pass an explicit ``engine=`` from the table to
:func:`nki.isa.tensor_copy`, :func:`nki.isa.tensor_scalar`, and
:func:`nki.isa.tensor_tensor`.

Tensor Engine
=============

:func:`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_example:: /nki/examples/tensor_indirection/ti_examples.py
   :language: python
   :marker: NKI_EXAMPLE_TI_MATMUL

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.
  :func:`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 ``stationary`` operand in the opposite
  order. With ``M`` offsets, row ``m`` of ``dst`` uses column
  ``offset[M - 1 - m]`` of ``stationary``. To get row ``m`` from column
  ``c[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 ``stationary`` operand can have at most 128
  elements per partition.
* For :func:`nki.isa.nc_matmul`, an indirect ``stationary`` or ``moving``
  operand must have a ``float16``, ``bfloat16``, or FP8 dtype.
* With ``is_transpose=True``, ``moving`` cannot be indirect.
* ``tile_position`` must be ``(0, 0)``.
* For :func:`nki.isa.nc_matmul_mx`, a data operand and its scale must use
  the same index tensor, or neither can be indirect.

.. figure:: ../img/tensor-indirection/ti-stationary-order.svg
   :align: center
   :width: 95%

   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.uint16`` SBUF 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, and
  ``index[:, 1:]`` is not. The same rule applies to the byte offset that you
  give in ``address=``.
* 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 ``data1`` of
  :func:`nki.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, :func:`nki.isa.tensor_copy` can
  gather ``bfloat16`` columns into a ``float32`` tile.
* 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_elem`` is at most ``16 * K``, where ``K`` is the number of columns of
  the index tensor.
* The Scalar Engine cannot scatter to PSUM.

Related Pages
=============

* :ref:`NKI Access Patterns <nki-aps>`: static access patterns, and dynamic
  DMA access with ``scalar_offset`` and ``vector_offset``.
* :ref:`Trainium3 architecture <arch-trn3-indirect-access>`: the hardware
  feature that tensor indirection uses.
* :meth:`~nki.language.NkiTensor.indirect`: the API reference.
