{"record":{"id":"70628733ff8191d1","repo":"jax-ml/jax","slug":"axis-argument-out-of-range-axis-for-operand-s","errorCode":null,"errorMessage":"axis argument out of range: {axis=} for {operand.shape=}","messagePattern":"axis argument out of range: (.+?) for (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"jax/_src/lax/lax.py","lineNumber":9036,"sourceCode":"    out = lower_comparator(sub_ctx, *comparator.arguments, num_keys=num_keys)\n    flat_out, _ = mlir.ir_tree_registry.flatten(out)\n    hlo.return_(flat_out)\n  return [mlir.lower_with_sharding_in_types(ctx, op, aval)\n          for op, aval in zip(sort.results, ctx.avals_out)]\n\nmlir.register_lowering(sort_p, _sort_lower)\n\n\ndef _top_k_abstract_eval(operand, *, k, axis, is_stable):\n  if dtypes.issubdtype(operand.dtype, np.complexfloating):\n    raise ValueError(\"top_k is not compatible with complex inputs.\")\n  if k < 0:\n    raise ValueError(f\"k argument to top_k must be nonnegative, got {k}\")\n  if len(operand.shape) == 0:\n    raise TypeError(\"top_k operand must have >= 1 dimension, got {}\"\n                    .format(operand.shape))\n  if not (0 <= axis < len(operand.shape)):\n    raise ValueError(f\"axis argument out of range: {axis=} for {operand.shape=}\")\n  shape = list(operand.shape)\n  if shape[axis] < k:\n    raise ValueError(\"k argument to top_k must be no larger than size along axis;\"\n                     f\" got {k=} with {shape=} and {axis=}\")\n  int32_max = dtypes.iinfo('int32').max\n  try:\n    too_large = (shape[axis] > int32_max + 1)\n  except core.InconclusiveDimensionOperation:\n    pass\n  else:\n    if too_large:\n      raise ValueError(\n          'top_k returns int32 indices, which will overflow for array'\n          f' dimensions larger than the maximum int32 ({int32_max}). Got'\n          f' {operand.shape=}')\n  shape[axis] = k\n  if operand.sharding.spec[axis] is not None:\n    raise core.ShardingTypeError(","sourceCodeStart":9018,"sourceCodeEnd":9054,"githubUrl":"https://github.com/jax-ml/jax/blob/1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb/jax/_src/lax/lax.py#L9018-L9054","documentation":"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.","triggerScenarios":"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).","commonSituations":"Rank changes from batching (vmap adds a leading axis, shifting intended indices); porting NumPy code where the axis was valid for a different layout.","solutions":["Use axis=-1 for the last dimension (rank-independent).","Recompute axis after batching/reshaping steps that change rank.","Validate: assert -x.ndim <= axis < x.ndim before the call."],"exampleFix":"# before\nvals, idx = jnp.top_k(x, k, axis=1)  # x is 1-D\n# after\nvals, idx = jnp.top_k(x, k, axis=-1)","handlingStrategy":"validation","validationCode":"assert -x.ndim <= axis < x.ndim, (axis, x.shape)\nvals, idx = jnp.top_k(x, k, axis=axis)","typeGuard":"def valid_axis(x, axis):\n    return -x.ndim <= axis < x.ndim","tryCatchPattern":null,"preventionTips":["Prefer axis=-1 (rank-independent).","Recompute axis indices after vmap/reshape changes rank."],"tags":["jax","top-k","axis","out-of-bounds"],"backgroundTag":"axis-out-of-bounds","analyzedSha":"1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb","analyzedAt":"2026-08-27T09:53:25.647Z","schemaVersion":2},"datasetVersion":"2026-08-27T13:17:12.746Z"}