{"record":{"id":"e1b883fff33eba6f","repo":"jax-ml/jax","slug":"attempt-to-get-argmax-of-an-empty-sequence","errorCode":null,"errorMessage":"attempt to get argmax of an empty sequence","messagePattern":"attempt to get argmax of an empty sequence","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"jax/_src/numpy/lax_numpy.py","lineNumber":8286,"sourceCode":"    Array([[1],\n           [0]], dtype=int32)\n  \"\"\"\n  arr = util.ensure_arraylike(\"argmax\", a)\n  if out is not None:\n    raise NotImplementedError(\"The 'out' argument to jnp.argmax is not supported.\")\n  return _argmax(arr, None if axis is None else operator.index(axis),\n                 keepdims=bool(keepdims))\n\n@api.jit(static_argnames=('axis', 'keepdims'), inline=True)\ndef _argmax(a: Array, axis: int | None = None, keepdims: bool = False) -> Array:\n  if axis is None:\n    dims = list(range(np.ndim(a)))\n    a = ravel(a)\n    axis = 0\n  else:\n    dims = [axis]\n  if a.shape[axis] == 0:\n    raise ValueError(\"attempt to get argmax of an empty sequence\")\n  # TODO(phawkins): use an int64 index if the dimension is large enough.\n  result = lax.argmax(a, _canonicalize_axis(axis, a.ndim), int)\n  return expand_dims(result, dims) if keepdims else result\n\n\n@export\ndef argmin(a: ArrayLike, axis: int | None = None, out: None = None,\n           keepdims: bool | None = None) -> Array:\n  \"\"\"Return the index of the minimum value of an array.\n\n  JAX implementation of :func:`numpy.argmin`.\n\n  Args:\n    a: input array\n    axis: optional integer specifying the axis along which to find the minimum\n      value. If ``axis`` is not specified, ``a`` will be flattened.\n    out: unused by JAX\n    keepdims: if True, then return an array with the same number of dimensions","sourceCodeStart":8268,"sourceCodeEnd":8304,"githubUrl":"https://github.com/jax-ml/jax/blob/1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb/jax/_src/numpy/lax_numpy.py#L8268-L8304","documentation":"Raised by jnp.argmax when the (possibly raveled) array has zero elements along the reduction axis; argmax of an empty sequence is undefined and, unlike NumPy's error-prone behavior, JAX raises deterministically.","triggerScenarios":"jnp.argmax(jnp.array([])); jnp.argmax(a, axis=k) where a.shape[k] == 0; a filtered/computed array that became empty at runtime under jit.","commonSituations":"Data-dependent filtering (a[a > thresh]) leaving zero elements; empty batches in a training loop; edge-case shapes in tests.","solutions":["Guard with a size check: if a.size == 0 (or a.shape[axis] == 0) handle the empty case explicitly","Fix upstream filtering so the array cannot be empty","Use a sentinel: run argmax on a padded array (e.g. append -inf) and ignore the sentinel index"],"exampleFix":"// before\nidx = jnp.argmax(masked)  # may be empty\n// after\nidx = jnp.argmax(masked) if masked.size else -1\n","handlingStrategy":"validation","validationCode":"if a.size == 0: return -1  # explicit empty handling\nreturn int(jnp.argmax(a))","typeGuard":"def nonempty_for_argmax(a, axis=None):\n    a = jnp.asarray(a)\n    return a.size > 0 if axis is None else a.shape[axis] > 0","tryCatchPattern":"try:\n    idx = jnp.argmax(a)\nexcept ValueError as e:\n    if 'empty sequence' in str(e):\n        idx = -1\n    else:\n        raise","preventionTips":["Guard size before reductions on filtered arrays","Handle empty batches explicitly in loops","Beware data-dependent masks under jit — use fixed-shape masking + sentinel"],"tags":["jax","argmax","empty-array"],"backgroundTag":"argmax-of-empty-array","analyzedSha":"1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb","analyzedAt":"2026-08-27T09:53:25.647Z","schemaVersion":2},"datasetVersion":"2026-08-27T13:17:12.746Z"}