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

hidden not divisible by heads

Error message

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

What it means

ViTConfig.head_dim guard: hidden is not evenly divisible by heads, so per-head dimension would be fractional and the qkv reshape into (B,N,3,H,hd) could not be formed.

Solutions

  1. Use compatible pairs like hidden=768 with heads=12
  2. Choose heads as a divisor of hidden
  3. Adjust hidden to the nearest multiple of heads
Defensive patterns

Strategy: validation

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.

Appendix: 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)