{"record":{"id":"d5e3b7a0e1306076","repo":"rohitg00/ai-engineering-from-scratch","slug":"expected-4d-input-got-tuple-x-shape","errorCode":null,"errorMessage":"expected 4D input, got {tuple(x.shape)}","messagePattern":"expected 4D input, got (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"phases/19-capstone-projects/58-vision-encoder-patches/code/main.py","lineNumber":156,"sourceCode":"    \"\"\"\n    rng = np.random.default_rng(seed)\n    noise = rng.standard_normal((channels, image_size, image_size)).astype(\"float32\") * 0.1\n    y_coords = np.linspace(0.0, 1.0, image_size, dtype=\"float32\")\n    x_coords = np.linspace(0.0, 1.0, image_size, dtype=\"float32\")\n    gx, gy = np.meshgrid(x_coords, y_coords, indexing=\"xy\")\n    gradient = np.stack([gx, gy, (gx + gy) * 0.5], axis=0).astype(\"float32\")\n    img = np.clip(gradient + noise + 0.5, 0.0, 1.0)\n    return torch.from_numpy(img).unsqueeze(0)\n\n\ndef unfold_then_linear(x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor, patch_size: int) -> torch.Tensor:\n    \"\"\"Reference implementation of patch projection via unfold + matmul.\n\n    Used by the tests to assert that the Conv2d projection matches the\n    flatten-then-linear math.\n    \"\"\"\n    if x.dim() != 4:\n        raise ValueError(f\"expected 4D input, got {tuple(x.shape)}\")\n    patches = x.unfold(2, patch_size, patch_size).unfold(3, patch_size, patch_size)\n    b, c, gh, gw, ph, pw = patches.shape\n    flat = patches.permute(0, 2, 3, 1, 4, 5).reshape(b, gh * gw, c * ph * pw)\n    w_flat = weight.reshape(weight.shape[0], -1)\n    return flat @ w_flat.T + bias\n\n\ndef describe_token_norms(tokens: torch.Tensor, max_show: int = 8) -> str:\n    \"\"\"Print the L2 norm of the first few tokens for sanity inspection.\"\"\"\n    norms = tokens.detach().norm(dim=-1)[0].tolist()\n    head = norms[:max_show]\n    return \", \".join(f\"{v:.3f}\" for v in head)\n\n\ndef main() -> None:\n    print(\"=\" * 60)\n    print(\"VISION ENCODER PATCHES\")\n    print(\"=\" * 60)","sourceCodeStart":138,"sourceCodeEnd":174,"githubUrl":"https://github.com/rohitg00/ai-engineering-from-scratch/blob/39ea8a1c6d0b61f071226eff7ede4d4105fed820/phases/19-capstone-projects/58-vision-encoder-patches/code/main.py#L138-L174","documentation":"Error \"expected 4D input, got {tuple(x.shape)}\" thrown in rohitg00/ai-engineering-from-scratch.","triggerScenarios":"Thrown at phases/19-capstone-projects/58-vision-encoder-patches/code/main.py:156 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"}