--- /dev/null
+name: Rust
+
+on:
+ push:
+ branches:
+ - master
+ pull_request:
+
+jobs:
+ build:
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ os: [ubuntu-latest, windows-latest, macOS-latest]
+
+ steps:
+ - uses: actions/checkout@v1
+
+ - name: Install Rust Stable
+ uses: actions-rs/toolchain@v1
+ with:
+ toolchain: stable
+ components: rustfmt, clippy
+ override: true
+
+ - name: Install cargo-readme for Ubuntu
+ if: matrix.os == 'ubuntu-latest'
+ uses: actions-rs/cargo@v1
+ with:
+ command: install
+ args: cargo-readme
+
+ - name: Build
+ uses: actions-rs/cargo@v1
+ with:
+ command: build
+ args: --all-targets --verbose --manifest-path ./safetensors/Cargo.toml
+
+ - name: Lint with Clippy
+ uses: actions-rs/cargo@v1
+ with:
+ command: clippy
+ args: --manifest-path ./safetensors/Cargo.toml --all-targets --all-features -- -D warnings
+
+ - name: Run Tests
+ uses: actions-rs/cargo@v1
+ with:
+ command: test
+ args: --verbose --manifest-path ./safetensors/Cargo.toml
+
+ # Verify that Readme.md is up to date.
+ - name: Make sure, Readme generated from lib.rs matches actual Readme
+ if: matrix.os == 'ubuntu-latest'
+ shell: bash
+ working-directory: ./safetensors
+ run: cargo readme > must_match_readme.md && diff must_match_readme.md README.md
--- /dev/null
+# Safetensors
+
+This repository implements a new simple format for storing tensors
+safely (as opposed to pickle) and that is still fast (zero-copy).
+
+
+## Yet another format ?
+
+The main rationale for this crate is to remove the need to use
+`pickle` on `PyTorch` which is used by default.
+
+
+Let's take a look at alternatives.
+
+| Format | Safe\* | Zero-copy | Not file size limit | (B)Float-16 support | Flexibility |
+| --- | --- | --- | --- | --- | --- |
+| pickle (PyTorch) |
+| H5 (Tensorflow) |
+| SavedModel (Tensorflow) |
+| MsgPack (flax) |
+| Protobuf (ONNX) |
+| Cap'n'Proto |
+| SafeTensors | 🗸 | 🗸 | 🗸 | 🗸 | ✗ |
+
+
__version__ = "0.0.1"
-from typing import Dict
-import numpy as np
-from .safetensors_rust import deserialize, serialize, deserialize_file, serialize_file
-import torch
-
-def save(tensor_dict: Dict[str, np.ndarray]) -> bytes:
- flattened = {
- k: {"dtype": v.dtype.name, "shape": v.shape, "data": v.tobytes()}
- for k, v in tensor_dict.items()
- }
- serialized = serialize(flattened)
- result = bytes(serialized)
- 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 getdtype(dtype_str: str) -> np.dtype:
- return TYPES[dtype_str]
-
-
-def load_file(filename: str) -> Dict[str, np.ndarray]:
- flat = deserialize_file(filename)
- return view2np(flat)
-
-
-def load(buffer: bytes) -> Dict[str, np.ndarray]:
- flat = deserialize(buffer)
- return view2np(flat)
-
-
-def view2np(safeview):
- result = {}
- for k, v in safeview:
- dtype = getdtype(v["dtype"])
- arr = np.frombuffer(v["data"], dtype=dtype)
- result[k] = arr
- return result
-
-
-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
-
-
-def save_pt(tensors: Dict[str, torch.Tensor]) -> bytes:
- 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)
+from .numpy_functions import save, save_pt, load_file
+from .torch_functions import save_pt, save_file_pt, load_file_pt
--- /dev/null
+import numpy as np
+from .safetensors_rust import deserialize, serialize, deserialize_file, serialize_file
+from typing import Dict
+
+
+def save(tensor_dict: Dict[str, np.ndarray]) -> bytes:
+ flattened = {
+ k: {"dtype": v.dtype.name, "shape": v.shape, "data": v.tobytes()}
+ for k, v in tensor_dict.items()
+ }
+ serialized = serialize(flattened)
+ result = bytes(serialized)
+ return result
+
+
+TYPES = {
+ "F64": np.float64,
+ "F32": np.float32,
+ "F16": np.float16,
+ "I64": np.int64,
+ "U64": np.uint64,
+ "I32": np.int32,
+ "U32": np.uint32,
+ "I16": np.int16,
+ "U16": np.uint16,
+ "I8": np.int8,
+ "U8": np.uint8,
+ "BOOL": np.bool,
+}
+
+
+def getdtype(dtype_str: str) -> np.dtype:
+ return TYPES[dtype_str]
+
+
+def load_file(filename: str) -> Dict[str, np.ndarray]:
+ flat = deserialize_file(filename)
+ return view2np(flat)
+
+
+def load(buffer: bytes) -> Dict[str, np.ndarray]:
+ flat = deserialize(buffer)
+ return view2np(flat)
+
+
+def view2np(safeview):
+ result = {}
+ for k, v in safeview:
+ dtype = getdtype(v["dtype"])
+ arr = np.frombuffer(v["data"], dtype=dtype).reshape(v["shape"])
+ result[k] = arr
+ 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)
--- /dev/null
+from safetensors.numpy_functions import save, save_file, load_file, load
+import numpy as np
+from typing import Dict
+import torch
+
+
+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
+
+
+def save_pt(tensors: Dict[str, torch.Tensor]) -> bytes:
+ for k, v in tensors.items():
+ tensors[k] = v.numpy()
+ return save(tensors)
+
+
+def save_file_pt(tensors: Dict[str, torch.Tensor], filename: str):
+ for k, v in tensors.items():
+ tensors[k] = v.numpy()
+ return save_file(tensors, filename)
+
+
+def load_pt(buffer: bytes) -> Dict[str, torch.Tensor]:
+ flat = load(buffer)
+ return np2pt(flat)
+
+
+def load_file_pt(filename: str) -> Dict[str, torch.Tensor]:
+ flat = load_file(filename)
+ return np2pt(flat)
+#![deny(missing_docs)]
+//! Dummy doc
use memmap::MmapOptions;
use pyo3::exceptions;
use pyo3::prelude::*;
use pyo3::types::{PyByteArray, PyBytes, PyDict, PyList};
-use safetensors::{Dtype, SafeTensor, SafeTensorBorrowed, Tensor};
+use safetensors::{Dtype, SafeTensors, Tensor};
use std::collections::HashMap;
use std::fs::File;
-use std::io::Write;
-fn prepare<'a, 'b>(
- py: Python<'b>,
- tensor_dict: HashMap<String, &'a PyDict>,
-) -> PyResult<HashMap<String, Tensor<'a>>> {
- let start = std::time::Instant::now();
+fn prepare<'a>(tensor_dict: HashMap<String, &'a PyDict>) -> PyResult<HashMap<String, Tensor<'a>>> {
let mut tensors = HashMap::new();
for (tensor_name, tensor_desc) in tensor_dict {
let mut shape: Vec<usize> = vec![];
"dtype" => {
let value: &str = value.extract()?;
dtype = match value {
+ "bool" => Dtype::BOOL,
+ "int8" => Dtype::I8,
+ "uint8" => Dtype::U8,
+ "int16" => Dtype::I16,
+ "uint16" => Dtype::U16,
+ "int32" => Dtype::I32,
+ "uint32" => Dtype::U32,
+ "int64" => Dtype::I64,
+ "uint64" => Dtype::U64,
+ "float16" => Dtype::F16,
"float32" => Dtype::F32,
"float64" => Dtype::F64,
- "int32" => Dtype::I32,
dtype_str => {
unimplemented!("Did not cover this dtype: {}", dtype_str)
}
py: Python<'b>,
tensor_dict: HashMap<String, &'a PyDict>,
) -> PyResult<&'b PyBytes> {
- let tensors = prepare(py, tensor_dict)?;
- let out = SafeTensor::serialize(&tensors);
+ let tensors = prepare(tensor_dict)?;
+ let out = safetensors::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)?;
+fn serialize_file<'a>(tensor_dict: HashMap<String, &'a PyDict>, filename: &str) -> PyResult<()> {
+ let tensors = prepare(tensor_dict)?;
+ safetensors::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();
- let safetensor = SafeTensorBorrowed::deserialize(bytes).map_err(|e| {
+ let safetensor = SafeTensors::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 pyshape: PyObject = PyList::new(py, tensor.get_shape().into_iter()).into();
+ let pydtype: PyObject = format!("{:?}", tensor.get_dtype()).into_py(py);
- let pydata: PyObject = PyByteArray::new(py, tensor.data).into();
+ let pydata: PyObject = PyByteArray::new(py, tensor.get_data()).into();
map.insert("shape".to_string(), pyshape);
map.insert("dtype".to_string(), pydtype);
filename: &str,
) -> PyResult<Vec<(String, HashMap<String, PyObject>)>> {
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)? };
- deserialize(py, &mmap)
+ let deserialized = deserialize(py, &mmap);
+ // Make sure mmap does not leak.
+ drop(mmap);
+ deserialized
}
/// A Python module implemented in Rust.
from huggingface_hub import hf_hub_download
import torch
import datetime
+import os
+
+
+MODEL_ID = os.getenv("MODEL_ID", "gpt2")
class BigTestCase(unittest.TestCase):
def test_gpt2_deserialization_safe(self):
- filename = hf_hub_download("gpt2", filename="pytorch_model.bin")
+ filename = hf_hub_download(MODEL_ID, filename="pytorch_model.bin")
data = torch.load(filename)
local = "out_safe.bin"
print("Deserialization (Safe) took ", datetime.datetime.now() - start)
def test_gpt2_deserialization_safe_mmap(self):
- filename = hf_hub_download("gpt2", filename="pytorch_model.bin")
+ filename = hf_hub_download(MODEL_ID, filename="pytorch_model.bin")
data = torch.load(filename)
local = "out_safe_mmap.bin"
print("Deserialization (Safe) took ", datetime.datetime.now() - start)
def test_gpt2_deserialization_pt(self):
- filename = hf_hub_download("gpt2", filename="pytorch_model.bin")
+ filename = hf_hub_download(MODEL_ID, filename="pytorch_model.bin")
start = datetime.datetime.now()
torch.load(filename)
print()
print("Deserialization (PT) took ", datetime.datetime.now() - start)
+ def test_gpt2_deserialization_flax(self):
+ from flax.serialization import msgpack_restore
+
+ filename = "/home/nicolas/src/gpt2/flax_model.msgpack"
+ start = datetime.datetime.now()
+ with open(filename, "rb") as f:
+ data = f.read()
+ msgpack_restore(data)
+ print()
+ print("Deserialization (flax) took ", datetime.datetime.now() - start)
+
+ def test_gpt2_deserialization_tf(self):
+ import h5py
+ import numpy as np
+
+ filename = "/home/nicolas/src/gpt2/tf_model.h5"
+ start = datetime.datetime.now()
+ tensors = {}
+
+ def _load(f, prefix=""):
+ for k in f.keys():
+ if isinstance(f[k], h5py._hl.dataset.Dataset):
+ tensors[f"{prefix}_{k}"] = np.array(f[k])
+ else:
+ _load(f[k], prefix=f"{prefix}_{k}")
+
+ with h5py.File(filename, "r") as f:
+ _load(f)
+
+ print()
+ print("Deserialization (TF) took ", datetime.datetime.now() - start)
+
def test_gpt2_serialization_pt(self):
- filename = hf_hub_download("gpt2", filename="pytorch_model.bin")
+ filename = hf_hub_download(MODEL_ID, filename="pytorch_model.bin")
data = torch.load(filename)
start = datetime.datetime.now()
print("Serialization (PT) took ", datetime.datetime.now() - start)
def test_gpt2_serialization_safe(self):
- filename = hf_hub_download("gpt2", filename="pytorch_model.bin")
+ filename = hf_hub_download(MODEL_ID, filename="pytorch_model.bin")
data = torch.load(filename)
start = datetime.datetime.now()
outfilename = "out_py_test.bin"
+#![deny(missing_docs)]
+//! Safetensors documentation
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufWriter, Write};
+/// Possible errors that could occur while reading
+/// A Safetensor file.
#[derive(Debug)]
pub enum SafeTensorError {
+ /// The header is an invalid UTF-8 string and cannot be read.
InvalidHeader,
+ /// The header does contain a valid string, but it is not valid JSON.
+ InvalidHeaderDeserialization,
}
-pub struct SafeTensor {
- metadata: Metadata,
- offset: usize,
- data: Vec<u8>,
-}
-
-impl SafeTensor {
- 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(),
- data_offsets: (offset, offset + n),
- };
- offset += n;
- hmetadata.insert(name.to_string(), tensor_info);
- tensors.push(tensor);
- }
-
- let metadata: Metadata = Metadata(hmetadata);
-
- (metadata, tensors, offset)
+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(),
+ data_offsets: (offset, offset + n),
+ };
+ offset += n;
+ hmetadata.insert(name.to_string(), tensor_info);
+ tensors.push(tensor);
}
- 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);
- for tensor in tensors {
- buffer.extend(tensor.data);
- }
- buffer
- }
+ let metadata: Metadata = Metadata(hmetadata);
- 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(())
- }
+ (metadata, tensors, offset)
+}
- 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 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(SafeTensor {
- metadata,
- offset: n + 8,
- data: buffer,
- })
+/// Serialize to an owned byte buffer the dictionnary of tensors.
+pub fn serialize(data: &HashMap<String, Tensor>) -> Vec<u8> {
+ let (metadata, tensors, offset) = 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);
+ for tensor in tensors {
+ buffer.extend(tensor.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
+/// Serialize to an regular file the dictionnary of tensors.
+/// Writing directly to file reduces the need to allocate the whole amount to
+/// memory.
+pub fn serialize_to_file(
+ data: &HashMap<String, Tensor>,
+ filename: &str,
+) -> Result<(), std::io::Error> {
+ let (metadata, tensors, _) = 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 struct SafeTensorBorrowed<'data> {
+/// A structure owning some metadata to lookup tensors on a shared `data`
+/// byte-buffer (not owned).
+pub struct SafeTensors<'data> {
metadata: Metadata,
offset: usize,
data: &'data [u8],
}
-impl<'data> SafeTensorBorrowed<'data> {
+
+impl<'data> SafeTensors<'data> {
+ /// Given a byte-buffer representing the whole safetenosr file
+ /// parses it and returns the Deserialized form (No Tensor allocation).
pub fn deserialize<'in_data>(buffer: &'in_data [u8]) -> Result<Self, SafeTensorError>
where
'in_data: 'data,
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)?;
+ let metadata: Metadata = serde_json::from_str(string)
+ .map_err(|_| SafeTensorError::InvalidHeaderDeserialization)?;
Ok(Self {
metadata,
offset: n + 8,
})
}
+ /// Allow the user to iterate over tensors within the SafeTensors.
+ /// The tensors returned are merely views and the data is not owned by this
+ /// structure.
pub fn tensors(&self) -> Vec<(String, TensorView<'_>)> {
let mut tensors = vec![];
for (name, info) in &self.metadata.0 {
}
}
+/// 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<String, TensorInfo>);
+/// A view of a Tensor within the file.
+/// Contains references to data within the full byte-buffer
+/// And is thus a readable view of a single tensor
#[derive(Debug)]
pub struct TensorView<'data> {
- pub dtype: &'data Dtype,
- pub shape: &'data [usize],
- pub data: &'data [u8],
+ dtype: &'data Dtype,
+ shape: &'data [usize],
+ data: &'data [u8],
+}
+
+impl<'data> TensorView<'data> {
+ /// The current tensor dtype
+ pub fn get_dtype(&self) -> &'data Dtype {
+ self.dtype
+ }
+
+ /// The current tensor shape
+ pub fn get_shape(&self) -> &'data [usize] {
+ self.shape
+ }
+
+ /// The current tensor byte-buffer
+ pub fn get_data(&self) -> &'data [u8] {
+ self.data
+ }
}
+/// A single tensor information.
+/// Endianness is assumed to be little endian
+/// Ordering is assumed to be 'C'.
#[derive(Debug, Deserialize, Serialize, Clone)]
struct TensorInfo {
+ /// The type of each element of the tensor
dtype: Dtype,
+ /// The shape of the tensor
shape: Vec<usize>,
+ /// The offsets to find the data within the byte-buffer array.
data_offsets: (usize, usize),
}
+/// The various available dtypes
#[derive(Debug, Deserialize, Serialize, Clone)]
+#[non_exhaustive]
pub enum Dtype {
+ /// Boolan type
BOOL,
+ /// Unsigned byte
U8,
+ /// Signed byte
+ I8,
+ /// Signed integer (16-bit)
+ I16,
+ /// Unsigned integer (16-bit)
+ U16,
+ /// Signed integer (32-bit)
I32,
+ /// Unsigned integer (32-bit)
+ U32,
+ /// Signed integer (64-bit)
I64,
+ /// Unsigned integer (64-bit)
+ U64,
+ /// Half-precision floating point
F16,
+ /// Brain floating point
BF16,
+ /// Floating point (32-bit)
F32,
+ /// Floating point (64-bit)
F64,
}
-pub struct Tensor<'a> {
+/// A struct representing a Tensor, the byte-buffer is not owned
+/// but dtype a shape are.
+pub struct Tensor<'data> {
shape: Vec<usize>,
dtype: Dtype,
- data: &'a [u8],
+ data: &'data [u8],
}
impl<'a> Tensor<'a> {
+ /// Simple Tensor creation.
pub fn new(data: &'a [u8], dtype: Dtype, shape: Vec<usize>) -> Self {
Self { data, dtype, shape }
}
let metadata: HashMap<String, Tensor> =
[("attn.0".to_string(), attn_0)].into_iter().collect();
- let out = SafeTensor::serialize(&metadata);
- SafeTensor::deserialize(out).unwrap();
+ let out = serialize(&metadata);
+ let _parsed = SafeTensors::deserialize(&out).unwrap();
}
#[test]
let filename = format!("./out_{}.bin", model_id);
- let out = SafeTensor::serialize(&metadata);
+ let out = serialize(&metadata);
std::fs::write(&filename, out).unwrap();
let raw = std::fs::read(&filename).unwrap();
- SafeTensor::deserialize(raw).unwrap();
+ let _deserialized = SafeTensors::deserialize(&raw).unwrap();
}
}