jax-ml/jax · error · ValueError

jnp.pad: constant_values has unsupported shape {constant_val

Error message

jnp.pad: constant_values has unsupported shape {constant_values.shape}. If the shape is 1D or 2D, the last dimension must be of size 1 or 2.

What it means

For mode='constant', jnp.pad requires constant_values to be a scalar or have last dimension of size 1 or 2 (one value, or before/after values per axis). A 1-D constant_values with last dim other than 1 or 2 is invalid.

Source

Thrown at jax/_src/numpy/lax_numpy.py:3950

    raise ValueError(msg.format(mode))


def _pad_constant(array: Array, pad_width: PadValue[int], constant_values: Array) -> Array:
  nd = np.ndim(array)
  constant_values = lax._convert_element_type(
      constant_values, array.dtype, dtypes.is_weakly_typed(array))
  constant_values_nd = np.ndim(constant_values)

  if constant_values_nd == 0:
    widths = [(low, high, 0) for (low, high) in pad_width]
    return lax.pad(array, constant_values, widths)

  if constant_values_nd == 1:
    if constant_values.shape[-1] == 1:
      widths = [(low, high, 0) for (low, high) in pad_width]
      return lax.pad(array, squeeze(constant_values), widths)
    elif constant_values.shape[-1] != 2:
      raise ValueError("jnp.pad: constant_values has unsupported shape "
                      f"{constant_values.shape}. If the shape is 1D or 2D, the "
                      "last dimension must be of size 1 or 2.")

  constant_values = broadcast_to(constant_values, (nd, 2))
  for i in range(nd):
    widths = [(0, 0, 0)] * nd
    if pad_width[i][0] != 0:
      widths[i] = (pad_width[i][0], 0, 0)
      array = lax.pad(array, constant_values[i, 0], widths)
    if pad_width[i][1] != 0:
      widths[i] = (0, pad_width[i][1], 0)
      array = lax.pad(array, constant_values[i, 1], widths)
  return array


def _pad_wrap(array: Array, pad_width: PadValue[int]) -> Array:
  for i in range(np.ndim(array)):
    if array.shape[i] == 0:

View on GitHub (pinned to 1e1c6a8fc0)

Solutions

  1. Use a scalar constant, a (nd,1) or (nd,2) array, or a single pair

Example fix

// before
jnp.pad(x, 1, constant_values=[1, 2, 3])
// after
jnp.pad(x, 1, constant_values=[(1, 2), (1, 2)])
Defensive patterns

Strategy: validation

Validate before calling

cv = np.asarray(constant_values)
assert cv.ndim == 0 or cv.shape[-1] in (1, 2), 'constant_values last dim must be 1 or 2'

Prevention

When it happens

Trigger: jnp.pad(x, 2, constant_values=jnp.array([1,2,3])) — shape (3,), last dim is 3, invalid.

Common situations: Passing per-axis constant lists of the wrong length, e.g. 3 values for a 2-axis problem, or forgetting to nest per-axis pairs.

Related errors


AI-assisted analysis of jax-ml/jax@1e1c6a8fc0 (2026-08-27). Data as JSON: /api/errors/31c30af55f799b49. Report an issue: GitHub.