Skip to content
Medium Framework

Gather Elements

Select columns independently from each row of a matrix. Each index tells you which column to read from that same row; it does not select a row.

Your task

Implement gather(x, indices).

  • x is a floating-point tensor of shape (m, n), with n > 0.
  • indices has shape (m, k) on the same device. Its values are valid column IDs in [0, n), delivered as integer-valued floats. Cast them to integers.
  • Return shape (m, k) with x's dtype and device, leaving both inputs unchanged.
output[i, j] = x[i, indices[i, j]]

For x=[[10, 20, 30], [40, 50, 60]] and indices=[[2, 0], [1, 2]], return [[30, 10], [50, 60]]. Each row uses its own indices.

Keep the index order and repetitions. Repeating a column ID repeats its value in the output. The output width k can exceed n when indices repeat. With k=0, return shape (m, 0) rather than dropping the row dimension.

Use torch.gather(x, dim=1, index=indices.long()) in PyTorch or jnp.take_along_axis(x, indices.astype(jnp.int32), axis=1) in JAX. Do not flatten x or use indices from one row for every row.