From 736d990c335e0e2efcfcc212731635a2d944aab3 Mon Sep 17 00:00:00 2001 From: Nicolas Patry Date: Fri, 18 Nov 2022 15:24:35 +0100 Subject: [PATCH] Accepting `pathlib.Path` in `save_file/load_file/safe_open`. (#86) * 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 | 4 +- bindings/python/py_src/safetensors/numpy.py | 4 +- .../python/py_src/safetensors/tensorflow.py | 4 +- bindings/python/py_src/safetensors/torch.py | 4 +- bindings/python/src/lib.rs | 52 ++++++++++--------- bindings/python/tests/test_simple.py | 11 ++++ safetensors/src/tensor.rs | 3 +- 7 files changed, 48 insertions(+), 34 deletions(-) diff --git a/bindings/python/py_src/safetensors/flax.py b/bindings/python/py_src/safetensors/flax.py index 36909ea..f0e90f2 100644 --- a/bindings/python/py_src/safetensors/flax.py +++ b/bindings/python/py_src/safetensors/flax.py @@ -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. diff --git a/bindings/python/py_src/safetensors/numpy.py b/bindings/python/py_src/safetensors/numpy.py index e91ed3e..7d575bd 100644 --- a/bindings/python/py_src/safetensors/numpy.py +++ b/bindings/python/py_src/safetensors/numpy.py @@ -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. diff --git a/bindings/python/py_src/safetensors/tensorflow.py b/bindings/python/py_src/safetensors/tensorflow.py index 76fbf81..782b53e 100644 --- a/bindings/python/py_src/safetensors/tensorflow.py +++ b/bindings/python/py_src/safetensors/tensorflow.py @@ -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. diff --git a/bindings/python/py_src/safetensors/torch.py b/bindings/python/py_src/safetensors/torch.py index 69d2087..4d39bc8 100644 --- a/bindings/python/py_src/safetensors/torch.py +++ b/bindings/python/py_src/safetensors/torch.py @@ -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. diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index 81f7d00..9c02b4a 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -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) -> PyResult( /// 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, - filename: &str, + filename: PathBuf, metadata: Option>, ) -> 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) -> PyResult { - let file = File::open(filename)?; + fn new(filename: PathBuf, framework: Framework, device: Option) -> PyResult { + 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> { 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> { 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: diff --git a/bindings/python/tests/test_simple.py b/bindings/python/tests/test_simple.py index 18b1290..ad6aa37 100644 --- a/bindings/python/tests/test_simple.py +++ b/bindings/python/tests/test_simple.py @@ -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): diff --git a/safetensors/src/tensor.rs b/safetensors/src/tensor.rs index aff324d..67a2c43 100644 --- a/safetensors/src/tensor.rs +++ b/safetensors/src/tensor.rs @@ -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, data_info: &Option>, - filename: &str, + filename: &Path, ) -> Result<(), SafeTensorError> { let (metadata, tensors, _) = prepare(data, data_info)?; let metadata_buf = serde_json::to_string(&metadata).unwrap().into_bytes(); -- 2.43.0