rohitg00/ai-engineering-from-scratch · error · ValueError

hidden must divide by heads

Error message

hidden must divide by heads

What it means

Error "hidden must divide by heads" thrown in rohitg00/ai-engineering-from-scratch.

Source

Thrown at phases/19-capstone-projects/38-classifier-finetuning/code/main.py:63

        while len(raw) < max_len:
            raw.append(self.PAD_ID)
            attn.append(0)
        return raw, attn

    def decode(self, ids: Sequence[int]) -> str:
        return bytes(i for i in ids if i < 256).decode("utf-8", errors="replace")


# ---------------------------------------------------------------------------
# Tiny transformer body
# ---------------------------------------------------------------------------


class MultiHeadAttention(nn.Module):
    def __init__(self, hidden: int, heads: int):
        super().__init__()
        if hidden % heads != 0:
            raise ValueError("hidden must divide by heads")
        self.heads = heads
        self.head_dim = hidden // heads
        self.qkv = nn.Linear(hidden, hidden * 3, bias=False)
        self.out = nn.Linear(hidden, hidden, bias=False)

    def forward(self, x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
        B, T, D = x.shape
        qkv = self.qkv(x).view(B, T, 3, self.heads, self.head_dim).permute(2, 0, 3, 1, 4)
        q, k, v = qkv[0], qkv[1], qkv[2]
        att = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)
        # mask: B x T, 1 for real, 0 for pad. broadcast to B x 1 x 1 x T.
        m = mask.view(B, 1, 1, T).to(att.dtype)
        att = att.masked_fill(m == 0, float("-inf"))
        weights = F.softmax(att, dim=-1)
        # Replace nan rows (all-pad keys, never happens for valid input) with zeros.
        weights = torch.nan_to_num(weights, nan=0.0)
        ctx = (weights @ v).transpose(1, 2).contiguous().view(B, T, D)
        return self.out(ctx)

View on GitHub (pinned to 39ea8a1c6d)

When it happens

Trigger: Thrown at phases/19-capstone-projects/38-classifier-finetuning/code/main.py:63 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of rohitg00/ai-engineering-from-scratch@39ea8a1c6d (2026-08-26). Data as JSON: /api/errors/13a07d839e032eba. Report an issue: GitHub.