rohitg00/ai-engineering-from-scratch · error · ValueError
expected 4D input (B,C,H,W), got shape {tuple(x.shape)}
Error message
expected 4D input (B,C,H,W), got shape {tuple(x.shape)} What it means
Error "expected 4D input (B,C,H,W), got shape {tuple(x.shape)}" thrown in rohitg00/ai-engineering-from-scratch.
Source
Thrown at phases/19-capstone-projects/58-vision-encoder-patches/code/main.py:89
Output shape on a (B, C, H, W) input is (B, N, hidden) where
N = (H / patch_size) * (W / patch_size).
"""
def __init__(self, cfg: FrontEndConfig) -> None:
super().__init__()
self.cfg = cfg
self.proj = nn.Conv2d(
cfg.in_channels,
cfg.hidden,
kernel_size=cfg.patch_size,
stride=cfg.patch_size,
bias=True,
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
if x.dim() != 4:
raise ValueError(f"expected 4D input (B,C,H,W), got shape {tuple(x.shape)}")
if x.shape[1] != self.cfg.in_channels:
raise ValueError(
f"channel mismatch: got {x.shape[1]}, expected {self.cfg.in_channels}"
)
if x.shape[2] != self.cfg.image_size or x.shape[3] != self.cfg.image_size:
raise ValueError(
f"spatial mismatch: got {tuple(x.shape[2:])}, expected "
f"({self.cfg.image_size}, {self.cfg.image_size})"
)
out = self.proj(x)
b = out.shape[0]
out = out.flatten(2).transpose(1, 2)
return out
class VisionFrontEnd(nn.Module):
"""Patch embed + CLS prepend + 2D sinusoidal position.
View on GitHub (pinned to 39ea8a1c6d)
When it happens
Trigger: Thrown at phases/19-capstone-projects/58-vision-encoder-patches/code/main.py:89 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/b5558c09c167b022.
Report an issue: GitHub.