keras-team/keras · error · ValueError

Incompatible shapes between `a` and `b`. Expected `a.shape[-

Error message

Incompatible shapes between `a` and `b`. Expected `a.shape[-2] == b.shape[-2]`. Received: a.shape={a.shape}, b.shape={b.shape}

What it means

When a and b have the same rank, keras.ops.solve and keras.ops.solve_triangular require a.shape[-2] == b.shape[-2]: the number of equations (rows of the coefficient matrix) must match the rows of the right-hand side. _assert_a_b_compat raises this in the same-rank branch when the two matrix row counts disagree.

Source

Thrown at keras/src/ops/linalg.py:868

                "Expected input to have rank >= 2. "
                f"Received input with shape {a.shape}."
            )


def _assert_square(*arrays):
    for a in arrays:
        m, n = a.shape[-2:]
        if m != n:
            raise ValueError(
                "Expected a square matrix. "
                f"Received non-square input with shape {a.shape}"
            )


def _assert_a_b_compat(a, b):
    if a.ndim == b.ndim:
        if a.shape[-2] != b.shape[-2]:
            raise ValueError(
                "Incompatible shapes between `a` and `b`. "
                "Expected `a.shape[-2] == b.shape[-2]`. "
                f"Received: a.shape={a.shape}, b.shape={b.shape}"
            )
    elif a.ndim == b.ndim - 1:
        if a.shape[-1] != b.shape[-1]:
            raise ValueError(
                "Incompatible shapes between `a` and `b`. "
                "Expected `a.shape[-1] == b.shape[-1]`. "
                f"Received: a.shape={a.shape}, b.shape={b.shape}"
            )


class JVP(Operation):
    def __init__(self, has_aux=False, *, name=None):
        super().__init__(name=name)
        self.has_aux = has_aux

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Reshape b so its shape[-2] equals a.shape[-2]: for a single RHS use b.reshape(n, 1) where n == a.shape[-2].
  2. In the batched case ensure both a and b carry the same leading batch dims and b's row axis matches a's row axis (a (B, n, n), b (B, n, k)).
  3. Check that A and b were generated from the same number of equations; if b was sliced or padded differently, regenerate it consistently.

Example fix

// before
import numpy as np
from keras import ops
A = np.random.rand(3, 3)
b = np.random.rand(4)          # 4 RHS rows vs 3 equations
x = ops.solve(A, b)            # ValueError

// after
A = np.random.rand(3, 3)
b = np.random.rand(3)          # matches A's row count
x = ops.solve(A, ops.reshape(b, (3, 1)))  # shape (3, 1) result
Defensive patterns

Strategy: validation

Validate before calling

from keras import ops

def check_solve_same_rank(a, b):
    if a.ndim == b.ndim:
        sa, sb = ops.shape(a)[-2], ops.shape(b)[-2]
        assert sa is None or sb is None or sa == sb, (
            f"a.shape[-2]={sa} != b.shape[-2]={sb}")

check_solve_same_rank(A, b)
x = ops.solve(A, b)

Type guard

def rhs_matches_system(a, b) -> bool:
    return a.ndim == b.ndim and (
        a.shape[-2] is None or b.shape[-2] is None or a.shape[-2] == b.shape[-2]
    )

Prevention

When it happens

Trigger: Calling keras.ops.solve(A, b) with A of shape (3, 3) and b reshaped to (4, 1) or (2, 4, 1) vs A of (2, 3, 3); passing a stacked RHS whose per-batch row count differs from the stacked A; using solve_triangular after an LU/Cholesky factor where the RHS was sliced to a different length.

Common situations: Porting np.linalg.solve code where b of shape (n,) worked and the Keras reshape to (m, 1) introduced a mismatch; batched systems where A and b come from different data loaders with mismatched slicing; forgetting which axis of b is the row axis.

Related errors


AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25). Data as JSON: /api/errors/5d6cf684d544c35b. Report an issue: GitHub.