{"record":{"id":"9275252cf0670fe7","repo":"huggingface/pytorch-image-models","slug":"output-fmt-nchw-requires-a-raw-image-b-c-h-w","errorCode":null,"errorMessage":"output_fmt='NCHW' requires a raw image (B, C, H, W) input.","messagePattern":"output_fmt='NCHW' requires a raw image \\(B, C, H, W\\) input\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"timm/models/gemma4_vit.py","lineNumber":960,"sourceCode":"        def _cb(i: int, y: torch.Tensor) -> None:\n            if i in take_indices:\n                intermediates.append(y)\n\n        max_block_index = None\n        if stop_early and not torch.jit.is_scripting():\n            max_block_index = max_index\n\n        x = self._encode(\n            x,\n            position_ids,\n            padding_positions,\n            block_callback=_cb,\n            max_block_index=max_block_index,\n        )\n\n        if reshape:\n            if raw_input_ndim != 4:\n                raise ValueError(\"output_fmt='NCHW' requires a raw image (B, C, H, W) input.\")\n            # Recover grid from internal (x, y) position_ids max.\n            B = position_ids.shape[0]\n            pW = int(position_ids[..., 0].max().item()) + 1\n            pH = int(position_ids[..., 1].max().item()) + 1\n            intermediates = [y.reshape(B, pH, pW, -1).permute(0, 3, 1, 2).contiguous() for y in intermediates]\n\n        if output_dict:\n            result_dict: Dict[str, Any] = {'image_intermediates': intermediates}\n            if not intermediates_only:\n                result_dict['image_features'] = x\n            result_dict['patch_valid'] = ~padding_positions\n            return result_dict\n\n        if intermediates_only:\n            return intermediates\n\n        return x, intermediates\n","sourceCodeStart":942,"sourceCodeEnd":978,"githubUrl":"https://github.com/huggingface/pytorch-image-models/blob/9a5261e31b3b5128526eb2658333b4c0a54464ae/timm/models/gemma4_vit.py#L942-L978","documentation":"Gemma4VitEncoder.forward_intermediates can reshape intermediate token outputs into spatial NCHW maps, but the grid can only be recovered from position_ids derived from a raw image input. If reshape=True (output_fmt='NCHW') and the input was pre-patchified or otherwise not a 4D raw image, the reshape is impossible and ValueError is raised.","triggerScenarios":"Calling enc.forward_intermediates(patches, patch_coord=..., output_fmt='NCHW') with a 3D/5D pre-patchified input instead of a raw (B,C,H,W) image.","commonSituations":"Reusing the same forward_intermediates call for both raw-image and cached-token paths with a fixed output_fmt; writing generic feature-extraction utilities that always request NCHW.","solutions":["Pass a raw 4D image when you need output_fmt='NCHW'","Or use output_fmt='NLC' for pre-patchified input and reshape externally using your known grid (from patch_coord maxima)","Compute the grid yourself: pH/pW = position_ids.max()+1 per axis, then reshape tokens to (B, pH, pW, C) and permute"],"exampleFix":"# before\nfeats = enc.forward_intermediates(patches, patch_coord=c, output_fmt='NCHW')\n# after\nfeats = enc.forward_intermediates(patches, patch_coord=c, output_fmt='NLC')\nmaps = [y.reshape(B, pH, pW, -1).permute(0, 3, 1, 2) for y in feats]","handlingStrategy":"validation","validationCode":"raw = x.ndim == 4 and patch_coord is None\nfmt = 'NCHW' if raw else 'NLC'\nfeats = enc.forward_intermediates(x, patch_coord=patch_coord, output_fmt=fmt)","typeGuard":"def can_use_nchw_output(x: torch.Tensor) -> bool:\n    return x.ndim == 4","tryCatchPattern":"try:\n    feats = enc.forward_intermediates(x, patch_coord=c, output_fmt='NCHW')\nexcept ValueError as e:\n    if 'NCHW' in str(e):\n        feats = enc.forward_intermediates(x, patch_coord=c, output_fmt='NLC')\n    else:\n        raise","preventionTips":["Request NCHW only when feeding raw 4D images","Keep a grid-recovery helper that reshapes NLC using patch_coord maxima","Test feature-extraction paths for both raw and pre-patchified inputs"],"tags":["timm","gemma4-vit","feature-extraction","tensor-shape"],"backgroundTag":"incompatible-output-format-request","analyzedSha":"9a5261e31b3b5128526eb2658333b4c0a54464ae","analyzedAt":"2026-08-27T02:34:25.417Z","schemaVersion":2},"datasetVersion":"2026-08-27T03:17:27.898Z"}