]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Fixing the fact that the context manager wasn't properly cleaning up after itself...
authorNicolas Patry <patry.nicolas@protonmail.com>
Thu, 19 Jan 2023 13:30:56 +0000 (14:30 +0100)
committerGitHub <noreply@github.com>
Thu, 19 Jan 2023 13:30:56 +0000 (14:30 +0100)
* Adding failing test for windows.

* This should fail.

* Fixing Windows issue by actually dropping the rust resources.

* Making the rust module private.

bindings/python/py_src/safetensors/__init__.py
bindings/python/py_src/safetensors/numpy.py
bindings/python/py_src/safetensors/torch.py
bindings/python/setup.py
bindings/python/src/lib.rs
bindings/python/tests/test_pt_comparison.py
bindings/python/tests/test_simple.py

index 36154609c7b4b6262823a5277ed80cd2b1b2cfe5..6b983974a3dfeb41a96c4ca85eccf92adf2d2040 100644 (file)
@@ -1,4 +1,20 @@
 __version__ = "0.2.9"
 
 # Re-export this
-from .safetensors_rust import safe_open  # noqa: F401
+from ._safetensors_rust import safe_open as rust_open, serialize, serialize_file, deserialize, SafetensorError
+
+
+class safe_open:
+    def __init__(self, *args, **kwargs):
+        self.args = args
+        self.kwargs = kwargs
+
+    def __getattr__(self, __name: str):
+        return getattr(self.f, __name)
+
+    def __enter__(self):
+        self.f = rust_open(*self.args, **self.kwargs)
+        return self
+
+    def __exit__(self, type, value, traceback):
+        del self.f
index 8a4c661bdb7aa9e97edd3096ef159e87f0aba390..bae82b883eadcb05c637d8e68873f906705a5b10 100644 (file)
@@ -4,7 +4,7 @@ from typing import Dict, Optional, Union
 
 import numpy as np
 
-from .safetensors_rust import deserialize, safe_open, serialize, serialize_file
+from safetensors import deserialize, safe_open, serialize, serialize_file
 
 
 def save(tensor_dict: Dict[str, np.ndarray], metadata: Optional[Dict[str, str]] = None) -> bytes:
index 110f3261e48286652804bb0a6816e00eb42f506a..1df67f302b9674810f336c296264656884a2d1d8 100644 (file)
@@ -5,7 +5,7 @@ from typing import Any, Dict, Optional, Union
 
 import torch
 
-from .safetensors_rust import deserialize, safe_open, serialize, serialize_file
+from safetensors import deserialize, safe_open, serialize, serialize_file
 
 
 def save(tensors: Dict[str, torch.Tensor], metadata: Optional[Dict[str, str]] = None) -> bytes:
index eed0e2c6aba33b0bb5fdd7f8b26ea028af84ebe6..ea2c6c31620389b5fe70bf9461f10fcccae62688 100644 (file)
@@ -59,7 +59,7 @@ setup(
     author_email="",
     url="https://github.com/huggingface/safetensors",
     license="Apache License 2.0",
-    rust_extensions=[RustExtension("safetensors.safetensors_rust", binding=Binding.PyO3, debug=False)],
+    rust_extensions=[RustExtension("safetensors._safetensors_rust", binding=Binding.PyO3, debug=False)],
     extras_require=extras,
     classifiers=[
         "Development Status :: 5 - Production/Stable",
index 19a885a27f7c5af358f08cded38b1badc227ec02..58a6e3d5cda009a1ccb26bc2ae7db453081770fd 100644 (file)
@@ -1021,7 +1021,7 @@ pyo3::create_exception!(
 
 /// A Python module implemented in Rust.
 #[pymodule]
-fn safetensors_rust(py: Python, m: &PyModule) -> PyResult<()> {
+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)?)?;
index 8c5c3cec76537eae1c8f02c83a41f551e63a5297..38f4f389f1cc3b0a5436031bd5c6090ec42f405d 100644 (file)
@@ -2,7 +2,7 @@ import unittest
 
 import torch
 
-from safetensors.safetensors_rust import safe_open
+from safetensors import safe_open
 from safetensors.torch import load, load_file, save, save_file
 
 
index 2b6497e4da21a90986bd6634c1b3d5282767178b..e05552bf37d52b146c0e657676f377f8084bf42b 100644 (file)
@@ -6,7 +6,7 @@ import numpy as np
 import torch
 
 from safetensors.numpy import load, load_file, save, save_file
-from safetensors.safetensors_rust import SafetensorError, serialize
+from safetensors import safe_open, SafetensorError, serialize
 from safetensors.torch import load_file as load_file_pt
 from safetensors.torch import save_file as save_file_pt
 
@@ -59,6 +59,20 @@ class TestCase(unittest.TestCase):
         os.remove(Path("./out.safetensors"))
 
 
+class WindowsTestCase(unittest.TestCase):
+    def test_get_correctly_dropped(self):
+        tensors = {
+            "a": torch.zeros((2, 2)),
+            "b": torch.zeros((2, 3), dtype=torch.uint8),
+        }
+        save_file_pt(tensors, "./out.safetensors")
+        with safe_open("./out.safetensors", framework="pt") as f:
+            pass
+
+        with open("./out.safetensors", "w") as g:
+            g.write("something")
+
+
 class ReadmeTestCase(unittest.TestCase):
     def assertTensorEqual(self, tensors1, tensors2, equality_fn):
         self.assertEqual(tensors1.keys(), tensors2.keys(), "tensor keys don't match")