jax-ml/jax · error · ValueError

matrix_transpose requires at least 2 dimensions; got {ndim=}

Error message

matrix_transpose requires at least 2 dimensions; got {ndim=}

What it means

jnp.linalg.matrix_transpose only transposes the last two axes of an array, so it requires an input with ndim >= 2. Passing a scalar or 1-D vector (ndim < 2) raises this ValueError immediately, mirroring NumPy 2.0's matrix transpose semantics. The caller here was the internal _H helper, which forwards whatever object it is given to matrix_transpose.

Source

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

            [2, 4]],
    <BLANKLINE>
           [[5, 7],
            [6, 8]]], dtype=int32)

    For convenience, the same computation can be done via the
    :attr:`~jax.Array.mT` property of JAX array objects:

    >>> x.mT
    Array([[[1, 3],
            [2, 4]],
    <BLANKLINE>
           [[5, 7],
            [6, 8]]], dtype=int32)
  """
  x_arr = ensure_arraylike('jnp.linalg.matrix_transpose', x)
  ndim = x_arr.ndim
  if ndim < 2:
    raise ValueError(f"matrix_transpose requires at least 2 dimensions; got {ndim=}")
  return lax.transpose(x_arr, (*range(ndim - 2), ndim - 1, ndim - 2))


@export
def vector_norm(x: ArrayLike, /, *, axis: int | tuple[int, ...] | None = None, keepdims: bool = False,
                ord: int | str | float = 2) -> Array:
  """Compute the vector norm of a vector or batch of vectors.

  JAX implementation of :func:`numpy.linalg.vector_norm`.

  Args:
    x: N-dimensional array for which to take the norm.
    axis: optional axis along which to compute the vector norm. If None (default)
      then ``x`` is flattened and the norm is taken over all values.
    keepdims: if True, keep the reduced dimensions in the output.
    ord: A string or int specifying the type of norm; default is the 2-norm.
      See :func:`numpy.linalg.norm` for details on available options.

View on GitHub (pinned to 1e1c6a8fc0)

Solutions

  1. Check x.ndim >= 2 before calling matrix_transpose (or use .mT only on matrices).
  2. If you relied on NumPy's x.T being a no-op on 1-d arrays, keep the array unchanged instead of transposing.
  3. Reshape/expand dims: x = x.reshape(1, -1) or jnp.atleast_2d(x) if a matrix was intended.

Example fix

// before
y = jnp.linalg.matrix_transpose(jnp.array([1, 2, 3]))  # ValueError
// after
x = jnp.array([1, 2, 3])
y = x if x.ndim < 2 else jnp.linalg.matrix_transpose(x)
Defensive patterns

Strategy: validation

Validate before calling

x = jnp.asarray(x)
if x.ndim < 2:
    raise ValueError(f'expected >=2 dims, got {x.shape}')
y = jnp.linalg.matrix_transpose(x)

Type guard

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

Try / catch

try:
    y = jnp.linalg.matrix_transpose(x)
except ValueError as e:
    if 'at least 2 dimensions' in str(e):
        y = x  # 1-D/scalar transpose is identity
    else:
        raise

Prevention

When it happens

Trigger: Calling jnp.linalg.matrix_transpose(x) or x.mT where x is a Python scalar, a 0-d or 1-d jnp/NumPy array; indirectly via jax arrays' .mT property or library internals like _H on vector/scalar inputs.

Common situations: Applying .mT to what the developer assumes is a matrix but is actually a flattened vector (e.g. after jnp.ravel, squeezing batch dims away, or indexing a batch of matrices to a single row); porting NumPy code that used x.T on 1-d arrays (which is a no-op) to the stricter matrix_transpose API.

Related errors


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