From: Thomas Wang <24695242+thomasw21@users.noreply.github.com> Date: Sat, 29 Oct 2022 14:08:45 +0000 (+0200) Subject: Use BTreeMap instead of HashMap (#42) X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=ae706149a25c945e0dfba78651785a95eddb7839;p=safetensors.git Use BTreeMap instead of HashMap (#42) * Use BTreeMap instead of HashMap Co-authored-by: OlivierDehaene <23298448+OlivierDehaene@users.noreply.github.com> --- diff --git a/bindings/python/py_src/safetensors/torch.py b/bindings/python/py_src/safetensors/torch.py index 2360bff..32ab804 100644 --- a/bindings/python/py_src/safetensors/torch.py +++ b/bindings/python/py_src/safetensors/torch.py @@ -84,7 +84,6 @@ def _view2torch(safeview) -> Dict[str, torch.Tensor]: def _tobytes(tensor: torch.Tensor, name: str) -> bytes: - try: if not tensor.is_contiguous(): raise ValueError( diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index afff7b5..08b4608 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -9,13 +9,14 @@ use pyo3::types::{PyByteArray, PyBytes, PyDict, PyList}; use pyo3::{intern, PyErr}; use safetensors::slice::TensorIndexer; use safetensors::tensor::{Dtype, Metadata, SafeTensors, TensorInfo, TensorView}; -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use std::fs::File; +use std::iter::FromIterator; use std::ops::Bound; use std::sync::Arc; -fn prepare(tensor_dict: HashMap) -> PyResult>> { - let mut tensors = HashMap::new(); +fn prepare(tensor_dict: HashMap) -> PyResult>> { + let mut tensors = BTreeMap::new(); for (tensor_name, tensor_desc) in tensor_dict { let mut shape: Vec = vec![]; let mut dtype = Dtype::F32; @@ -62,7 +63,8 @@ fn serialize<'a, 'b>( metadata: Option>, ) -> PyResult<&'b PyBytes> { let tensors = prepare(tensor_dict)?; - let out = safetensors::tensor::serialize(&tensors, &metadata).map_err(|e| { + let metadata_btreemap = metadata.map(|data| BTreeMap::from_iter(data.into_iter())); + let out = safetensors::tensor::serialize(&tensors, &metadata_btreemap).map_err(|e| { exceptions::PyException::new_err(format!("Error while serializing: {:?}", e)) })?; let pybytes = PyBytes::new(py, &out); @@ -76,9 +78,10 @@ fn serialize_file( metadata: Option>, ) -> PyResult<()> { let tensors = prepare(tensor_dict)?; - safetensors::tensor::serialize_to_file(&tensors, &metadata, filename).map_err(|e| { - exceptions::PyException::new_err(format!("Error while serializing: {:?}", e)) - })?; + 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)), + )?; Ok(()) } @@ -239,7 +242,7 @@ impl safe_open { }) } - pub fn metadata(&self) -> Option> { + pub fn metadata(&self) -> Option> { self.metadata.metadata().clone() } diff --git a/bindings/python/tests/test_simple.py b/bindings/python/tests/test_simple.py index 6c020da..e079acc 100644 --- a/bindings/python/tests/test_simple.py +++ b/bindings/python/tests/test_simple.py @@ -33,6 +33,13 @@ class TestCase(unittest.TestCase): self.assertEqual(list(out.keys()), ["test"]) np.testing.assert_array_equal(out["test"], np.zeros((2, 2), dtype=np.int32)) + def test_serialization_order_invariant(self): + data = np.zeros((2, 2), dtype=np.int32) + out1 = save({"test1": data, "test2": data}) + out2 = save({"test2": data, "test1": data}) + + self.assertEqual(out1, out2) + class ReadmeTestCase(unittest.TestCase): def assertTensorEqual(self, tensors1, tensors2, equality_fn): diff --git a/safetensors/benches/benchmark.rs b/safetensors/benches/benchmark.rs index 82bb0e0..769888e 100644 --- a/safetensors/benches/benchmark.rs +++ b/safetensors/benches/benchmark.rs @@ -1,6 +1,6 @@ use criterion::{black_box, criterion_group, criterion_main, Criterion}; use safetensors::tensor::*; -use std::collections::HashMap; +use std::collections::BTreeMap; // Returns a sample data of size 2_MB fn get_sample_data() -> (Vec, Vec, Dtype) { @@ -16,7 +16,7 @@ pub fn bench_serialize(c: &mut Criterion) { let (data, shape, dtype) = get_sample_data(); let n_layers = 5; - let mut metadata: HashMap = HashMap::new(); + let mut metadata: BTreeMap = BTreeMap::new(); // 2_MB x 5 = 10_MB for i in 0..n_layers { let tensor = TensorView::new(dtype, shape.clone(), &data[..]); @@ -34,7 +34,7 @@ pub fn bench_deserialize(c: &mut Criterion) { let (data, shape, dtype) = get_sample_data(); let n_layers = 5; - let mut metadata: HashMap = HashMap::new(); + let mut metadata: BTreeMap = BTreeMap::new(); // 2_MB x 5 = 10_MB for i in 0..n_layers { let tensor = TensorView::new(dtype, shape.clone(), &data[..]); diff --git a/safetensors/src/tensor.rs b/safetensors/src/tensor.rs index d043e2f..aff324d 100644 --- a/safetensors/src/tensor.rs +++ b/safetensors/src/tensor.rs @@ -1,7 +1,7 @@ //! Module Containing the most important structures use crate::slice::{InvalidSlice, SliceIterator, TensorIndexer}; use serde::{Deserialize, Serialize}; -use std::collections::HashMap; +use std::collections::BTreeMap; use std::fs::File; use std::io::{BufWriter, Write}; @@ -34,11 +34,11 @@ impl From for SafeTensorError { } fn prepare<'hash, 'data>( - data: &'hash HashMap>, - data_info: &'hash Option>, + data: &'hash BTreeMap>, + data_info: &'hash Option>, ) -> Result<(Metadata, Vec<&'hash TensorView<'data>>, usize), SafeTensorError> { let mut tensors: Vec<&TensorView> = vec![]; - let mut hmetadata = HashMap::new(); + let mut hmetadata = BTreeMap::new(); let mut offset = 0; for (name, tensor) in data { let n = tensor.data.len(); @@ -59,8 +59,8 @@ fn prepare<'hash, 'data>( /// Serialize to an owned byte buffer the dictionnary of tensors. pub fn serialize( - data: &HashMap, - data_info: &Option>, + data: &BTreeMap, + data_info: &Option>, ) -> Result, SafeTensorError> { let (metadata, tensors, offset) = prepare(data, data_info)?; let metadata_buf = serde_json::to_string(&metadata).unwrap().into_bytes(); @@ -79,8 +79,8 @@ pub fn serialize( /// Writing directly to file reduces the need to allocate the whole amount to /// memory. pub fn serialize_to_file( - data: &HashMap, - data_info: &Option>, + data: &BTreeMap, + data_info: &Option>, filename: &str, ) -> Result<(), SafeTensorError> { let (metadata, tensors, _) = prepare(data, data_info)?; @@ -184,15 +184,15 @@ impl<'data> SafeTensors<'data> { pub struct Metadata { #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "__metadata__")] - metadata: Option>, + metadata: Option>, #[serde(flatten)] - tensors: HashMap, + tensors: BTreeMap, } impl Metadata { fn new( - metadata: Option>, - tensors: HashMap, + metadata: Option>, + tensors: BTreeMap, ) -> Result { let metadata = Self { metadata, tensors }; metadata.validate()?; @@ -220,12 +220,12 @@ impl Metadata { } /// Gives back the tensor metadata - pub fn tensors(&self) -> &HashMap { + pub fn tensors(&self) -> &BTreeMap { &self.tensors } /// Gives back the tensor metadata - pub fn metadata(&self) -> &Option> { + pub fn metadata(&self) -> &Option> { &self.metadata } } @@ -363,7 +363,7 @@ mod tests { .collect(); let shape = vec![1, 2, 3]; let attn_0 = TensorView::new(Dtype::F32, shape, &data); - let metadata: HashMap = + let metadata: BTreeMap = [("attn.0".to_string(), attn_0)].into_iter().collect(); let out = serialize(&metadata, &None).unwrap(); @@ -381,7 +381,7 @@ mod tests { shape: vec![1, 2, 3], data: &data, }; - let metadata: HashMap = + let metadata: BTreeMap = [("attn.0".to_string(), attn_0)].into_iter().collect(); let out = serialize(&metadata, &None).unwrap(); @@ -458,7 +458,7 @@ mod tests { .sum::() * dtype.size(); // 4 let all_data = vec![0; n]; - let mut metadata: HashMap = HashMap::new(); + let mut metadata: BTreeMap = BTreeMap::new(); let mut offset = 0; for (name, shape) in tensors_desc { let n: usize = shape.iter().product(); @@ -495,7 +495,7 @@ mod tests { #[test] fn test_json_attack() { - let mut tensors = HashMap::new(); + let mut tensors = BTreeMap::new(); let dtype = Dtype::F32; let shape = vec![2, 2]; let data_offsets = (0, 16);