]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Adding mmap loading to prevent the extra copy while remaining safe.
authorNicolas Patry <patry.nicolas@protonmail.com>
Fri, 25 Feb 2022 12:47:45 +0000 (13:47 +0100)
committerNicolas Patry <patry.nicolas@protonmail.com>
Fri, 25 Feb 2022 12:47:45 +0000 (13:47 +0100)
bindings/python/Cargo.toml
bindings/python/py_src/safetensors/__init__.py
bindings/python/src/lib.rs
bindings/python/tests/test_pt_comparison.py

index b5bfa9d419f49f485f75388aa906c91e2a37b72f..9d2812fe160dc3f854004c29b69375bb442bd909 100644 (file)
@@ -10,6 +10,7 @@ crate-type = ["cdylib"]
 
 [dependencies]
 pyo3 = { version = "0.15.1", features = ["extension-module"] }
+memmap = "0.7"
 
 [dependencies.safetensors]
 version = "*"
index d830908893b28b82a606d4b57e0f795d6f81156f..83b54e988cef7fd3f5fb41add880357bdb614804 100644 (file)
@@ -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:
index 4e7039da15304cef51e8c3c8202008602ef83265..92fb1e6eed125625622a5771e7d54d1b4f2c0ffe 100644 (file)
@@ -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<Vec<(String, HashMap<String, PyObject>)>> {
     let start = std::time::Instant::now();
@@ -69,10 +71,21 @@ fn deserialize(py: Python, bytes: &[u8]) -> PyResult<Vec<(String, HashMap<String
     Ok(items)
 }
 
+#[pyfunction]
+fn deserialize_file(
+    py: Python,
+    filename: &str,
+) -> PyResult<Vec<(String, HashMap<String, PyObject>)>> {
+    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(())
 }
index 2a3879549042e1d3e57b5459e80659682d862924..93972c24c573b9e275064f5bbb218844e62f5242 100644 (file)
@@ -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):