{"record":{"id":"06522361eab633c7","repo":"jax-ml/jax","slug":"fill-value-must-be-a-scalar-or-a-tuple-of-length","errorCode":null,"errorMessage":"fill_value must be a scalar or a tuple of length {arr.ndim}; got {fill_value}","messagePattern":"fill_value must be a scalar or a tuple of length (.+?); got (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"jax/_src/numpy/lax_numpy.py","lineNumber":3733,"sourceCode":"    raise ValueError(\"Calling nonzero on 0d arrays is not allowed. \"\n                     \"Use jnp.atleast_1d(scalar).nonzero() instead.\")\n  mask = arr if arr.dtype == bool else (arr != 0)\n  calculated_size_ = mask.sum() if size is None else size\n  calculated_size: int = core.concrete_dim_or_error(calculated_size_,\n    \"The size argument of jnp.nonzero must be statically specified \"\n    \"to use jnp.nonzero within JAX transformations.\")\n  if arr.size == 0 or calculated_size == 0:\n    return tuple(array_creation.zeros(calculated_size, int) for dim in arr.shape)\n  flat_indices = reductions.cumsum(\n      bincount(reductions.cumsum(mask), length=calculated_size))\n  strides: np.ndarray = np.cumprod(arr.shape[::-1])[::-1] // arr.shape\n  if all(core.is_constant_dim(d) for d in strides):\n    strides = strides.astype(flat_indices.dtype)\n  out = tuple((flat_indices // stride) % size for stride, size in zip(strides, arr.shape))\n  if fill_value is not None:\n    fill_value_tup = fill_value if isinstance(fill_value, tuple) else arr.ndim * (fill_value,)\n    if any(np.shape(val) != () for val in fill_value_tup):\n      raise ValueError(f\"fill_value must be a scalar or a tuple of length {arr.ndim}; got {fill_value}\")\n    fill_mask = arange(calculated_size) >= mask.sum()\n    out = tuple(where(fill_mask, fval, entry) for fval, entry in safe_zip(fill_value_tup, out))\n  return out\n\n\n@export\ndef flatnonzero(a: ArrayLike, *, size: int | None = None,\n                fill_value: None | ArrayLike | tuple[ArrayLike, ...] = None) -> Array:\n  \"\"\"Return indices of nonzero elements in a flattened array\n\n  JAX implementation of :func:`numpy.flatnonzero`.\n\n  ``jnp.flatnonzero(x)`` is equivalent to ``nonzero(ravel(a))[0]``. For a full\n  discussion of the parameters to this function, refer to :func:`jax.numpy.nonzero`.\n\n  Args:\n    a: N-dimensional array.\n    size: optional static integer specifying the number of nonzero entries to","sourceCodeStart":3715,"sourceCodeEnd":3751,"githubUrl":"https://github.com/jax-ml/jax/blob/1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb/jax/_src/numpy/lax_numpy.py#L3715-L3751","documentation":"In jnp.nonzero(..., fill_value=...), each fill value must be a scalar (0-d shape). A fill_value (or element of a tuple fill_value) with non-empty shape is rejected, since output padding entries must be scalars per dimension.","triggerScenarios":"jnp.nonzero(x, size=5, fill_value=jnp.array([0])) — a 1-element array is not a scalar; or a tuple element that is a 1-d array.","commonSituations":"Passing fill_value loaded from config as an array; reusing index-typed defaults like fill_value=jnp.zeros(1); tuple fill values built from per-dimension arrays.","solutions":["Pass Python scalars or 0-d values: fill_value=0 or fill_value=(0, 0)","Convert arrays: fill_value=int(fv) or fv.item()","Verify each element of tuple fill_value has np.shape(val) == ()"],"exampleFix":"// before\njnp.nonzero(x, size=5, fill_value=jnp.array([0]))\n// after\njnp.nonzero(x, size=5, fill_value=0)","handlingStrategy":"validation","validationCode":"if fill_value is not None:\n    if not isinstance(fill_value, tuple):\n        fill_value = (fill_value,) * ndim\n    fill_value = tuple(v.item() if hasattr(v, 'item') else v for v in fill_value)","typeGuard":"def is_scalar_fill(v) -> bool:\n    import numpy as np\n    return np.shape(v) == ()","tryCatchPattern":null,"preventionTips":["Always pass Python scalars as fill_value","Validate tuple elements have () shape in wrappers"],"tags":["jax","nonzero","fill-value","scalar-validation"],"backgroundTag":"non-scalar-fill-value","analyzedSha":"1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb","analyzedAt":"2026-08-27T09:53:25.647Z","schemaVersion":2},"datasetVersion":"2026-08-27T13:17:12.746Z"}