{"record":{"id":"2974a3fefe94897e","repo":"tracel-ai/burn","slug":"dimension-mismatch-cannot-broadcast-dimension-te","errorCode":null,"errorMessage":"Dimension mismatch: cannot broadcast dimension {tensor_dim} of tensor to target shape","messagePattern":"Dimension mismatch: cannot broadcast dimension (.+?) of tensor to target shape","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/burn-cubecl/src/ops/base.rs","lineNumber":275,"sourceCode":"\n    // Calculate the difference in dimensions\n    let dim_diff = ndims_out.saturating_sub(ndims_in);\n\n    // Compare dimensions from the end, setting strides for matching dimensions or broadcasted ones\n    let mut tensor_dim_iter = tensor.meta.shape().iter().rev();\n    for i in (0..ndims_out).rev() {\n        if i >= dim_diff {\n            if let Some(&tensor_dim) = tensor_dim_iter.next() {\n                if tensor_dim == target_shape[i] || tensor_dim == 1 {\n                    // Copy stride for non-broadcast dimensions or set to 0 for broadcast ones\n                    new_strides[i] = if tensor_dim == target_shape[i] {\n                        tensor.meta.strides()[i - dim_diff]\n                    } else {\n                        0\n                    };\n                } else {\n                    // Error handling: Dimension mismatch for broadcasting\n                    panic!(\n                        \"Dimension mismatch: cannot broadcast dimension {tensor_dim} of tensor to target shape\"\n                    );\n                }\n            } else {\n                // If the input tensor has fewer dimensions, treat missing dimensions as 1\n                // and set stride to 0 (broadcasting)\n                new_strides[i] = 0;\n            }\n        } else {\n            // For extra dimensions in the target shape, set stride to 0 (broadcasting)\n            new_strides[i] = 0;\n        }\n    }\n\n    // Extra check to ensure block scales must be properly handled once they're added\n    if tensor.qparams.is_some() && tensor.scheme().block_size().is_some() {\n        todo!()\n    }","sourceCodeStart":257,"sourceCodeEnd":293,"githubUrl":"https://github.com/tracel-ai/burn/blob/d16f7ba2ed0d41408189384044cc886fb4c8f957/crates/burn-cubecl/src/ops/base.rs#L257-L293","documentation":"expand creates a broadcast view of a tensor toward a target shape; each tensor dimension must either equal the target dimension or be 1 (in which case stride 0 is used). If a tensor dimension is neither 1 nor equal to the target, the stride computation cannot proceed and the library panics. This is a shape-contract violation detected client-side before any kernel launch.","triggerScenarios":"Calling bool_expand/int_expand/float_expand (or expand via them) with a target shape whose dimension i is > 1 and != tensor's dimension i, for some aligned trailing dimensions.","commonSituations":"Expanding [3, 4] to [8, 4], mixing batch dims like expanding [B, 1] to [B2, C] with wrong ordering, or hard-coded target shapes that don't match runtime batch sizes.","solutions":["Make each tensor dim either 1 or equal to the target dim before expanding","Insert an unsqueeze first so singleton dims line up with the target shape's trailing dims","Print both shapes and compare right-aligned (broadcasting aligns trailing dims)","Compute the target shape from the input at runtime instead of hard-coding it"],"exampleFix":"// before: expand([3,4] -> [8,4]) panics\nlet y = x.expand([8, 4]);\n// after: expand along a dim that is 1\nlet x = Tensor::ones([1, 4]);\nlet y = x.expand([8, 4]);","handlingStrategy":"validation","validationCode":"fn can_expand(shape: &[usize], target: &[usize]) -> bool {\n    let off = target.len() - shape.len();\n    shape.iter().zip(&target[off..]).all(|(s, t)| *s == 1 || s == t)\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Always align shapes right-aligned mentally when broadcasting","Insert unsqueeze for missing leading dims before expand","Derive expand targets from input shapes at runtime"],"tags":["shape","broadcast","dimension-mismatch","burn"],"backgroundTag":"broadcast-shape-mismatch","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"}