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[-1] == b.shape[-1]`. Received: a.shape={a.shape}, b.shape={b.shape} What it means
In the rank(a) == rank(b) - 1 branch of _assert_a_b_compat, keras.ops.solve / keras.ops.solve_triangular treat b as a batch of vectors and require a.shape[-1] == b.shape[-1]: the number of unknowns must equal the length of each RHS vector. This error means the coefficient matrix's column count differs from the right-hand-side vector length.
Source
Thrown at keras/src/ops/linalg.py:875
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
def call(self, fun, primals, tangents):
"""Computes the JVP of `fun` at `primals` along `tangents`.
Args:
fun: A callable that takes tensors (or nested structures) as input
and returns a tensor (or nested structure) as output.
primals: Input tensors (or nested structures) at which the JacobianView on GitHub (pinned to 7a34a03db6)
Solutions
- Align dimensions: build b with b.shape[-1] == a.shape[-1]; for multiple RHS use shape (n, k) so ranks match and the row rule applies.
- Audit where b is produced and ensure it is not a slice/padding artifact with a different length than the system size.
- Add a pre-call check: assert a.shape[-1] == b.shape[-1] (vector case) or a.shape[-2] == b.shape[-2] (matrix case).
Example fix
// before from keras import ops import numpy as np A = np.random.rand(5, 5) b = np.random.rand(7) # length 7, but 5 unknowns x = ops.solve(A, b) # ValueError // after A = np.random.rand(5, 5) b = np.random.rand(5) # one entry per unknown x = ops.solve(A, b)
Defensive patterns
Strategy: validation
Validate before calling
from keras import ops
def check_solve_vector_case(a, b):
if a.ndim == b.ndim - 1:
sa, sb = ops.shape(a)[-1], ops.shape(b)[-1]
assert sa is None or sb is None or sa == sb, (
f"a.shape[-1]={sa} != b.shape[-1]={sb}")
check_solve_vector_case(A, b)
x = ops.solve(A, b) Type guard
def vector_rhs_matches(a, b) -> bool:
return a.ndim == b.ndim - 1 and (
a.shape[-1] is None or b.shape[-1] is None or a.shape[-1] == b.shape[-1]
) Prevention
- Prefer a matrix RHS (n, k) over a vector RHS to hit the clearer row rule.
- Assemble b from the same code that sizes A.
- Add shape asserts in custom layer call() before solve.
When it happens
Trigger: Calling keras.ops.solve(A, b) with A of shape (3, 3) and b of shape (4,) (rank differs by one), or batched A (B, 5, 5) with vectors b of shape (B, 4); using solve_triangular with a factor of size n but an RHS vector of length m != n.
Common situations: Solving square systems where the RHS was assembled from a different feature dimension; migrating from np.linalg.solve where NumPy raises its own mismatch error, making the Keras requirement non-obvious; feeding flattened labels of the wrong length as b.
Related errors
- Incompatible shapes between `a` and `b`. Expected `a.shape[-
- Expected input to have rank >= 2. Received input with shape
- Expected a square matrix. Received non-square input with sha
- The `weights` argument should be either `None` (random initi
- Expected mode to be one of `caffe`, `tf` or `torch`. Receive
AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25).
Data as JSON: /api/errors/c73ba75c09f27cbb.
Report an issue: GitHub.