]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Zero width shape are OK (0-rank tensors). They are simply a scalar. (#208)
authorNicolas Patry <patry.nicolas@protonmail.com>
Tue, 28 Mar 2023 13:32:41 +0000 (15:32 +0200)
committerGitHub <noreply@github.com>
Tue, 28 Mar 2023 13:32:41 +0000 (15:32 +0200)
* 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

index cb5a057729bd28e72ae08e2560ee998c3952cc3a..ecd986b5d02087281ae1bdfc2ab5f011bec4c900 100644 (file)
@@ -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";