From ec6fc4a174e822b5bbaed87b617bfabf9a2f71e5 Mon Sep 17 00:00:00 2001 From: Nicolas Patry Date: Thu, 30 Mar 2023 14:58:08 +0200 Subject: [PATCH] Remove the breaking change of disallowing zero sized tensors. (#221) * 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 | 3 ++- bindings/python/src/lib.rs | 24 +++++++++++++------ bindings/python/tests/test_flax_comparison.py | 11 +++++++++ .../python/tests/test_paddle_comparison.py | 12 ++++++++++ bindings/python/tests/test_pt_comparison.py | 9 +++++++ bindings/python/tests/test_tf_comparison.py | 11 +++++++++ safetensors/src/tensor.rs | 16 ++++++------- 7 files changed, 70 insertions(+), 16 deletions(-) diff --git a/bindings/python/py_src/safetensors/torch.py b/bindings/python/py_src/safetensors/torch.py index 32964c8..2ada235 100644 --- a/bindings/python/py_src/safetensors/torch.py +++ b/bindings/python/py_src/safetensors/torch.py @@ -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() diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index 7c01cba..2f6d999 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -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 => { diff --git a/bindings/python/tests/test_flax_comparison.py b/bindings/python/tests/test_flax_comparison.py index ffe867c..fcb0db5 100644 --- a/bindings/python/tests/test_flax_comparison.py +++ b/bindings/python/tests/test_flax_comparison.py @@ -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) diff --git a/bindings/python/tests/test_paddle_comparison.py b/bindings/python/tests/test_paddle_comparison.py index 47b69ce..2b3b7f3 100644 --- a/bindings/python/tests/test_paddle_comparison.py +++ b/bindings/python/tests/test_paddle_comparison.py @@ -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) diff --git a/bindings/python/tests/test_pt_comparison.py b/bindings/python/tests/test_pt_comparison.py index 0074c46..c68efbe 100644 --- a/bindings/python/tests/test_pt_comparison.py +++ b/bindings/python/tests/test_pt_comparison.py @@ -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), diff --git a/bindings/python/tests/test_tf_comparison.py b/bindings/python/tests/test_tf_comparison.py index efcf3a9..bdaae06 100644 --- a/bindings/python/tests/test_tf_comparison.py +++ b/bindings/python/tests/test_tf_comparison.py @@ -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) diff --git a/safetensors/src/tensor.rs b/safetensors/src/tensor.rs index c90d1fc..bb6ff60 100644 --- a/safetensors/src/tensor.rs +++ b/safetensors/src/tensor.rs @@ -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] -- 2.43.0