keras-team/keras · error · ValueError

Batch dimensions of inputs to `cdist` must be broadcastable.

Error message

Batch dimensions of inputs to `cdist` must be broadcastable. Received shapes: x.shape={x.shape}, y.shape={y.shape}

What it means

cdist broadcasts the leading (batch) dimensions of x and y via broadcast_shapes. If those batch shapes cannot be broadcast together (e.g. (4,) vs (3,)), compute_output_spec catches the underlying ValueError and re-raises it with this cdist-specific message.

Source

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

            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")
def cdist(x, y):
    """Computes pairwise distances between two collections of vectors.

    This function computes the Euclidean distance between each pair of the two
    collections of inputs.

    Args:
        x: Tensor of shape `(..., m, d)`.

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Align batch dims so one side is 1 where broadcasting is intended: ops.expand_dims(y, 0) or reshape to (1, m, d).
  2. If batches genuinely differ, loop per batch element (or vmap) instead of relying on broadcasting.
  3. Inspect x.shape[:-2] and y.shape[:-2] right before the call.

Example fix

// before
from keras import ops
x = ops.ones((4, 5, 2))
y = ops.ones((3, 6, 2))
d = ops.cdist(x, y)   # ValueError: batch dims 4 vs 3

// after
x = ops.ones((4, 5, 2))
y = ops.ones((1, 6, 2))          # broadcast one point set over the batch
d = ops.cdist(x, y)               # (4, 5, 6)
Defensive patterns

Strategy: validation

Validate before calling

from keras import ops
from keras.src.ops.operation_utils import broadcast_shapes

def cdist_batches_broadcast(x, y) -> bool:
    try:
        broadcast_shapes(x.shape[:-2], y.shape[:-2])
        return True
    except ValueError:
        return False

if not cdist_batches_broadcast(x, y):
    y = ops.expand_dims(y, 0)  # or loop over the batch

Type guard

def cdist_batchable(x, y) -> bool:
    try:
        from keras.src.ops.operation_utils import broadcast_shapes
        broadcast_shapes(x.shape[:-2], y.shape[:-2])
        return True
    except ValueError:
        return False

Prevention

When it happens

Trigger: Calling keras.ops.cdist on batched inputs x (4, 5, 2) and y (3, 6, 2) where the batch dims 4 and 3 are incompatible; comparing per-group point sets where group counts differ and neither is 1.

Common situations: Batched distance computation between point clouds with different group structure; hardcoding batch dims instead of broadcasting against a size-1 axis; padded batches where padding changed the leading dims.

Related errors


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