keras-team/keras · error · ValueError

Last dimension of inputs to `cdist` must match

Error message

Last dimension of inputs to `cdist` must match

What it means

Feature-dimension guard in the NumPy backend's `cdist`: pairwise distances are only defined between points living in the same space, so after the rank check the implementation verifies `x.shape[-1] == y.shape[-1]`. Mismatched feature dimensions (e.g. comparing 128-D against 256-D embeddings) fail this equality check and the call is rejected.

Solutions

  1. Project or slice both inputs to the same feature dimension (e.g. x[..., :D] with D = min of the two)
  2. Fix a pipeline bug where one embedding set was produced by a different model/dimension than the other
  3. Pad the smaller feature dimension (e.g. zeros) only if that is semantically valid for the comparison
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at keras/src/backend/numpy/ops/math.py:116 when the library encounters an invalid state.

Common situations: See trigger scenarios.


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

Appendix: source

Thrown at keras/src/backend/numpy/ops/math.py:116

def logsumexp(x, axis=None, keepdims=False):
    x = convert_to_tensor(x)
    dtype = dtypes.result_type(x.dtype, float)
    return scipy.special.logsumexp(x, axis=axis, keepdims=keepdims).astype(
        dtype
    )


def cdist(x, y):
    x = np.asarray(x)
    y = np.asarray(y)
    dtype = dtypes.result_type(x.dtype, y.dtype, float)
    x = x.astype(dtype)
    y = y.astype(dtype)
    if x.ndim < 2 or y.ndim < 2:
        raise ValueError("`cdist` inputs must have rank >= 2")
    if x.shape[-1] != y.shape[-1]:
        raise ValueError("Last dimension of inputs to `cdist` must match")
    diff = x[..., :, None, :] - y[..., None, :, :]
    return np.sqrt(np.sum(diff * diff, axis=-1))


def extract_sequences(x, sequence_length, sequence_stride):
    *batch_shape, _ = x.shape
    batch_shape = list(batch_shape)
    shape = x.shape[:-1] + (
        (x.shape[-1] - (sequence_length - sequence_stride)) // sequence_stride,
        sequence_length,
    )
    strides = x.strides[:-1] + (
        sequence_stride * x.strides[-1],
        x.strides[-1],
    )
    x = np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides)
    return np.reshape(x, (*batch_shape, *x.shape[-2:]))

View on GitHub (pinned to 7a34a03db6)