From 5976446c9276f0dbd54a1222a9125dae45c0fd6f Mon Sep 17 00:00:00 2001 From: Nicolas Patry Date: Fri, 25 Feb 2022 14:55:50 +0100 Subject: [PATCH] Writing to file using BufWriter. --- .../python/py_src/safetensors/__init__.py | 24 +++++++++--- bindings/python/src/lib.rs | 27 +++++++++++-- bindings/python/tests/test_pt_comparison.py | 37 +++++++++--------- safetensors/src/lib.rs | 38 ++++++++++++++----- 4 files changed, 88 insertions(+), 38 deletions(-) diff --git a/bindings/python/py_src/safetensors/__init__.py b/bindings/python/py_src/safetensors/__init__.py index 83b54e9..2378fe0 100644 --- a/bindings/python/py_src/safetensors/__init__.py +++ b/bindings/python/py_src/safetensors/__init__.py @@ -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) diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index 92fb1e6..0ba32d8 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -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, -) -> PyResult<&'b PyBytes> { +) -> PyResult>> { 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, +) -> 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, + filename: &str, +) -> PyResult<()> { + let tensors = prepare(py, tensor_dict)?; + SafeTensor::serialize_to_file(&tensors, filename)?; + Ok(()) +} + #[pyfunction] fn deserialize(py: Python, bytes: &[u8]) -> PyResult)>> { 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(()) diff --git a/bindings/python/tests/test_pt_comparison.py b/bindings/python/tests/test_pt_comparison.py index 93972c2..e6b670c 100644 --- a/bindings/python/tests/test_pt_comparison.py +++ b/bindings/python/tests/test_pt_comparison.py @@ -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 diff --git a/safetensors/src/lib.rs b/safetensors/src/lib.rs index c63f946..ddf0ca4 100644 --- a/safetensors/src/lib.rs +++ b/safetensors/src/lib.rs @@ -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) -> Vec { + fn prepare<'hash, 'data>( + data: &'hash HashMap>, + ) -> (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 = Vec::with_capacity(1 + metadata_buf.len() + offset); + pub fn serialize(data: &HashMap) -> Vec { + 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 = 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, + 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) -> Result { 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(); } } -- 2.43.0