keras-team/keras · error · ValueError

Cannot do batch_dot on inputs with shapes

Error message

Cannot do batch_dot on inputs with shapes {x_shape} and {y_shape} with axes={axes}. x.shape[{axes[0]}] != y.shape[{axes[1]}] ({d1} != {d2}).

What it means

Final dimension check in batch_dot: after axes are resolved to non-negative indices, the sizes of the two contracted axes (d1 on x, d2 on y) must be equal for the inner product to be defined; a mismatch in those specific positions raises this error.

Solutions

  1. Make the contracted dimensions equal: adjust the last dense layer size, embedding dim, or reshape so x.shape[axes[0]] == y.shape[axes[1]]
  2. Choose different axes whose sizes already match (e.g. axes=(-1, -1) to contract the feature dims)
  3. If shapes are dynamic (None), verify with concrete data that the actual runtime sizes match
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at keras/src/layers/merging/dot.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/f6f78970d74c4aaf. Report an issue: GitHub.

Appendix: source

Thrown at keras/src/layers/merging/dot.py:116

    if axes[0] < 0:
        axes[0] += x_ndim
    if axes[1] < 0:
        axes[1] += y_ndim

    # sanity checks
    if 0 in axes:
        raise ValueError(
            "Cannot perform batch_dot over axis 0. "
            "If your inputs are not batched, "
            "add a dummy batch dimension to your "
            "inputs using keras.ops.expand_dims(x, 0)"
        )
    a0, a1 = axes
    d1 = x_shape[a0]
    d2 = y_shape[a1]

    if d1 is not None and d2 is not None and d1 != d2:
        raise ValueError(
            f"Cannot do batch_dot on inputs with shapes "
            f"{x_shape} and {y_shape} with axes={axes}. "
            f"x.shape[{axes[0]}] != y.shape[{axes[1]}] ({d1} != {d2})."
        )

    # backup ndims. Need them later.
    orig_x_ndim = x_ndim
    orig_y_ndim = y_ndim

    # if rank is 2, expand to 3.
    if x_ndim == 2:
        x = ops.expand_dims(x, 1)
        a0 += 1
        x_ndim += 1
    if y_ndim == 2:
        y = ops.expand_dims(y, 2)
        y_ndim += 1

View on GitHub (pinned to 7a34a03db6)