jax-ml/jax · error · ValueError
index can't contain negative values
Error message
index can't contain negative values
What it means
jnp.pad rejects pad_width containing negative values; negative padding (numpy also disallows effective shrinking via negative widths in jnp) cannot be expressed, so any negative entry raises ValueError 'index can't contain negative values'.
Source
Thrown at jax/_src/numpy/lax_numpy.py:4191
nd = np.ndim(array)
if nd == 0:
return array
stat_funcs: dict[str, PadStatFunc] = {
"maximum": reductions.amax,
"minimum": reductions.amin,
"mean": reductions.mean,
"median": reductions.median
}
pad_width = _broadcast_to_pairs(pad_width, nd, "pad_width")
pad_width_arr = np.array(pad_width)
if pad_width_arr.shape != (nd, 2):
raise ValueError(f"Expected pad_width to have shape {(nd, 2)}; got {pad_width_arr.shape}.")
if np.any(pad_width_arr < 0):
raise ValueError("index can't contain negative values")
if mode == "constant":
return _pad_constant(array, pad_width, asarray(constant_values))
elif mode == "wrap":
return _pad_wrap(array, pad_width)
elif mode in ("symmetric", "reflect"):
return _pad_symmetric_or_reflect(array, pad_width, str(mode), reflect_type)
elif mode == "edge":
return _pad_edge(array, pad_width)
elif mode == "linear_ramp":
end_values = _broadcast_to_pairs(end_values, nd, "end_values")
return _pad_linear_ramp(array, pad_width, end_values)
elif mode in stat_funcs:View on GitHub (pinned to 1e1c6a8fc0)
Solutions
- Clamp computed widths: max(0, target - x.shape[0])
- Use dynamic_slice or lax.slice to actually crop when shrink is intended
Example fix
// before jnp.pad(x, (target - x.shape[0], 0)) // after jnp.pad(x, (max(0, target - x.shape[0]), 0))
Defensive patterns
Strategy: validation
Validate before calling
assert np.all(np.asarray(pad_width) >= 0), 'negative pad width'
Prevention
- Clamp computed widths with max(0, ...); use slicing for cropping
When it happens
Trigger: jnp.pad(x, (-1, 2)) or computed widths that go negative, e.g. (target_len - x.shape[0]) when the array is already longer than target.
Common situations: Padding sequences to a fixed length where some inputs already exceed the target, making the computed pad amount negative.
Related errors
- `{name}` entries must be the same shape: {nvals}
- jnp.pad: {name} with {nd=} has unsupported shape {nvals.shap
- Cannot apply '{}' padding to empty axis
- jnp.pad: constant_values has unsupported shape {constant_val
- Shape polymorphism is supported for jnp.pad with 'reflect' o
AI-assisted analysis of jax-ml/jax@1e1c6a8fc0 (2026-08-27).
Data as JSON: /api/errors/e569a093b7f7dab5.
Report an issue: GitHub.