jax-ml/jax · error · ValueError

jnp.linalg.cond: input array must be at least 2D; got {arr.s

Error message

jnp.linalg.cond: input array must be at least 2D; got {arr.shape=}

What it means

jnp.linalg.cond computes the condition number, which is defined via singular values or matrix norms of a matrix (its last two axes). A 0-D or 1-D input has no matrix structure, so cond refuses it rather than returning something meaningless.

Source

Thrown at jax/_src/numpy/linalg.py:2291

  Examples:

    Well-conditioned matrix:

    >>> x = jnp.array([[1, 2],
    ...                [2, 1]])
    >>> jnp.linalg.cond(x)
    Array(3., dtype=float32)

    Ill-conditioned matrix:

    >>> x = jnp.array([[1, 2],
    ...                [0, 0]])
    >>> jnp.linalg.cond(x)
    Array(inf, dtype=float32)
  """
  arr = ensure_arraylike("cond", x)
  if arr.ndim < 2:
    raise ValueError(f"jnp.linalg.cond: input array must be at least 2D; got {arr.shape=}")
  if arr.shape[-1] == 0 or arr.shape[-2] == 0:
    raise ValueError(f"jnp.linalg.cond: input array must not be empty; got {arr.shape=}")
  if p is None or p == 2:
    s = svdvals(x)
    return s[..., 0] / s[..., -1]
  elif p == -2:
    s = svdvals(x)
    r = s[..., -1] / s[..., 0]
  else:
    if arr.shape[-2] != arr.shape[-1]:
      raise ValueError(f"jnp.linalg.cond: for {p=}, array must be square; got {arr.shape=}")
    r = norm(x, ord=p, axis=(-2, -1)) * norm(inv(x), ord=p, axis=(-2, -1))
  # Convert NaNs to infs where original array has no NaNs.
  return jnp.where(ufuncs.isnan(r) & ~ufuncs.isnan(x).any(axis=(-2, -1)), np.inf, r)


@export
def trace(x: ArrayLike, /, *,

View on GitHub (pinned to 1e1c6a8fc0)

Solutions

  1. Ensure input has ndim >= 2; use jnp.atleast_2d(x) if a matrix was intended.
  2. If you meant the ratio of largest to smallest magnitude element of a vector, compute jnp.max(jnp.abs(x)) / jnp.min(jnp.abs(x)) yourself.
  3. Check the shape your data actually has (print x.shape) before calling.

Example fix

// before
c = jnp.linalg.cond(v)  # v: (n,)
// after
c = jnp.linalg.cond(jnp.atleast_2d(v))  # or diag/v2d as appropriate
Defensive patterns

Strategy: validation

Validate before calling

x = jnp.asarray(x)
if x.ndim < 2:
    x = jnp.atleast_2d(x)
c = jnp.linalg.cond(x)

Type guard

def is_at_least_2d(x) -> bool:
    return getattr(x, 'ndim', 0) >= 2

Prevention

When it happens

Trigger: jnp.linalg.cond(x) with x a scalar, vector, or 1-D array; passing a list of numbers that becomes shape (n,).

Common situations: Indexing a batch of matrices with a single index but landing on a vector (e.g. mats[i] on shape (B, N) storage); assuming cond of a vector means max/min abs ratio (it doesn't — that's a different computation).

Related errors


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