rohitg00/ai-engineering-from-scratch · error · ValueError
sinusoidal_2d dim must be divisible by 4, got
Error message
sinusoidal_2d dim must be divisible by 4, got {dim} What it means
Position-embedding guard in sinusoidal_2d: dim is not divisible by 4, but the table splits dim into row/column halves that each need an even number of sin/cos channels.
Solutions
- Use a dim divisible by 4 (e.g. 768)
- Round dim up to the next multiple of 4 and truncate if exact shape is required
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at phases/19-capstone-projects/58-vision-encoder-patches/code/main.py:50 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/f6094dd9ededf5f2.
Report an issue: GitHub.
Appendix: source
Thrown at phases/19-capstone-projects/58-vision-encoder-patches/code/main.py:50
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}")
half = dim // 2
quarter = half // 2
freq = torch.arange(quarter, dtype=torch.float32)
inv = torch.exp(-math.log(10000.0) * freq / max(1, quarter))
rows = torch.arange(grid_h, dtype=torch.float32).unsqueeze(1) * inv.unsqueeze(0)
cols = torch.arange(grid_w, dtype=torch.float32).unsqueeze(1) * inv.unsqueeze(0)
row_emb = torch.cat([torch.sin(rows), torch.cos(rows)], dim=1)
col_emb = torch.cat([torch.sin(cols), torch.cos(cols)], dim=1)
table = torch.zeros(grid_h, grid_w, dim)
table[:, :, :half] = row_emb.unsqueeze(1).expand(-1, grid_w, -1)
table[:, :, half:] = col_emb.unsqueeze(0).expand(grid_h, -1, -1)
return table.reshape(grid_h * grid_w, dim)
View on GitHub (pinned to 39ea8a1c6d)