From 8375de6d25673c78de9947bded483ca3359fea82 Mon Sep 17 00:00:00 2001 From: Nicolas Patry Date: Tue, 28 Mar 2023 15:32:41 +0200 Subject: [PATCH] Zero width shape are OK (0-rank tensors). They are simply a scalar. (#208) * Zero width shape are OK (0-rank tensors). They are simply a scalar. Reasosn for support is that both torch and numpy support them, and they flow naturally from the definition that an empty product has length 1. * not allowed -> allowed --- safetensors/src/tensor.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/safetensors/src/tensor.rs b/safetensors/src/tensor.rs index cb5a057..ecd986b 100644 --- a/safetensors/src/tensor.rs +++ b/safetensors/src/tensor.rs @@ -796,6 +796,19 @@ mod tests { std::fs::remove_file(&filename).unwrap(); } + #[test] + fn test_empty_shapes_allowed() { + let serialized = b"8\x00\x00\x00\x00\x00\x00\x00{\"test\":{\"dtype\":\"I32\",\"shape\":[],\"data_offsets\":[0,4]}}\x00\x00\x00\x00\x00\x00\x00\x00"; + + let loaded = SafeTensors::deserialize(serialized).unwrap(); + assert_eq!(loaded.names(), vec!["test"]); + let tensor = loaded.tensor("test").unwrap(); + assert!(tensor.shape().is_empty()); + assert_eq!(tensor.dtype(), Dtype::I32); + // 4 bytes + assert_eq!(tensor.data(), b"\0\0\0\0"); + } + #[test] fn test_deserialization() { let serialized = b"<\x00\x00\x00\x00\x00\x00\x00{\"test\":{\"dtype\":\"I32\",\"shape\":[2,2],\"data_offsets\":[0,16]}}\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; -- 2.43.0