keras-team/keras · error · ValueError

The last dimension of inputs to `cdist` must match. Received

Error message

The last dimension of inputs to `cdist` must match. Received shapes: x.shape={x.shape}, y.shape={y.shape}

What it means

cdist computes distances between corresponding points, so the feature dimension (last axis) of x and y must match. Cdist.compute_output_spec raises this when both x.shape[-1] and y.shape[-1] are statically known and unequal.

Source

Thrown at keras/src/ops/math.py:390

            y, -3
        )
        return backend.numpy.sqrt(
            backend.numpy.sum(backend.numpy.square(diff), axis=-1)
        )

    def compute_output_spec(self, x, y):
        if x.ndim < 2 or y.ndim < 2:
            raise ValueError(
                "Inputs to `cdist` must have rank >= 2. "
                f"Received shapes: x.shape={x.shape}, y.shape={y.shape}"
            )

        if (
            x.shape[-1] is not None
            and y.shape[-1] is not None
            and x.shape[-1] != y.shape[-1]
        ):
            raise ValueError(
                "The last dimension of inputs to `cdist` must match. "
                f"Received shapes: x.shape={x.shape}, y.shape={y.shape}"
            )

        try:
            batch_shape = broadcast_shapes(x.shape[:-2], y.shape[:-2])
        except ValueError:
            raise ValueError(
                "Batch dimensions of inputs to `cdist` must be broadcastable. "
                f"Received shapes: x.shape={x.shape}, y.shape={y.shape}"
            )

        output_shape = tuple(batch_shape + [x.shape[-2], y.shape[-2]])
        dtype = result_type(x.dtype, y.dtype, float)
        return KerasTensor(shape=output_shape, dtype=dtype)


@keras_export("keras.ops.cdist")

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Project one side so feature dims match (a Dense layer, or pad/truncate to a common d), then call cdist.
  2. Fix the layout: operands must be (..., n, d) with the same d; use ops.transpose if coordinates are axis-first.
  3. Assert x.shape[-1] == y.shape[-1] before the call to fail with your own context.

Example fix

// before
from keras import ops
x = ops.ones((10, 3))
y = ops.ones((7, 2))
d = ops.cdist(x, y)   # ValueError: 3 != 2

// after
x = ops.ones((10, 3))
y = ops.pad(ops.ones((7, 2)), [[0, 0], [0, 1]])  # match feature dim
d = ops.cdist(x, y)
Defensive patterns

Strategy: validation

Validate before calling

from keras import ops

def assert_cdist_feature_match(x, y):
    fx, fy = x.shape[-1], y.shape[-1]
    assert fx is None or fy is None or fx == fy, (
        f"feature dims differ: {fx} vs {fy}")

assert_cdist_feature_match(x, y)
d = ops.cdist(x, y)

Type guard

def cdist_features_match(x, y) -> bool:
    a, b = x.shape[-1], y.shape[-1]
    return a is None or b is None or a == b

Prevention

When it happens

Trigger: Calling keras.ops.cdist(x, y) with x of shape (N, 3) and y of shape (M, 2); comparing embeddings from two encoders with different output dims; forgetting to transpose coordinate arrays so the feature axis is not last.

Common situations: Two-branch Siamese/contrastive models whose towers have different output dims; mixing row-major vs column-major coordinate layouts; comparing a (T, D) time series against a (D, K) codebook transposed incorrectly.

Related errors


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