jax-ml/jax · error · ValueError

n must be a positive integer; got {n}.

Error message

n must be a positive integer; got {n}.

What it means

jax.scipy.linalg.convolution_matrix builds an n-column convolution matrix and requires n to be a positive Python integer (it goes through operator.index, which also rejects floats/strings with TypeError). n <= 0 raises this ValueError because a zero/negative output width is meaningless.

Source

Thrown at jax/_src/scipy/linalg.py:2851

  Returns:
    A convolution matrix of shape ``(..., k, n)``, where ``k`` depends on
    ``mode`` as described above.

  See also:
    :func:`jax.scipy.linalg.toeplitz`

  Examples:
    >>> jax.scipy.linalg.convolution_matrix(jnp.array([-1, 4, -2]), 5, mode='same')
    Array([[ 4, -1,  0,  0,  0],
           [-2,  4, -1,  0,  0],
           [ 0, -2,  4, -1,  0],
           [ 0,  0, -2,  4, -1],
           [ 0,  0,  0, -2,  4]], dtype=int32)
  """
  n = operator.index(n)
  if n <= 0:
    raise ValueError(f"n must be a positive integer; got {n}.")
  check_arraylike("convolution_matrix", a)
  a_arr = jnp.asarray(a)
  if a_arr.ndim == 0:
    raise ValueError(
        "convolution_matrix: a must be at least 1-dimensional, got a scalar.")
  m = a_arr.shape[-1]
  if m < 1:
    raise ValueError(f"len(a) must be at least 1; got shape {a_arr.shape}.")
  if mode not in ('full', 'valid', 'same'):
    raise ValueError(
        f"mode must be one of 'full', 'valid', 'same'; got {mode!r}.")
  pad_widths = [(0, 0)] * (a_arr.ndim - 1) + [(0, n - 1)]
  az = jnp.pad(a_arr, pad_widths)
  raz = jnp.pad(jnp.flip(a_arr, axis=-1), pad_widths)
  L = m + n - 1
  if mode == 'same':
    trim = min(n, m) - 1
    tb = trim // 2

View on GitHub (pinned to 1e1c6a8fc0)

Solutions

  1. Ensure n is a plain positive int (use int(n) if it's a numpy/float value)
  2. Fix the arithmetic producing n <= 0 and handle the degenerate case before calling
  3. Under jit, mark n as static or pass it as a Python constant

Example fix

# before
C = convolution_matrix(a, len(b) - len(a))  # may be 0
# after
n = len(b) - len(a)
if n <= 0:
    raise ValueError('insufficient output length')
C = convolution_matrix(a, n)
Defensive patterns

Strategy: validation

Validate before calling

import operator
n = operator.index(n)  # raises TypeError early for non-integers
if n <= 0:
    raise ValueError(f'n must be positive, got {n}')
C = convolution_matrix(a, n)

Type guard

def is_positive_int(n) -> bool:
    return isinstance(n, int) and not isinstance(n, bool) and n > 0

Try / catch

try:
    convolution_matrix(a, n)
except ValueError as e:
    if 'n must be a positive integer' in str(e):
        raise ValueError('output width computed as non-positive; check inputs') from e
    raise

Prevention

When it happens

Trigger: Calling convolution_matrix(a, 0), convolution_matrix(a, -3), or with a numpy scalar/float like np.int64(5) wrapped incorrectly or n as a traced JAX value (operator.index fails during tracing).

Common situations: Computing n from a difference that evaluates to 0 (e.g. len(b) - len(a)); passing n as a jnp scalar under jit; passing n as float 5.0.

Related errors


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