]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Getting something decent.
authorNicolas Patry <patry.nicolas@protonmail.com>
Tue, 22 Feb 2022 16:45:50 +0000 (17:45 +0100)
committerNicolas Patry <patry.nicolas@protonmail.com>
Tue, 22 Feb 2022 16:45:50 +0000 (17:45 +0100)
- Still a copy at the Rust/Python boundaries (ideally we need to
  std::mem::forget, and pass raw pointers to Python world to avoid the
  copy)
- Saving/Loading, use pure bytes array to avoid writing to disk, but
  that does incure more memory usage, maybe something to add later.

bindings/python/.gitignore [new file with mode: 0644]
bindings/python/Cargo.toml [new file with mode: 0644]
bindings/python/README.md [new file with mode: 0644]
bindings/python/bench.py [deleted file]
bindings/python/py_src/safetensors/__init__.py [new file with mode: 0644]
bindings/python/setup.py [new file with mode: 0644]
bindings/python/src/lib.rs [new file with mode: 0644]
bindings/python/tests/test_simple.py [new file with mode: 0644]
safetensors/src/lib.rs

diff --git a/bindings/python/.gitignore b/bindings/python/.gitignore
new file mode 100644 (file)
index 0000000..af3ca5e
--- /dev/null
@@ -0,0 +1,72 @@
+/target
+
+# Byte-compiled / optimized / DLL files
+__pycache__/
+.pytest_cache/
+*.py[cod]
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+.venv/
+env/
+bin/
+build/
+develop-eggs/
+dist/
+eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+include/
+man/
+venv/
+*.egg-info/
+.installed.cfg
+*.egg
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+pip-selfcheck.json
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.coverage
+.cache
+nosetests.xml
+coverage.xml
+
+# Translations
+*.mo
+
+# Mr Developer
+.mr.developer.cfg
+.project
+.pydevproject
+
+# Rope
+.ropeproject
+
+# Django stuff:
+*.log
+*.pot
+
+.DS_Store
+
+# Sphinx documentation
+docs/_build/
+
+# PyCharm
+.idea/
+
+# VSCode
+.vscode/
+
+# Pyenv
+.python-version
\ No newline at end of file
diff --git a/bindings/python/Cargo.toml b/bindings/python/Cargo.toml
new file mode 100644 (file)
index 0000000..b5bfa9d
--- /dev/null
@@ -0,0 +1,16 @@
+[package]
+name = "safetensors-python"
+version = "0.1.0"
+edition = "2018"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+[lib]
+name = "safetensors_rust"
+crate-type = ["cdylib"]
+
+[dependencies]
+pyo3 = { version = "0.15.1", features = ["extension-module"] }
+
+[dependencies.safetensors]
+version = "*"
+path = "../../safetensors"
diff --git a/bindings/python/README.md b/bindings/python/README.md
new file mode 100644 (file)
index 0000000..660915d
--- /dev/null
@@ -0,0 +1 @@
+Tmp
diff --git a/bindings/python/bench.py b/bindings/python/bench.py
deleted file mode 100644 (file)
index 22ab1b1..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-from huggingface_hub import hf_hub_download
-from transformers import AutoModel
-import torch
-import os
-import datetime
-
-
-def bench_auto_trained(model_id: str):
-    AutoModel.from_pretrained(model_id)
-
-
-def bench_torch_load(model_id: str):
-    filename = hf_hub_download(model_id, filename="pytorch_model.bin")
-    data = torch.load(filename)
-    import ipdb
-
-    ipdb.set_trace()
-
-
-benches = [
-    bench_torch_load,
-    bench_auto_trained,
-]
-
-
-def sizeof_fmt(num, suffix="B"):
-    for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
-        if abs(num) < 1024.0:
-            return f"{num:3.1f}{unit}{suffix}"
-        num /= 1024.0
-    return f"{num:.1f}Yi{suffix}"
-
-
-def main():
-    os.environ["TRANSFORMERS_OFFLINE"] = "1"
-    for model_id in ["gpt2", "gpt2-medium"]:
-        # Make sure everything is on disk
-        benches[-1](model_id)
-        filename = hf_hub_download(model_id, filename="pytorch_model.bin")
-        size = os.path.getsize(filename)
-
-        start = datetime.datetime.now()
-        open(filename, "rb").read()
-        print(
-            f"{model_id} ({sizeof_fmt(size)}): pure read: {datetime.datetime.now() - start}"
-        )
-        for bench in benches:
-            start = datetime.datetime.now()
-            bench(model_id)
-            print(
-                f"{model_id} ({sizeof_fmt(size)}): {bench.__name__}: {datetime.datetime.now() - start}"
-            )
-
-
-if __name__ == "__main__":
-    main()
diff --git a/bindings/python/py_src/safetensors/__init__.py b/bindings/python/py_src/safetensors/__init__.py
new file mode 100644 (file)
index 0000000..bc52d71
--- /dev/null
@@ -0,0 +1,53 @@
+__version__ = "0.0.1"
+
+from typing import Dict
+import numpy as np
+from .safetensors_rust import deserialize, serialize
+import torch
+
+
+def save(tensor_dict: Dict[str, np.ndarray]) -> bytes:
+    import datetime
+
+    start = datetime.datetime.now()
+    flattened = {
+        k: {"dtype": v.dtype.name, "shape": v.shape, "data": v.tobytes()}
+        for k, v in tensor_dict.items()
+    }
+    print("Flattened", datetime.datetime.now() - start)
+    serialized = serialize(flattened)
+    print("Serialized", datetime.datetime.now() - start)
+    result = bytes(serialized)
+    print("Bytes", datetime.datetime.now() - start)
+    return result
+
+
+TYPES = {"F32": np.float32, "I32": np.int32}
+
+
+def getdtype(dtype_str: str) -> np.dtype:
+    return TYPES[dtype_str]
+
+
+def load(buffer: bytes) -> Dict[str, np.ndarray]:
+    flat = deserialize(buffer)
+
+    result = {}
+    for k, v in flat:
+        dtype = getdtype(v["dtype"])
+        arr = np.frombuffer(v["data"], dtype=dtype)
+        result[k] = arr
+    return result
+
+
+def load_pt(buffer: bytes) -> Dict[str, torch.Tensor]:
+    out = load(buffer)
+    for k, v in out.items():
+        out[k] = torch.from_numpy(v)
+    return out
+
+
+def save_pt(tensors: Dict[str, torch.Tensor]) -> bytes:
+    for k, v in tensors.items():
+        tensors[k] = v.numpy()
+    return save(tensors)
diff --git a/bindings/python/setup.py b/bindings/python/setup.py
new file mode 100644 (file)
index 0000000..7e8e6a5
--- /dev/null
@@ -0,0 +1,46 @@
+from setuptools import setup
+from setuptools_rust import Binding, RustExtension
+
+extras = {}
+extras["testing"] = [
+    "pytest",
+    "numpy",
+]
+extras["docs"] = ["sphinx", "sphinx_rtd_theme", "setuptools_rust"]
+
+setup(
+    name="safetensors",
+    version="0.0.1",
+    description="Fast and Safe Tensor serialization",
+    long_description=open("README.md", "r", encoding="utf-8").read(),
+    long_description_content_type="text/markdown",
+    keywords="",
+    author="",
+    author_email="",
+    url="https://github.com/huggingface/safetensors",
+    license="Apache License 2.0",
+    rust_extensions=[
+        RustExtension("safetensors.safetensors_rust", binding=Binding.PyO3, debug=False)
+    ],
+    extras_require=extras,
+    classifiers=[
+        "Development Status :: 5 - Production/Stable",
+        "Intended Audience :: Developers",
+        "Intended Audience :: Education",
+        "Intended Audience :: Science/Research",
+        "License :: OSI Approved :: Apache Software License",
+        "Operating System :: OS Independent",
+        "Programming Language :: Python :: 3",
+        "Programming Language :: Python :: 3.7",
+        "Programming Language :: Python :: 3.8",
+        "Programming Language :: Python :: 3.9",
+        "Programming Language :: Python :: 3.10",
+        "Topic :: Scientific/Engineering :: Artificial Intelligence",
+    ],
+    package_dir={"": "py_src"},
+    packages=[
+        "safetensors",
+    ],
+    package_data={},
+    zip_safe=False,
+)
diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs
new file mode 100644 (file)
index 0000000..60dca86
--- /dev/null
@@ -0,0 +1,78 @@
+use pyo3::exceptions;
+use pyo3::prelude::*;
+use pyo3::types::{PyBytes, PyDict, PyList};
+use safetensors::{Dtype, SafeTensor, SafeTensorBorrowed, Tensor};
+use std::collections::HashMap;
+
+/// Formats the sum of two numbers as string.
+#[pyfunction]
+fn serialize<'a, 'b>(
+    py: Python<'b>,
+    tensor_dict: HashMap<String, &'a PyDict>,
+) -> PyResult<&'b PyBytes> {
+    let start = std::time::Instant::now();
+    let mut tensors = HashMap::new();
+    for (tensor_name, tensor_desc) in tensor_dict {
+        let mut shape: Vec<usize> = vec![];
+        let mut dtype = Dtype::F32;
+        let mut data: &[u8] = &[];
+        for (key, value) in tensor_desc {
+            let key: &str = key.extract()?;
+            match key {
+                "shape" => shape = value.extract()?,
+                "dtype" => {
+                    let value: &str = value.extract()?;
+                    dtype = match value {
+                        "float32" => Dtype::F32,
+                        "float64" => Dtype::F64,
+                        "int32" => Dtype::I32,
+                        dtype_str => {
+                            unimplemented!("Did not cover this dtype: {}", dtype_str)
+                        }
+                    }
+                }
+                "data" => data = value.extract()?,
+                _ => println!("Ignored unknown kwarg option {}", key),
+            };
+        }
+
+        let tensor = Tensor::new(data, dtype, shape);
+        tensors.insert(tensor_name, tensor);
+    }
+    let out = SafeTensor::serialize(&tensors);
+    let pybytes = PyBytes::new(py, &out);
+    Ok(pybytes)
+}
+
+/// Formats the sum of two numbers as string.
+#[pyfunction]
+fn deserialize(py: Python, bytes: &[u8]) -> PyResult<Vec<(String, HashMap<String, PyObject>)>> {
+    let start = std::time::Instant::now();
+    let safetensor = SafeTensorBorrowed::deserialize(bytes).map_err(|e| {
+        exceptions::PyException::new_err(format!("Error while deserializing: {:?}", e))
+    })?;
+    let mut items = vec![];
+
+    for (tensor_name, tensor) in safetensor.tensors() {
+        let mut map = HashMap::new();
+
+        let pyshape: PyObject = PyList::new(py, tensor.shape.into_iter()).into();
+        let pydtype: PyObject = format!("{:?}", tensor.dtype).into_py(py);
+
+        let pydata: PyObject = PyBytes::new(py, tensor.data).into();
+
+        map.insert("shape".to_string(), pyshape);
+        map.insert("dtype".to_string(), pydtype);
+        map.insert("data".to_string(), pydata);
+        items.push((tensor_name, map));
+    }
+    Ok(items)
+}
+
+/// A Python module implemented in Rust.
+#[pymodule]
+fn safetensors_rust(_py: Python, m: &PyModule) -> PyResult<()> {
+    m.add_function(wrap_pyfunction!(serialize, m)?)?;
+    m.add_function(wrap_pyfunction!(deserialize, m)?)?;
+    Ok(())
+}
diff --git a/bindings/python/tests/test_simple.py b/bindings/python/tests/test_simple.py
new file mode 100644 (file)
index 0000000..7e927f2
--- /dev/null
@@ -0,0 +1,58 @@
+import unittest
+from safetensors import save, load, load_pt, save_pt
+import numpy as np
+from huggingface_hub import hf_hub_download
+import torch
+import os
+import datetime
+
+
+class TestCase(unittest.TestCase):
+    def test_serialization(self):
+        data = np.zeros((2, 2), dtype=np.int32)
+        out = save({"test": data})
+
+        self.assertEqual(
+            out,
+            b"""<\x00\x00\x00\x00\x00\x00\x00{"test":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]}}\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00""",
+        )
+
+        data[1, 1] = 1
+        out = save({"test": data})
+
+        self.assertEqual(
+            out,
+            b"""<\x00\x00\x00\x00\x00\x00\x00{"test":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]}}\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\00""",
+        )
+
+    def test_deserialization(self):
+        serialized = b"""<\x00\x00\x00\x00\x00\x00\x00{"test":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]}}\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"""
+
+        out = load(serialized)
+        self.assertEqual(list(out.keys()), ["test"])
+        np.testing.assert_array_equal(out["test"], np.zeros((2, 2), dtype=np.int32))
+
+
+class BigTestCase(unittest.TestCase):
+    def test_gpt2_deserialization(self):
+        start = datetime.datetime.now()
+        with open("out_py.bin", "rb") as f:
+            serialized = f.read()
+        print("Reading file took ", datetime.datetime.now() - start)
+        out = load_pt(serialized)
+        print("Deserialization took ", datetime.datetime.now() - start)
+
+    def test_gpt2_serialization(self):
+        filename = hf_hub_download("gpt2", filename="pytorch_model.bin")
+        data = torch.load(filename)
+
+        start = datetime.datetime.now()
+        out = save_pt(data)
+        with open("out_py_test.bin", "wb") as f:
+            f.write(out)
+        print("Saving took ", datetime.datetime.now() - start)
+
+        start = datetime.datetime.now()
+        with open("out_py_test_pt.bin", "wb") as f:
+            torch.save(data, f)
+        print("PT Saving took ", datetime.datetime.now() - start)
index 6f5c2f92228082b0e83f3a5774d2e7f8dd09180d..01dbf8253ffbdf59d8900ba817ed12744db76162 100644 (file)
@@ -1,18 +1,20 @@
 use serde::{Deserialize, Serialize};
 use std::collections::HashMap;
 
-enum SafeTensorError {
+#[derive(Debug)]
+pub enum SafeTensorError {
     InvalidHeader,
 }
 
-struct SafeTensor {
+pub struct SafeTensor {
     metadata: Metadata,
+    offset: usize,
     data: Vec<u8>,
 }
 
 impl SafeTensor {
-    pub fn serialize(data: &HashMap<String, OwnedTensor>) -> Vec<u8> {
-        let mut tensors: Vec<&OwnedTensor> = vec![];
+    pub fn serialize(data: &HashMap<String, Tensor>) -> Vec<u8> {
+        let mut tensors: Vec<&Tensor> = vec![];
         let mut hmetadata = HashMap::new();
         let mut offset = 0;
         for (name, tensor) in data {
@@ -37,10 +39,11 @@ impl SafeTensor {
         buffer.extend(&n.to_le_bytes().to_vec());
         buffer.extend(&metadata_buf);
         for tensor in tensors {
-            buffer.extend(&tensor.data);
+            buffer.extend(tensor.data);
         }
         buffer
     }
+
     pub fn deserialize(buffer: Vec<u8>) -> Result<SafeTensor, SafeTensorError> {
         let arr: [u8; 8] = [
             buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6], buffer[7],
@@ -50,17 +53,78 @@ impl SafeTensor {
             std::str::from_utf8(&buffer[8..8 + n]).map_err(|_| SafeTensorError::InvalidHeader)?;
         let metadata: Metadata =
             serde_json::from_str(string).map_err(|_| SafeTensorError::InvalidHeader)?;
-        let data = &buffer[8 + n..];
         Ok(SafeTensor {
             metadata,
+            offset: n + 8,
             data: buffer,
         })
     }
+
+    pub fn tensors<'data>(&'data self) -> Vec<(String, TensorView<'data>)> {
+        let mut tensors = vec![];
+        for (name, info) in &self.metadata.0 {
+            let tensorview = TensorView {
+                dtype: &info.dtype,
+                shape: &info.shape,
+                data: &self.data
+                    [info.data_offsets.0 + self.offset..info.data_offsets.1 + self.offset],
+            };
+            tensors.push((name.to_string(), tensorview));
+        }
+        tensors
+    }
+}
+
+pub struct SafeTensorBorrowed<'data> {
+    metadata: Metadata,
+    offset: usize,
+    data: &'data [u8],
+}
+impl<'data> SafeTensorBorrowed<'data> {
+    pub fn deserialize<'in_data>(buffer: &'in_data [u8]) -> Result<Self, SafeTensorError>
+    where
+        'in_data: 'data,
+    {
+        let arr: [u8; 8] = [
+            buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6], buffer[7],
+        ];
+        let n = u64::from_le_bytes(arr) as usize;
+        let string =
+            std::str::from_utf8(&buffer[8..8 + n]).map_err(|_| SafeTensorError::InvalidHeader)?;
+        let metadata: Metadata =
+            serde_json::from_str(string).map_err(|_| SafeTensorError::InvalidHeader)?;
+        Ok(Self {
+            metadata,
+            offset: n + 8,
+            data: buffer,
+        })
+    }
+
+    pub fn tensors(&self) -> Vec<(String, TensorView<'_>)> {
+        let mut tensors = vec![];
+        for (name, info) in &self.metadata.0 {
+            let tensorview = TensorView {
+                dtype: &info.dtype,
+                shape: &info.shape,
+                data: &self.data
+                    [info.data_offsets.0 + self.offset..info.data_offsets.1 + self.offset],
+            };
+            tensors.push((name.to_string(), tensorview));
+        }
+        tensors
+    }
 }
 
 #[derive(Debug, Deserialize, Serialize)]
 struct Metadata(HashMap<String, TensorInfo>);
 
+#[derive(Debug)]
+pub struct TensorView<'data> {
+    pub dtype: &'data Dtype,
+    pub shape: &'data [usize],
+    pub data: &'data [u8],
+}
+
 #[derive(Debug, Deserialize, Serialize, Clone)]
 struct TensorInfo {
     dtype: Dtype,
@@ -69,25 +133,27 @@ struct TensorInfo {
 }
 
 #[derive(Debug, Deserialize, Serialize, Clone)]
-enum Dtype {
+pub enum Dtype {
     BOOL,
     U8,
+    I32,
+    I64,
     F16,
     BF16,
     F32,
     F64,
 }
 
-struct Tensor<'a> {
+pub struct Tensor<'a> {
     shape: Vec<usize>,
     dtype: Dtype,
     data: &'a [u8],
 }
 
-struct OwnedTensor {
-    shape: Vec<usize>,
-    dtype: Dtype,
-    data: Vec<u8>,
+impl<'a> Tensor<'a> {
+    pub fn new(data: &'a [u8], dtype: Dtype, shape: Vec<usize>) -> Self {
+        Self { data, dtype, shape }
+    }
 }
 
 #[cfg(test)]
@@ -96,78 +162,71 @@ mod tests {
 
     #[test]
     fn test_serialization() {
-        let attn_0 = OwnedTensor {
+        let data: Vec<u8> = vec![0.0f32, 1.0, 2.0, 3.0, 4.0, 5.0]
+            .into_iter()
+            .flat_map(|f| f.to_le_bytes())
+            .collect();
+        let attn_0 = Tensor {
             dtype: Dtype::F32,
             shape: vec![1, 2, 3],
-            data: vec![0.0f32, 1.0, 2.0, 3.0, 4.0, 5.0]
-                .into_iter()
-                .flat_map(|f| f.to_le_bytes())
-                .collect(),
+            data: &data,
         };
-        let metadata: HashMap<String, OwnedTensor> =
+        let metadata: HashMap<String, Tensor> =
             [("attn.0".to_string(), attn_0)].into_iter().collect();
 
         let out = SafeTensor::serialize(&metadata);
-        let loaded = SafeTensor::deserialize(out);
-    }
-
-    fn get_tensor(shape: Vec<usize>) -> OwnedTensor {
-        let n = shape.iter().product();
-        let data = vec![0.0f32; n];
-        OwnedTensor {
-            dtype: Dtype::F32,
-            shape,
-            data: data.into_iter().flat_map(|f| f.to_le_bytes()).collect(),
-        }
+        SafeTensor::deserialize(out).unwrap();
     }
 
     #[test]
     fn test_gpt2() {
-        gpt2_like(12);
+        gpt2_like(12, "gpt2");
     }
 
     #[test]
     fn test_gpt2_medium() {
-        gpt2_like(24);
+        gpt2_like(24, "gpt2_medium");
     }
 
-    fn gpt2_like(n_heads: usize) {
-        let mut tensors = vec![];
-        tensors.push(("wte".to_string(), get_tensor(vec![50257, 768])));
-        tensors.push(("wpe".to_string(), get_tensor(vec![1024, 768])));
+    fn gpt2_like(n_heads: usize, model_id: &str) {
+        let mut tensors_desc = vec![];
+        tensors_desc.push(("wte".to_string(), vec![50257, 768]));
+        tensors_desc.push(("wpe".to_string(), vec![1024, 768]));
         for i in 0..n_heads {
-            tensors.push((format!("h.{}.ln_1.weight", i), get_tensor(vec![768])));
-            tensors.push((format!("h.{}.ln_1.bias", i), get_tensor(vec![768])));
-            tensors.push((
-                format!("h.{}.attn.bias", i),
-                get_tensor(vec![1, 1, 1024, 1024]),
-            ));
-            tensors.push((
-                format!("h.{}.attn.c_attn.weight", i),
-                get_tensor(vec![768, 2304]),
-            ));
-            tensors.push((format!("h.{}.attn.c_attn.bias", i), get_tensor(vec![2304])));
-            tensors.push((
-                format!("h.{}.attn.c_proj.weight", i),
-                get_tensor(vec![768, 768]),
-            ));
-            tensors.push((format!("h.{}.attn.c_proj.bias", i), get_tensor(vec![768])));
-            tensors.push((format!("h.{}.ln_2.weight", i), get_tensor(vec![768])));
-            tensors.push((format!("h.{}.ln_2.bias", i), get_tensor(vec![768])));
-            tensors.push((
-                format!("h.{}.mlp.c_fc.weight", i),
-                get_tensor(vec![768, 3072]),
-            ));
-            tensors.push((format!("h.{}.mlp.c_fc.bias", i), get_tensor(vec![3072])));
-            tensors.push((
-                format!("h.{}.mlp.c_proj.weight", i),
-                get_tensor(vec![3072, 768]),
-            ));
-            tensors.push((format!("h.{}.mlp.c_proj.bias", i), get_tensor(vec![768])));
+            tensors_desc.push((format!("h.{}.ln_1.weight", i), vec![768]));
+            tensors_desc.push((format!("h.{}.ln_1.bias", i), vec![768]));
+            tensors_desc.push((format!("h.{}.attn.bias", i), vec![1, 1, 1024, 1024]));
+            tensors_desc.push((format!("h.{}.attn.c_attn.weight", i), vec![768, 2304]));
+            tensors_desc.push((format!("h.{}.attn.c_attn.bias", i), vec![2304]));
+            tensors_desc.push((format!("h.{}.attn.c_proj.weight", i), vec![768, 768]));
+            tensors_desc.push((format!("h.{}.attn.c_proj.bias", i), vec![768]));
+            tensors_desc.push((format!("h.{}.ln_2.weight", i), vec![768]));
+            tensors_desc.push((format!("h.{}.ln_2.bias", i), vec![768]));
+            tensors_desc.push((format!("h.{}.mlp.c_fc.weight", i), vec![768, 3072]));
+            tensors_desc.push((format!("h.{}.mlp.c_fc.bias", i), vec![3072]));
+            tensors_desc.push((format!("h.{}.mlp.c_proj.weight", i), vec![3072, 768]));
+            tensors_desc.push((format!("h.{}.mlp.c_proj.bias", i), vec![768]));
         }
-        tensors.push(("ln_f.weight".to_string(), get_tensor(vec![768])));
-        tensors.push(("ln_f.bias".to_string(), get_tensor(vec![768])));
-        let metadata: HashMap<String, OwnedTensor> = tensors.into_iter().collect();
+        tensors_desc.push(("ln_f.weight".to_string(), vec![768]));
+        tensors_desc.push(("ln_f.bias".to_string(), vec![768]));
+
+        let n: usize = tensors_desc
+            .iter()
+            .map(|item| item.1.iter().product::<usize>())
+            .sum::<usize>()
+            * 4; // 4 == float32
+        let all_data = vec![0; n];
+        let mut metadata: HashMap<String, Tensor> = HashMap::new();
+        let mut offset = 0;
+        for (name, shape) in tensors_desc {
+            let n: usize = shape.iter().product();
+            let buffer = &all_data[offset..offset + n];
+            let tensor = Tensor::new(buffer, Dtype::F32, shape);
+            metadata.insert(name, tensor);
+            offset += n;
+        }
+
+        let filename = format!("./out_{}.bin", model_id);
 
         use std::time::Instant;
         let start = Instant::now();
@@ -175,19 +234,15 @@ mod tests {
         println!("Serialization {:?}", start.elapsed());
 
         let start = Instant::now();
-        std::fs::write("./out.bin", out);
+        std::fs::write(&filename, out).unwrap();
         println!("Write to file {:?}", start.elapsed());
 
         let start = Instant::now();
-        let raw = std::fs::read("./out.bin").unwrap();
+        let raw = std::fs::read(&filename).unwrap();
         println!("Read from file {:?}", start.elapsed());
 
         let start = Instant::now();
-        let raw2 = std::fs::read("./out.bin").unwrap();
-        println!("Read twice from file {:?}", start.elapsed());
-
-        let start = Instant::now();
-        let loaded = SafeTensor::deserialize(raw2);
+        SafeTensor::deserialize(raw).unwrap();
         println!("Deserialization {:?}", start.elapsed());
     }