jnp.nonzero with size pads with 0 instead of fill_value when the input is empty
Description
jnp.nonzero(a, size=n, fill_value=v) pads the result with 0 instead of v when a has no
elements. jnp.flatnonzero, jnp.argwhere and the one-argument jnp.where do the same, with and
without jit. An input with elements but no nonzero entries is padded with v. Since 0 is a valid
index, the caller cannot tell the padding from a result.
import jax.numpy as jnp
empty = jnp.zeros((0,), dtype=jnp.int32)
print(jnp.nonzero(empty, size=3, fill_value=99))
print(jnp.argwhere(empty, size=3, fill_value=99).ravel())
print(jnp.nonzero(jnp.zeros((3,), dtype=jnp.int32), size=3, fill_value=99))
Output on jax 0.12.0.1 (0.8.0 gives the same):
(Array([0, 0, 0], dtype=int32),)
[0 0 0]
(Array([99, 99, 99], dtype=int32),)
Expected: [99, 99, 99] on all three lines. The
jnp.nonzero docs say: "If
there are fewer nonzero elements than the specified size, then indices will be padded with
fill_value, which defaults to zero."
Possible cause: when a.size == 0, _nonzero_impl returns jnp.empty(...) and never uses
fill_value
(hijax.py#L613-L627).
System info (python version, jaxlib version, accelerator, etc.)
jax: 0.12.0.1
jaxlib: 0.12.0.1
numpy: 2.5.4
python: 3.12.16 (main, Oct 28 2026, 02:01:35) [GCC 12.2.0]
device info: cpu-1, 1 local devices"
process_count: 1
platform: uname_result(system='Linux', node='1530f43e4938', release='6.8.0-138-generic', version='#138~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Fri Aug 7 13:43:15 UTC ', machine='x86_64')
JAX_PLATFORMS=cpu
opened #42242 with a fix.
Thanks for the report! Should be fixed by #42238.