{"record":{"id":"2536b3a114a09675","repo":"tracel-ai/burn","slug":"data-should-have-the-same-element-type-as-the-tens","errorCode":null,"errorMessage":"Data should have the same element type as the tensor {err:?}","messagePattern":"Data should have the same element type as the tensor (.+?)","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/burn-ndarray/src/tensor.rs","lineNumber":685,"sourceCode":"    }\n\n    /// Create a tensor with owned storage.\n    ///\n    /// This may or may not copy data depending on whether the underlying bytes\n    /// can be reclaimed (via `try_into_vec`). If bytes are uniquely owned,\n    /// no copy occurs; otherwise data is copied to a new allocation.\n    fn from_data_owned(data: TensorData) -> NdArrayTensor {\n        let shape = data.shape.to_vec(); // TODO: into_vec\n\n        macro_rules! execute {\n            ($data: expr, [$($dtype: pat => $ty: ty),*]) => {\n                match $data.dtype {\n                    $( $dtype => {\n                        match data.try_into_vec::<$ty>() {\n                            Ok(vec) => ArrayD::from_shape_vec(shape, vec)\n                                .expect(\"Data should have as many elements as the shape\")\n                                .into_shared(),\n                            Err(err) => panic!(\"Data should have the same element type as the tensor {err:?}\"),\n                        }.into()\n                    }, )*\n                    other => unimplemented!(\"Unsupported dtype {other:?}\"),\n                }\n            };\n        }\n\n        execute!(data, [\n            DType::F64 => f64, DType::F32 => f32,\n            DType::I64 => i64, DType::I32 => i32, DType::I16 => i16, DType::I8 => i8,\n            DType::U64 => u64, DType::U32 => u32, DType::U16 => u16, DType::U8 => u8,\n            DType::Bool(BoolStore::Native) => bool\n        ])\n    }\n}\n\n/// A quantized tensor for the ndarray backend.\n#[derive(Clone, Debug)]","sourceCodeStart":667,"sourceCodeEnd":703,"githubUrl":"https://github.com/tracel-ai/burn/blob/d16f7ba2ed0d41408189384044cc886fb4c8f957/crates/burn-ndarray/src/tensor.rs#L667-L703","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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>()."],"exampleFix":"// before\nlet data = TensorData::new(vec![1.0f64, 2.0], shape); // F64 data\nlet tensor = Tensor::<Backend, 1>::from_data(data, &device); // panics: f32 tensor\n// after\nlet data = TensorData::new(vec![1.0f32, 2.0], shape); // matches Float dtype\nlet tensor = Tensor::<Backend, 1>::from_data(data, &device);","handlingStrategy":"validation","validationCode":"fn ensure_dtype_matches(data: &TensorData, want: DType) -> Result<(), String> {\n    if data.dtype != want {\n        return Err(format!(\"tensor data dtype {:?} != expected {:?}\", data.dtype, want));\n    }\n    Ok(())\n}\n// call before: ensure_dtype_matches(&data, DType::F32)?;","typeGuard":"fn is_f32_data(data: &TensorData) -> bool {\n    matches!(data.dtype, DType::F32)\n}","tryCatchPattern":null,"preventionTips":["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."],"tags":["rust","burn","ndarray","dtype-mismatch"],"backgroundTag":"tensor-dtype-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"}