{"record":{"id":"f6094dd9ededf5f2","repo":"rohitg00/ai-engineering-from-scratch","slug":"sinusoidal-2d-dim-must-be-divisible-by-4-got-dim","errorCode":null,"errorMessage":"sinusoidal_2d dim must be divisible by 4, got {dim}","messagePattern":"sinusoidal_2d dim must be divisible by 4, got (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"phases/19-capstone-projects/58-vision-encoder-patches/code/main.py","lineNumber":50,"sourceCode":"            raise ValueError(\n                f\"patch_size {self.patch_size} must divide image_size {self.image_size}\"\n            )\n        return self.image_size // self.patch_size\n\n    @property\n    def num_patches(self) -> int:\n        return self.grid_size * self.grid_size\n\n\ndef sinusoidal_2d(grid_h: int, grid_w: int, dim: int) -> torch.Tensor:\n    \"\"\"Build a deterministic 2D sinusoidal position table of shape (grid_h * grid_w, dim).\n\n    Half of dim encodes row position, half encodes column position. Within each\n    half, frequencies span the standard Transformer sin/cos band. Identical\n    inputs always produce identical outputs, with no learned state.\n    \"\"\"\n    if dim % 4 != 0:\n        raise ValueError(f\"sinusoidal_2d dim must be divisible by 4, got {dim}\")\n    half = dim // 2\n    quarter = half // 2\n\n    freq = torch.arange(quarter, dtype=torch.float32)\n    inv = torch.exp(-math.log(10000.0) * freq / max(1, quarter))\n\n    rows = torch.arange(grid_h, dtype=torch.float32).unsqueeze(1) * inv.unsqueeze(0)\n    cols = torch.arange(grid_w, dtype=torch.float32).unsqueeze(1) * inv.unsqueeze(0)\n\n    row_emb = torch.cat([torch.sin(rows), torch.cos(rows)], dim=1)\n    col_emb = torch.cat([torch.sin(cols), torch.cos(cols)], dim=1)\n\n    table = torch.zeros(grid_h, grid_w, dim)\n    table[:, :, :half] = row_emb.unsqueeze(1).expand(-1, grid_w, -1)\n    table[:, :, half:] = col_emb.unsqueeze(0).expand(grid_h, -1, -1)\n    return table.reshape(grid_h * grid_w, dim)\n\n","sourceCodeStart":32,"sourceCodeEnd":68,"githubUrl":"https://github.com/rohitg00/ai-engineering-from-scratch/blob/39ea8a1c6d0b61f071226eff7ede4d4105fed820/phases/19-capstone-projects/58-vision-encoder-patches/code/main.py#L32-L68","documentation":"Error \"sinusoidal_2d dim must be divisible by 4, got {dim}\" thrown in rohitg00/ai-engineering-from-scratch.","triggerScenarios":"Thrown at phases/19-capstone-projects/58-vision-encoder-patches/code/main.py:50 when the library encounters an invalid state.","commonSituations":"See trigger scenarios.","solutions":[],"exampleFix":null,"handlingStrategy":null,"validationCode":null,"typeGuard":null,"tryCatchPattern":null,"preventionTips":[],"tags":[],"backgroundTag":null,"analyzedSha":"39ea8a1c6d0b61f071226eff7ede4d4105fed820","analyzedAt":"2026-08-26T03:13:46.626Z","schemaVersion":2},"datasetVersion":"2026-08-26T07:17:17.940Z"}