Skip to content

← JAX Foundations step 6 of 25

Easy Primitives

Functional Update with .at[].add()

Jump to the task

Add contributions to selected positions

Scatter-add collects values by destination. Several contributions can target the same entry, as in a histogram or an embedding gradient. arr.at[indices].add(values) adds them to arr's existing contents and returns the updated array value.

import jax.numpy as jnp

arr = jnp.array([10., 20., 30.])
indices = jnp.array([0, 0, 2])
values = jnp.array([1., 3., -5.])
updated = arr.at[indices].add(values)
# [14., 20., 25.]
# index 0: 10 + 1 + 3; index 2: 30 - 5

Arr stays [10, 20, 30]. Keep or return updated; discarding the result does not change arr. Starting from nonzero values matters: this is accumulation into the original array, not a sum into a new zero array.

Repeated indices accumulate

All contributions to a destination participate in the sum. This differs from .set, which replaces values and has no portable last-write rule for conflicting destinations.

Accumulation order can vary with backend and execution. Floating-point addition is not associative, so repeated-index sums are not guaranteed bitwise identical across hardware. The mathematical sum includes every update; its floating-point rounding can depend on their order.

Indexing is not arbitrary wraparound

The default .at update behavior does not wrap a large positive index around the array. Out-of-range updates are normally dropped under the default promise_in_bounds mode, which does not validate the promise. Negative indices count from the end by default, as in ordinary Python indexing. These are separate behaviors. Explicit drop or clip modes are available when a task needs a particular boundary policy.

Here every index is nonnegative and in range, so boundary handling is not part of the exercise. Convert the supplied whole-number float indices to int32; casting fractional values would not validate them.

Problem

Implement accumulate_at_indices(arr, indices, values) with .at[].add().

Arr and values are one-dimensional finite float32 JAX arrays. Indices contains nonnegative whole numbers supplied as floats, representable as int32 and less than arr.shape[0]. Indices and values have the same length. Repeated indices are allowed and must accumulate.

Return a JAX array with arr's shape and dtype. Preserve entries without updates, include each entry's initial value, and leave arr unchanged. Empty indices and values return unchanged contents; an empty arr is valid only with no updates.

For a zero array of length three, indices [0, 0, 1] and values [1, 2, 5] produce [3, 5, 0]. Do not use .set or gather the old values and write them back once, since those patterns do not express repeated additions.