tracel-ai/burn · error
Data should have as many elements as the shape
Error message
Data should have as many elements as the shape
What it means
Shape/length invariant check in `NdArrayTensor::from_data_owned`: the flattened element count of `TensorData` does not match the product of the declared shape, so ndarray cannot view the buffer with that shape and conversion panics.
Source
Thrown at crates/burn-ndarray/src/tensor.rs:683
dtype,
})
}
/// Create a tensor with owned storage.
///
/// This may or may not copy data depending on whether the underlying bytes
/// can be reclaimed (via `try_into_vec`). If bytes are uniquely owned,
/// no copy occurs; otherwise data is copied to a new allocation.
fn from_data_owned(data: TensorData) -> NdArrayTensor {
let shape = data.shape.to_vec(); // TODO: into_vec
macro_rules! execute {
($data: expr, [$($dtype: pat => $ty: ty),*]) => {
match $data.dtype {
$( $dtype => {
match data.try_into_vec::<$ty>() {
Ok(vec) => ArrayD::from_shape_vec(shape, vec)
.expect("Data should have as many elements as the shape")
.into_shared(),
Err(err) => panic!("Data should have the same element type as the tensor {err:?}"),
}.into()
}, )*
other => unimplemented!("Unsupported dtype {other:?}"),
}
};
}
execute!(data, [
DType::F64 => f64, DType::F32 => f32,
DType::I64 => i64, DType::I32 => i32, DType::I16 => i16, DType::I8 => i8,
DType::U64 => u64, DType::U32 => u32, DType::U16 => u16, DType::U8 => u8,
DType::Bool(BoolStore::Native) => bool
])
}
}
View on GitHub (pinned to d16f7ba2ed)
Solutions
- Verify `TensorData.shape` matches `data.len()` (or vec length) before conversion
- Recompute the shape from the data instead of hardcoding it
- Check for off-by-one or truncated reads when the data was produced
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at crates/burn-ndarray/src/tensor.rs:683 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of tracel-ai/burn@d16f7ba2ed (2026-09-05).
Data as JSON: /api/errors/9d3e9bfc1fb400e5.
Report an issue: GitHub.