{"record":{"id":"67cb8e5ba6a92750","repo":"huggingface/candle","slug":"error-in-prelu-unexpected-number-of-channels-for","errorCode":null,"errorMessage":"error in prelu: unexpected number of channels for the input, got {num_channels}, weight dim is {num_weights}","messagePattern":"error in prelu: unexpected number of channels for the input, got (.+?), weight dim is (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"candle-nn/src/activation.rs","lineNumber":82,"sourceCode":"        &self.weight\n    }\n\n    pub fn is_scalar(&self) -> bool {\n        self.is_scalar\n    }\n}\n\nimpl candle::Module for PReLU {\n    fn forward(&self, xs: &Tensor) -> Result<Tensor> {\n        let weight = if self.is_scalar {\n            self.weight.reshape(())?\n        } else if xs.shape() == self.weight.shape() {\n            self.weight.clone()\n        } else if xs.rank() >= 2 {\n            let num_channels = xs.dim(1)?;\n            let num_weights = self.weight.elem_count();\n            if num_weights != num_channels {\n                candle::bail!(\"error in prelu: unexpected number of channels for the input, got {num_channels}, weight dim is {num_weights}\")\n            }\n            let mut s = vec![1; xs.rank()];\n            s[1] = num_weights;\n            self.weight.reshape(s)?\n        } else {\n            self.weight.clone()\n        };\n        let zeros = xs.zeros_like()?;\n        xs.maximum(&zeros)? + xs.minimum(&zeros)?.broadcast_mul(&weight)?\n    }\n}\n\n/// Create or initialize a new PReLU layer.\n///\n/// This uses some default name for weights, namely `\"weight\"`.\n/// # Arguments\n///\n/// * `num_channels` - The number of channels. Use `None` to have as single trainable value and","sourceCodeStart":64,"sourceCodeEnd":100,"githubUrl":"https://github.com/huggingface/candle/blob/d5fee525bfde3273eb7c9b75fd2bc4937be867ca/candle-nn/src/activation.rs#L64-L100","documentation":"candle-nn's PReLU with a per-channel weight requires the number of weights to equal the number of input channels (dim 1 for rank>=2 inputs). When neither an exact broadcast match nor a full-shape match applies, the library validates channel count and bails on mismatch.","triggerScenarios":"Creating Prelu::new with a weight of length N but feeding an input whose dim(1) != N and whose full shape does not equal the weight shape.","commonSituations":"Config mismatch: PReLU built for one channel count but a conv/linear upstream produces another; input rank-1 tensors vs multi-channel expectations; reusing a PReLU module across differently-shaped layers.","solutions":["Resize the PReLU weight to match the input channel count: Prelu::new(Tensor::ones((channels,), ...))","Reshape the input so dim(1) equals num_weights","Use a scalar weight (rank-0) PReLU if channel-wise slopes are not needed","Check the upstream layer's out_channels matches the PReLU construction"],"exampleFix":"// before\nlet prelu = Prelu::new(Tensor::new(0.25f32, &dev)?); // scalar but input needs 64 channels\nlet y = prelu.forward(&x)?; // x.dim(1)==64 -> error\n// after\nlet prelu = Prelu::new(Tensor::ones((64,), &dev)? * 0.25)?;\nlet y = prelu.forward(&x)?;","handlingStrategy":"validation","validationCode":"let channels = xs.dim(1)?;\nif weight.elem_count() != channels && weight.shape() != xs.shape() {\n    return Err(anyhow!(\"prelu weight len {} != input channels {channels}\", weight.elem_count()));\n}","typeGuard":null,"tryCatchPattern":"match result {\n    Err(e) if e.to_string().contains(\"error in prelu\") => {\n        eprintln!(\"rebuild PReLU with weight len = input dim(1)\");\n    }\n    other => other?,\n}","preventionTips":["Construct PReLU with one weight per input channel","Check upstream layer out_channels before wiring PReLU","Use a scalar weight if you do not need per-channel slopes"],"tags":["candle-nn","prelu","shape-mismatch","channels"],"backgroundTag":"tensor-shape-mismatch","analyzedSha":"d5fee525bfde3273eb7c9b75fd2bc4937be867ca","analyzedAt":"2026-09-02T00:15:47.023Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-09T06:17:21.866Z"}