{"record":{"id":"371114581634fcf5","repo":"tracel-ai/burn","slug":"invalid-dimension-the-shape-of-the-index-tensor-s","errorCode":null,"errorMessage":"Invalid dimension: the shape of the index tensor should be the same as the value tensor: Index {:?} value {:?}","messagePattern":"Invalid dimension: the shape of the index tensor should be the same as the value tensor: Index (.+?) value (.+?)","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/burn-ndarray/src/ops/base.rs","lineNumber":163,"sourceCode":"    ) -> SharedArray<E> {\n        let ndims = tensor.shape().num_dims();\n        if dim != ndims - 1 {\n            tensor.swap_axes(ndims - 1, dim);\n            indices.swap_axes(ndims - 1, dim);\n            value.swap_axes(ndims - 1, dim);\n        }\n\n        let (shape_tensor, shape_indices, shape_value) =\n            (tensor.shape().into_shape(), indices.shape(), value.shape());\n        let (size_tensor, size_index, size_value) = (\n            shape_tensor[ndims - 1],\n            shape_indices[ndims - 1],\n            shape_value[ndims - 1],\n        );\n        let batch_size = Self::gather_batch_size(&shape_tensor, shape_indices);\n\n        if shape_value != shape_indices {\n            panic!(\n                \"Invalid dimension: the shape of the index tensor should be the same as the value \\\n                 tensor: Index {:?} value {:?}\",\n                shape_indices, shape_value\n            );\n        }\n\n        let indices = NdArrayOps::reshape(indices, Shape::new([batch_size, size_index]));\n        let value = NdArrayOps::reshape(value, Shape::new([batch_size, size_value]));\n        let mut tensor = NdArrayOps::reshape(tensor, Shape::new([batch_size, size_tensor]));\n\n        for b in 0..batch_size {\n            let indices = indices.slice(s!(b, ..));\n\n            for (i, index) in indices.iter().enumerate() {\n                let index = index.elem::<i64>() as usize;\n                tensor[[b, index]].add_assign(value[[b, i]]);\n            }\n        }","sourceCodeStart":145,"sourceCodeEnd":181,"githubUrl":"https://github.com/tracel-ai/burn/blob/d16f7ba2ed0d41408189384044cc886fb4c8f957/crates/burn-ndarray/src/ops/base.rs#L145-L181","documentation":"The NdArray `scatter` op panics when the index tensor's shape does not exactly equal the value tensor's shape. scatter (burn-ndarray/src/ops/base.rs) requires index/value shape equality by construction — every element of `values` has a corresponding index — so mismatched shapes are rejected with a panic naming both shapes.","triggerScenarios":"Calling `scatter(dim, indices, values)` where `indices.dims() != values.dims()`; e.g. indices of shape [N, K] with values of shape [N, K'] or a squeezed/expanded index tensor.","commonSituations":"Hand-building scatter inputs where indices were gathered for a differently-shaped value set; off-by-one or wrong-dim expansion when broadcasting indices; porting from PyTorch's scatter (which broadcasts) into burn's stricter API.","solutions":["Reshape/expand the index tensor to exactly match the value tensor's shape before calling scatter (use `indices.expand(values.shape())` or repeat along mismatched dims).","Or reshape/slice the value tensor to the index tensor's shape.","If porting PyTorch code, note burn's scatter does not broadcast — construct both tensors with identical shapes explicitly.","Add a debug assert on `indices.shape() == values.shape()` in your calling code to fail earlier with your own message."],"exampleFix":"// before\nlet out = x.scatter(1, &idx /* [N,1] */, &vals /* [N,K] */); // panics\n// after\nlet idx_full = idx.expand(vals.shape());\nlet out = x.scatter(1, &idx_full, &vals);","handlingStrategy":"validation","validationCode":"fn ensure_scatter_shapes<B: Backend>(indices: &Tensor<B,2>, values: &Tensor<B,2>) -> Result<(), String> {\n    (indices.shape() == values.shape())\n        .then_some(())\n        .ok_or_else(|| format!(\"scatter shape mismatch: indices {:?} vs values {:?}\",\n            indices.shape(), values.shape()))\n}","typeGuard":null,"tryCatchPattern":"let out = std::panic::catch_unwind(AssertUnwindSafe(|| x.scatter(dim, &idx, &vals)))\n    .map_err(|_| anyhow!(\"scatter requires indices.shape() == values.shape()\"))?;","preventionTips":["Assert indices.shape() == values.shape() before scatter — the API does not broadcast","When porting PyTorch scatter code, explicitly expand indices to the value shape","Check squeeze/expand operations that change index rank or dims upstream","Compare shapes at construction time, not at the scatter call site"],"tags":["panic","burn","ndarray","scatter","shape-mismatch"],"backgroundTag":"tensor-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"}