]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Remove the breaking change of disallowing zero sized tensors. (#221)
authorNicolas Patry <patry.nicolas@protonmail.com>
Thu, 30 Mar 2023 12:58:08 +0000 (14:58 +0200)
committerGitHub <noreply@github.com>
Thu, 30 Mar 2023 12:58:08 +0000 (14:58 +0200)
* Remove the breaking change of disallowing zero sized tensors.

Some files out there might exist with this.
While being questionnable, it's not worth doing a breaking change
since there doesn't seem to be either a security implication
nor a performance hit.

* Full support for zero-sized tensor on torch==1.10

* Adding a nice comment.

bindings/python/py_src/safetensors/torch.py
bindings/python/src/lib.rs
bindings/python/tests/test_flax_comparison.py
bindings/python/tests/test_paddle_comparison.py
bindings/python/tests/test_pt_comparison.py
bindings/python/tests/test_tf_comparison.py
safetensors/src/tensor.rs

index 32964c8f22549d18c2eec9d66bd0e5ed55a2cf03..2ada2355199aeb7085aa626c2a86cacdba340a17 100644 (file)
@@ -204,8 +204,9 @@ def _tobytes(tensor: torch.Tensor, name: str) -> bytes:
     total_bytes = length * bytes_per_item
 
     ptr = tensor.data_ptr()
+    if ptr == 0:
+        return b""
     newptr = ctypes.cast(ptr, ctypes.POINTER(ctypes.c_ubyte))
-
     data = np.ctypeslib.as_array(newptr, (total_bytes,))  # no internal copy
 
     return data.tobytes()
index 7c01cba65867bd69522a26be293d3396a79de3d9..2f6d9992eaf404c7194b8f1c06b20036cf4c45c4 100644 (file)
@@ -813,16 +813,26 @@ fn create_tensor(
         }
         .ok_or_else(|| SafetensorError::new_err(format!("Could not find module {framework:?}",)))?
         .as_ref(py);
-        let frombuffer = module.getattr(intern!(py, "frombuffer"))?;
         let dtype: PyObject = get_pydtype(module, dtype)?;
-        let kwargs = [
-            (intern!(py, "buffer"), array),
-            (intern!(py, "dtype"), dtype),
-        ]
-        .into_py_dict(py);
-        let tensor = frombuffer.call((), Some(kwargs))?;
+        let count: usize = shape.iter().product();
         let shape = shape.to_vec();
         let shape: PyObject = shape.into_py(py);
+        let tensor = if count == 0 {
+            // Torch==1.10 does not allow frombuffer on empty buffers so we create
+            // the tensor manually.
+            let zeros = module.getattr(intern!(py, "zeros"))?;
+            let args = (shape.clone(),);
+            let kwargs = [(intern!(py, "dtype"), dtype)].into_py_dict(py);
+            zeros.call(args, Some(kwargs))?
+        } else {
+            let frombuffer = module.getattr(intern!(py, "frombuffer"))?;
+            let kwargs = [
+                (intern!(py, "buffer"), array),
+                (intern!(py, "dtype"), dtype),
+            ]
+            .into_py_dict(py);
+            frombuffer.call((), Some(kwargs))?
+        };
         let mut tensor: &PyAny = tensor.getattr(intern!(py, "reshape"))?.call1((shape,))?;
         let tensor = match framework {
             Framework::Flax => {
index ffe867c4d4971807861c4f503ae1c6af377accb1..fcb0db5d2074357d63d86285773f5c923056ec77 100644 (file)
@@ -31,6 +31,17 @@ class LoadTestCase(unittest.TestCase):
 
         save_file(data, self.sf_filename)
 
+    def test_zero_sized(self):
+        data = {
+            "test": jnp.zeros((2, 0), dtype=jnp.float32),
+        }
+        local = "./tests/data/out_safe_flat_mmap_small2.safetensors"
+        save_file(data.copy(), local)
+        reloaded = load_file(local)
+        # Empty tensor != empty tensor on numpy, so comparing shapes
+        # instead
+        self.assertEqual(data["test"].shape, reloaded["test"].shape)
+
     def test_deserialization_safe(self):
         weights = load_file(self.sf_filename)
 
index 47b69ce2263ff4d0361218cdba5ee6b233b882e7..2b3b7f32e8881ff48304637c6694c592374be766 100644 (file)
@@ -19,6 +19,18 @@ class SafeTestCase(unittest.TestCase):
         paddle.save(data, self.paddle_filename)
         save_file(data, self.sf_filename)
 
+    @unittest.expectedFailure
+    def test_zero_sized(self):
+        # This fails because paddle wants initialized tensor before
+        # sending to numpy
+        data = {
+            "test": paddle.zeros((2, 0), dtype=paddle.float32),
+        }
+        local = "./tests/data/out_safe_paddle_mmap_small2.safetensors"
+        save_file(data, local)
+        reloaded = load_file(local)
+        self.assertTrue(paddle.equal(data["test"], reloaded["test"]))
+
     def test_deserialization_safe(self):
         weights = load_file(self.sf_filename)
 
index 0074c461358c49606e7d8e2f131ddd0e803fd71b..c68efbe23fc2cc57e6af3fad14c890bb23190e42 100644 (file)
@@ -20,6 +20,15 @@ class TorchTestCase(unittest.TestCase):
         self.assertTrue(torch.equal(data["test2"], reloaded["test2"]))
         self.assertTrue(torch.equal(data["test3"], reloaded["test3"]))
 
+    def test_zero_sized(self):
+        data = {
+            "test": torch.zeros((2, 0), dtype=torch.float),
+        }
+        local = "./tests/data/out_safe_pt_mmap_small2.safetensors"
+        save_file(data, local)
+        reloaded = load_file(local)
+        self.assertTrue(torch.equal(data["test"], reloaded["test"]))
+
     def test_in_memory(self):
         data = {
             "test": torch.zeros((2, 2), dtype=torch.float32),
index efcf3a907e26e5330d9501ed0cf284d0e45a2a83..bdaae0612b314d1cd81f954bd79e428373961273 100644 (file)
@@ -41,6 +41,17 @@ class SafeTestCase(unittest.TestCase):
             _save(f, data)
         save_file(data, self.sf_filename)
 
+    def test_zero_sized(self):
+        data = {
+            "test": tf.zeros((2, 0), dtype=tf.float32),
+        }
+        local = "./tests/data/out_safe_flat_mmap_small2.safetensors"
+        save_file(data.copy(), local)
+        reloaded = load_file(local)
+        # Empty tensor != empty tensor on numpy, so comparing shapes
+        # instead
+        self.assertEqual(data["test"].shape, reloaded["test"].shape)
+
     def test_deserialization_safe(self):
         weights = load_file(self.sf_filename)
 
index c90d1fca3342174578faabe9d33c441d4a1aeb91..bb6ff6041c834ef9bb864d411268770382af2e44 100644 (file)
@@ -469,7 +469,7 @@ impl Metadata {
         let mut start = 0;
         for (i, info) in self.tensors.iter().enumerate() {
             let (s, e) = info.data_offsets;
-            if s != start || e <= s {
+            if s != start || e < s {
                 let tensor_name = self
                     .index_map
                     .iter()
@@ -1072,14 +1072,14 @@ mod tests {
 
     #[test]
     fn test_zero_sized_tensor() {
-        let serialized = b"<\x00\x00\x00\x00\x00\x00\x00{\"test\":{\"dtype\":\"I32\",\"shape\":[2,0],\"data_offsets\":[0, 0]}}\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
+        let serialized = b"<\x00\x00\x00\x00\x00\x00\x00{\"test\":{\"dtype\":\"I32\",\"shape\":[2,0],\"data_offsets\":[0, 0]}}";
+        let loaded = SafeTensors::deserialize(serialized).unwrap();
 
-        match SafeTensors::deserialize(serialized) {
-            Err(SafeTensorError::InvalidOffset(_)) => {
-                // Yes we have the correct error
-            }
-            _ => panic!("This should not be able to be deserialized"),
-        }
+        assert_eq!(loaded.names(), vec!["test"]);
+        let tensor = loaded.tensor("test").unwrap();
+        assert_eq!(tensor.shape(), vec![2, 0]);
+        assert_eq!(tensor.dtype(), Dtype::I32);
+        assert_eq!(tensor.data(), b"");
     }
 
     #[test]