{"record":{"id":"221ee58446979b03","repo":"tracel-ai/burn","slug":"cannot-substitute-1-for-a-non-existing-dimension","errorCode":null,"errorMessage":"Cannot substitute -1 for a non-existing dimension! Got {:?}","messagePattern":"Cannot substitute -1 for a non-existing dimension! Got (.+?)","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/burn-tensor/src/tensor/api/base.rs","lineNumber":3404,"sourceCode":"            .map(|x| {\n                let primitive = x.as_index();\n                if primitive < -1 || primitive == 0 {\n                    panic!(\n                        \"Broadcast arguments must be positive or -1! Got {}\",\n                        primitive\n                    );\n                }\n                primitive\n            })\n            .zip(shape.iter().rev().chain(repeat(&0)).take(self.len())) // Pad the original shape with 0s\n            .map(|(x, &y)| if x == -1 { y } else { x as usize })\n            .collect::<Vec<_>>()\n            .into_iter()\n            .rev()\n            .collect();\n\n        if new_shape.contains(&0) {\n            panic!(\n                \"Cannot substitute -1 for a non-existing dimension! Got {:?}\",\n                new_shape\n            );\n        }\n\n        let new_shape: [usize; D2] = new_shape.try_into().unwrap();\n\n        Shape::from(new_shape)\n    }\n}\n\nimpl<const D: usize, K> Serialize for Tensor<D, K>\nwhere\n    K: Basic,\n{\n    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {\n        let data = self.to_data();\n        data.serialize(serializer)","sourceCodeStart":3386,"sourceCodeEnd":3422,"githubUrl":"https://github.com/tracel-ai/burn/blob/d16f7ba2ed0d41408189384044cc886fb4c8f957/crates/burn-tensor/src/tensor/api/base.rs#L3386-L3422","documentation":"After resolving broadcast args, a resulting dimension of 0 means a -1 could not be substituted — i.e. the code path that replaces -1 with the existing dimension found no valid dimension to take the size from. Burn panics with the resolved new_shape for diagnosis. In practice this indicates the -1 inference produced an invalid shape: the -1s could not be mapped onto the tensor's existing dims (e.g. more -1s than original dims, or the resolved shape collapsed to 0).","triggerScenarios":"Using multiple -1 entries in a broadcast/reshape argument where at most one can be inferred, so the resolution yields a 0 entry; broadcasting a higher-rank argument array against a lower-rank tensor so some -1s have no source dimension; a -1 landing on a dimension the original tensor doesn't have.","commonSituations":"Copy-pasted numpy/torch reshape code that uses -1 freely, run against Burn's stricter broadcast semantics; dynamically built shape vectors where the number of -1 placeholders outgrew the tensor rank; refactors that changed tensor rank without updating the -1 placeholders.","solutions":["Use at most one -1 per broadcast/reshape call and give every other dimension an explicit positive size","Ensure the argument array's rank matches the tensor's rank so each -1 maps to an existing dimension","Print/inspect x.dims() and the target shape, then replace ambiguous -1s with concrete sizes (e.g. 1 for broadcast-expanded dims)","Use tensor.to_dtype-free helpers like reshape with an explicit Shape built from known dims instead of -1 inference"],"exampleFix":"// before, x is [B, C]\nlet y = x.reshape([-1, -1, 64]); // -1s cannot all be resolved -> resolved shape contains 0 -> panic\n// after\nlet y = x.reshape([-1, 1, 64]); // only one -1; other dims explicit","handlingStrategy":"validation","validationCode":"// Ensure at most one -1 and that the arg rank matches the tensor rank\nlet minus_ones = args.iter().filter(|d| d.as_index() == -1).count();\nassert!(minus_ones <= 1, \"at most one -1 can be inferred\");\nassert!(args.len() >= x.shape().num_dims());","typeGuard":null,"tryCatchPattern":"// Panic API; build the shape explicitly instead of relying on -1 inference:\nlet mut target = x.dims(); target[0] = 1; // construct concrete dims, then reshape(target)","preventionTips":["Use at most one -1 per reshape/broadcast and make all other dims explicit","Keep the argument array's rank aligned with the tensor's rank so -1 maps to a real dim","Build target shapes from known dims rather than -1 placeholders when ranks are dynamic","When porting numpy/torch code, replace extra -1s with 1 (broadcast-expand) or concrete sizes"],"tags":["tensor","shape","broadcast","panic","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"}