Skip to content

← JAX Foundations step 21 of 25

Medium Primitives

take_along_axis (Gather)

Jump to the task

Why this matters

Sometimes each row of a matrix needs a different set of columns. jnp.take_along_axis(matrix, indices, axis=1) uses each row of indices to choose values from the matching matrix row.

For example, after sorting scores separately in each row, you can use the resulting indices to gather the scores in that order.

Worked mini-example

import jax.numpy as jnp

matrix = jnp.array([[10, 20, 30, 40], [50, 60, 70, 80]])
indices = jnp.array([[3, 0], [2, 1]], dtype=jnp.int32)
out = jnp.take_along_axis(matrix, indices, axis=1)
# out = [[40, 10], [70, 60]], shape (2, 2)

Row zero selects columns 3 and 0. Row one selects columns 2 and 1. The order of indices becomes the order of values in the result. Repeating an index repeats the selected value.

Common pitfalls

  • With an explicit axis, the input and indices need the same number of dimensions. Other dimensions must be compatible for broadcasting. This exercise uses the same row count.
  • Indices must have an integer dtype. The fixtures supply integer-valued floats, so convert them with indices.astype(jnp.int32).
  • jnp.take(matrix, [3, 0], axis=1) selects columns 3 and 0 in every row. It flattens the input only when axis is omitted. It does not apply a separate index row to each matrix row.
  • Do not rely on an exception for an invalid index. JAX gather behavior depends on the operation and its bounds mode. The inputs for this exercise stay within the valid range.
  • Casting is not validation: a fractional input would be truncated. This task supplies whole-number indices.

Problem

Implement gather_top_k_per_row(matrix, indices) with jnp.take_along_axis along axis 1.

The matrix has shape (N, K). Indices have shape (N, M) and contain integer-valued numbers from zero through K - 1. Convert them to an integer dtype before gathering.

Return shape (N, M), with out[i, j] = matrix[i, indices[i, j]].

Despite the function name, the indices are already supplied. Do not sort the matrix or find the largest values. For matrix = [[10, 20], [30, 40]] and indices = [[1, 0], [0, 0]], return [[20, 10], [30, 30]].