keras-team/keras · error · ValueError

Expected ` ` to have shape (B, 1, T, S) or (B, N, T, S)…

Error message

Expected `{t_name}` to have shape (B, 1, T, S) or (B, N, T, S) with N={N} but got {t.shape}.

What it means

Shape check inside _dot_product_attention_xla's grouped-attention helper: an optional tensor (bias or mask, named t_name) is promoted to 4D and its head dimension (axis 1) must be either 1 (broadcast over heads) or exactly N (query heads) so it can be broadcast across the G head groups. Any other head count fails this guard.

Solutions

  1. Reshape the bias/mask so its head axis is 1 (shared across all heads) or N (one per head)
  2. Tile a per-group bias to full head count: np.repeat(bias, G, axis=1) if you have G groups
  3. Verify N equals query.shape[2] and that you didn't pass a (B, T, S) or (B, G, T, S) tensor where heads are expected
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at keras/src/backend/jax/ops/nn.py:1857 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/bc02895aef243fab. Report an issue: GitHub.

Appendix: source

Thrown at keras/src/backend/jax/ops/nn.py:1857

    # _dot_product_attention_xla
    B, T, N, H = query.shape
    G = N // K
    query = jnp.reshape(query, (B, T, K, G, H))

    def _reshape_to_grouped(t, t_name):
        if t is not None:
            while t.ndim < 4:
                if t.ndim == 3 and t.shape[1] == N:
                    t = jnp.expand_dims(t, axis=2)
                else:
                    t = jnp.expand_dims(t, axis=1)
            tB, tN, tT, tS = t.shape
            if tN == 1:
                t = jnp.broadcast_to(t[:, :, None, :, :], (tB, tN, G, tT, tS))
            else:
                if tN != N:
                    raise ValueError(
                        f"Expected `{t_name}` to have shape (B, 1, T, S) or "
                        f"(B, N, T, S) with N={N} but got {t.shape}."
                    )
                t = jnp.reshape(t, (tB, K, G, tT, tS))
        return t

    bias = _reshape_to_grouped(bias, "bias")
    mask = _reshape_to_grouped(mask, "mask")
    vmapped_fn = jax.vmap(
        _dot_product_attention_core,
        in_axes=(3, None, None, 2, 2, None, None),
        out_axes=3,
    )
    encoded = vmapped_fn(query, key, value, bias, mask, is_causal, scale)
    return jnp.reshape(encoded, output_shape)


def unfold(input, kernel_size, dilation=1, padding=0, stride=1):

View on GitHub (pinned to 7a34a03db6)