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

hidden {self.hidden} not divisible by heads {self.heads}

Error message

hidden {self.hidden} not divisible by heads {self.heads}

What it means

Error "hidden {self.hidden} not divisible by heads {self.heads}" thrown in rohitg00/ai-engineering-from-scratch.

Source

Thrown at phases/19-capstone-projects/59-vit-transformer/code/main.py:62

VisionFrontEnd = _front_module.VisionFrontEnd
synthesize_image = _front_module.synthesize_image


@dataclass(frozen=True)
class ViTConfig:
    image_size: int = 224
    patch_size: int = 16
    in_channels: int = 3
    hidden: int = 768
    depth: int = 12
    heads: int = 12
    mlp_ratio: float = 4.0
    dropout: float = 0.0

    @property
    def head_dim(self) -> int:
        if self.hidden % self.heads != 0:
            raise ValueError(f"hidden {self.hidden} not divisible by heads {self.heads}")
        return self.hidden // self.heads

    def front_end_config(self) -> FrontEndConfig:
        return FrontEndConfig(
            image_size=self.image_size,
            patch_size=self.patch_size,
            in_channels=self.in_channels,
            hidden=self.hidden,
        )


class MultiHeadSelfAttention(nn.Module):
    def __init__(self, cfg: ViTConfig) -> None:
        super().__init__()
        self.cfg = cfg
        self.qkv = nn.Linear(cfg.hidden, cfg.hidden * 3, bias=True)
        self.out = nn.Linear(cfg.hidden, cfg.hidden, bias=True)
        self.drop = nn.Dropout(cfg.dropout)

View on GitHub (pinned to 39ea8a1c6d)

When it happens

Trigger: Thrown at phases/19-capstone-projects/59-vit-transformer/code/main.py:62 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/27f9a3bce10abb54. Report an issue: GitHub.