{"record":{"id":"737d8c3fee31ac90","repo":"huggingface/candle","slug":"kernel-size-kernel-size-is-larger-than-the-inp","errorCode":null,"errorMessage":"kernel-size {kernel_size:?} is larger than the input size {h},{w}","messagePattern":"kernel-size (.+?) is larger than the input size (.+?),(.+?)","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"candle-core/src/tensor.rs","lineNumber":1360,"sourceCode":"    /// the two last dimensions using a kernel of size `sz`. The returned element is the average\n    /// value over the kernel window.\n    pub fn avg_pool2d<T: crate::ToUsize2>(&self, sz: T) -> Result<Self> {\n        let sz = sz.to_usize2();\n        self.avg_pool2d_with_stride(sz, sz)\n    }\n\n    /// Same as `avg_pool2d` but with a `stride` that can be set to a value different from the\n    /// kernel size.\n    pub fn avg_pool2d_with_stride<T: crate::ToUsize2>(\n        &self,\n        kernel_size: T,\n        stride: T,\n    ) -> Result<Self> {\n        let kernel_size = kernel_size.to_usize2();\n        let stride = stride.to_usize2();\n        let (n, c, h, w) = self.dims4()?;\n        if h < kernel_size.0 || w < kernel_size.1 {\n            bail!(\"kernel-size {kernel_size:?} is larger than the input size {h},{w}\")\n        }\n        // https://pytorch.org/docs/stable/generated/torch.nn.AvgPool2d.html#torch.nn.AvgPool2d\n        let h_out = (h - kernel_size.0) / stride.0 + 1;\n        let w_out = (w - kernel_size.1) / stride.1 + 1;\n        let op = BackpropOp::new1(self, |arg| Op::AvgPool2D {\n            arg,\n            kernel_size,\n            stride,\n        });\n        let storage = self\n            .storage()\n            .avg_pool2d(self.layout(), kernel_size, stride)?;\n        Ok(from_storage(storage, (n, c, h_out, w_out), op, false))\n    }\n\n    /// 2D max pooling over an input tensor with multiple channels.\n    ///\n    /// The input tensor should have four dimensions, `(batch, channels, h, w)`, the returned","sourceCodeStart":1342,"sourceCodeEnd":1378,"githubUrl":"https://github.com/huggingface/candle/blob/d5fee525bfde3273eb7c9b75fd2bc4937be867ca/candle-core/src/tensor.rs#L1342-L1378","documentation":"avg_pool2d requires the input's spatial dims to be at least as large as the pooling kernel; otherwise the output H/W formula would be negative. The check compares the 4-D input's h,w against kernel_size before computing output sizes.","triggerScenarios":"Calling tensor.avg_pool2d(kernel_size, stride) where kernel_size.0 > h or kernel_size.1 > w on an [N,C,H,W] tensor — e.g. kernel (2,2) on a 1x1 or (h=1) feature map.","commonSituations":"Very small intermediate feature maps after aggressive downsampling in a CNN; wrong kernel-size config; feeding a low-resolution image into a network designed for larger inputs.","solutions":["Reduce the pooling kernel size (and stride) so kernel_size <= (h, w) at that layer.","Keep spatial resolution larger by removing an earlier downsample/stride or using padding.","Reconfigure the model for your input resolution, or resize inputs up before the pool.","Guard at runtime: check h/w via t.dims4()? before calling avg_pool2d."],"exampleFix":"// before\nlet pooled = feat.avg_pool2d((2, 2), (2, 2))?; // feat is [1,8,1,1]\n// after\nlet (_, _, h, w) = feat.dims4()?;\nlet k = (2.min(h), 2.min(w));\nlet pooled = feat.avg_pool2d(k, k)?;","handlingStrategy":"validation","validationCode":"let (_, _, h, w) = feat.dims4()?;\nlet (kh, kw) = kernel_size;\nif h < kh || w < kw {\n    return Err(anyhow!(\"input {}x{} smaller than kernel {}x{}\", h, w, kh, kw));\n}\nlet pooled = feat.avg_pool2d(kernel_size, stride)?;","typeGuard":null,"tryCatchPattern":"match feat.avg_pool2d(kernel_size, stride) {\n    Ok(p) => p,\n    Err(e) if e.to_string().contains(\"larger than the input size\") =>\n        // fall back to a smaller kernel or adaptive handling\n        feat.avg_pool2d((1, 1), stride)?,\n    Err(e) => return Err(e.into()),\n}","preventionTips":["Track feature-map sizes through the network; compute expected H/W at each layer.","Clamp kernel size to input size at runtime for dynamic-shape inputs.","Test models with the smallest input resolution you intend to support."],"tags":["shape","avgpool","cnn","kernel-size"],"backgroundTag":"kernel-larger-than-input","analyzedSha":"d5fee525bfde3273eb7c9b75fd2bc4937be867ca","analyzedAt":"2026-09-02T00:15:47.023Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-09T06:17:21.866Z"}