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

patch_size must divide image_size

Error message

patch_size {self.patch_size} must divide image_size {self.image_size}

What it means

FrontEndConfig.grid_size guard: image_size is not an exact multiple of patch_size, so the patch grid would have fractional dimensions and the Conv2d patchifier could not tile the image.

Solutions

  1. Use standard ViT pairs like 224/16 or 224/14
  2. Resize or crop the image to a multiple of patch_size
  3. Choose a patch_size that divides the configured image_size
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at phases/19-capstone-projects/58-vision-encoder-patches/code/main.py:32 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/6a0bb29ff860a861. Report an issue: GitHub.

Appendix: source

Thrown at phases/19-capstone-projects/58-vision-encoder-patches/code/main.py:32

import math
from dataclasses import dataclass

import numpy as np
import torch
import torch.nn as nn


@dataclass(frozen=True)
class FrontEndConfig:
    image_size: int = 224
    patch_size: int = 16
    in_channels: int = 3
    hidden: int = 768

    @property
    def grid_size(self) -> int:
        if self.image_size % self.patch_size != 0:
            raise ValueError(
                f"patch_size {self.patch_size} must divide image_size {self.image_size}"
            )
        return self.image_size // self.patch_size

    @property
    def num_patches(self) -> int:
        return self.grid_size * self.grid_size


def sinusoidal_2d(grid_h: int, grid_w: int, dim: int) -> torch.Tensor:
    """Build a deterministic 2D sinusoidal position table of shape (grid_h * grid_w, dim).

    Half of dim encodes row position, half encodes column position. Within each
    half, frequencies span the standard Transformer sin/cos band. Identical
    inputs always produce identical outputs, with no learned state.
    """
    if dim % 4 != 0:
        raise ValueError(f"sinusoidal_2d dim must be divisible by 4, got {dim}")

View on GitHub (pinned to 39ea8a1c6d)