From 960cd17702430a2f033fa4dc5361119a6dac8b55 Mon Sep 17 00:00:00 2001 From: Nicolas Patry Date: Fri, 24 Feb 2023 14:56:51 +0100 Subject: [PATCH] Better Rust API (tch-rs) (#179) * Implementing a trait API for the Rust (should make tch-rs interaction easier). * Companion type. * Re-export major formats + 3rd example in the trait doc. * Even clearer OpaqueGPU type. * Moving to `Cow<[u8]>`. Feels simpler. * Fixes. --- .pre-commit-config.yaml | 2 +- safetensors/src/lib.rs | 1 + safetensors/src/tensor.rs | 188 +++++++++++++++++++++++++++++++------- 3 files changed, 157 insertions(+), 34 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a37f05c..06f77d2 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -40,7 +40,7 @@ repos: name: "Python (black)" args: ["--line-length", "119", "--target-version", "py35"] types: ["python"] - - repo: https://gitlab.com/pycqa/flake8 + - repo: https://github.com/pycqa/flake8 rev: 3.8.3 hooks: - id: flake8 diff --git a/safetensors/src/lib.rs b/safetensors/src/lib.rs index b34446a..7dcbdc1 100644 --- a/safetensors/src/lib.rs +++ b/safetensors/src/lib.rs @@ -144,3 +144,4 @@ pub mod slice; pub mod tensor; +pub use tensor::{serialize, serialize_to_file, Dtype, SafeTensorError, SafeTensors, View}; diff --git a/safetensors/src/tensor.rs b/safetensors/src/tensor.rs index fd2489a..09bb2b8 100644 --- a/safetensors/src/tensor.rs +++ b/safetensors/src/tensor.rs @@ -1,6 +1,7 @@ //! Module Containing the most important structures use crate::slice::{InvalidSlice, SliceIterator, TensorIndexer}; use serde::{ser::SerializeMap, Deserialize, Deserializer, Serialize, Serializer}; +use std::borrow::Cow; use std::collections::HashMap; use std::fs::File; use std::io::{BufWriter, Write}; @@ -48,34 +49,125 @@ impl std::fmt::Display for SafeTensorError { impl std::error::Error for SafeTensorError {} -struct PreparedData<'hash, 'data> { +struct PreparedData { n: u64, header_bytes: Vec, - tensors: Vec<&'hash TensorView<'data>>, offset: usize, } -fn prepare<'hash, 'data>( - data: &'hash HashMap>, - data_info: &'hash Option>, +/// The trait necessary to enable safetensors to serialize a tensor +/// If you have an owned tensor like this: +/// +/// ```rust +/// use safetensors::tensor::{View, Dtype}; +/// use std::borrow::Cow; +/// struct Tensor{ dtype: MyDtype, shape: Vec, data: Vec} +/// +/// # type MyDtype = Dtype; +/// impl<'data> View for &'data Tensor{ +/// fn dtype(&self) -> Dtype{ +/// self.dtype.into() +/// } +/// fn shape(&self) -> &[usize]{ +/// &self.shape +/// } +/// fn data(&self) -> Cow<[u8]>{ +/// (&self.data).into() +/// } +/// fn data_len(&self) -> usize{ +/// self.data.len() +/// } +/// } +/// ``` +/// +/// For a borrowed tensor: +/// +/// ```rust +/// use safetensors::tensor::{View, Dtype}; +/// use std::borrow::Cow; +/// struct Tensor<'data>{ dtype: MyDtype, shape: Vec, data: &'data[u8]} +/// +/// # type MyDtype = Dtype; +/// impl<'data> View for Tensor<'data>{ +/// fn dtype(&self) -> Dtype{ +/// self.dtype.into() +/// } +/// fn shape(&self) -> &[usize]{ +/// &self.shape +/// } +/// fn data(&self) -> Cow<[u8]>{ +/// self.data.into() +/// } +/// fn data_len(&self) -> usize{ +/// self.data.len() +/// } +/// } +/// ``` +/// +/// Now if you have some unknown buffer that could be on GPU for instance, +/// you can implement the trait to return an owned local buffer containing the data +/// on CPU (needed to write on disk) +/// ```rust +/// use safetensors::tensor::{View, Dtype}; +/// use std::borrow::Cow; +/// +/// # type MyDtype = Dtype; +/// # type OpaqueGpu = Vec; +/// struct Tensor{ dtype: MyDtype, shape: Vec, data: OpaqueGpu } +/// +/// impl View for Tensor{ +/// fn dtype(&self) -> Dtype{ +/// self.dtype.into() +/// } +/// fn shape(&self) -> &[usize]{ +/// &self.shape +/// } +/// fn data(&self) -> Cow<[u8]>{ +/// // This copies data from GPU to CPU. +/// let data: Vec = self.data.to_vec(); +/// data.into() +/// } +/// fn data_len(&self) -> usize{ +/// let n: usize = self.shape.iter().product(); +/// let bytes_per_element = self.dtype.size(); +/// n * bytes_per_element +/// } +/// } +/// ``` +pub trait View { + /// The `Dtype` of the tensor + fn dtype(&self) -> Dtype; + /// The shape of the tensor + fn shape(&self) -> &[usize]; + /// The data of the tensor + fn data(&self) -> Cow<[u8]>; + /// The length of the data, in bytes. + /// This is necessary as this might be faster to get than `data().len()` + /// for instance for tensors residing in GPU. + fn data_len(&self) -> usize; +} + +fn prepare + Ord + std::fmt::Display, V: View, I: IntoIterator>( + data: I, + data_info: &Option>, // ) -> Result<(Metadata, Vec<&'hash TensorView<'data>>, usize), SafeTensorError> { -) -> Result, SafeTensorError> { +) -> Result<(PreparedData, Vec), SafeTensorError> { // Make sure we're sorting by descending dtype alignment // Then by name - let mut data: Vec<_> = data.iter().collect(); + let mut data: Vec<_> = data.into_iter().collect(); data.sort_by(|(lname, left), (rname, right)| { - right.dtype.cmp(&left.dtype).then(lname.cmp(rname)) + right.dtype().cmp(&left.dtype()).then(lname.cmp(rname)) }); - let mut tensors: Vec<&TensorView> = vec![]; + let mut tensors: Vec = Vec::with_capacity(data.len()); let mut hmetadata = Vec::with_capacity(data.len()); let mut offset = 0; let data: Vec<_> = data.into_iter().collect(); for (name, tensor) in data { - let n = tensor.data.len(); + let n = tensor.data_len(); let tensor_info = TensorInfo { - dtype: tensor.dtype, - shape: tensor.shape.to_vec(), + dtype: tensor.dtype(), + shape: tensor.shape().to_vec(), data_offsets: (offset, offset + n), }; offset += n; @@ -91,31 +183,39 @@ fn prepare<'hash, 'data>( let n: u64 = metadata_buf.len() as u64; - Ok(PreparedData { - n, - header_bytes: metadata_buf, + Ok(( + PreparedData { + n, + header_bytes: metadata_buf, + offset, + }, tensors, - offset, - }) + )) } /// Serialize to an owned byte buffer the dictionnary of tensors. -pub fn serialize( - data: &HashMap, +pub fn serialize< + S: AsRef + Ord + std::fmt::Display, + V: View, + I: IntoIterator, +>( + data: I, data_info: &Option>, ) -> Result, SafeTensorError> { - let PreparedData { - n, - header_bytes, + let ( + PreparedData { + n, + header_bytes, + offset, + }, tensors, - offset, - } = prepare(data, data_info)?; + ) = prepare(data, data_info)?; let expected_size = 8 + header_bytes.len() + offset; let mut buffer: Vec = Vec::with_capacity(expected_size); buffer.extend(&n.to_le_bytes().to_vec()); buffer.extend(&header_bytes); for tensor in tensors { - buffer.extend(tensor.data); + buffer.extend(tensor.data().as_ref()); } Ok(buffer) } @@ -123,22 +223,26 @@ pub fn serialize( /// Serialize to a 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, +pub fn serialize_to_file< + S: AsRef + Ord + std::fmt::Display, + V: View, + I: IntoIterator, +>( + data: I, data_info: &Option>, filename: &Path, ) -> Result<(), SafeTensorError> { - let PreparedData { - n, - header_bytes, + let ( + PreparedData { + n, header_bytes, .. + }, tensors, - .. - } = prepare(data, data_info)?; + ) = prepare(data, data_info)?; let mut f = BufWriter::new(File::create(filename)?); f.write_all(n.to_le_bytes().as_ref())?; f.write_all(&header_bytes)?; for tensor in tensors { - f.write_all(tensor.data)?; + f.write_all(tensor.data().as_ref())?; } f.flush()?; Ok(()) @@ -373,6 +477,24 @@ pub struct TensorView<'data> { data: &'data [u8], } +impl<'data> View for &TensorView<'data> { + fn dtype(&self) -> Dtype { + self.dtype + } + + fn shape(&self) -> &[usize] { + &self.shape + } + + fn data(&self) -> Cow<[u8]> { + self.data.into() + } + + fn data_len(&self) -> usize { + self.data.len() + } +} + impl<'data> TensorView<'data> { /// Create new tensor view pub fn new( -- 2.43.0