From: Sylvain Gugger <35901082+sgugger@users.noreply.github.com> Date: Wed, 28 Sep 2022 16:05:00 +0000 (-0400) Subject: PoC for additional metadata (#9) X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=c5c1316c7a7d4a6c5011ce9fde6d330aed9b64cd;p=safetensors.git PoC for additional metadata (#9) * PoC for additional metadata * Address review comments and fix tests * Don't push format metadata --- diff --git a/bindings/python/py_src/safetensors/flax.py b/bindings/python/py_src/safetensors/flax.py index e315d2b..aed53f4 100644 --- a/bindings/python/py_src/safetensors/flax.py +++ b/bindings/python/py_src/safetensors/flax.py @@ -1,6 +1,6 @@ from safetensors import numpy import numpy as np -from typing import Dict +from typing import Dict, Optional import jax.numpy as jnp @@ -16,14 +16,14 @@ def jnp2np(jnp_dict: Dict[str, jnp.DeviceArray]) -> Dict[str, np.array]: return jnp_dict -def save(tensors: Dict[str, jnp.DeviceArray]) -> bytes: +def save(tensors: Dict[str, jnp.DeviceArray], metadata: Optional[Dict[str, str]] = None) -> bytes: np_tensors = jnp2np(tensors) - return numpy.save(np_tensors) + return numpy.save(np_tensors, metadata=metadata) -def save_file(tensors: Dict[str, jnp.DeviceArray], filename: str): +def save_file(tensors: Dict[str, jnp.DeviceArray], filename: str, metadata: Optional[Dict[str, str]] = None): np_tensors = jnp2np(tensors) - return numpy.save_file(np_tensors, filename) + return numpy.save_file(np_tensors, filename, metadata=metadata) def load(buffer: bytes) -> Dict[str, jnp.DeviceArray]: @@ -34,3 +34,7 @@ def load(buffer: bytes) -> Dict[str, jnp.DeviceArray]: def load_file(filename: str) -> Dict[str, jnp.DeviceArray]: flat = numpy.load_file(filename) return np2jnp(flat) + + +def read_metadata_in_file(filename: str) -> Dict[str, str]: + return numpy.read_metadata(filename) \ No newline at end of file diff --git a/bindings/python/py_src/safetensors/numpy.py b/bindings/python/py_src/safetensors/numpy.py index aa8eff2..8d990e5 100644 --- a/bindings/python/py_src/safetensors/numpy.py +++ b/bindings/python/py_src/safetensors/numpy.py @@ -1,14 +1,14 @@ import numpy as np -from .safetensors_rust import deserialize, serialize, deserialize_file, serialize_file -from typing import Dict +from .safetensors_rust import deserialize, serialize, deserialize_file, serialize_file, read_metadata +from typing import Dict, Optional -def save(tensor_dict: Dict[str, np.ndarray]) -> bytes: +def save(tensor_dict: Dict[str, np.ndarray], metadata: Optional[Dict[str, str]] = None) -> bytes: flattened = { k: {"dtype": v.dtype.name, "shape": v.shape, "data": v.tobytes()} for k, v in tensor_dict.items() } - serialized = serialize(flattened) + serialized = serialize(flattened, metadata=metadata) result = bytes(serialized) return result @@ -52,9 +52,13 @@ def view2np(safeview): return result -def save_file(tensor_dict: Dict[str, np.ndarray], filename: str): +def save_file(tensor_dict: Dict[str, np.ndarray], filename: str, metadata: Optional[Dict[str, str]] = None): flattened = { k: {"dtype": v.dtype.name, "shape": v.shape, "data": v.tobytes()} for k, v in tensor_dict.items() } - serialize_file(flattened, filename) + serialize_file(flattened, metadata, filename) + + +def read_metadata_in_file(filename: str) -> Dict[str, str]: + return read_metadata(filename) diff --git a/bindings/python/py_src/safetensors/tensorflow.py b/bindings/python/py_src/safetensors/tensorflow.py index 6970079..ac6efc9 100644 --- a/bindings/python/py_src/safetensors/tensorflow.py +++ b/bindings/python/py_src/safetensors/tensorflow.py @@ -1,6 +1,6 @@ from safetensors import numpy import numpy as np -from typing import Dict +from typing import Dict, Optional import tensorflow as tf @@ -16,14 +16,14 @@ def tf2np(tf_dict: Dict[str, tf.DeviceArray]) -> Dict[str, np.array]: return tf_dict -def save(tensors: Dict[str, tf.DeviceArray]) -> bytes: +def save(tensors: Dict[str, tf.DeviceArray], metadata: Optional[Dict[str, str]] = None) -> bytes: np_tensors = tf2np(tensors) - return numpy.save(np_tensors) + return numpy.save(np_tensors, metadata=metadata) -def save_file(tensors: Dict[str, tf.DeviceArray], filename: str): +def save_file(tensors: Dict[str, tf.DeviceArray], filename: str, metadata: Optional[Dict[str, str]] = None): np_tensors = tf2np(tensors) - return numpy.save_file(np_tensors, filename) + return numpy.save_file(np_tensors, filename, metadata=metadata) def load(buffer: bytes) -> Dict[str, tf.DeviceArray]: @@ -34,3 +34,6 @@ def load(buffer: bytes) -> Dict[str, tf.DeviceArray]: def load_file(filename: str) -> Dict[str, tf.DeviceArray]: flat = numpy.load_file(filename) return np2tf(flat) + +def read_metadata_in_file(filename: str) -> Dict[str, str]: + return numpy.read_metadata(filename) \ No newline at end of file diff --git a/bindings/python/py_src/safetensors/torch.py b/bindings/python/py_src/safetensors/torch.py index 8a44747..712a4bd 100644 --- a/bindings/python/py_src/safetensors/torch.py +++ b/bindings/python/py_src/safetensors/torch.py @@ -1,7 +1,7 @@ from safetensors import numpy -from .safetensors_rust import serialize_file +from .safetensors_rust import serialize_file, read_metadata import numpy as np -from typing import Dict +from typing import Dict, Optional import torch @@ -17,9 +17,9 @@ def pt2np(torch_dict: Dict[str, torch.Tensor]) -> Dict[str, np.array]: return torch_dict -def save(tensors: Dict[str, torch.Tensor]) -> bytes: +def save(tensors: Dict[str, torch.Tensor], metadata: Optional[Dict[str, str]] = None) -> bytes: np_tensors = pt2np(tensors) - return numpy.save(np_tensors) + return numpy.save(np_tensors, metadata=metadata) SIZE = { @@ -50,12 +50,12 @@ def tobytes(tensor: torch.Tensor) -> bytes: return data.tobytes() -def save_file(tensors: Dict[str, torch.Tensor], filename: str): +def save_file(tensors: Dict[str, torch.Tensor], filename: str, metadata: Optional[Dict[str, str]] = None): flattened = { k: {"dtype": str(v.dtype).split(".")[-1], "shape": v.shape, "data": tobytes(v)} for k, v in tensors.items() } - serialize_file(flattened, filename) + serialize_file(flattened, metadata, filename) def load(buffer: bytes) -> Dict[str, torch.Tensor]: @@ -66,3 +66,7 @@ def load(buffer: bytes) -> Dict[str, torch.Tensor]: def load_file(filename: str) -> Dict[str, torch.Tensor]: flat = numpy.load_file(filename) return np2pt(flat) + + +def read_metadata_in_file(filename: str) -> Dict[str, str]: + return read_metadata(filename) diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index 707b672..2291d03 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -54,17 +54,22 @@ fn prepare<'a>(tensor_dict: HashMap) -> PyResult( py: Python<'b>, tensor_dict: HashMap, + metadata: Option>, ) -> PyResult<&'b PyBytes> { let tensors = prepare(tensor_dict)?; - let out = safetensors::serialize(&tensors); + let out = safetensors::serialize(&tensors, &metadata); let pybytes = PyBytes::new(py, &out); Ok(pybytes) } #[pyfunction] -fn serialize_file<'a>(tensor_dict: HashMap, filename: &str) -> PyResult<()> { +fn serialize_file<'a>( + tensor_dict: HashMap, + metadata: Option>, + filename: &str, +) -> PyResult<()> { let tensors = prepare(tensor_dict)?; - safetensors::serialize_to_file(&tensors, filename)?; + safetensors::serialize_to_file(&tensors, &metadata, filename)?; Ok(()) } @@ -107,6 +112,22 @@ fn deserialize_file( deserialized } +#[pyfunction] +fn read_metadata(filename: &str) -> PyResult>> { + let file = File::open(filename)?; + + // SAFETY: Mmap is used to prevent allocating in Rust + // before making a copy within Python. + let mmap = unsafe { MmapOptions::new().map(&file)? }; + let safetensor = SafeTensors::deserialize(&mmap).map_err(|e| { + exceptions::PyException::new_err(format!("Error while deserializing: {:?}", e)) + })?; + let metadata = safetensor.get_metadata(); + // Make sure mmap does not leak. + drop(mmap); + Ok(metadata) +} + /// A Python module implemented in Rust. #[pymodule] fn safetensors_rust(_py: Python, m: &PyModule) -> PyResult<()> { @@ -114,5 +135,6 @@ fn safetensors_rust(_py: Python, m: &PyModule) -> PyResult<()> { m.add_function(wrap_pyfunction!(serialize_file, m)?)?; m.add_function(wrap_pyfunction!(deserialize, m)?)?; m.add_function(wrap_pyfunction!(deserialize_file, m)?)?; + m.add_function(wrap_pyfunction!(read_metadata, m)?)?; Ok(()) } diff --git a/bindings/python/tests/test_simple.py b/bindings/python/tests/test_simple.py index 3adf447..a44f8f9 100644 --- a/bindings/python/tests/test_simple.py +++ b/bindings/python/tests/test_simple.py @@ -51,6 +51,8 @@ class ReadmeTestCase(unittest.TestCase): loaded = load_file("./out.bin") self.assertTensorEqual(tensors, loaded, np.allclose) + metadata = + def test_torch_example(self): tensors = { "a": torch.zeros((2, 2)), diff --git a/safetensors/src/lib.rs b/safetensors/src/lib.rs index 3d8231d..b79e17f 100644 --- a/safetensors/src/lib.rs +++ b/safetensors/src/lib.rs @@ -80,6 +80,7 @@ pub enum SafeTensorError { fn prepare<'hash, 'data>( data: &'hash HashMap>, + data_info: &'hash Option>, ) -> (Metadata, Vec<&'hash Tensor<'data>>, usize) { let mut tensors: Vec<&Tensor> = vec![]; let mut hmetadata = HashMap::new(); @@ -96,14 +97,17 @@ fn prepare<'hash, 'data>( tensors.push(tensor); } - let metadata: Metadata = Metadata(hmetadata); + let metadata: Metadata = Metadata::new(data_info.clone(), hmetadata); (metadata, tensors, offset) } /// Serialize to an owned byte buffer the dictionnary of tensors. -pub fn serialize(data: &HashMap) -> Vec { - let (metadata, tensors, offset) = prepare(data); +pub fn serialize( + data: &HashMap, + data_info: &Option>, +) -> Vec { + let (metadata, tensors, offset) = prepare(data, data_info); let metadata_buf = serde_json::to_string(&metadata).unwrap().into_bytes(); let expected_size = 8 + metadata_buf.len() + offset; let mut buffer: Vec = Vec::with_capacity(expected_size); @@ -121,9 +125,10 @@ pub fn serialize(data: &HashMap) -> Vec { /// memory. pub fn serialize_to_file( data: &HashMap, + data_info: &Option>, filename: &str, ) -> Result<(), std::io::Error> { - let (metadata, tensors, _) = prepare(data); + let (metadata, tensors, _) = prepare(data, data_info); let metadata_buf = serde_json::to_string(&metadata).unwrap().into_bytes(); let n: u64 = metadata_buf.len() as u64; let mut f = BufWriter::new(File::create(filename)?); @@ -171,7 +176,7 @@ impl<'data> SafeTensors<'data> { /// structure. pub fn tensors(&self) -> Vec<(String, TensorView<'_>)> { let mut tensors = vec![]; - for (name, info) in &self.metadata.0 { + for (name, info) in &self.metadata.tensors { let tensorview = TensorView { dtype: &info.dtype, shape: &info.shape, @@ -187,7 +192,7 @@ impl<'data> SafeTensors<'data> { /// The tensor returned is merely a view and the data is not owned by this /// structure. pub fn tensor(&self, tensor_name: &str) -> Result, SafeTensorError> { - for (name, info) in &self.metadata.0 { + for (name, info) in &self.metadata.tensors { if name == tensor_name { return Ok(TensorView { dtype: &info.dtype, @@ -204,14 +209,44 @@ impl<'data> SafeTensors<'data> { /// The tensor returned is merely a view and the data is not owned by this /// structure. pub fn names(&self) -> Vec<&'_ String> { - self.metadata.0.iter().map(|(name, _)| name).collect() + self.metadata.tensors.iter().map(|(name, _)| name).collect() + } + + /// Returns additional metadata passed along by the user. + pub fn get_metadata(&self) -> Option> { + self.metadata.metadata.clone() } } /// The stuct representing the header of safetensor files which allow /// indexing into the raw byte-buffer array and how to interpret it. #[derive(Debug, Deserialize, Serialize)] -struct Metadata(HashMap); +pub struct Metadata { + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(rename = "__metadata__")] + metadata: Option>, + #[serde(flatten)] + tensors: HashMap, +} + +impl Metadata { + fn new( + metadata: Option>, + tensors: HashMap, + ) -> Self { + Self { metadata, tensors } + } + + /// Gives back the tensor metadata + pub fn tensors(&self) -> &HashMap { + &self.tensors + } + + /// Gives back the metadata + pub fn metadata(&self) -> &Option> { + &self.metadata + } +} /// A view of a Tensor within the file. /// Contains references to data within the full byte-buffer @@ -244,7 +279,7 @@ impl<'data> TensorView<'data> { /// Endianness is assumed to be little endian /// Ordering is assumed to be 'C'. #[derive(Debug, Deserialize, Serialize, Clone)] -struct TensorInfo { +pub struct TensorInfo { /// The type of each element of the tensor dtype: Dtype, /// The shape of the tensor @@ -318,7 +353,7 @@ mod tests { let metadata: HashMap = [("attn.0".to_string(), attn_0)].into_iter().collect(); - let out = serialize(&metadata); + let out = serialize(&metadata, &None); let _parsed = SafeTensors::deserialize(&out).unwrap(); } @@ -354,6 +389,9 @@ mod tests { tensors_desc.push(("ln_f.weight".to_string(), vec![768])); tensors_desc.push(("ln_f.bias".to_string(), vec![768])); + let data_info: HashMap = + HashMap::from([("framework".to_string(), "pt".to_string())]); + let n: usize = tensors_desc .iter() .map(|item| item.1.iter().product::()) @@ -372,7 +410,7 @@ mod tests { let filename = format!("./out_{}.bin", model_id); - let out = serialize(&metadata); + let out = serialize(&metadata, &Some(data_info)); std::fs::write(&filename, out).unwrap();