]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Writing to file using BufWriter.
authorNicolas Patry <patry.nicolas@protonmail.com>
Fri, 25 Feb 2022 13:55:50 +0000 (14:55 +0100)
committerNicolas Patry <patry.nicolas@protonmail.com>
Fri, 25 Feb 2022 13:55:50 +0000 (14:55 +0100)
bindings/python/py_src/safetensors/__init__.py
bindings/python/src/lib.rs
bindings/python/tests/test_pt_comparison.py
safetensors/src/lib.rs

index 83b54e988cef7fd3f5fb41add880357bdb614804..2378fe0a37f7283de264821356e562b49b32cf2c 100644 (file)
@@ -2,7 +2,7 @@ __version__ = "0.0.1"
 
 from typing import Dict
 import numpy as np
-from .safetensors_rust import deserialize, serialize, deserialize_file
+from .safetensors_rust import deserialize, serialize, deserialize_file, serialize_file
 import torch
 
 
@@ -16,6 +16,14 @@ def save(tensor_dict: Dict[str, np.ndarray]) -> bytes:
     return result
 
 
+def save_file(tensor_dict: Dict[str, np.ndarray], filename: str):
+    flattened = {
+        k: {"dtype": v.dtype.name, "shape": v.shape, "data": v.tobytes()}
+        for k, v in tensor_dict.items()
+    }
+    serialize_file(flattened, filename)
+
+
 TYPES = {"F32": np.float32, "I32": np.int32}
 
 
@@ -25,15 +33,15 @@ def getdtype(dtype_str: str) -> np.dtype:
 
 def load_file(filename: str) -> Dict[str, np.ndarray]:
     flat = deserialize_file(filename)
-    return to_numpy(flat)
+    return view2np(flat)
 
 
 def load(buffer: bytes) -> Dict[str, np.ndarray]:
     flat = deserialize(buffer)
-    return to_numpy(flat)
+    return view2np(flat)
 
 
-def to_numpy(safeview):
+def view2np(safeview):
     result = {}
     for k, v in safeview:
         dtype = getdtype(v["dtype"])
@@ -42,7 +50,7 @@ def to_numpy(safeview):
     return result
 
 
-def to_pt(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, torch.Tensor]:
+def np2pt(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, torch.Tensor]:
     for k, v in numpy_dict.items():
         numpy_dict[k] = torch.from_numpy(v)
     return numpy_dict
@@ -52,3 +60,9 @@ def save_pt(tensors: Dict[str, torch.Tensor]) -> bytes:
     for k, v in tensors.items():
         tensors[k] = v.numpy()
     return save(tensors)
+
+
+def save_file_pt(tensors: Dict[str, torch.Tensor], filename: str) -> bytes:
+    for k, v in tensors.items():
+        tensors[k] = v.numpy()
+    return save_file(tensors, filename)
index 92fb1e6eed125625622a5771e7d54d1b4f2c0ffe..0ba32d8bc89d1e291dd46eee7d899a077a611e8a 100644 (file)
@@ -7,12 +7,10 @@ use std::collections::HashMap;
 use std::fs::File;
 use std::io::Write;
 
-/// Formats the sum of two numbers as string.
-#[pyfunction]
-fn serialize<'a, 'b>(
+fn prepare<'a, 'b>(
     py: Python<'b>,
     tensor_dict: HashMap<String, &'a PyDict>,
-) -> PyResult<&'b PyBytes> {
+) -> PyResult<HashMap<String, Tensor<'a>>> {
     let start = std::time::Instant::now();
     let mut tensors = HashMap::new();
     for (tensor_name, tensor_desc) in tensor_dict {
@@ -42,11 +40,31 @@ fn serialize<'a, 'b>(
         let tensor = Tensor::new(data, dtype, shape);
         tensors.insert(tensor_name, tensor);
     }
+    Ok(tensors)
+}
+
+#[pyfunction]
+fn serialize<'a, 'b>(
+    py: Python<'b>,
+    tensor_dict: HashMap<String, &'a PyDict>,
+) -> PyResult<&'b PyBytes> {
+    let tensors = prepare(py, tensor_dict)?;
     let out = SafeTensor::serialize(&tensors);
     let pybytes = PyBytes::new(py, &out);
     Ok(pybytes)
 }
 
+#[pyfunction]
+fn serialize_file<'a, 'b>(
+    py: Python<'b>,
+    tensor_dict: HashMap<String, &'a PyDict>,
+    filename: &str,
+) -> PyResult<()> {
+    let tensors = prepare(py, tensor_dict)?;
+    SafeTensor::serialize_to_file(&tensors, filename)?;
+    Ok(())
+}
+
 #[pyfunction]
 fn deserialize(py: Python, bytes: &[u8]) -> PyResult<Vec<(String, HashMap<String, PyObject>)>> {
     let start = std::time::Instant::now();
@@ -85,6 +103,7 @@ fn deserialize_file(
 #[pymodule]
 fn safetensors_rust(_py: Python, m: &PyModule) -> PyResult<()> {
     m.add_function(wrap_pyfunction!(serialize, m)?)?;
+    m.add_function(wrap_pyfunction!(serialize_file, m)?)?;
     m.add_function(wrap_pyfunction!(deserialize, m)?)?;
     m.add_function(wrap_pyfunction!(deserialize_file, m)?)?;
     Ok(())
index 93972c24c573b9e275064f5bbb218844e62f5242..e6b670c63e7c7d2c36448c29c648266f87fd7a50 100644 (file)
@@ -1,5 +1,5 @@
 import unittest
-from safetensors import save_pt, load_file, to_pt, load
+from safetensors import save_file_pt, load_file, np2pt, load
 from huggingface_hub import hf_hub_download
 import torch
 import datetime
@@ -8,32 +8,28 @@ 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)
+        local = "out_safe.bin"
+        save_file_pt(data, local)
 
         start = datetime.datetime.now()
         with open(local, "rb") as f:
             serialized = f.read()
         print()
         print("Reading file took ", datetime.datetime.now() - start)
-        to_pt(load(serialized))
+        np2pt(load(serialized))
         print("Deserialization (Safe) took ", datetime.datetime.now() - start)
 
     def test_gpt2_deserialization_safe_mmap(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)
+        local = "out_safe_mmap.bin"
+        save_file_pt(data, local)
 
         start = datetime.datetime.now()
-        to_pt(load_file(local))
+        np2pt(load_file(local))
         print()
         print("Deserialization (Safe) took ", datetime.datetime.now() - start)
 
@@ -45,19 +41,20 @@ class BigTestCase(unittest.TestCase):
         print()
         print("Deserialization (PT) took ", datetime.datetime.now() - start)
 
-    def test_gpt2_serialization(self):
+    def test_gpt2_serialization_pt(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)
+
+    def test_gpt2_serialization_safe(self):
+        filename = hf_hub_download("gpt2", filename="pytorch_model.bin")
+        data = torch.load(filename)
+        start = datetime.datetime.now()
+        outfilename = "out_py_test.bin"
+        out = save_file_pt(data, outfilename)
+        print("Serialization (safe) took ", datetime.datetime.now() - start)
+        del out
index c63f946ba15fec077defc39df6055b4a0456b967..ddf0ca471e6cd58b3f509f280daac32361427dbc 100644 (file)
@@ -1,5 +1,7 @@
 use serde::{Deserialize, Serialize};
 use std::collections::HashMap;
+use std::fs::File;
+use std::io::{BufWriter, Write};
 
 #[derive(Debug)]
 pub enum SafeTensorError {
@@ -13,13 +15,14 @@ pub struct SafeTensor {
 }
 
 impl SafeTensor {
-    pub fn serialize(data: &HashMap<String, Tensor>) -> Vec<u8> {
+    fn prepare<'hash, 'data>(
+        data: &'hash HashMap<String, Tensor<'data>>,
+    ) -> (Metadata, Vec<&'hash Tensor<'data>>, usize) {
         let mut tensors: Vec<&Tensor> = vec![];
         let mut hmetadata = HashMap::new();
         let mut offset = 0;
         for (name, tensor) in data {
             let n = tensor.data.len();
-
             let tensor_info = TensorInfo {
                 dtype: tensor.dtype.clone(),
                 shape: tensor.shape.clone(),
@@ -32,9 +35,14 @@ impl SafeTensor {
 
         let metadata: Metadata = Metadata(hmetadata);
 
-        let metadata_buf = serde_json::to_string(&metadata).unwrap().into_bytes();
+        (metadata, tensors, offset)
+    }
 
-        let mut buffer: Vec<u8> = Vec::with_capacity(1 + metadata_buf.len() + offset);
+    pub fn serialize(data: &HashMap<String, Tensor>) -> Vec<u8> {
+        let (metadata, tensors, offset) = Self::prepare(data);
+        let metadata_buf = serde_json::to_string(&metadata).unwrap().into_bytes();
+        let expected_size = 8 + metadata_buf.len() + offset;
+        let mut buffer: Vec<u8> = Vec::with_capacity(expected_size);
         let n: u64 = metadata_buf.len() as u64;
         buffer.extend(&n.to_le_bytes().to_vec());
         buffer.extend(&metadata_buf);
@@ -44,6 +52,23 @@ impl SafeTensor {
         buffer
     }
 
+    pub fn serialize_to_file(
+        data: &HashMap<String, Tensor>,
+        filename: &str,
+    ) -> Result<(), std::io::Error> {
+        let (metadata, tensors, _) = Self::prepare(data);
+        let metadata_buf = serde_json::to_string(&metadata).unwrap().into_bytes();
+        let n: u64 = metadata_buf.len() as u64;
+        let mut f = BufWriter::new(File::create(filename)?);
+        f.write_all(&n.to_le_bytes().to_vec())?;
+        f.write_all(&metadata_buf)?;
+        for tensor in tensors {
+            f.write_all(tensor.data)?;
+        }
+        f.flush()?;
+        Ok(())
+    }
+
     pub fn deserialize(buffer: Vec<u8>) -> Result<SafeTensor, SafeTensorError> {
         let arr: [u8; 8] = [
             buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6], buffer[7],
@@ -228,17 +253,12 @@ mod tests {
 
         let filename = format!("./out_{}.bin", model_id);
 
-        use std::time::Instant;
-        let start = Instant::now();
         let out = SafeTensor::serialize(&metadata);
 
-        let start = Instant::now();
         std::fs::write(&filename, out).unwrap();
 
-        let start = Instant::now();
         let raw = std::fs::read(&filename).unwrap();
 
-        let start = Instant::now();
         SafeTensor::deserialize(raw).unwrap();
     }
 }