rohitg00/ai-engineering-from-scratch · error · ValueError
image_size ( ) must be divisible by patch_size ( )
Error message
image_size ({image_size}) must be divisible by patch_size ({patch_size}) What it means
Divisibility check in grid_shape: image_size % patch_size must be 0 so the image tiles exactly into a square patch grid; a remainder would mean edge patches are cropped or padded, which this patch-token implementation forbids.
Solutions
- Choose a patch_size that divides image_size exactly, e.g. 224/16 or 224/14
- Resize the image to the nearest compatible multiple before patching
- Add explicit padding logic if fractional grids must be supported
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at phases/12-multimodal-ai/01-vision-transformer-patch-tokens/code/main.py:44 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/f370f2eb8fb4f7a4.
Report an issue: GitHub.
Appendix: source
Thrown at phases/12-multimodal-ai/01-vision-transformer-patch-tokens/code/main.py:44
registers: int = 0
cls_token: bool = True
ZOO = [
ViTConfig("ViT-B/16 @ 224", 224, 16, 768, 12, 12),
ViTConfig("ViT-L/14 @ 336 (CLIP)", 336, 14, 1024, 24, 16),
ViTConfig("DINOv2 ViT-g/14 @ 224", 224, 14, 1536, 40, 24, registers=4),
ViTConfig("SigLIP SO400m/14 @ 378", 378, 14, 1152, 27, 16, registers=4,
cls_token=False),
ViTConfig("Qwen2.5-VL ViT @ 896x896", 896, 14, 1280, 32, 16),
]
def grid_shape(image_size: int, patch_size: int) -> tuple[int, int]:
if image_size <= 0 or patch_size <= 0:
raise ValueError(f"image_size and patch_size must be positive, got {image_size=} {patch_size=}")
if image_size % patch_size != 0:
raise ValueError(f"image_size ({image_size}) must be divisible by patch_size ({patch_size})")
g = image_size // patch_size
return (g, g)
def seq_length(cfg: ViTConfig) -> int:
h, w = grid_shape(cfg.image_size, cfg.patch_size)
extra = (1 if cfg.cls_token else 0) + cfg.registers
return h * w + extra
def patch_embed_params(cfg: ViTConfig) -> int:
p = cfg.patch_size
return 3 * p * p * cfg.hidden + cfg.hidden
def pos_embed_params(cfg: ViTConfig) -> int:
return seq_length(cfg) * cfg.hidden
View on GitHub (pinned to 39ea8a1c6d)