jax-ml/jax · error · ValueError

axis argument out of range: {axis=} for {operand.shape=}

Error message

axis argument out of range: {axis=} for {operand.shape=}

What it means

The axis argument to top_k is not in [0, operand.ndim). Unlike some APIs, top_k does not accept out-of-range axes; the check is done on the static shape during tracing.

Source

Thrown at jax/_src/lax/lax.py:9036

    out = lower_comparator(sub_ctx, *comparator.arguments, num_keys=num_keys)
    flat_out, _ = mlir.ir_tree_registry.flatten(out)
    hlo.return_(flat_out)
  return [mlir.lower_with_sharding_in_types(ctx, op, aval)
          for op, aval in zip(sort.results, ctx.avals_out)]

mlir.register_lowering(sort_p, _sort_lower)


def _top_k_abstract_eval(operand, *, k, axis, is_stable):
  if dtypes.issubdtype(operand.dtype, np.complexfloating):
    raise ValueError("top_k is not compatible with complex inputs.")
  if k < 0:
    raise ValueError(f"k argument to top_k must be nonnegative, got {k}")
  if len(operand.shape) == 0:
    raise TypeError("top_k operand must have >= 1 dimension, got {}"
                    .format(operand.shape))
  if not (0 <= axis < len(operand.shape)):
    raise ValueError(f"axis argument out of range: {axis=} for {operand.shape=}")
  shape = list(operand.shape)
  if shape[axis] < k:
    raise ValueError("k argument to top_k must be no larger than size along axis;"
                     f" got {k=} with {shape=} and {axis=}")
  int32_max = dtypes.iinfo('int32').max
  try:
    too_large = (shape[axis] > int32_max + 1)
  except core.InconclusiveDimensionOperation:
    pass
  else:
    if too_large:
      raise ValueError(
          'top_k returns int32 indices, which will overflow for array'
          f' dimensions larger than the maximum int32 ({int32_max}). Got'
          f' {operand.shape=}')
  shape[axis] = k
  if operand.sharding.spec[axis] is not None:
    raise core.ShardingTypeError(

View on GitHub (pinned to 1e1c6a8fc0)

Solutions

  1. Use axis=-1 for the last dimension (rank-independent).
  2. Recompute axis after batching/reshaping steps that change rank.
  3. Validate: assert -x.ndim <= axis < x.ndim before the call.

Example fix

# before
vals, idx = jnp.top_k(x, k, axis=1)  # x is 1-D
# after
vals, idx = jnp.top_k(x, k, axis=-1)
Defensive patterns

Strategy: validation

Validate before calling

assert -x.ndim <= axis < x.ndim, (axis, x.shape)
vals, idx = jnp.top_k(x, k, axis=axis)

Type guard

def valid_axis(x, axis):
    return -x.ndim <= axis < x.ndim

Prevention

When it happens

Trigger: jnp.top_k(x, k, axis=1) on a 1-D array; axis=2 on a matrix; axis computed as x.ndim (one past the end).

Common situations: Rank changes from batching (vmap adds a leading axis, shifting intended indices); porting NumPy code where the axis was valid for a different layout.

Related errors


AI-assisted analysis of jax-ml/jax@1e1c6a8fc0 (2026-08-27). Data as JSON: /api/errors/70628733ff8191d1. Report an issue: GitHub.