from typing import Dict
import numpy as np
-from .safetensors_rust import deserialize, serialize, deserialize_file
+from .safetensors_rust import deserialize, serialize, deserialize_file, serialize_file
import torch
return result
+def save_file(tensor_dict: Dict[str, np.ndarray], filename: str):
+ flattened = {
+ k: {"dtype": v.dtype.name, "shape": v.shape, "data": v.tobytes()}
+ for k, v in tensor_dict.items()
+ }
+ serialize_file(flattened, filename)
+
+
TYPES = {"F32": np.float32, "I32": np.int32}
def load_file(filename: str) -> Dict[str, np.ndarray]:
flat = deserialize_file(filename)
- return to_numpy(flat)
+ return view2np(flat)
def load(buffer: bytes) -> Dict[str, np.ndarray]:
flat = deserialize(buffer)
- return to_numpy(flat)
+ return view2np(flat)
-def to_numpy(safeview):
+def view2np(safeview):
result = {}
for k, v in safeview:
dtype = getdtype(v["dtype"])
return result
-def to_pt(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, torch.Tensor]:
+def np2pt(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, torch.Tensor]:
for k, v in numpy_dict.items():
numpy_dict[k] = torch.from_numpy(v)
return numpy_dict
for k, v in tensors.items():
tensors[k] = v.numpy()
return save(tensors)
+
+
+def save_file_pt(tensors: Dict[str, torch.Tensor], filename: str) -> bytes:
+ for k, v in tensors.items():
+ tensors[k] = v.numpy()
+ return save_file(tensors, filename)
use std::fs::File;
use std::io::Write;
-/// Formats the sum of two numbers as string.
-#[pyfunction]
-fn serialize<'a, 'b>(
+fn prepare<'a, 'b>(
py: Python<'b>,
tensor_dict: HashMap<String, &'a PyDict>,
-) -> PyResult<&'b PyBytes> {
+) -> PyResult<HashMap<String, Tensor<'a>>> {
let start = std::time::Instant::now();
let mut tensors = HashMap::new();
for (tensor_name, tensor_desc) in tensor_dict {
let tensor = Tensor::new(data, dtype, shape);
tensors.insert(tensor_name, tensor);
}
+ Ok(tensors)
+}
+
+#[pyfunction]
+fn serialize<'a, 'b>(
+ py: Python<'b>,
+ tensor_dict: HashMap<String, &'a PyDict>,
+) -> PyResult<&'b PyBytes> {
+ let tensors = prepare(py, tensor_dict)?;
let out = SafeTensor::serialize(&tensors);
let pybytes = PyBytes::new(py, &out);
Ok(pybytes)
}
+#[pyfunction]
+fn serialize_file<'a, 'b>(
+ py: Python<'b>,
+ tensor_dict: HashMap<String, &'a PyDict>,
+ filename: &str,
+) -> PyResult<()> {
+ let tensors = prepare(py, tensor_dict)?;
+ SafeTensor::serialize_to_file(&tensors, filename)?;
+ Ok(())
+}
+
#[pyfunction]
fn deserialize(py: Python, bytes: &[u8]) -> PyResult<Vec<(String, HashMap<String, PyObject>)>> {
let start = std::time::Instant::now();
#[pymodule]
fn safetensors_rust(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(serialize, m)?)?;
+ m.add_function(wrap_pyfunction!(serialize_file, m)?)?;
m.add_function(wrap_pyfunction!(deserialize, m)?)?;
m.add_function(wrap_pyfunction!(deserialize_file, m)?)?;
Ok(())
import unittest
-from safetensors import save_pt, load_file, to_pt, load
+from safetensors import save_file_pt, load_file, np2pt, load
from huggingface_hub import hf_hub_download
import torch
import datetime
class BigTestCase(unittest.TestCase):
def test_gpt2_deserialization_safe(self):
filename = hf_hub_download("gpt2", filename="pytorch_model.bin")
- local = "out_safe.bin"
data = torch.load(filename)
- out = save_pt(data)
- with open(local, "wb") as f:
- f.write(out)
+ local = "out_safe.bin"
+ save_file_pt(data, local)
start = datetime.datetime.now()
with open(local, "rb") as f:
serialized = f.read()
print()
print("Reading file took ", datetime.datetime.now() - start)
- to_pt(load(serialized))
+ np2pt(load(serialized))
print("Deserialization (Safe) took ", datetime.datetime.now() - start)
def test_gpt2_deserialization_safe_mmap(self):
filename = hf_hub_download("gpt2", filename="pytorch_model.bin")
- local = "out_safe.bin"
data = torch.load(filename)
- out = save_pt(data)
- with open(local, "wb") as f:
- f.write(out)
+ local = "out_safe_mmap.bin"
+ save_file_pt(data, local)
start = datetime.datetime.now()
- to_pt(load_file(local))
+ np2pt(load_file(local))
print()
print("Deserialization (Safe) took ", datetime.datetime.now() - start)
print()
print("Deserialization (PT) took ", datetime.datetime.now() - start)
- def test_gpt2_serialization(self):
+ def test_gpt2_serialization_pt(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()
- print("Serialization (safe) took ", datetime.datetime.now() - start)
- del out
-
start = datetime.datetime.now()
with open("out_pt.bin", "wb") as f:
torch.save(data, f)
print("Serialization (PT) took ", datetime.datetime.now() - start)
+
+ def test_gpt2_serialization_safe(self):
+ filename = hf_hub_download("gpt2", filename="pytorch_model.bin")
+ data = torch.load(filename)
+ start = datetime.datetime.now()
+ outfilename = "out_py_test.bin"
+ out = save_file_pt(data, outfilename)
+ print("Serialization (safe) took ", datetime.datetime.now() - start)
+ del out
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
+use std::fs::File;
+use std::io::{BufWriter, Write};
#[derive(Debug)]
pub enum SafeTensorError {
}
impl SafeTensor {
- pub fn serialize(data: &HashMap<String, Tensor>) -> Vec<u8> {
+ fn prepare<'hash, 'data>(
+ data: &'hash HashMap<String, Tensor<'data>>,
+ ) -> (Metadata, Vec<&'hash Tensor<'data>>, usize) {
let mut tensors: Vec<&Tensor> = vec![];
let mut hmetadata = HashMap::new();
let mut offset = 0;
for (name, tensor) in data {
let n = tensor.data.len();
-
let tensor_info = TensorInfo {
dtype: tensor.dtype.clone(),
shape: tensor.shape.clone(),
let metadata: Metadata = Metadata(hmetadata);
- let metadata_buf = serde_json::to_string(&metadata).unwrap().into_bytes();
+ (metadata, tensors, offset)
+ }
- let mut buffer: Vec<u8> = Vec::with_capacity(1 + metadata_buf.len() + offset);
+ pub fn serialize(data: &HashMap<String, Tensor>) -> Vec<u8> {
+ let (metadata, tensors, offset) = Self::prepare(data);
+ let metadata_buf = serde_json::to_string(&metadata).unwrap().into_bytes();
+ let expected_size = 8 + metadata_buf.len() + offset;
+ let mut buffer: Vec<u8> = Vec::with_capacity(expected_size);
let n: u64 = metadata_buf.len() as u64;
buffer.extend(&n.to_le_bytes().to_vec());
buffer.extend(&metadata_buf);
buffer
}
+ pub fn serialize_to_file(
+ data: &HashMap<String, Tensor>,
+ filename: &str,
+ ) -> Result<(), std::io::Error> {
+ let (metadata, tensors, _) = Self::prepare(data);
+ 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)?);
+ f.write_all(&n.to_le_bytes().to_vec())?;
+ f.write_all(&metadata_buf)?;
+ for tensor in tensors {
+ f.write_all(tensor.data)?;
+ }
+ f.flush()?;
+ Ok(())
+ }
+
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],
let filename = format!("./out_{}.bin", model_id);
- use std::time::Instant;
- let start = Instant::now();
let out = SafeTensor::serialize(&metadata);
- let start = Instant::now();
std::fs::write(&filename, out).unwrap();
- let start = Instant::now();
let raw = std::fs::read(&filename).unwrap();
- let start = Instant::now();
SafeTensor::deserialize(raw).unwrap();
}
}