tracel-ai/burn · error
Data should have the same element type as the tensor {err:?}
Error message
Data should have the same element type as the tensor {err:?} What it means
This panic fires inside the ndarray backend's macro that converts TensorData into an ArrayD. When the data's element type does not match any supported dtype branch, try_into_vec::<$ty> fails and the code panics with the conversion error. It means the byte buffer handed to from_data_owned was interpreted under a dtype that doesn't match the Vec element type the macro branch expects.
Source
Thrown at crates/burn-ndarray/src/tensor.rs:685
}
/// 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
])
}
}
/// A quantized tensor for the ndarray backend.
#[derive(Clone, Debug)]View on GitHub (pinned to d16f7ba2ed)
Solutions
- Make sure the Vec element type matches the tensor dtype: use f32 Vecs for Float tensors (Tensor::<B,1>::from_data(TensorData::new(vec![1.0f32], &[1]), &device)).
- Check the dtype of the source data (TensorData::as_slice / dtype field) and convert explicitly before creating the tensor.
- When loading checkpoints, ensure the exported model and the loading backend agree on numeric types (f32 vs f64).
- Convert with .cast() after creation instead of relying on implicit conversion: create the tensor with the data's native dtype then call .convert::<OtherDtype>().
Example fix
// before let data = TensorData::new(vec![1.0f64, 2.0], shape); // F64 data let tensor = Tensor::<Backend, 1>::from_data(data, &device); // panics: f32 tensor // after let data = TensorData::new(vec![1.0f32, 2.0], shape); // matches Float dtype let tensor = Tensor::<Backend, 1>::from_data(data, &device);
Defensive patterns
Strategy: validation
Validate before calling
fn ensure_dtype_matches(data: &TensorData, want: DType) -> Result<(), String> {
if data.dtype != want {
return Err(format!("tensor data dtype {:?} != expected {:?}", data.dtype, want));
}
Ok(())
}
// call before: ensure_dtype_matches(&data, DType::F32)?; Type guard
fn is_f32_data(data: &TensorData) -> bool {
matches!(data.dtype, DType::F32)
} Prevention
- Always construct TensorData with literals suffixed to the expected width (1.0f32 for Float tensors).
- Check data.dtype before from_data; log or assert it in tests.
- When converting from other frameworks/checkpoints, cast to f32 explicitly before building TensorData.
- Add a debug_assert on dtype in helper functions that wrap tensor creation.
When it happens
Trigger: Calling Tensor::from_data or from_data_owned with TensorData created from a Vec whose element type differs from the tensor's declared dtype (e.g. data created as f64/typed as F64 but the tensor is Float), or passing data whose dtype enum doesn't match its actual backing buffer.
Common situations: Loading weights/checkpoints serialized with a different float width (f64 vs f32) than the model tensor expects; building test tensors with `TensorData::new(vec_of_f64, shape)` for an f32 tensor; inference outputs fed back as inputs with mismatched dtype.
Related errors
- Dim not supported {ndims}
- Not a valid float kind
- Expected bool data type, got {dtype:?}
- svd requires a float tensor
- todo!("grid_sample_2d with {:?} mode is not implemented", op
AI-assisted analysis of tracel-ai/burn@d16f7ba2ed (2026-09-05).
Data as JSON: /api/errors/2536b3a114a09675.
Report an issue: GitHub.