{"record":{"id":"a690d09bf3c4df5e","repo":"jax-ml/jax","slug":"matrix-transpose-requires-at-least-2-dimensions-g","errorCode":null,"errorMessage":"matrix_transpose requires at least 2 dimensions; got {ndim=}","messagePattern":"matrix_transpose requires at least 2 dimensions; got (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"jax/_src/numpy/linalg.py","lineNumber":1731,"sourceCode":"            [2, 4]],\n    <BLANKLINE>\n           [[5, 7],\n            [6, 8]]], dtype=int32)\n\n    For convenience, the same computation can be done via the\n    :attr:`~jax.Array.mT` property of JAX array objects:\n\n    >>> x.mT\n    Array([[[1, 3],\n            [2, 4]],\n    <BLANKLINE>\n           [[5, 7],\n            [6, 8]]], dtype=int32)\n  \"\"\"\n  x_arr = ensure_arraylike('jnp.linalg.matrix_transpose', x)\n  ndim = x_arr.ndim\n  if ndim < 2:\n    raise ValueError(f\"matrix_transpose requires at least 2 dimensions; got {ndim=}\")\n  return lax.transpose(x_arr, (*range(ndim - 2), ndim - 1, ndim - 2))\n\n\n@export\ndef vector_norm(x: ArrayLike, /, *, axis: int | tuple[int, ...] | None = None, keepdims: bool = False,\n                ord: int | str | float = 2) -> Array:\n  \"\"\"Compute the vector norm of a vector or batch of vectors.\n\n  JAX implementation of :func:`numpy.linalg.vector_norm`.\n\n  Args:\n    x: N-dimensional array for which to take the norm.\n    axis: optional axis along which to compute the vector norm. If None (default)\n      then ``x`` is flattened and the norm is taken over all values.\n    keepdims: if True, keep the reduced dimensions in the output.\n    ord: A string or int specifying the type of norm; default is the 2-norm.\n      See :func:`numpy.linalg.norm` for details on available options.\n","sourceCodeStart":1713,"sourceCodeEnd":1749,"githubUrl":"https://github.com/jax-ml/jax/blob/1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb/jax/_src/numpy/linalg.py#L1713-L1749","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Check x.ndim >= 2 before calling matrix_transpose (or use .mT only on matrices).","If you relied on NumPy's x.T being a no-op on 1-d arrays, keep the array unchanged instead of transposing.","Reshape/expand dims: x = x.reshape(1, -1) or jnp.atleast_2d(x) if a matrix was intended."],"exampleFix":"// before\ny = jnp.linalg.matrix_transpose(jnp.array([1, 2, 3]))  # ValueError\n// after\nx = jnp.array([1, 2, 3])\ny = x if x.ndim < 2 else jnp.linalg.matrix_transpose(x)","handlingStrategy":"validation","validationCode":"x = jnp.asarray(x)\nif x.ndim < 2:\n    raise ValueError(f'expected >=2 dims, got {x.shape}')\ny = jnp.linalg.matrix_transpose(x)","typeGuard":"def is_matrix(x) -> bool:\n    return hasattr(x, 'ndim') and getattr(x, 'ndim', 0) >= 2","tryCatchPattern":"try:\n    y = jnp.linalg.matrix_transpose(x)\nexcept ValueError as e:\n    if 'at least 2 dimensions' in str(e):\n        y = x  # 1-D/scalar transpose is identity\n    else:\n        raise","preventionTips":["Check ndim before using .mT / matrix_transpose","Use jnp.atleast_2d when a matrix is intended"],"tags":["jax","numpy","shape-validation","linalg"],"backgroundTag":"invalid-shape-argument","analyzedSha":"1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb","analyzedAt":"2026-08-27T09:53:25.647Z","schemaVersion":2},"datasetVersion":"2026-08-27T13:17:12.746Z"}