{"record":{"id":"cdfff15bda23c59f","repo":"keras-team/keras","slug":"batch-dimensions-of-inputs-to-cdist-must-be-broa","errorCode":null,"errorMessage":"Batch dimensions of inputs to `cdist` must be broadcastable. Received shapes: x.shape={x.shape}, y.shape={y.shape}","messagePattern":"Batch dimensions of inputs to `cdist` must be broadcastable\\. Received shapes: x\\.shape=(.+?), y\\.shape=(.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"keras/src/ops/math.py","lineNumber":398,"sourceCode":"            raise ValueError(\n                \"Inputs to `cdist` must have rank >= 2. \"\n                f\"Received shapes: x.shape={x.shape}, y.shape={y.shape}\"\n            )\n\n        if (\n            x.shape[-1] is not None\n            and y.shape[-1] is not None\n            and x.shape[-1] != y.shape[-1]\n        ):\n            raise ValueError(\n                \"The last dimension of inputs to `cdist` must match. \"\n                f\"Received shapes: x.shape={x.shape}, y.shape={y.shape}\"\n            )\n\n        try:\n            batch_shape = broadcast_shapes(x.shape[:-2], y.shape[:-2])\n        except ValueError:\n            raise ValueError(\n                \"Batch dimensions of inputs to `cdist` must be broadcastable. \"\n                f\"Received shapes: x.shape={x.shape}, y.shape={y.shape}\"\n            )\n\n        output_shape = tuple(batch_shape + [x.shape[-2], y.shape[-2]])\n        dtype = result_type(x.dtype, y.dtype, float)\n        return KerasTensor(shape=output_shape, dtype=dtype)\n\n\n@keras_export(\"keras.ops.cdist\")\ndef cdist(x, y):\n    \"\"\"Computes pairwise distances between two collections of vectors.\n\n    This function computes the Euclidean distance between each pair of the two\n    collections of inputs.\n\n    Args:\n        x: Tensor of shape `(..., m, d)`.","sourceCodeStart":380,"sourceCodeEnd":416,"githubUrl":"https://github.com/keras-team/keras/blob/7a34a03db60bf60042242d6a556fc3be119046a5/keras/src/ops/math.py#L380-L416","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Align batch dims so one side is 1 where broadcasting is intended: ops.expand_dims(y, 0) or reshape to (1, m, d).","If batches genuinely differ, loop per batch element (or vmap) instead of relying on broadcasting.","Inspect x.shape[:-2] and y.shape[:-2] right before the call."],"exampleFix":"// before\nfrom keras import ops\nx = ops.ones((4, 5, 2))\ny = ops.ones((3, 6, 2))\nd = ops.cdist(x, y)   # ValueError: batch dims 4 vs 3\n\n// after\nx = ops.ones((4, 5, 2))\ny = ops.ones((1, 6, 2))          # broadcast one point set over the batch\nd = ops.cdist(x, y)               # (4, 5, 6)","handlingStrategy":"validation","validationCode":"from keras import ops\nfrom keras.src.ops.operation_utils import broadcast_shapes\n\ndef cdist_batches_broadcast(x, y) -> bool:\n    try:\n        broadcast_shapes(x.shape[:-2], y.shape[:-2])\n        return True\n    except ValueError:\n        return False\n\nif not cdist_batches_broadcast(x, y):\n    y = ops.expand_dims(y, 0)  # or loop over the batch","typeGuard":"def cdist_batchable(x, y) -> bool:\n    try:\n        from keras.src.ops.operation_utils import broadcast_shapes\n        broadcast_shapes(x.shape[:-2], y.shape[:-2])\n        return True\n    except ValueError:\n        return False","tryCatchPattern":null,"preventionTips":["Design one operand with batch dim 1 when broadcasting is intended.","Loop or vmap for genuinely different group counts.","Inspect x.shape[:-2] and y.shape[:-2] in tests for all batch configurations."],"tags":["keras","cdist","pairwise-distance","broadcasting","shape-validation"],"backgroundTag":"shape-broadcasting-error","analyzedSha":"7a34a03db60bf60042242d6a556fc3be119046a5","analyzedAt":"2026-08-25T21:25:25.994Z","schemaVersion":2},"datasetVersion":"2026-08-26T02:17:13.382Z"}