huggingface/candle · error

image is too large ({w}, {h}), maximum size {IMAGE_SIZE}

Error message

image is too large ({w}, {h}), maximum size {IMAGE_SIZE}

What it means

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.

Source

Thrown at candle-transformers/src/models/segment_anything/sam.rs:214

        )
    }

    pub fn unpreprocess(&self, img: &Tensor) -> Result<Tensor> {
        let img = img
            .broadcast_mul(&self.pixel_std)?
            .broadcast_add(&self.pixel_mean)?;
        img.maximum(&img.zeros_like()?)?
            .minimum(&(img.ones_like()? * 255.)?)
    }

    pub fn preprocess(&self, img: &Tensor) -> Result<Tensor> {
        let (_c, h, w) = img.dims3()?;
        let img = img
            .to_dtype(DType::F32)?
            .broadcast_sub(&self.pixel_mean)?
            .broadcast_div(&self.pixel_std)?;
        if h > IMAGE_SIZE || w > IMAGE_SIZE {
            candle::bail!("image is too large ({w}, {h}), maximum size {IMAGE_SIZE}")
        }
        let img = img.pad_with_zeros(1, 0, IMAGE_SIZE - h)?;
        img.pad_with_zeros(2, 0, IMAGE_SIZE - w)
    }

    fn process_crop(
        &self,
        img: &Tensor,
        cb: CropBox,
        point_grids: &[(f64, f64)],
    ) -> Result<Vec<crate::object_detection::Bbox<Tensor>>> {
        // Crop the image and calculate embeddings.
        let img = img.i((.., cb.y0..cb.y1, cb.x0..cb.x1))?;
        let img = self.preprocess(&img)?.unsqueeze(0)?;
        let img_embeddings = self.image_encoder.forward(&img)?;

        let crop_w = cb.x1 - cb.x0;
        let crop_h = cb.y1 - cb.y0;

View on GitHub (pinned to d5fee525bf)

Solutions

  1. Resize the image so its longest side is <= 1024 before passing it to SAM (preserving aspect ratio, e.g. longest-side resize).
  2. Preprocess with the model's own transform pipeline (resize + normalize) instead of feeding raw pixel tensors.
  3. If you must keep resolution, crop/tile the image into <=1024 chunks and run SAM per tile (as `process_crop` intends).
  4. Check `dims3()` output and clamp: `let scale = 1024f64 / w.max(h) as f64;` then resample.

Example fix

// before
let img = Tensor::from_fn((2048, 1536), ...);
let emb = sam.embeddings(&img)?;
// after
let img = resize_longest_side(&img, 1024)?; // downscale
let emb = sam.embeddings(&img)?;
Defensive patterns

Strategy: validation

Validate before calling

let (_c, h, w) = img.dims3()?;
if h > 1024 || w > 1024 {
    img = resize_longest_side(img, 1024)?; // downscale before calling SAM
}

Type guard

fn fits_sam(img: &Tensor) -> candle::Result<bool> {
    let (_, h, w) = img.dims3()?;
    Ok(h <= 1024 && w <= 1024)
}

Try / catch

match sam.embeddings(&img) {
    Ok(t) => t,
    Err(e) if e.to_string().contains("image is too large") => {
        let img = resize_longest_side(&img, 1024)?;
        sam.embeddings(&img)
    }
    Err(e) => return Err(e.into()),
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of huggingface/candle@d5fee525bf (2026-09-02). Data as JSON: /api/errors/e2069c968e969ca7. Report an issue: GitHub.