From: Nicolas Patry Date: Fri, 25 Feb 2022 12:47:45 +0000 (+0100) Subject: Adding mmap loading to prevent the extra copy while remaining safe. X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=1070d7d80ec0dbb8923c0354c7cf33d4ec9ed2bb;p=safetensors.git Adding mmap loading to prevent the extra copy while remaining safe. --- diff --git a/bindings/python/Cargo.toml b/bindings/python/Cargo.toml index b5bfa9d..9d2812f 100644 --- a/bindings/python/Cargo.toml +++ b/bindings/python/Cargo.toml @@ -10,6 +10,7 @@ crate-type = ["cdylib"] [dependencies] pyo3 = { version = "0.15.1", features = ["extension-module"] } +memmap = "0.7" [dependencies.safetensors] version = "*" diff --git a/bindings/python/py_src/safetensors/__init__.py b/bindings/python/py_src/safetensors/__init__.py index d830908..83b54e9 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 +from .safetensors_rust import deserialize, serialize, deserialize_file import torch @@ -23,22 +23,29 @@ def getdtype(dtype_str: str) -> np.dtype: return TYPES[dtype_str] +def load_file(filename: str) -> Dict[str, np.ndarray]: + flat = deserialize_file(filename) + return to_numpy(flat) + + def load(buffer: bytes) -> Dict[str, np.ndarray]: flat = deserialize(buffer) + return to_numpy(flat) + +def to_numpy(safeview): result = {} - for k, v in flat: + for k, v in safeview: dtype = getdtype(v["dtype"]) arr = np.frombuffer(v["data"], dtype=dtype) result[k] = arr return result -def load_pt(buffer: bytes) -> Dict[str, torch.Tensor]: - out = load(buffer) - for k, v in out.items(): - out[k] = torch.from_numpy(v) - return out +def to_pt(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 def save_pt(tensors: Dict[str, torch.Tensor]) -> bytes: diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index 4e7039d..92fb1e6 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -1,8 +1,11 @@ +use memmap::MmapOptions; use pyo3::exceptions; use pyo3::prelude::*; use pyo3::types::{PyByteArray, PyBytes, PyDict, PyList}; use safetensors::{Dtype, SafeTensor, SafeTensorBorrowed, Tensor}; use std::collections::HashMap; +use std::fs::File; +use std::io::Write; /// Formats the sum of two numbers as string. #[pyfunction] @@ -44,7 +47,6 @@ fn serialize<'a, 'b>( Ok(pybytes) } -/// Formats the sum of two numbers as string. #[pyfunction] fn deserialize(py: Python, bytes: &[u8]) -> PyResult)>> { let start = std::time::Instant::now(); @@ -69,10 +71,21 @@ fn deserialize(py: Python, bytes: &[u8]) -> PyResult PyResult)>> { + let file = File::open(filename)?; + let mmap = unsafe { MmapOptions::new().map(&file)? }; + deserialize(py, &mmap) +} + /// A Python module implemented in Rust. #[pymodule] fn safetensors_rust(_py: Python, m: &PyModule) -> PyResult<()> { m.add_function(wrap_pyfunction!(serialize, 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 2a38795..93972c2 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 load_pt, save_pt +from safetensors import save_pt, load_file, to_pt, load from huggingface_hub import hf_hub_download import torch import datetime @@ -20,7 +20,21 @@ class BigTestCase(unittest.TestCase): serialized = f.read() print() print("Reading file took ", datetime.datetime.now() - start) - load_pt(serialized) + to_pt(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) + + start = datetime.datetime.now() + to_pt(load_file(local)) + print() print("Deserialization (Safe) took ", datetime.datetime.now() - start) def test_gpt2_deserialization_pt(self):