.. meta::
    :description: Scatter-add ``src`` into a copy of ``input`` for arbitrary (repeated) indices.
    :date-modified: 11/30/2026

.. currentmodule:: nkilib.experimental.misc

Scatter-Add Dedup Kernel API Reference
======================================

Scatter-add ``src`` into a copy of ``input`` for arbitrary (repeated) indices.

Equivalent to PyTorch's ``input.index_add(0, index, src)``: ``output[index[k], :] = input[index[k], :] + src[k, :]`` summed over every k, including all the k that share an index, in any positions.

Background
-----------

``scatter_add_dedup`` scatter-adds ``src`` into a copy of ``input`` for arbitrary, possibly repeated, row indices, equivalent to PyTorch's ``input.index_add(0, index, src)``. Duplicate indices within a 128-index tile are deduplicated on the Tensor Engine so repeats accumulate correctly.

API Reference
--------------

**Source code for this kernel API can be found at**: `scatter_add_dedup.py <https://github.com/aws-neuron/nki-library/blob/2.34/src/nkilib_src/nkilib/experimental/misc/scatter_add_dedup.py>`_

scatter_add_dedup
^^^^^^^^^^^^^^^^^

.. py:function:: scatter_add_dedup(input: nl.NkiTensor, dim: int, index: nl.NkiTensor, src: nl.NkiTensor, unique_indices: bool = False) -> nl.NkiTensor

   Scatter-add ``src`` into a copy of ``input`` for arbitrary (repeated) indices.

   :param input: [N, D], Destination values to accumulate into (not modified), float32, bfloat16 or float16.
   :type input: ``nl.NkiTensor``
   :param dim: Dimension along which to scatter (must be 0).
   :type dim: ``int``
   :param index: [K], 1D int32 row indices into input, all in [0, N).
   :type index: ``nl.NkiTensor``
   :param src: [K, D], Source values, same dtype as input.
   :type src: ``nl.NkiTensor``
   :param unique_indices: The caller guarantees that the indices of every 128-index tile, ``index[128 * t : 128 * (t + 1)]``, are distinct, as with scatter_add's ``unique_indices=True`` (repeats across tiles are fine). The per-tile deduplication is then skipped. Repeats inside a tile give wrong sums, without an error, when this is set. Default False.
   :type unique_indices: ``bool``
   :return: [N, D], A new tensor holding input plus the scattered sources.
   :rtype: ``nl.NkiTensor``

   **Notes**:

   * Any index pattern is exact (unless unique_indices is set): repeats inside a 128-index tile, across tiles, or all indices equal.
   * Indices must lie in [0, N); they are not checked.
   * N must be at most 2^24 - 2048, because indices are compared as float32.
   * Narrow rows (under 2 KB) accumulate in float32; wide rows, and rows accumulated in the output itself, accumulate in the input dtype as scatter_add does, with the summed duplicates of a tile (or of a group of tiles) rounded to that dtype once. Small tables sum in fp32 PSUM and round once.
   * LNC=2: wide rows are split over columns, narrow rows and small tables over index tiles (each core sums into its own float32 buffers, then the cores reduce half of the rows each after a core barrier).
   * The path and the buffers come from cost models measured on trn2 (_plan_scatter_add_dedup): one-hot matmuls for small tables, one or two accumulation buffers per core otherwise, and for few tiles over a large table the output itself as the one buffer (no zeroing and no fold).
   * Static DMA descriptors are used for the index and source loads, so the time of a standalone call (index and src are inputs of the NEFF) depends on NEURON_RT_IO_RING_CACHE_SIZE, mostly at LNC=2; the design spec has the measurements.
   * Cost is about one read-modify-write per 128 sources (2.3 us on one core for rows up to 256 bytes), whatever the number of repeats. Pseudocode (read-modify-write paths; small tables use one-hot matmuls instead): for tile in tiles(K):                      # 128 indices, tiles dealt to 1 or 2 buffers if unique_indices: summed, row = src[tile], index[tile] else: E = (index[tile] == index[tile]^T) summed = E^T @ src[tile]           # TensorE, fp32 accumulate row = index[tile] where first occurrence else N + position buffer[tile % chains][row] += summed   # one dma_compute read-modify-write output = input + sum(buffers)              # or output is the one buffer (in place; with repeats the # tiles then go in groups of gathers, adds and plain scatters)

   **Dimensions**:

   * N: Number of rows in input tensor
   * D: Feature dimension size

