{"record":{"id":"e2069c968e969ca7","repo":"huggingface/candle","slug":"image-is-too-large-w-h-maximum-size-image","errorCode":null,"errorMessage":"image is too large ({w}, {h}), maximum size {IMAGE_SIZE}","messagePattern":"image is too large \\((.+?), (.+?)\\), maximum size (.+?)","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"candle-transformers/src/models/segment_anything/sam.rs","lineNumber":214,"sourceCode":"        )\n    }\n\n    pub fn unpreprocess(&self, img: &Tensor) -> Result<Tensor> {\n        let img = img\n            .broadcast_mul(&self.pixel_std)?\n            .broadcast_add(&self.pixel_mean)?;\n        img.maximum(&img.zeros_like()?)?\n            .minimum(&(img.ones_like()? * 255.)?)\n    }\n\n    pub fn preprocess(&self, img: &Tensor) -> Result<Tensor> {\n        let (_c, h, w) = img.dims3()?;\n        let img = img\n            .to_dtype(DType::F32)?\n            .broadcast_sub(&self.pixel_mean)?\n            .broadcast_div(&self.pixel_std)?;\n        if h > IMAGE_SIZE || w > IMAGE_SIZE {\n            candle::bail!(\"image is too large ({w}, {h}), maximum size {IMAGE_SIZE}\")\n        }\n        let img = img.pad_with_zeros(1, 0, IMAGE_SIZE - h)?;\n        img.pad_with_zeros(2, 0, IMAGE_SIZE - w)\n    }\n\n    fn process_crop(\n        &self,\n        img: &Tensor,\n        cb: CropBox,\n        point_grids: &[(f64, f64)],\n    ) -> Result<Vec<crate::object_detection::Bbox<Tensor>>> {\n        // Crop the image and calculate embeddings.\n        let img = img.i((.., cb.y0..cb.y1, cb.x0..cb.x1))?;\n        let img = self.preprocess(&img)?.unsqueeze(0)?;\n        let img_embeddings = self.image_encoder.forward(&img)?;\n\n        let crop_w = cb.x1 - cb.x0;\n        let crop_h = cb.y1 - cb.y0;","sourceCodeStart":196,"sourceCodeEnd":232,"githubUrl":"https://github.com/huggingface/candle/blob/d5fee525bfde3273eb7c9b75fd2bc4937be867ca/candle-transformers/src/models/segment_anything/sam.rs#L196-L232","documentation":"SAM's preprocess normalizes the input image then zero-pads it up to IMAGE_SIZE (1024). Padding with a negative amount is impossible, so any image with height or width greater than 1024 bails before resizing/padding, listing the offending (w, h) and the maximum.","triggerScenarios":"Calling `Sam::embeddings`, `forward`, or `process_crop` with an input image tensor whose H or W exceeds IMAGE_SIZE=1024, e.g. loading a 2048x1536 photo directly without downscaling.","commonSituations":"Users pass full-resolution camera or microscopy images to the prompt encoder; some sources must be larger than 1024 but the model was trained at 1024; forgetting that SAM expects the image already resized on the longest side.","solutions":["Resize the image so its longest side is <= 1024 before passing it to SAM (preserving aspect ratio, e.g. longest-side resize).","Preprocess with the model's own transform pipeline (resize + normalize) instead of feeding raw pixel tensors.","If you must keep resolution, crop/tile the image into <=1024 chunks and run SAM per tile (as `process_crop` intends).","Check `dims3()` output and clamp: `let scale = 1024f64 / w.max(h) as f64;` then resample."],"exampleFix":"// before\nlet img = Tensor::from_fn((2048, 1536), ...);\nlet emb = sam.embeddings(&img)?;\n// after\nlet img = resize_longest_side(&img, 1024)?; // downscale\nlet emb = sam.embeddings(&img)?;","handlingStrategy":"validation","validationCode":"let (_c, h, w) = img.dims3()?;\nif h > 1024 || w > 1024 {\n    img = resize_longest_side(img, 1024)?; // downscale before calling SAM\n}","typeGuard":"fn fits_sam(img: &Tensor) -> candle::Result<bool> {\n    let (_, h, w) = img.dims3()?;\n    Ok(h <= 1024 && w <= 1024)\n}","tryCatchPattern":"match sam.embeddings(&img) {\n    Ok(t) => t,\n    Err(e) if e.to_string().contains(\"image is too large\") => {\n        let img = resize_longest_side(&img, 1024)?;\n        sam.embeddings(&img)\n    }\n    Err(e) => return Err(e.into()),\n}","preventionTips":["Resize so the longest side is <= 1024 before any SAM call.","Use the model's own preprocessing pipeline (resize + pixel_mean/std normalize).","For large images, tile/crop into <=1024 patches and run per tile.","Check dims3() of your tensor against IMAGE_SIZE in a debug assertion."],"tags":["image-size","preprocessing","input-validation","candle"],"backgroundTag":"input-dimension-out-of-range","analyzedSha":"d5fee525bfde3273eb7c9b75fd2bc4937be867ca","analyzedAt":"2026-09-02T00:15:47.023Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-09T06:17:21.866Z"}