]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Accepting `pathlib.Path` in `save_file/load_file/safe_open`. (#86)
authorNicolas Patry <patry.nicolas@protonmail.com>
Fri, 18 Nov 2022 14:24:35 +0000 (15:24 +0100)
committerGitHub <noreply@github.com>
Fri, 18 Nov 2022 14:24:35 +0000 (15:24 +0100)
* Accepting `pathlib.Path` in `save_file/load_file/safe_open`.

* as_path.

* Update docstrings.

- Removed unused `:obj:`
- Put `os.PathLike` everywhere it's needed
- python stub.py

bindings/python/py_src/safetensors/flax.py
bindings/python/py_src/safetensors/numpy.py
bindings/python/py_src/safetensors/tensorflow.py
bindings/python/py_src/safetensors/torch.py
bindings/python/src/lib.rs
bindings/python/tests/test_simple.py
safetensors/src/tensor.rs

index 36909ea5127372205defa5102f14db032020b6fa..f0e90f29b65d3e95f26d99c90231bcf93724d344 100644 (file)
@@ -46,7 +46,7 @@ def save_file(
     Args:
         tensors (`Dict[str, jnp.DeviceArray]`):
             The incoming tensors. Tensors need to be contiguous and dense.
-        filename (`str`):
+        filename (`str`, or `os.PathLike`)):
             The filename we're saving into.
         metadata (`Dict[str, str]`, *optional*, defaults to `None`):
             Optional text only metadata you might want to save in your header.
@@ -102,7 +102,7 @@ def load_file(filename: str) -> Dict[str, jnp.DeviceArray]:
     Loads a safetensors file into flax format.
 
     Args:
-        filename (`str`):
+        filename (`str`, or `os.PathLike`)):
             The name of the file which contains the tensors
         device (`Dict[str, any]`, *optional*, defaults to `cpu`):
             The device where the tensors need to be located after load.
index e91ed3e94b1285f93a0f497475a1e510dbbd7fdb..7d575bd0a982c07ee9e1ef4f4bcbb117c60cb575 100644 (file)
@@ -48,7 +48,7 @@ def save_file(tensor_dict: Dict[str, np.ndarray], filename: str, metadata: Optio
     Args:
         tensors (`Dict[str, np.ndarray]`):
             The incoming tensors. Tensors need to be contiguous and dense.
-        filename (`str`):
+        filename (`str`, or `os.PathLike`)):
             The filename we're saving into.
         metadata (`Dict[str, str]`, *optional*, defaults to `None`):
             Optional text only metadata you might want to save in your header.
@@ -104,7 +104,7 @@ def load_file(filename: str) -> Dict[str, np.ndarray]:
     Loads a safetensors file into numpy format.
 
     Args:
-        filename (`str`):
+        filename (`str`, or `os.PathLike`)):
             The name of the file which contains the tensors
         device (`Dict[str, any]`, *optional*, defaults to `cpu`):
             The device where the tensors need to be located after load.
index 76fbf812714d1a9a185e4eaa8cf35706db90a38e..782b53e51b397a2a6640ec74c2b7be4f9fafe249 100644 (file)
@@ -46,7 +46,7 @@ def save_file(
     Args:
         tensors (`Dict[str, tf.Tensor]`):
             The incoming tensors. Tensors need to be contiguous and dense.
-        filename (`str`):
+        filename (`str`, or `os.PathLike`)):
             The filename we're saving into.
         metadata (`Dict[str, str]`, *optional*, defaults to `None`):
             Optional text only metadata you might want to save in your header.
@@ -102,7 +102,7 @@ def load_file(filename: str) -> Dict[str, tf.Tensor]:
     Loads a safetensors file into tensorflow format.
 
     Args:
-        filename (`str`):
+        filename (`str`, or `os.PathLike`)):
             The name of the file which contains the tensors
         device (`Dict[str, any]`, *optional*, defaults to `cpu`):
             The device where the tensors need to be located after load.
index 69d2087fce1a9cc7c370f9790647b25dff893c8d..4d39bc871ef19ec86cc1b9f2ba20196163433cd2 100644 (file)
@@ -48,7 +48,7 @@ def save_file(
     Args:
         tensors (`Dict[str, torch.Tensor]`):
             The incoming tensors. Tensors need to be contiguous and dense.
-        filename (`str`):
+        filename (`str`, or `os.PathLike`)):
             The filename we're saving into.
         metadata (`Dict[str, str]`, *optional*, defaults to `None`):
             Optional text only metadata you might want to save in your header.
@@ -76,7 +76,7 @@ def load_file(filename: str, device="cpu") -> Dict[str, torch.Tensor]:
     Loads a safetensors file into torch format.
 
     Args:
-        filename (`str`):
+        filename (`str`, or `os.PathLike`)):
             The name of the file which contains the tensors
         device (`Dict[str, any]`, *optional*, defaults to `cpu`):
             The device where the tensors need to be located after load.
index 81f7d006cd6328f670be63ca39c17e40d82f07a9..9c02b4a4c601aca34256b4aab7d4c924ed6ec940 100644 (file)
@@ -15,6 +15,7 @@ use std::collections::{BTreeMap, HashMap};
 use std::fs::File;
 use std::iter::FromIterator;
 use std::ops::Bound;
+use std::path::PathBuf;
 use std::sync::Arc;
 
 #[repr(C)]
@@ -83,14 +84,14 @@ fn prepare(tensor_dict: HashMap<String, &PyDict>) -> PyResult<BTreeMap<String, T
 /// Serializes raw data.
 ///
 /// Args:
-///     tensor_dict (:obj:`Dict[str, Dict[Any]]`):
+///     tensor_dict (`Dict[str, Dict[Any]]`):
 ///         The tensor dict is like:
 ///             {"tensor_name": {"dtype": "F32", "shape": [2, 3], "data": b"\0\0"}}
-///     metadata (:obj:`Dict[str, str]`, *optional*):
+///     metadata (`Dict[str, str]`, *optional*):
 ///         The optional purely text annotations
 ///
 /// Returns:
-///     (:obj:`bytes`):
+///     (`bytes`):
 ///         The serialized content.
 #[pyfunction]
 #[pyo3(text_signature = "(tensor_dict, metadata=None)")]
@@ -111,40 +112,41 @@ fn serialize<'a, 'b>(
 /// Serializes raw data.
 ///
 /// Args:
-///     tensor_dict (:obj:`Dict[str, Dict[Any]]`):
+///     tensor_dict (`Dict[str, Dict[Any]]`):
 ///         The tensor dict is like:
 ///             {"tensor_name": {"dtype": "F32", "shape": [2, 3], "data": b"\0\0"}}
-///     filename (:obj:`str`):
+///     filename (`str`, or `os.PathLike`):
 ///         The name of the file to write into.
-///     metadata (:obj:`Dict[str, str]`, *optional*):
+///     metadata (`Dict[str, str]`, *optional*):
 ///         The optional purely text annotations
 ///
 /// Returns:
-///     (:obj:`bytes`):
+///     (`bytes`):
 ///         The serialized content.
 #[pyfunction]
 #[pyo3(text_signature = "(tensor_dict, filename, metadata=None)")]
 fn serialize_file(
     tensor_dict: HashMap<String, &PyDict>,
-    filename: &str,
+    filename: PathBuf,
     metadata: Option<HashMap<String, String>>,
 ) -> PyResult<()> {
     let tensors = prepare(tensor_dict)?;
     let metadata_btreemap = metadata.map(|data| BTreeMap::from_iter(data.into_iter()));
-    safetensors::tensor::serialize_to_file(&tensors, &metadata_btreemap, filename).map_err(
-        |e| exceptions::PyException::new_err(format!("Error while serializing: {:?}", e)),
-    )?;
+    safetensors::tensor::serialize_to_file(&tensors, &metadata_btreemap, filename.as_path())
+        .map_err(|e| {
+            exceptions::PyException::new_err(format!("Error while serializing: {:?}", e))
+        })?;
     Ok(())
 }
 
 /// Opens a safetensors lazily and returns tensors as asked
 ///
 /// Args:
-///     data (:obj:`bytes`):
+///     data (`bytes`):
 ///         The byte content of a file
 ///
 /// Returns:
-///     (:obj:`List[str, Dict[str, Dict[str, any]]]`):
+///     (`List[str, Dict[str, Dict[str, any]]]`):
 ///         The deserialized content is like:
 ///             [("tensor_name", {"shape": [2, 3], "dtype": "F32", "data": b"\0\0.." }), (...)]
 #[pyfunction]
@@ -444,14 +446,14 @@ impl Version {
 /// Opens a safetensors lazily and returns tensors as asked
 ///
 /// Args:
-///     filename (:obj:`str`):
+///     filename (`str`, or `os.PathLike`):
 ///         The filename to open
 ///
-///     framework (:obj:`str`):
+///     framework (`str`):
 ///         The framework you want you tensors in. Supported values:
 ///         `pt`, `tf`, `flax`, `numpy`.
 ///
-///     device (:obj:`str`, defaults to :obj:`"cpu"`):
+///     device (`str`, defaults to `"cpu"`):
 ///         The device on which you want the tensors.
 #[pyclass]
 #[allow(non_camel_case_types)]
@@ -467,8 +469,8 @@ struct safe_open {
 #[pymethods]
 impl safe_open {
     #[new]
-    fn new(filename: &str, framework: Framework, device: Option<Device>) -> PyResult<Self> {
-        let file = File::open(filename)?;
+    fn new(filename: PathBuf, framework: Framework, device: Option<Device>) -> PyResult<Self> {
+        let file = File::open(&filename)?;
         let device = device.unwrap_or(Device::Cpu);
 
         if device != Device::Cpu && framework != Framework::Pytorch {
@@ -558,7 +560,7 @@ impl safe_open {
     /// Return the special non tensor information in the header
     ///
     /// Returns:
-    ///     (:obj:`Dict[str, str]`):
+    ///     (`Dict[str, str]`):
     ///         The freeform metadata.
     pub fn metadata(&self) -> Option<BTreeMap<String, String>> {
         self.metadata.metadata().clone()
@@ -567,7 +569,7 @@ impl safe_open {
     /// Returns the names of the tensors in the file.
     ///
     /// Returns:
-    ///     (:obj:`List[str]`):
+    ///     (`List[str]`):
     ///         The name of the tensors contained in that file
     pub fn keys(&self) -> PyResult<Vec<String>> {
         let mut keys: Vec<_> = self.metadata.tensors().keys().cloned().collect();
@@ -578,11 +580,11 @@ impl safe_open {
     /// Returns a full tensor
     ///
     /// Args:
-    ///     name (:obj:`str`):
+    ///     name (`str`):
     ///         The name of the tensor you want
     ///
     /// Returns:
-    ///     (:obj:`Tensor`):
+    ///     (`Tensor`):
     ///         The tensor in the framework you opened the file for.
     ///
     /// Example:
@@ -661,11 +663,11 @@ impl safe_open {
     /// Returns a full slice view object
     ///
     /// Args:
-    ///     name (:obj:`str`):
+    ///     name (`str`):
     ///         The name of the tensor you want
     ///
     /// Returns:
-    ///     (:obj:`PySafeSlice`):
+    ///     (`PySafeSlice`):
     ///         A dummy object you can slice into to get a real tensor
     /// Example:
     /// ```python
@@ -756,7 +758,7 @@ impl PySafeSlice {
     /// Returns the shape of the full underlying tensor
     ///
     /// Returns:
-    ///     (:obj:`List[int]`):
+    ///     (`List[int]`):
     ///         The shape of the full tensor
     ///
     /// Example:
index 18b1290386972ec5c6a3970c015010995c1c9925..ad6aa3725f26edee2239b3eceea72c32dbbdca8e 100644 (file)
@@ -1,4 +1,6 @@
+import os
 import unittest
+from pathlib import Path
 
 import numpy as np
 import torch
@@ -46,6 +48,15 @@ class TestCase(unittest.TestCase):
         with self.assertRaises(ValueError):
             save({"test1": data})
 
+    def test_accept_path(self):
+        tensors = {
+            "a": torch.zeros((2, 2)),
+            "b": torch.zeros((2, 3), dtype=torch.uint8),
+        }
+        save_file_pt(tensors, Path("./out.safetensors"))
+        load_file_pt(Path("./out.safetensors"))
+        os.remove(Path("./out.safetensors"))
+
 
 class ReadmeTestCase(unittest.TestCase):
     def assertTensorEqual(self, tensors1, tensors2, equality_fn):
index aff324d4a8c3da575e42cc5db42177e35b0c63a6..67a2c433b96efec31ae93a155f8c54f2dacb3461 100644 (file)
@@ -4,6 +4,7 @@ use serde::{Deserialize, Serialize};
 use std::collections::BTreeMap;
 use std::fs::File;
 use std::io::{BufWriter, Write};
+use std::path::Path;
 
 const MAX_HEADER_SIZE: usize = 100_000_000;
 
@@ -81,7 +82,7 @@ pub fn serialize(
 pub fn serialize_to_file(
     data: &BTreeMap<String, TensorView>,
     data_info: &Option<BTreeMap<String, String>>,
-    filename: &str,
+    filename: &Path,
 ) -> Result<(), SafeTensorError> {
     let (metadata, tensors, _) = prepare(data, data_info)?;
     let metadata_buf = serde_json::to_string(&metadata).unwrap().into_bytes();