{"record":{"id":"a1930cfd4f95cc90","repo":"tracel-ai/burn","slug":"input-rank-for-groupnorm-should-be-at-least-3-but","errorCode":null,"errorMessage":"input rank for GroupNorm should be at least 3, but got {}","messagePattern":"input rank for GroupNorm should be at least 3, but got (.+?)","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/burn-nn/src/modules/norm/group.rs","lineNumber":160,"sourceCode":"/// - `Y` is the output tensor\n/// - `γ` is the learnable weight\n/// - `β` is the learnable bias\n///\npub(crate) fn group_norm<const D: usize>(\n    input: Tensor<D>,\n    gamma: Option<Tensor<1>>,\n    beta: Option<Tensor<1>>,\n    num_groups: usize,\n    epsilon: f64,\n    affine: bool,\n) -> Tensor<D> {\n    if (beta.is_none() || gamma.is_none()) && affine {\n        panic!(\"Affine is set to true, but gamma or beta is None\");\n    }\n\n    let shape = input.shape();\n    if shape.num_elements() <= 2 {\n        panic!(\n            \"input rank for GroupNorm should be at least 3, but got {}\",\n            shape.num_elements()\n        );\n    }\n\n    let batch_size = shape[0];\n    let num_channels = shape[1];\n\n    let hidden_size = shape[2..].iter().product::<usize>() * num_channels / num_groups;\n    let input = input.reshape([batch_size, num_groups, hidden_size]);\n\n    // Widen before the reduction when the input dtype cannot hold a sum of\n    // squares (see [`accumulation_dtype`]); `square()` below is what overflows.\n    // Narrowed again straight after, so the affine still runs at the model's\n    // own dtype and only the statistics pay for the wider arithmetic.\n    let original: FloatDType = input.dtype().into();\n    let widened = accumulation_dtype(input.dtype());\n    let input = match widened {","sourceCodeStart":142,"sourceCodeEnd":178,"githubUrl":"https://github.com/tracel-ai/burn/blob/d16f7ba2ed0d41408189384044cc886fb4c8f957/crates/burn-nn/src/modules/norm/group.rs#L142-L178","documentation":"GroupNorm in burn-nn panics when the input tensor's rank (number of dimensions) is less than 3. GroupNorm normalizes over the channel dimension within each batch sample, so it requires at least [batch, channels, spatial...] shaped input. Rather than returning a Result, group_norm panics immediately because a rank < 3 input is always a programming error.","triggerScenarios":"Calling group_norm (via GroupNorm::forward or forward_with_slicing) with a tensor of rank 2 or lower, e.g. a flattened tensor of shape [N, C] or a single [C] vector.","commonSituations":"Feeding a flattened tensor straight from a Linear layer into GroupNorm; forgetting to reshape after a squeeze/view; passing a 1D bias-like tensor; misconfigured model that removes the spatial dims before normalization.","solutions":["Reshape the input to at least 3 dimensions ([batch, channels, ...]) before calling forward on GroupNorm.","Check input.dims().len() >= 3 (and > 2 elements) before invoking group_norm.","Audit the layer order so normalization happens before any flatten/reshape to 2D."],"exampleFix":"// before\nlet logits = model(x);            // shape [batch, classes]\nlet out = group_norm.forward(logits); // panics: rank 2\n// after\nlet features = features.reshape([batch, channels, spatial]);\nlet normed = group_norm.forward(features);","handlingStrategy":"validation","validationCode":"fn ensure_groupnorm_rank<B: burn::tensor::backend::Backend>(x: &burn::tensor::Tensor<B, 2>) -> burn::tensor::Tensor<B, 3> {\n    // rank < 3 would panic inside group_norm; reshape to [1, C, N] minimum\n    x.reshape([1, x.dims()[0], x.dims()[1]])\n}","typeGuard":"fn is_valid_groupnorm_input(shape: &[usize]) -> bool {\n    shape.len() >= 3\n}","tryCatchPattern":"// panic-based API: validate before calling instead of catching\nif !is_valid_groupnorm_input(&input.dims()) {\n    input = input.reshape([...]); // fix rank before forward\n}\nlet out = group_norm.forward(input);","preventionTips":["Assert input.dims().len() >= 3 at model boundaries (debug_assert in dev builds).","Never flatten tensors before normalization layers; flatten only after the last norm/pool.","Add a unit test feeding a rank-2 tensor to catch regressions early.","Wrap GroupNorm usage in helper functions that reshape to [N, C, ...] automatically."],"tags":["rust","panic","shape-validation","groupnorm","tensor-rank"],"backgroundTag":"invalid-tensor-rank","analyzedSha":"d16f7ba2ed0d41408189384044cc886fb4c8f957","analyzedAt":"2026-09-05T13:19:14.260Z","contentChangedAt":"2026-09-05T13:19:14.260Z","schemaVersion":2},"datasetVersion":"2026-09-12T17:17:11.597Z"}