]> khamidou — GitHub mirrors - safetensors.git/commitdiff
ByteArray (to be writeable for torch support).
authorNicolas Patry <patry.nicolas@protonmail.com>
Thu, 24 Feb 2022 18:27:51 +0000 (19:27 +0100)
committerNicolas Patry <patry.nicolas@protonmail.com>
Thu, 24 Feb 2022 18:27:51 +0000 (19:27 +0100)
bindings/python/py_src/safetensors/__init__.py
bindings/python/src/lib.rs
bindings/python/tests/test_pt_comparison.py [new file with mode: 0644]
bindings/python/tests/test_simple.py
safetensors/src/lib.rs

index bc52d71dc81f65a9d4620377861aaad995594fe4..d830908893b28b82a606d4b57e0f795d6f81156f 100644 (file)
@@ -7,18 +7,12 @@ import torch
 
 
 def save(tensor_dict: Dict[str, np.ndarray]) -> bytes:
-    import datetime
-
-    start = datetime.datetime.now()
     flattened = {
         k: {"dtype": v.dtype.name, "shape": v.shape, "data": v.tobytes()}
         for k, v in tensor_dict.items()
     }
-    print("Flattened", datetime.datetime.now() - start)
     serialized = serialize(flattened)
-    print("Serialized", datetime.datetime.now() - start)
     result = bytes(serialized)
-    print("Bytes", datetime.datetime.now() - start)
     return result
 
 
index 60dca86741b04593a4502a65a2564476bac7ac4f..4e7039da15304cef51e8c3c8202008602ef83265 100644 (file)
@@ -1,6 +1,6 @@
 use pyo3::exceptions;
 use pyo3::prelude::*;
-use pyo3::types::{PyBytes, PyDict, PyList};
+use pyo3::types::{PyByteArray, PyBytes, PyDict, PyList};
 use safetensors::{Dtype, SafeTensor, SafeTensorBorrowed, Tensor};
 use std::collections::HashMap;
 
@@ -59,7 +59,7 @@ fn deserialize(py: Python, bytes: &[u8]) -> PyResult<Vec<(String, HashMap<String
         let pyshape: PyObject = PyList::new(py, tensor.shape.into_iter()).into();
         let pydtype: PyObject = format!("{:?}", tensor.dtype).into_py(py);
 
-        let pydata: PyObject = PyBytes::new(py, tensor.data).into();
+        let pydata: PyObject = PyByteArray::new(py, tensor.data).into();
 
         map.insert("shape".to_string(), pyshape);
         map.insert("dtype".to_string(), pydtype);
diff --git a/bindings/python/tests/test_pt_comparison.py b/bindings/python/tests/test_pt_comparison.py
new file mode 100644 (file)
index 0000000..2a38795
--- /dev/null
@@ -0,0 +1,49 @@
+import unittest
+from safetensors import load_pt, save_pt
+from huggingface_hub import hf_hub_download
+import torch
+import datetime
+
+
+class BigTestCase(unittest.TestCase):
+    def test_gpt2_deserialization_safe(self):
+        filename = hf_hub_download("gpt2", filename="pytorch_model.bin")
+        local = "out_safe.bin"
+        data = torch.load(filename)
+
+        out = save_pt(data)
+        with open(local, "wb") as f:
+            f.write(out)
+
+        start = datetime.datetime.now()
+        with open(local, "rb") as f:
+            serialized = f.read()
+        print()
+        print("Reading file took ", datetime.datetime.now() - start)
+        load_pt(serialized)
+        print("Deserialization (Safe) took ", datetime.datetime.now() - start)
+
+    def test_gpt2_deserialization_pt(self):
+        filename = hf_hub_download("gpt2", filename="pytorch_model.bin")
+
+        start = datetime.datetime.now()
+        torch.load(filename)
+        print()
+        print("Deserialization (PT) took ", datetime.datetime.now() - start)
+
+    def test_gpt2_serialization(self):
+        filename = hf_hub_download("gpt2", filename="pytorch_model.bin")
+        data = torch.load(filename)
+
+        start = datetime.datetime.now()
+        out = save_pt(data)
+        with open("out_py_test.bin", "wb") as f:
+            f.write(out)
+        print()
+        print("Serialization (safe) took ", datetime.datetime.now() - start)
+        del out
+
+        start = datetime.datetime.now()
+        with open("out_pt.bin", "wb") as f:
+            torch.save(data, f)
+        print("Serialization (PT) took ", datetime.datetime.now() - start)
index 7e927f2776b7b6dfc3a021fc844f49d01cfa9a63..8ea009d726dd15e5960155d0fc7b855b3532daa0 100644 (file)
@@ -3,7 +3,6 @@ from safetensors import save, load, load_pt, save_pt
 import numpy as np
 from huggingface_hub import hf_hub_download
 import torch
-import os
 import datetime
 
 
@@ -31,28 +30,3 @@ class TestCase(unittest.TestCase):
         out = load(serialized)
         self.assertEqual(list(out.keys()), ["test"])
         np.testing.assert_array_equal(out["test"], np.zeros((2, 2), dtype=np.int32))
-
-
-class BigTestCase(unittest.TestCase):
-    def test_gpt2_deserialization(self):
-        start = datetime.datetime.now()
-        with open("out_py.bin", "rb") as f:
-            serialized = f.read()
-        print("Reading file took ", datetime.datetime.now() - start)
-        out = load_pt(serialized)
-        print("Deserialization took ", datetime.datetime.now() - start)
-
-    def test_gpt2_serialization(self):
-        filename = hf_hub_download("gpt2", filename="pytorch_model.bin")
-        data = torch.load(filename)
-
-        start = datetime.datetime.now()
-        out = save_pt(data)
-        with open("out_py_test.bin", "wb") as f:
-            f.write(out)
-        print("Saving took ", datetime.datetime.now() - start)
-
-        start = datetime.datetime.now()
-        with open("out_py_test_pt.bin", "wb") as f:
-            torch.save(data, f)
-        print("PT Saving took ", datetime.datetime.now() - start)
index 01dbf8253ffbdf59d8900ba817ed12744db76162..c63f946ba15fec077defc39df6055b4a0456b967 100644 (file)
@@ -231,32 +231,14 @@ mod tests {
         use std::time::Instant;
         let start = Instant::now();
         let out = SafeTensor::serialize(&metadata);
-        println!("Serialization {:?}", start.elapsed());
 
         let start = Instant::now();
         std::fs::write(&filename, out).unwrap();
-        println!("Write to file {:?}", start.elapsed());
 
         let start = Instant::now();
         let raw = std::fs::read(&filename).unwrap();
-        println!("Read from file {:?}", start.elapsed());
 
         let start = Instant::now();
         SafeTensor::deserialize(raw).unwrap();
-        println!("Deserialization {:?}", start.elapsed());
     }
-
-    // use std::fs::File;
-    // use std::io::Read;
-    // use std::time::Instant;
-    // #[test]
-    // fn read_gpt2() {
-    //     let start = Instant::now();
-    //     let filename = "gpt2.bin";
-    //     let mut f = File::open(&filename).unwrap();
-    //     let metadata = std::fs::metadata(&filename).expect("unable to read metadata");
-    //     let mut buffer = vec![0; metadata.len() as usize];
-    //     f.read(&mut buffer).expect("buffer overflow");
-    //     println!("Read gpt2 in {:?}", start.elapsed());
-    // }
 }