]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Big revamp: (#10)
authorNicolas Patry <patry.nicolas@protonmail.com>
Thu, 29 Sep 2022 07:34:13 +0000 (09:34 +0200)
committerGitHub <noreply@github.com>
Thu, 29 Sep 2022 07:34:13 +0000 (09:34 +0200)
* Adding slicing support on tensorview.

Clippy 1.64.

Improve the comment.

[WIP] Bad python slice API for now, still looking for a nice pythonesque
one

But at least this works !

Much better API.

Pros:
- handles a lot of boilerplate for caller.
- Feels more pythonesque

Cons:
- Unsure about soundness of keeping Mmap struct.
- Lots more boilerplate in the binding

Removing unused code.

Improved API names hopefully.

Adding .keys() support.

Big revamp:

- Remove `Tensor` to fuse with `TensorView` (the price to pay for shape
  cloning should be small enough that it shouldn't make too much of a
difference
- Remove `deserialize_file`, now that we have `safe_open` facility.
- Tried to remove `torch` dependency on `numpy` (Still need the
  `torch.Tensor` to bytes without copying facility.
- Revamped the speed tests to show metrics side by side. They need
  to be taken with extreme caution, timings are never reproducible.

New possibility to save metadata.

Fixing the workflow.

Rename.

Black.

Installing other libs.

Make windows happy.

Non venv.

Install jax on windows is impossible ?

More private python functions + Windows(flax) shenanigans.

Fixing TF to be ACTUALLY TF native.

Option<Metadata>

* Black.

* Export metadata.

15 files changed:
.github/workflows/python.yml [new file with mode: 0644]
bindings/python/Cargo.toml
bindings/python/py_src/safetensors/__init__.py
bindings/python/py_src/safetensors/flax.py
bindings/python/py_src/safetensors/numpy.py
bindings/python/py_src/safetensors/tensorflow.py
bindings/python/py_src/safetensors/torch.py
bindings/python/src/lib.rs
bindings/python/tests/test_flax_comparison.py
bindings/python/tests/test_pt_comparison.py
bindings/python/tests/test_simple.py
bindings/python/tests/test_tf_comparison.py
safetensors/src/lib.rs
safetensors/src/slice.rs [new file with mode: 0644]
safetensors/src/tensor.rs [new file with mode: 0644]

diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml
new file mode 100644 (file)
index 0000000..3867df1
--- /dev/null
@@ -0,0 +1,72 @@
+name: Python
+
+on:
+  pull_request:
+    paths:
+      - bindings/python/**
+      - safetensors/**
+
+jobs:
+  build_and_test:
+    name: Check everything builds & tests
+    runs-on: ${{ matrix.os }}
+    strategy:
+      matrix:
+        os: [ubuntu-18.04, macos-latest, windows-latest]
+    steps:
+      - name: Checkout repository
+        uses: actions/checkout@v1
+        
+
+      - name: Install Rust
+        uses: actions-rs/toolchain@v1
+        with:
+          toolchain: stable
+          components: rustfmt, clippy
+
+      - name: Install Python
+        uses: actions/setup-python@v2
+        with:
+          python-version: 3.9
+          architecture: "x64"
+
+
+      - name: Cache Cargo Registry
+        uses: actions/cache@v1
+        with:
+          path: ~/.cargo/registry
+          key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
+
+      - name: Lint with RustFmt
+        uses: actions-rs/cargo@v1
+        with:
+          toolchain: stable
+          command: fmt
+          args: --manifest-path ./bindings/python/Cargo.toml -- --check
+
+      - name: Lint with Clippy
+        uses: actions-rs/cargo@v1
+        with:
+          command: clippy
+          args: --manifest-path ./bindings/python/Cargo.toml --all-targets --all-features -- -D warnings
+
+      - name: Install
+        working-directory: ./bindings/python
+        run: |
+          pip install -U pip
+          pip install pytest requests setuptools_rust numpy pyarrow datasets
+          pip install torch tensorflow numpy
+          pip install jax jaxlib flax
+          python setup.py develop
+
+      - name: Check style
+        working-directory: ./bindings/python
+        run: |
+          pip install black==20.8b1 click==8.0.4
+          black --check --line-length 100 --target-version py36 py_src/safetensors tests
+
+      - name: Run tests
+        working-directory: ./bindings/python
+        run: |
+          cargo test
+          pytest -sv tests/
index 951d335a4d0da5a84af3e20595f3f05d12729450..2ab4f711ac3e8fa4c002c7f6985a79d7295fe7e7 100644 (file)
@@ -9,8 +9,9 @@ name = "safetensors_rust"
 crate-type = ["cdylib"]
 
 [dependencies]
-pyo3 = { version = "0.15.1", features = ["extension-module"] }
+pyo3 = { version = "0.17.1", features = ["extension-module"] }
 memmap = "0.7"
+serde_json = "1.0"
 
 [dependencies.safetensors]
 version = "*"
index c0ae2e04ff4db209639ab1b89948a682d43387a7..171a9612dd49fc3c0d75a64b9a6f8e7f6d5c0470 100644 (file)
@@ -1 +1,4 @@
 __version__ = "0.0.2.dev0"
+
+# Re-export this
+from .safetensors_rust import safe_open
index aed53f4ca2f0d749da40a0630c4cf7d61297b232..7ad527c7d3fde468bb55868cdf4268d087d8dc6f 100644 (file)
@@ -4,37 +4,37 @@ from typing import Dict, Optional
 import jax.numpy as jnp
 
 
-def np2jnp(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, jnp.DeviceArray]:
+def _np2jnp(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, jnp.DeviceArray]:
     for k, v in numpy_dict.items():
         numpy_dict[k] = jnp.array(v)
     return numpy_dict
 
 
-def jnp2np(jnp_dict: Dict[str, jnp.DeviceArray]) -> Dict[str, np.array]:
+def _jnp2np(jnp_dict: Dict[str, jnp.DeviceArray]) -> Dict[str, np.array]:
     for k, v in jnp_dict.items():
         jnp_dict[k] = np.asarray(v)
     return jnp_dict
 
 
 def save(tensors: Dict[str, jnp.DeviceArray], metadata: Optional[Dict[str, str]] = None) -> bytes:
-    np_tensors = jnp2np(tensors)
-    return numpy.save(np_tensors, metadata=metadata)
+    np_tensors = _jnp2np(tensors)
+    return numpy.save(np_tensors)
 
 
-def save_file(tensors: Dict[str, jnp.DeviceArray], filename: str, metadata: Optional[Dict[str, str]] = None):
-    np_tensors = jnp2np(tensors)
-    return numpy.save_file(np_tensors, filename, metadata=metadata)
+def save_file(
+    tensors: Dict[str, jnp.DeviceArray],
+    filename: str,
+    metadata: Optional[Dict[str, str]] = None,
+):
+    np_tensors = _jnp2np(tensors)
+    return numpy.save_file(np_tensors, filename)
 
 
 def load(buffer: bytes) -> Dict[str, jnp.DeviceArray]:
     flat = numpy.load(buffer)
-    return np2jnp(flat)
+    return _np2jnp(flat)
 
 
 def load_file(filename: str) -> Dict[str, jnp.DeviceArray]:
     flat = numpy.load_file(filename)
-    return np2jnp(flat)
-
-
-def read_metadata_in_file(filename: str) -> Dict[str, str]:
-    return numpy.read_metadata(filename)
\ No newline at end of file
+    return _np2jnp(flat)
index 8d990e5567f9b3e9758692019bf665cbc871bed9..bbce5005aa1c6b6fb196b408e263911abd2c5de3 100644 (file)
@@ -1,5 +1,5 @@
 import numpy as np
-from .safetensors_rust import deserialize, serialize, deserialize_file, serialize_file, read_metadata
+from .safetensors_rust import serialize, serialize_file, safe_open, deserialize
 from typing import Dict, Optional
 
 
@@ -13,7 +13,28 @@ def save(tensor_dict: Dict[str, np.ndarray], metadata: Optional[Dict[str, str]]
     return result
 
 
-TYPES = {
+def load(filename: str) -> Dict[str, np.ndarray]:
+    flat = deserialize(filename)
+    return _view2np(flat)
+
+
+def load_file(filename: str) -> Dict[str, np.ndarray]:
+    result = {}
+    with safe_open(filename, framework="np") as f:
+        for k in f.keys():
+            result[k] = f.get_tensor(k)
+    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 = {
     "F64": np.float64,
     "F32": np.float32,
     "F16": np.float16,
@@ -29,36 +50,14 @@ TYPES = {
 }
 
 
-def getdtype(dtype_str: str) -> np.dtype:
-    return TYPES[dtype_str]
+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):
+def _view2np(safeview) -> Dict[str, np.ndarray]:
     result = {}
     for k, v in safeview:
-        dtype = getdtype(v["dtype"])
+        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, metadata: Optional[Dict[str, str]] = None):
-    flattened = {
-        k: {"dtype": v.dtype.name, "shape": v.shape, "data": v.tobytes()}
-        for k, v in tensor_dict.items()
-    }
-    serialize_file(flattened, metadata, filename)
-
-
-def read_metadata_in_file(filename: str) -> Dict[str, str]:
-    return read_metadata(filename)
index ac6efc9a9b5e8cc5a82a09ee688a68dd97d7348b..a47293d47fd0e40eb6f4848011738ccd4c1876ae 100644 (file)
@@ -4,36 +4,37 @@ from typing import Dict, Optional
 import tensorflow as tf
 
 
-def np2tf(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, tf.DeviceArray]:
+def _np2tf(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, tf.Tensor]:
     for k, v in numpy_dict.items():
         numpy_dict[k] = tf.convert_to_tensor(v)
     return numpy_dict
 
 
-def tf2np(tf_dict: Dict[str, tf.DeviceArray]) -> Dict[str, np.array]:
+def _tf2np(tf_dict: Dict[str, tf.Tensor]) -> Dict[str, np.array]:
     for k, v in tf_dict.items():
         tf_dict[k] = v.numpy()
     return tf_dict
 
 
-def save(tensors: Dict[str, tf.DeviceArray], metadata: Optional[Dict[str, str]] = None) -> bytes:
-    np_tensors = tf2np(tensors)
-    return numpy.save(np_tensors, metadata=metadata)
+def save(tensors: Dict[str, tf.Tensor], metadata: Optional[Dict[str, str]] = None) -> bytes:
+    np_tensors = _tf2np(tensors)
+    return numpy.save(np_tensors)
 
 
-def save_file(tensors: Dict[str, tf.DeviceArray], filename: str, metadata: Optional[Dict[str, str]] = None):
-    np_tensors = tf2np(tensors)
-    return numpy.save_file(np_tensors, filename, metadata=metadata)
+def save_file(
+    tensors: Dict[str, tf.Tensor],
+    filename: str,
+    metadata: Optional[Dict[str, str]] = None,
+):
+    np_tensors = _tf2np(tensors)
+    return numpy.save_file(np_tensors, filename)
 
 
-def load(buffer: bytes) -> Dict[str, tf.DeviceArray]:
+def load(buffer: bytes) -> Dict[str, tf.Tensor]:
     flat = numpy.load(buffer)
-    return np2tf(flat)
+    return _np2tf(flat)
 
 
-def load_file(filename: str) -> Dict[str, tf.DeviceArray]:
+def load_file(filename: str) -> Dict[str, tf.Tensor]:
     flat = numpy.load_file(filename)
-    return np2tf(flat)
-
-def read_metadata_in_file(filename: str) -> Dict[str, str]:
-    return numpy.read_metadata(filename)
\ No newline at end of file
+    return _np2tf(flat)
index 712a4bd337326be06d007ea444abaee27ae7e138..2a5485ddac612e1431d09c53d6149ae7e871ad86 100644 (file)
@@ -1,44 +1,91 @@
-from safetensors import numpy
-from .safetensors_rust import serialize_file, read_metadata
-import numpy as np
+from .safetensors_rust import serialize_file, serialize, safe_open, deserialize
+import math
 from typing import Dict, Optional
+
 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(tensors: Dict[str, torch.Tensor], metadata: Optional[Dict[str, str]] = None) -> bytes:
+    flattened = {
+        k: {"dtype": str(v.dtype).split(".")[-1], "shape": v.shape, "data": _tobytes(v)}
+        for k, v in tensors.items()
+    }
+    serialized = serialize(flattened, metadata=metadata)
+    result = bytes(serialized)
+    return result
 
 
-def pt2np(torch_dict: Dict[str, torch.Tensor]) -> Dict[str, np.array]:
-    for k, v in torch_dict.items():
-        torch_dict[k] = v.numpy()
-    return torch_dict
+def save_file(
+    tensors: Dict[str, torch.Tensor],
+    filename: str,
+    metadata: Optional[Dict[str, str]] = None,
+):
+    flattened = {
+        k: {"dtype": str(v.dtype).split(".")[-1], "shape": v.shape, "data": _tobytes(v)}
+        for k, v in tensors.items()
+    }
+    serialize_file(flattened, filename, metadata=metadata)
 
 
-def save(tensors: Dict[str, torch.Tensor], metadata: Optional[Dict[str, str]] = None) -> bytes:
-    np_tensors = pt2np(tensors)
-    return numpy.save(np_tensors, metadata=metadata)
+def load_file(filename: str) -> Dict[str, torch.Tensor]:
+    result = {}
+    with safe_open(filename, framework="pt") as f:
+        for k in f.keys():
+            result[k] = f.get_tensor(k)
+    return result
 
 
-SIZE = {
+def load(filename: str) -> Dict[str, torch.Tensor]:
+    flat = deserialize(filename)
+    return _view2torch(flat)
+
+
+_SIZE = {
+    torch.int64: 8,
+    torch.float32: 4,
+    torch.int32: 4,
     torch.bfloat16: 2,
     torch.float16: 2,
-    torch.float32: 4,
+    torch.int16: 2,
     torch.uint8: 1,
     torch.int8: 1,
-    torch.int16: 2,
-    torch.int32: 4,
-    torch.int64: 8,
+    torch.bool: 1,
+}
+
+_TYPES = {
+    "F64": torch.float64,
+    "F32": torch.float32,
+    "F16": torch.float16,
+    "I64": torch.int64,
+    # "U64": torch.uint64,
+    "I32": torch.int32,
+    # "U32": torch.uint32,
+    "I16": torch.int16,
+    # "U16": torch.uint16,
+    "I8": torch.int8,
+    "U8": torch.uint8,
+    "BOOL": torch.bool,
 }
 
 
-def tobytes(tensor: torch.Tensor) -> bytes:
+def _getdtype(dtype_str: str) -> torch.dtype:
+    return _TYPES[dtype_str]
+
+
+def _view2torch(safeview) -> Dict[str, torch.Tensor]:
+    result = {}
+    for k, v in safeview:
+        dtype = _getdtype(v["dtype"])
+        arr = torch.frombuffer(v["data"], dtype=dtype).reshape(v["shape"])
+        result[k] = arr
+
+
+def _tobytes(tensor: torch.Tensor) -> bytes:
     import ctypes
+    import numpy as np
 
-    length = np.prod(tensor.shape)
-    bytes_per_item = SIZE[tensor.dtype]
+    length = math.prod(tensor.shape)
+    bytes_per_item = _SIZE[tensor.dtype]
 
     total_bytes = length * bytes_per_item
 
@@ -48,25 +95,3 @@ def tobytes(tensor: torch.Tensor) -> bytes:
     data = np.ctypeslib.as_array(newptr, (total_bytes,))  # no internal copy
 
     return data.tobytes()
-
-
-def save_file(tensors: Dict[str, torch.Tensor], filename: str, metadata: Optional[Dict[str, str]] = None):
-    flattened = {
-        k: {"dtype": str(v.dtype).split(".")[-1], "shape": v.shape, "data": tobytes(v)}
-        for k, v in tensors.items()
-    }
-    serialize_file(flattened, metadata, filename)
-
-
-def load(buffer: bytes) -> Dict[str, torch.Tensor]:
-    flat = numpy.load(buffer)
-    return np2pt(flat)
-
-
-def load_file(filename: str) -> Dict[str, torch.Tensor]:
-    flat = numpy.load_file(filename)
-    return np2pt(flat)
-
-
-def read_metadata_in_file(filename: str) -> Dict[str, str]:
-    return read_metadata(filename)
index 2291d03db6cdaa65248783498ea25823538a43f3..367769cdfb2dc1c73adc6eb18a49a8f8c716b24d 100644 (file)
@@ -1,14 +1,20 @@
 #![deny(missing_docs)]
 //! Dummy doc
-use memmap::MmapOptions;
+use memmap::{Mmap, MmapOptions};
 use pyo3::exceptions;
 use pyo3::prelude::*;
+use pyo3::types::IntoPyDict;
+use pyo3::types::PySlice;
 use pyo3::types::{PyByteArray, PyBytes, PyDict, PyList};
-use safetensors::{Dtype, SafeTensors, Tensor};
+use pyo3::{intern, PyErr};
+use safetensors::slice::TensorIndexer;
+use safetensors::tensor::{Dtype, Metadata, SafeTensors, TensorInfo, TensorView};
 use std::collections::HashMap;
 use std::fs::File;
+use std::ops::Bound;
+use std::sync::Arc;
 
-fn prepare<'a>(tensor_dict: HashMap<String, &'a PyDict>) -> PyResult<HashMap<String, Tensor<'a>>> {
+fn prepare(tensor_dict: HashMap<String, &PyDict>) -> PyResult<HashMap<String, TensorView<'_>>> {
     let mut tensors = HashMap::new();
     for (tensor_name, tensor_desc) in tensor_dict {
         let mut shape: Vec<usize> = vec![];
@@ -44,7 +50,12 @@ fn prepare<'a>(tensor_dict: HashMap<String, &'a PyDict>) -> PyResult<HashMap<Str
             };
         }
 
-        let tensor = Tensor::new(data, dtype, shape);
+        let tensor = TensorView::new(dtype, shape, data).map_err(|e| {
+            exceptions::PyException::new_err(format!(
+                "Error while processing tensor {tensor_name:?} {:?}",
+                e
+            ))
+        })?;
         tensors.insert(tensor_name, tensor);
     }
     Ok(tensors)
@@ -57,19 +68,19 @@ fn serialize<'a, 'b>(
     metadata: Option<HashMap<String, String>>,
 ) -> PyResult<&'b PyBytes> {
     let tensors = prepare(tensor_dict)?;
-    let out = safetensors::serialize(&tensors, &metadata);
+    let out = safetensors::tensor::serialize(&tensors, &metadata);
     let pybytes = PyBytes::new(py, &out);
     Ok(pybytes)
 }
 
 #[pyfunction]
-fn serialize_file<'a>(
-    tensor_dict: HashMap<String, &'a PyDict>,
-    metadata: Option<HashMap<String, String>>,
+fn serialize_file(
+    tensor_dict: HashMap<String, &PyDict>,
     filename: &str,
+    metadata: Option<HashMap<String, String>>,
 ) -> PyResult<()> {
     let tensors = prepare(tensor_dict)?;
-    safetensors::serialize_to_file(&tensors, &metadata, filename)?;
+    safetensors::tensor::serialize_to_file(&tensors, &metadata, filename)?;
     Ok(())
 }
 
@@ -83,7 +94,7 @@ fn deserialize(py: Python, bytes: &[u8]) -> PyResult<Vec<(String, HashMap<String
     for (tensor_name, tensor) in safetensor.tensors() {
         let mut map = HashMap::new();
 
-        let pyshape: PyObject = PyList::new(py, tensor.get_shape().into_iter()).into();
+        let pyshape: PyObject = PyList::new(py, tensor.get_shape().iter()).into();
         let pydtype: PyObject = format!("{:?}", tensor.get_dtype()).into_py(py);
 
         let pydata: PyObject = PyByteArray::new(py, tensor.get_data()).into();
@@ -96,36 +107,246 @@ fn deserialize(py: Python, bytes: &[u8]) -> PyResult<Vec<(String, HashMap<String
     Ok(items)
 }
 
-#[pyfunction]
-fn deserialize_file(
-    py: Python,
-    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)? };
-    let deserialized = deserialize(py, &mmap);
-    // Make sure mmap does not leak.
-    drop(mmap);
-    deserialized
+fn slice_to_indexer(slice: &PySlice) -> Result<TensorIndexer, PyErr> {
+    let py_start = slice.getattr(intern!(slice.py(), "start"))?;
+    let start: Option<usize> = py_start.extract()?;
+    let start = if let Some(start) = start {
+        Bound::Included(start)
+    } else {
+        Bound::Unbounded
+    };
+
+    let py_stop = slice.getattr(intern!(slice.py(), "stop"))?;
+    let stop: Option<usize> = py_stop.extract()?;
+    let stop = if let Some(stop) = stop {
+        Bound::Excluded(stop)
+    } else {
+        Bound::Unbounded
+    };
+
+    Ok(TensorIndexer::Narrow(start, stop))
 }
 
-#[pyfunction]
-fn read_metadata(filename: &str) -> PyResult<Option<HashMap<String, String>>> {
-    let file = File::open(filename)?;
+#[derive(Debug, Clone)]
+enum Framework {
+    Pytorch,
+    Numpy,
+    Tensorflow,
+    Jax,
+}
 
-    // SAFETY: Mmap is used to prevent allocating in Rust
-    // before making a copy within Python.
-    let mmap = unsafe { MmapOptions::new().map(&file)? };
-    let safetensor = SafeTensors::deserialize(&mmap).map_err(|e| {
-        exceptions::PyException::new_err(format!("Error while deserializing: {:?}", e))
-    })?;
-    let metadata = safetensor.get_metadata();
-    // Make sure mmap does not leak.
-    drop(mmap);
-    Ok(metadata)
+impl<'source> FromPyObject<'source> for Framework {
+    fn extract(ob: &'source PyAny) -> PyResult<Self> {
+        let name: String = ob.extract()?;
+        match &name[..] {
+            "pt" => Ok(Framework::Pytorch),
+            "np" => Ok(Framework::Numpy),
+            "tf" => Ok(Framework::Tensorflow),
+            "jax" => Ok(Framework::Jax),
+            name => Err(exceptions::PyException::new_err(format!(
+                "framework {name} is invalid"
+            ))),
+        }
+    }
+}
+
+#[pyclass]
+#[allow(non_camel_case_types)]
+struct safe_open {
+    metadata: Metadata,
+    offset: usize,
+    framework: Framework,
+    mmap: Arc<Mmap>,
+}
+
+#[pymethods]
+impl safe_open {
+    #[new]
+    fn new(filename: &str, framework: Framework) -> PyResult<Self> {
+        let file = File::open(filename)?;
+
+        // SAFETY: Mmap is used to prevent allocating in Rust
+        // before making a copy within Python.
+        let buffer = unsafe { MmapOptions::new().map(&file)? };
+
+        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(|e| {
+            exceptions::PyException::new_err(format!("Error while deserializing header: {:?}", e))
+        })?;
+        let metadata: Metadata = serde_json::from_str(string).map_err(|e| {
+            exceptions::PyException::new_err(format!("Error while deserializing metadata: {:?}", e))
+        })?;
+
+        let offset = n + 8;
+
+        Ok(Self {
+            metadata,
+            offset,
+            framework,
+            mmap: Arc::new(buffer),
+        })
+    }
+
+    pub fn metadata(&self) -> Option<HashMap<String, String>> {
+        self.metadata.metadata().clone()
+    }
+
+    pub fn keys(&self) -> PyResult<Vec<String>> {
+        let mut keys: Vec<_> = self.metadata.tensors().keys().cloned().collect();
+        keys.sort();
+        Ok(keys)
+    }
+
+    pub fn get_tensor(&self, py: Python, name: &str) -> PyResult<PyObject> {
+        if let Some(info) = self.metadata.tensors().get(name) {
+            let data =
+                &self.mmap[info.data_offsets.0 + self.offset..info.data_offsets.1 + self.offset];
+
+            let tensor = TensorView::new(info.dtype, info.shape.clone(), data).map_err(|e| {
+                exceptions::PyException::new_err(format!("Error when creating TensorView {:?}", e))
+            })?;
+            let array: PyObject = PyByteArray::new(py, tensor.get_data()).into_py(py);
+
+            create_tensor(py, &self.framework, info.dtype, &info.shape, array)
+        } else {
+            Err(exceptions::PyException::new_err(format!(
+                "File does not contain tensor {name}",
+            )))
+        }
+    }
+
+    pub fn get_slice(&self, name: &str) -> PyResult<PySafeSlice> {
+        if let Some(info) = self.metadata.tensors().get(name) {
+            Ok(PySafeSlice {
+                info: info.clone(),
+                framework: self.framework.clone(),
+                offset: self.offset,
+                mmap: self.mmap.clone(),
+            })
+        } else {
+            Err(exceptions::PyException::new_err(format!(
+                "File does not contain tensor {name}",
+            )))
+        }
+    }
+
+    pub fn __enter__(slf: Py<Self>) -> Py<Self> {
+        slf
+    }
+
+    pub fn __exit__(&mut self, _exc_type: PyObject, _exc_value: PyObject, _traceback: PyObject) {}
+}
+
+#[pyclass]
+struct PySafeSlice {
+    info: TensorInfo,
+    framework: Framework,
+    offset: usize,
+    mmap: Arc<Mmap>,
+}
+
+#[derive(FromPyObject)]
+enum Slice<'a> {
+    // Index(usize),
+    Slice(&'a PySlice),
+    Slices(Vec<&'a PySlice>),
+}
+
+#[pymethods]
+impl PySafeSlice {
+    pub fn get_shape(&self, py: Python) -> PyResult<PyObject> {
+        let shape = self.info.shape.clone();
+        let shape: PyObject = shape.into_py(py);
+        Ok(shape)
+    }
+    pub fn __getitem__(&self, py: Python, slices: Slice) -> PyResult<PyObject> {
+        let slices: Vec<&PySlice> = match slices {
+            Slice::Slice(slice) => vec![slice],
+            Slice::Slices(slices) => slices,
+        };
+        let data = &self.mmap
+            [self.info.data_offsets.0 + self.offset..self.info.data_offsets.1 + self.offset];
+
+        let tensor =
+            TensorView::new(self.info.dtype, self.info.shape.clone(), data).map_err(|e| {
+                exceptions::PyException::new_err(format!("Error when creating TensorView {:?}", e))
+            })?;
+        let slices: Vec<TensorIndexer> = slices
+            .into_iter()
+            .map(slice_to_indexer)
+            .collect::<Result<_, _>>()?;
+        let iterator = tensor.get_sliced_data(slices.clone()).map_err(|e| {
+            exceptions::PyException::new_err(format!(
+                "Error during slicing {slices:?} vs {:?}:  {:?}",
+                self.info.shape, e
+            ))
+        })?;
+        let newshape = iterator.newshape();
+
+        let mut offset = 0;
+        let length = iterator.remaining_byte_len();
+        let array: PyObject = PyByteArray::new_with(py, length, |bytes: &mut [u8]| {
+            for slice in iterator {
+                let len = slice.len();
+                bytes[offset..offset + slice.len()].copy_from_slice(slice);
+                offset += len;
+            }
+            Ok(())
+        })?
+        .into_py(py);
+        create_tensor(py, &self.framework, self.info.dtype, &newshape, array)
+    }
+}
+
+fn create_tensor(
+    py: Python,
+    framework: &Framework,
+    dtype: Dtype,
+    shape: &[usize],
+    array: PyObject,
+) -> PyResult<PyObject> {
+    match framework {
+        Framework::Pytorch | Framework::Numpy => {
+            let module_name = match framework {
+                Framework::Numpy => "numpy",
+                Framework::Pytorch => "torch",
+                _ => unreachable!(),
+            };
+            let module = PyModule::import(py, module_name)?;
+            let frombuffer = module.getattr("frombuffer")?;
+            let dtype: PyObject = get_pydtype(module, dtype)?;
+            let kwargs = [("buffer", array), ("dtype", dtype)].into_py_dict(py);
+            let tensor = frombuffer.call((), Some(kwargs))?;
+            let shape = shape.to_vec();
+            let shape: PyObject = shape.into_py(py);
+            let tensor: PyObject = tensor.getattr("reshape")?.call1((shape,))?.into();
+            Ok(tensor)
+        }
+        framework => todo!("{framework:?}"),
+    }
+}
+
+fn get_pydtype(module: &PyModule, dtype: Dtype) -> PyResult<PyObject> {
+    let dtype: PyObject = match dtype {
+        Dtype::F64 => module.getattr("float64")?.into(),
+        Dtype::F32 => module.getattr("float32")?.into(),
+        Dtype::BF16 => module.getattr("bfloat16")?.into(),
+        Dtype::F16 => module.getattr("float16")?.into(),
+        Dtype::U64 => module.getattr("uint64")?.into(),
+        Dtype::I64 => module.getattr("int64")?.into(),
+        Dtype::U32 => module.getattr("uint32")?.into(),
+        Dtype::I32 => module.getattr("int32")?.into(),
+        Dtype::U16 => module.getattr("uint16")?.into(),
+        Dtype::I16 => module.getattr("int16")?.into(),
+        Dtype::U8 => module.getattr("uint8")?.into(),
+        Dtype::I8 => module.getattr("int8")?.into(),
+        Dtype::BOOL => module.getattr("bool")?.into(),
+        dtype => todo!("Dtype {dtype:?}"),
+    };
+    Ok(dtype)
 }
 
 /// A Python module implemented in Rust.
@@ -134,7 +355,6 @@ 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)?)?;
-    m.add_function(wrap_pyfunction!(read_metadata, m)?)?;
+    m.add_class::<safe_open>()?;
     Ok(())
 }
index a37570a563c3a6cfe66af9b5f776d50a3cfc3575..4329bbca603634e073ade249c4d1fe7acd7eb600 100644 (file)
@@ -1,11 +1,16 @@
 import unittest
-from safetensors.flax import save_file, load_file
 from huggingface_hub import hf_hub_download
-from flax.serialization import msgpack_restore, msgpack_serialize
 import numpy as np
-import jax.numpy as jnp
 import datetime
 import os
+import platform
+
+if platform.system() != "Windows":
+    # This platform is not supported, we don't want to crash on import
+    # This test will be skipped anyway.
+    from safetensors.flax import save_file, load_file
+    from flax.serialization import msgpack_restore, msgpack_serialize
+    import jax.numpy as jnp
 
 MODEL_ID = os.getenv("MODEL_ID", "gpt2")
 
@@ -24,6 +29,8 @@ def load(nested_np_dicts):
     return tensors
 
 
+# Jax doesn't not exist on Windows
+@unittest.skipIf(platform.system() == "Windows", "Jax is not available on Windows")
 class SafeTestCase(unittest.TestCase):
     def setUp(self):
         self.filename = hf_hub_download(MODEL_ID, filename="flax_model.msgpack")
@@ -34,38 +41,37 @@ class SafeTestCase(unittest.TestCase):
         save_file(self.data, self.local)
 
     def test_deserialization_safe(self):
-        start = datetime.datetime.now()
         load_file(self.local)
-        print()
-        print("Deserialization (Safe) took ", datetime.datetime.now() - start)
 
-    def test_serialization_safe(self):
         start = datetime.datetime.now()
-        outfilename = "./tests/data/out_safe.bin"
-        save_file(self.data, outfilename)
-        print()
-        print("Serialization (safe) took ", datetime.datetime.now() - start)
-
+        load_file(self.local)
+        safe_time = datetime.datetime.now() - start
 
-class FlaxTestCase(unittest.TestCase):
-    def setUp(self):
-        self.filename = hf_hub_download(MODEL_ID, filename="flax_model.msgpack")
         with open(self.filename, "rb") as f:
             data = f.read()
-        self.data = msgpack_restore(data)
 
-    def test_deserialization_flax(self):
         start = datetime.datetime.now()
         with open(self.filename, "rb") as f:
             data = f.read()
         msgpack_restore(data)
+        flax_time = datetime.datetime.now() - start
+
         print()
-        print("Deserialization (flax) took ", datetime.datetime.now() - start)
+        print(f"Deserialization (Safe) took {safe_time}")
+        print(f"Deserialization (flax) took {flax_time} (Safe is {flax_time/safe_time} faster)")
 
-    def test_serialization_flax(self):
+    def test_serialization_safe(self):
+        outfilename = "./tests/data/out_safe.bin"
+        save_file(self.data, outfilename)
+        start = datetime.datetime.now()
+        save_file(self.data, outfilename)
+        safe_time = datetime.datetime.now() - start
         start = datetime.datetime.now()
         serialized = msgpack_serialize(self.data)
         with open("./tests/data/out_flax.msgpack", "wb") as f:
             f.write(serialized)
+        flax_time = datetime.datetime.now() - start
         print()
+        print(f"Serialization (safe) took {safe_time}")
         print("Serialization (flax) took ", datetime.datetime.now() - start)
+        print(f"Deserialization (flax) took {flax_time} (Safe is {flax_time/safe_time} faster)")
index 71e1ae0ecbd71bd6c97dc7ad1e0834d5ff555a85..e3c7f1eae55d2730b424fd5eb7819c18e14b1c20 100644 (file)
@@ -1,5 +1,6 @@
 import unittest
-from safetensors.torch import save_file, load_file, load
+from safetensors.torch import save_file, load_file
+from safetensors.safetensors_rust import safe_open
 from huggingface_hub import hf_hub_download
 import torch
 import datetime
@@ -9,42 +10,92 @@ import os
 MODEL_ID = os.getenv("MODEL_ID", "gpt2")
 
 
-class SafeTestCase(unittest.TestCase):
+class TorchTestCase(unittest.TestCase):
+    def test_odd_dtype(self):
+        data = {
+            "test": torch.zeros((2, 2), dtype=torch.bfloat16),
+            "test2": torch.zeros((2, 2), dtype=torch.float16),
+            "test3": torch.zeros((2, 2), dtype=torch.bool),
+        }
+        local = "./tests/data/out_safe_pt_mmap.bin"
+        save_file(data, local)
+        reloaded = load_file(local)
+        self.assertTrue(torch.equal(data["test"], reloaded["test"]))
+        self.assertTrue(torch.equal(data["test2"], reloaded["test2"]))
+        self.assertTrue(torch.equal(data["test3"], reloaded["test3"]))
+
+
+class SpeedTestCase(unittest.TestCase):
     def setUp(self):
         self.filename = hf_hub_download(MODEL_ID, filename="pytorch_model.bin")
         self.data = torch.load(self.filename, map_location="cpu")
-        print("PT keys", len(self.data.keys()))
         self.local = "./tests/data/out_safe_pt_mmap.bin"
         # Need to copy since that call mutates the tensors to numpy
         save_file(self.data.copy(), self.local)
 
     def test_deserialization_safe(self):
         start = datetime.datetime.now()
+        # First time to hit disk
         load_file(self.local)
+        # Second time we should be in disk cache
+        start = datetime.datetime.now()
+        load_file(self.local)
+        safe_time = datetime.datetime.now() - start
+        torch.load(self.filename)
+        start = datetime.datetime.now()
+        torch.load(self.filename)
+        pt_time = datetime.datetime.now() - start
         print()
-        print("Deserialization (Safe) took ", datetime.datetime.now() - start)
+        print(f"Deserialization (Safe) took {safe_time}")
+        print(f"Deserialization (PT) took {pt_time} (Safe is {pt_time/safe_time} faster)")
 
     def test_serialization_safe(self):
         start = datetime.datetime.now()
         outfilename = "./tests/data/out_safe.bin"
         save_file(self.data, outfilename)
+        safe_time = datetime.datetime.now() - start
+
+        start = datetime.datetime.now()
+        with open("./tests/data/out_pt.bin", "wb") as f:
+            torch.save(self.data, f)
+        pt_time = datetime.datetime.now() - start
+
         print()
-        print("Serialization (safe) took ", datetime.datetime.now() - start)
+        print(f"Serialization (safe) took {safe_time}")
+        print(f"Serialization (PT) took {pt_time} (Safe is {pt_time/safe_time} faster)")
 
 
-class TorchTestCase(unittest.TestCase):
+class SliceTestCase(unittest.TestCase):
     def setUp(self):
-        self.filename = hf_hub_download(MODEL_ID, filename="pytorch_model.bin")
-        self.data = torch.load(self.filename)
+        self.tensor = torch.arange(6, dtype=torch.float32).reshape((1, 2, 3))
+        self.data = {"test": self.tensor}
+        self.local = "./tests/data/out_safe_pt_mmap.bin"
+        # Need to copy since that call mutates the tensors to numpy
+        save_file(self.data.copy(), self.local)
 
-    def test_deserialization(self):
-        start = datetime.datetime.now()
-        torch.load(self.filename)
-        print()
-        print("Deserialization (PT) took ", datetime.datetime.now() - start)
+    def test_deserialization_slice(self):
+        with safe_open(self.local, framework="pt") as f:
+            tensor = f.get_slice("test")[:, :, 1:2]
 
-    def test_serialization(self):
-        start = datetime.datetime.now()
-        with open("./tests/data/out_pt.bin", "wb") as f:
-            torch.save(self.data, f)
-        print("Serialization (PT) took ", datetime.datetime.now() - start)
+        self.assertEqual(
+            tensor.numpy().tobytes(),
+            b"\x00\x00\x80?\x00\x00\x80@",
+        )
+
+        self.assertTrue(torch.equal(tensor, torch.Tensor([[[1.0], [4.0]]])))
+        self.assertTrue(torch.equal(tensor, self.tensor[:, :, 1:2]))
+
+    def test_deserialization_metadata(self):
+        with safe_open(self.local, framework="pt") as f:
+            metadata = f.metadata()
+        self.assertEqual(metadata, None)
+
+        # Save another one *with* metadata
+        tensor = torch.arange(6, dtype=torch.float32).reshape((1, 2, 3))
+        data = {"test": tensor}
+        local = "./tests/data/out_safe_pt_mmap2.bin"
+        # Need to copy since that call mutates the tensors to numpy
+        save_file(data, local, metadata={"Something": "more"})
+        with safe_open(local, framework="pt") as f:
+            metadata = f.metadata()
+        self.assertEqual(metadata, {"Something": "more"})
index a44f8f98ae50d9c25cdad47883fd9bb4fc0650bc..abd6b6bf3412ab7d31004f49139c974de9a73f9e 100644 (file)
@@ -2,9 +2,7 @@ import unittest
 from safetensors.numpy import save, load, save_file, load_file
 from safetensors.torch import load_file as load_file_pt, save_file as save_file_pt
 import numpy as np
-from huggingface_hub import hf_hub_download
 import torch
-import datetime
 
 
 class TestCase(unittest.TestCase):
@@ -51,8 +49,6 @@ class ReadmeTestCase(unittest.TestCase):
         loaded = load_file("./out.bin")
         self.assertTensorEqual(tensors, loaded, np.allclose)
 
-        metadata = 
-
     def test_torch_example(self):
         tensors = {
             "a": torch.zeros((2, 2)),
index b5f7e178b6fa758369aee80452b1e11594cc6ae4..6d9fbb91e731c4fec73bfaedea5f9796f8a346e9 100644 (file)
@@ -1,10 +1,11 @@
 import unittest
-from safetensors.flax import save_file, load_file
+from safetensors.tensorflow import save_file, load_file
 from huggingface_hub import hf_hub_download
 import datetime
 import h5py
 import numpy as np
 import os
+import tensorflow as tf
 
 MODEL_ID = os.getenv("MODEL_ID", "gpt2")
 
@@ -12,7 +13,7 @@ MODEL_ID = os.getenv("MODEL_ID", "gpt2")
 def _load(f, tensors, prefix=""):
     for k in f.keys():
         if isinstance(f[k], h5py._hl.dataset.Dataset):
-            tensors[f"{prefix}_{k}"] = np.array(f[k])
+            tensors[f"{prefix}_{k}"] = tf.convert_to_tensor(np.array(f[k]))
         else:
             tensors.update(_load(f[k], tensors, prefix=f"{prefix}_{k}"))
     return tensors
@@ -20,6 +21,7 @@ def _load(f, tensors, prefix=""):
 
 def _save(f, tensors, prefix=""):
     for name, tensor in tensors.items():
+        tensor = tensor.numpy()
         dset = f.create_dataset(name, tensor.shape, dtype=tensor.dtype)
         dset[:] = tensor
 
@@ -31,44 +33,49 @@ class SafeTestCase(unittest.TestCase):
         with h5py.File(self.filename, "r") as f:
             self.data = _load(f, tensors)
 
-        print("TF keys", len(self.data.keys()))
+        # Weird copies are necessary because apparently calling
+        # tf.Tensor(..).numpy() converts inplace destroying the actual
+        # tf.Tensor.
+        data = self.data.copy()
         self.local = "./tests/data/out_safe_tf_mmap.h5"
-        save_file(self.data, self.local)
+        save_file(data, self.local)
 
     def test_deserialization_safe(self):
-        start = datetime.datetime.now()
         load_file(self.local)
-        print()
-        print("Deserialization (Safe) took ", datetime.datetime.now() - start)
 
-    def test_serialization_safe(self):
         start = datetime.datetime.now()
-        outfilename = "./tests/data/out_safe.bin"
-        save_file(self.data, outfilename)
-        print()
-        print("Serialization (Safe) took ", datetime.datetime.now() - start)
-
+        load_file(self.local)
+        safe_time = datetime.datetime.now() - start
 
-class TFTestCase(unittest.TestCase):
-    def setUp(self):
-        self.filename = hf_hub_download(MODEL_ID, filename="tf_model.h5")
         tensors = {}
         with h5py.File(self.filename, "r") as f:
             self.data = _load(f, tensors)
-        self.local = "./tests/data/out_safe_tf_mmap.bin"
-        save_file(self.data, self.local)
 
-    def test_deserialization_tf(self):
         start = datetime.datetime.now()
         tensors = {}
         with h5py.File(self.filename, "r") as f:
             self.data = _load(f, tensors)
+        tf_time = datetime.datetime.now() - start
         print()
-        print("Deserialization (TF) took ", datetime.datetime.now() - start)
+        print(f"Deserialization (Safe) took {safe_time}")
+        print(f"Deserialization (TF) took {tf_time} (Safe is {tf_time/safe_time} faster)")
+
+    def test_serialization_safe(self):
+        outfilename = "./tests/data/out_safe.bin"
+        data = self.data.copy()
+        save_file(data, outfilename)
 
-    def test_serialization_tf(self):
+        data = self.data.copy()
+        start = datetime.datetime.now()
+        save_file(data, outfilename)
+        safe_time = datetime.datetime.now() - start
+
+        data = self.data.copy()
         start = datetime.datetime.now()
         with h5py.File("./tests/data/out_tf_tf.h5", "w") as f:
-            _save(f, self.data)
+            _save(f, data)
+        tf_time = datetime.datetime.now() - start
+
         print()
-        print("Serialization (TF) took ", datetime.datetime.now() - start)
+        print(f"Serialization (Safe) took {safe_time}")
+        print(f"Serialization (TF) took {tf_time} (Safe is {tf_time/safe_time} faster)")
index b79e17f10113a4fddb7b8e9a588864e2ed840e4c..ae08b3ddef5cc673194f89f1aaf21da4b6c0e6e4 100644 (file)
 //!- Order: 'C' or row-major. This seems to have won. We can add that information later if needed.
 //!- Stride: No striding, all tensors need to be packed before being serialized. I have yet to see a case where it seems useful to have a strided tensor stored in serialized format
 //!
-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,
-    /// The tensor name was not found in the archive
-    TensorNotFound,
-}
-
-fn prepare<'hash, 'data>(
-    data: &'hash HashMap<String, Tensor<'data>>,
-    data_info: &'hash Option<HashMap<String, String>>,
-) -> (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::new(data_info.clone(), hmetadata);
-
-    (metadata, tensors, offset)
-}
-
-/// Serialize to an owned byte buffer the dictionnary of tensors.
-pub fn serialize(
-    data: &HashMap<String, Tensor>,
-    data_info: &Option<HashMap<String, String>>,
-) -> Vec<u8> {
-    let (metadata, tensors, offset) = prepare(data, data_info);
-    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
-}
-
-/// 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>,
-    data_info: &Option<HashMap<String, String>>,
-    filename: &str,
-) -> Result<(), std::io::Error> {
-    let (metadata, tensors, _) = prepare(data, data_info);
-    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().as_ref())?;
-    f.write_all(&metadata_buf)?;
-    for tensor in tensors {
-        f.write_all(tensor.data)?;
-    }
-    f.flush()?;
-    Ok(())
-}
-
-/// 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> 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 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::InvalidHeaderDeserialization)?;
-        Ok(Self {
-            metadata,
-            offset: n + 8,
-            data: buffer,
-        })
-    }
-
-    /// 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.tensors {
-            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
-    }
-
-    /// Allow the user to get a specific tensor within the SafeTensors.
-    /// The tensor returned is merely a view and the data is not owned by this
-    /// structure.
-    pub fn tensor(&self, tensor_name: &str) -> Result<TensorView<'_>, SafeTensorError> {
-        for (name, info) in &self.metadata.tensors {
-            if name == tensor_name {
-                return Ok(TensorView {
-                    dtype: &info.dtype,
-                    shape: &info.shape,
-                    data: &self.data
-                        [info.data_offsets.0 + self.offset..info.data_offsets.1 + self.offset],
-                });
-            }
-        }
-        Err(SafeTensorError::TensorNotFound)
-    }
-
-    /// Allow the user to get a specific tensor within the SafeTensors.
-    /// The tensor returned is merely a view and the data is not owned by this
-    /// structure.
-    pub fn names(&self) -> Vec<&'_ String> {
-        self.metadata.tensors.iter().map(|(name, _)| name).collect()
-    }
-
-    /// Returns additional metadata passed along by the user.
-    pub fn get_metadata(&self) -> Option<HashMap<String, String>> {
-        self.metadata.metadata.clone()
-    }
-}
-
-/// 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)]
-pub struct Metadata {
-    #[serde(skip_serializing_if = "Option::is_none")]
-    #[serde(rename = "__metadata__")]
-    metadata: Option<HashMap<String, String>>,
-    #[serde(flatten)]
-    tensors: HashMap<String, TensorInfo>,
-}
-
-impl Metadata {
-    fn new(
-        metadata: Option<HashMap<String, String>>,
-        tensors: HashMap<String, TensorInfo>,
-    ) -> Self {
-        Self { metadata, tensors }
-    }
-
-    /// Gives back the tensor metadata
-    pub fn tensors(&self) -> &HashMap<String, TensorInfo> {
-        &self.tensors
-    }
-
-    /// Gives back the metadata
-    pub fn metadata(&self) -> &Option<HashMap<String, String>> {
-        &self.metadata
-    }
-}
-
-/// 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> {
-    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)]
-pub 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,
-}
-
-/// 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: &'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 }
-    }
-}
-
-#[cfg(test)]
-mod tests {
-    use super::*;
-
-    #[test]
-    fn test_serialization() {
-        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: &data,
-        };
-        let metadata: HashMap<String, Tensor> =
-            [("attn.0".to_string(), attn_0)].into_iter().collect();
-
-        let out = serialize(&metadata, &None);
-        let _parsed = SafeTensors::deserialize(&out).unwrap();
-    }
-
-    #[test]
-    fn test_gpt2() {
-        gpt2_like(12, "gpt2");
-    }
-
-    #[test]
-    fn test_gpt2_medium() {
-        gpt2_like(24, "gpt2_medium");
-    }
-
-    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_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_desc.push(("ln_f.weight".to_string(), vec![768]));
-        tensors_desc.push(("ln_f.bias".to_string(), vec![768]));
-
-        let data_info: HashMap<String, String> =
-            HashMap::from([("framework".to_string(), "pt".to_string())]);
-
-        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);
-
-        let out = serialize(&metadata, &Some(data_info));
-
-        std::fs::write(&filename, out).unwrap();
-
-        let raw = std::fs::read(&filename).unwrap();
-        let _deserialized = SafeTensors::deserialize(&raw).unwrap();
-    }
-}
+pub mod slice;
+pub mod tensor;
diff --git a/safetensors/src/slice.rs b/safetensors/src/slice.rs
new file mode 100644 (file)
index 0000000..bd75fdd
--- /dev/null
@@ -0,0 +1,505 @@
+//! Module handling lazy loading via iterating on slices on the original buffer.
+use crate::tensor::TensorView;
+use std::ops::{
+    Bound, Range, RangeBounds, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive,
+};
+
+/// Error representing invalid slicing attempt
+#[derive(Debug)]
+pub enum InvalidSlice {
+    /// When the client asked for more slices than the tensors has dimensions
+    TooManySlices,
+}
+
+#[derive(Debug, Clone)]
+/// Generic structure used to index a slice of the tensor
+pub enum TensorIndexer {
+    //Select(usize),
+    /// This is a regular slice, purely indexing a chunk of the tensor
+    Narrow(Bound<usize>, Bound<usize>),
+    //IndexSelect(Tensor),
+}
+
+// impl From<usize> for TensorIndexer {
+//     fn from(index: usize) -> Self {
+//         TensorIndexer::Select(index)
+//     }
+// }
+
+// impl From<&[usize]> for TensorIndexer {
+//     fn from(index: &[usize]) -> Self {
+//         let tensor = index.into();
+//         TensorIndexer::IndexSelect(tensor)
+//     }
+// }
+//
+// impl From<Vec<usize>> for TensorIndexer {
+//     fn from(index: Vec<usize>) -> Self {
+//         let tensor = Tensor::of_slice(&index);
+//         TensorIndexer::IndexSelect(tensor)
+//     }
+// }
+
+macro_rules! impl_from_range {
+    ($range_type:ty) => {
+        impl From<$range_type> for TensorIndexer {
+            fn from(range: $range_type) -> Self {
+                use std::ops::Bound::*;
+
+                let start = match range.start_bound() {
+                    Included(idx) => Included(*idx),
+                    Excluded(idx) => Excluded(*idx),
+                    Unbounded => Unbounded,
+                };
+
+                let end = match range.end_bound() {
+                    Included(idx) => Included(*idx),
+                    Excluded(idx) => Excluded(*idx),
+                    Unbounded => Unbounded,
+                };
+
+                TensorIndexer::Narrow(start, end)
+            }
+        }
+    };
+}
+
+impl_from_range!(Range<usize>);
+impl_from_range!(RangeFrom<usize>);
+impl_from_range!(RangeFull);
+impl_from_range!(RangeInclusive<usize>);
+impl_from_range!(RangeTo<usize>);
+impl_from_range!(RangeToInclusive<usize>);
+
+/// Trait used to implement multiple signatures for ease of use of the slicing
+/// of a tensor
+pub trait IndexOp<'data, T> {
+    /// Returns a slicing iterator which are the chunks of data necessary to
+    /// reconstruct the desired tensor.
+    fn slice(&'data self, index: T) -> Result<SliceIterator<'data>, InvalidSlice>;
+}
+
+impl<'data, A> IndexOp<'data, A> for TensorView<'data>
+where
+    A: Into<TensorIndexer>,
+{
+    fn slice(&'data self, index: A) -> Result<SliceIterator<'data>, InvalidSlice> {
+        self.get_sliced_data(vec![index.into()])
+    }
+}
+
+impl<'data, A> IndexOp<'data, (A,)> for TensorView<'data>
+where
+    A: Into<TensorIndexer>,
+{
+    fn slice(&'data self, index: (A,)) -> Result<SliceIterator<'data>, InvalidSlice> {
+        let idx_a = index.0.into();
+        self.get_sliced_data(vec![idx_a])
+    }
+}
+
+impl<'data, A, B> IndexOp<'data, (A, B)> for TensorView<'data>
+where
+    A: Into<TensorIndexer>,
+    B: Into<TensorIndexer>,
+{
+    fn slice(&'data self, index: (A, B)) -> Result<SliceIterator<'data>, InvalidSlice> {
+        let idx_a = index.0.into();
+        let idx_b = index.1.into();
+        self.get_sliced_data(vec![idx_a, idx_b])
+    }
+}
+
+impl<'data, A, B, C> IndexOp<'data, (A, B, C)> for TensorView<'data>
+where
+    A: Into<TensorIndexer>,
+    B: Into<TensorIndexer>,
+    C: Into<TensorIndexer>,
+{
+    fn slice(&'data self, index: (A, B, C)) -> Result<SliceIterator<'data>, InvalidSlice> {
+        let idx_a = index.0.into();
+        let idx_b = index.1.into();
+        let idx_c = index.2.into();
+        self.get_sliced_data(vec![idx_a, idx_b, idx_c])
+    }
+}
+
+// impl<A, B, C, D> IndexOp<(A, B, C, D)> for TensorView<'data>
+// where
+//     A: Into<TensorIndexer>,
+//     B: Into<TensorIndexer>,
+//     C: Into<TensorIndexer>,
+//     D: Into<TensorIndexer>,
+// {
+//     fn slice(&self, index: (A, B, C, D)) -> TensorView<'data> {
+//         let idx_a = index.0.into();
+//         let idx_b = index.1.into();
+//         let idx_c = index.2.into();
+//         let idx_d = index.3.into();
+//         self.get_sliced_data(&[idx_a, idx_b, idx_c, idx_d])
+//     }
+// }
+//
+// impl<A, B, C, D, E> IndexOp<(A, B, C, D, E)> for TensorView<'data>
+// where
+//     A: Into<TensorIndexer>,
+//     B: Into<TensorIndexer>,
+//     C: Into<TensorIndexer>,
+//     D: Into<TensorIndexer>,
+//     E: Into<TensorIndexer>,
+// {
+//     fn slice(&self, index: (A, B, C, D, E)) -> TensorView<'data> {
+//         let idx_a = index.0.into();
+//         let idx_b = index.1.into();
+//         let idx_c = index.2.into();
+//         let idx_d = index.3.into();
+//         let idx_e = index.4.into();
+//         self.get_sliced_data(&[idx_a, idx_b, idx_c, idx_d, idx_e])
+//     }
+// }
+//
+// impl<A, B, C, D, E, F> IndexOp<(A, B, C, D, E, F)> for TensorView<'data>
+// where
+//     A: Into<TensorIndexer>,
+//     B: Into<TensorIndexer>,
+//     C: Into<TensorIndexer>,
+//     D: Into<TensorIndexer>,
+//     E: Into<TensorIndexer>,
+//     F: Into<TensorIndexer>,
+// {
+//     fn slice(&self, index: (A, B, C, D, E, F)) -> TensorView<'data> {
+//         let idx_a = index.0.into();
+//         let idx_b = index.1.into();
+//         let idx_c = index.2.into();
+//         let idx_d = index.3.into();
+//         let idx_e = index.4.into();
+//         let idx_f = index.5.into();
+//         self.get_sliced_data(&[idx_a, idx_b, idx_c, idx_d, idx_e, idx_f])
+//     }
+// }
+//
+// impl<A, B, C, D, E, F, G> IndexOp<(A, B, C, D, E, F, G)> for TensorView<'data>
+// where
+//     A: Into<TensorIndexer>,
+//     B: Into<TensorIndexer>,
+//     C: Into<TensorIndexer>,
+//     D: Into<TensorIndexer>,
+//     E: Into<TensorIndexer>,
+//     F: Into<TensorIndexer>,
+//     G: Into<TensorIndexer>,
+// {
+//     fn slice(&self, index: (A, B, C, D, E, F, G)) -> TensorView<'data> {
+//         let idx_a = index.0.into();
+//         let idx_b = index.1.into();
+//         let idx_c = index.2.into();
+//         let idx_d = index.3.into();
+//         let idx_e = index.4.into();
+//         let idx_f = index.5.into();
+//         let idx_g = index.6.into();
+//         self.get_sliced_data(&[idx_a, idx_b, idx_c, idx_d, idx_e, idx_f, idx_g])
+//     }
+// }
+
+/// Iterator used to return the bits of the overall tensor buffer
+/// when client asks for a slice of the original tensor.
+pub struct SliceIterator<'data> {
+    view: &'data TensorView<'data>,
+    indices: Vec<(usize, usize)>,
+    newshape: Vec<usize>,
+}
+
+impl<'data> SliceIterator<'data> {
+    pub(crate) fn new(
+        view: &'data TensorView<'data>,
+        slices: Vec<TensorIndexer>,
+    ) -> Result<Self, InvalidSlice> {
+        // Make sure n. axis does not exceed n. of dimensions
+        let n_slice = slices.len();
+        let n_shape = view.shape.len();
+        if n_slice > n_shape {
+            return Err(InvalidSlice::TooManySlices);
+        }
+        let mut newshape = Vec::with_capacity(view.shape.len());
+
+        // Minimum span is the span of 1 item;
+        let mut span = view.dtype.size();
+        let mut indices = vec![];
+        // Everything is row major.
+        for (i, &shape) in view.shape.iter().enumerate().rev() {
+            if i >= slices.len() {
+                // We are  not slicing yet, just increase the local span
+                newshape.push(shape);
+            } else {
+                let slice = &slices[i];
+                let (start, stop) = match slice {
+                    TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded) => (0, shape),
+                    TensorIndexer::Narrow(Bound::Unbounded, Bound::Excluded(stop)) => (0, *stop),
+                    TensorIndexer::Narrow(Bound::Unbounded, Bound::Included(stop)) => {
+                        (0, *stop + 1)
+                    }
+                    TensorIndexer::Narrow(Bound::Included(s), Bound::Unbounded) => (*s, shape),
+                    TensorIndexer::Narrow(Bound::Included(s), Bound::Excluded(stop)) => (*s, *stop),
+                    TensorIndexer::Narrow(Bound::Included(s), Bound::Included(stop)) => {
+                        (*s, *stop + 1)
+                    }
+                    TensorIndexer::Narrow(Bound::Excluded(s), Bound::Unbounded) => (*s + 1, shape),
+                    TensorIndexer::Narrow(Bound::Excluded(s), Bound::Excluded(stop)) => {
+                        (*s + 1, *stop)
+                    }
+                    TensorIndexer::Narrow(Bound::Excluded(s), Bound::Included(stop)) => {
+                        (*s + 1, *stop + 1)
+                    }
+                };
+                newshape.push(stop - start);
+                if indices.is_empty() {
+                    if start == 0 && stop == shape {
+                        // We haven't started to slice yet, just increase the span
+                    } else {
+                        let offset = start * span;
+                        let small_span = stop * span - offset;
+                        indices.push((offset, offset + small_span));
+                    }
+                } else {
+                    let mut newindices = vec![];
+                    for n in start..stop {
+                        let offset = n * span;
+                        for (old_start, old_stop) in &indices {
+                            newindices.push((old_start + offset, old_stop + offset));
+                        }
+                    }
+                    indices = newindices;
+                }
+            }
+            span *= shape;
+        }
+        if indices.is_empty() {
+            indices.push((0, view.data.len()));
+        }
+        // Reversing so we can pop faster while iterating on the slice
+        let indices = indices.into_iter().rev().collect();
+        let newshape = newshape.into_iter().rev().collect();
+        Ok(Self {
+            view,
+            indices,
+            newshape,
+        })
+    }
+
+    /// Gives back the amount of bytes still being in the iterator
+    pub fn remaining_byte_len(&self) -> usize {
+        self.indices
+            .iter()
+            .map(|(start, stop)| (stop - start))
+            .sum()
+    }
+
+    /// Gives back the amount of bytes still being in the iterator
+    pub fn newshape(&self) -> Vec<usize> {
+        self.newshape.clone()
+    }
+}
+
+impl<'data> Iterator for SliceIterator<'data> {
+    type Item = &'data [u8];
+
+    fn next(&mut self) -> Option<Self::Item> {
+        // TODO We might want to move the logic from `new`
+        // here actually to remove the need to get all the indices
+        // upfront.
+        let (start, stop) = self.indices.pop()?;
+        Some(&self.view.data[start..stop])
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::tensor::{Dtype, TensorView};
+
+    #[test]
+    fn test_helpers() {
+        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 = TensorView {
+            dtype: Dtype::F32,
+            shape: vec![1, 2, 3],
+            data: &data,
+        };
+
+        let iterator = SliceIterator::new(
+            &attn_0,
+            vec![TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded)],
+        )
+        .unwrap();
+        assert_eq!(iterator.remaining_byte_len(), 24);
+        assert_eq!(iterator.newshape(), vec![1, 2, 3]);
+
+        let iterator = SliceIterator::new(
+            &attn_0,
+            vec![
+                TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded),
+                TensorIndexer::Narrow(Bound::Included(0), Bound::Excluded(1)),
+            ],
+        )
+        .unwrap();
+        assert_eq!(iterator.remaining_byte_len(), 12);
+        assert_eq!(iterator.newshape(), vec![1, 1, 3]);
+    }
+
+    #[test]
+    fn test_dummy() {
+        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 = TensorView {
+            dtype: Dtype::F32,
+            shape: vec![1, 2, 3],
+            data: &data,
+        };
+
+        let mut iterator = SliceIterator::new(
+            &attn_0,
+            vec![TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded)],
+        )
+        .unwrap();
+        assert_eq!(iterator.next(), Some(&data[0..24]));
+        assert_eq!(iterator.next(), None);
+
+        let mut iterator = SliceIterator::new(
+            &attn_0,
+            vec![
+                TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded),
+                TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded),
+            ],
+        )
+        .unwrap();
+        assert_eq!(iterator.next(), Some(&data[0..24]));
+        assert_eq!(iterator.next(), None);
+
+        let mut iterator = SliceIterator::new(
+            &attn_0,
+            vec![
+                TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded),
+                TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded),
+            ],
+        )
+        .unwrap();
+        assert_eq!(iterator.next(), Some(&data[0..24]));
+        assert_eq!(iterator.next(), None);
+
+        let mut iterator = SliceIterator::new(
+            &attn_0,
+            vec![
+                TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded),
+                TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded),
+                TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded),
+            ],
+        )
+        .unwrap();
+        assert_eq!(iterator.next(), Some(&data[0..24]));
+        assert_eq!(iterator.next(), None);
+
+        assert!(SliceIterator::new(
+            &attn_0,
+            vec![
+                TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded),
+                TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded),
+                TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded),
+                TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded),
+            ],
+        )
+        .is_err(),);
+    }
+
+    #[test]
+    fn test_slice_variety() {
+        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 = TensorView {
+            dtype: Dtype::F32,
+            shape: vec![1, 2, 3],
+            data: &data,
+        };
+
+        let mut iterator = SliceIterator::new(
+            &attn_0,
+            vec![TensorIndexer::Narrow(
+                Bound::Included(0),
+                Bound::Excluded(1),
+            )],
+        )
+        .unwrap();
+        assert_eq!(iterator.next(), Some(&data[0..24]));
+        assert_eq!(iterator.next(), None);
+
+        let mut iterator = SliceIterator::new(
+            &attn_0,
+            vec![
+                TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded),
+                TensorIndexer::Narrow(Bound::Included(0), Bound::Excluded(1)),
+            ],
+        )
+        .unwrap();
+        assert_eq!(iterator.next(), Some(&data[0..12]));
+        assert_eq!(iterator.next(), None);
+
+        let mut iterator = SliceIterator::new(
+            &attn_0,
+            vec![
+                TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded),
+                TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded),
+                TensorIndexer::Narrow(Bound::Included(0), Bound::Excluded(1)),
+            ],
+        )
+        .unwrap();
+        assert_eq!(iterator.next(), Some(&data[0..4]));
+        assert_eq!(iterator.next(), Some(&data[12..16]));
+        assert_eq!(iterator.next(), None);
+
+        let mut iterator = SliceIterator::new(
+            &attn_0,
+            vec![
+                TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded),
+                TensorIndexer::Narrow(Bound::Included(1), Bound::Excluded(2)),
+                TensorIndexer::Narrow(Bound::Included(0), Bound::Excluded(1)),
+            ],
+        )
+        .unwrap();
+        assert_eq!(iterator.next(), Some(&data[12..16]));
+        assert_eq!(iterator.next(), None);
+    }
+
+    #[test]
+    fn test_slice_variety2() {
+        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 = TensorView {
+            dtype: Dtype::F32,
+            shape: vec![2, 3],
+            data: &data,
+        };
+
+        let mut iterator = SliceIterator::new(
+            &attn_0,
+            vec![
+                TensorIndexer::Narrow(Bound::Unbounded, Bound::Unbounded),
+                TensorIndexer::Narrow(Bound::Included(1), Bound::Excluded(3)),
+            ],
+        )
+        .unwrap();
+        assert_eq!(iterator.next(), Some(&data[4..12]));
+        assert_eq!(iterator.next(), Some(&data[16..24]));
+        assert_eq!(iterator.next(), None);
+    }
+}
diff --git a/safetensors/src/tensor.rs b/safetensors/src/tensor.rs
new file mode 100644 (file)
index 0000000..8b8cc56
--- /dev/null
@@ -0,0 +1,453 @@
+//! Module Containing the most important structures
+use crate::slice::{InvalidSlice, SliceIterator, TensorIndexer};
+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,
+    /// The tensor name was not found in the archive
+    TensorNotFound,
+    /// Invalid information between shape, dtype and the proposed offsets in the file
+    TensorInvalidInfo,
+}
+
+fn prepare<'hash, 'data>(
+    data: &'hash HashMap<String, TensorView<'data>>,
+    data_info: &'hash Option<HashMap<String, String>>,
+) -> (Metadata, Vec<&'hash TensorView<'data>>, usize) {
+    let mut tensors: Vec<&TensorView> = 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,
+            shape: tensor.shape.to_vec(),
+            data_offsets: (offset, offset + n),
+        };
+        offset += n;
+        hmetadata.insert(name.to_string(), tensor_info);
+        tensors.push(tensor);
+    }
+
+    let metadata: Metadata = Metadata::new(data_info.clone(), hmetadata);
+
+    (metadata, tensors, offset)
+}
+
+/// Serialize to an owned byte buffer the dictionnary of tensors.
+pub fn serialize(
+    data: &HashMap<String, TensorView>,
+    data_info: &Option<HashMap<String, String>>,
+) -> Vec<u8> {
+    let (metadata, tensors, offset) = prepare(data, data_info);
+    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
+}
+
+/// 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<String, TensorView>,
+    data_info: &Option<HashMap<String, String>>,
+    filename: &str,
+) -> Result<(), std::io::Error> {
+    let (metadata, tensors, _) = prepare(data, data_info);
+    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().as_ref())?;
+    f.write_all(&metadata_buf)?;
+    for tensor in tensors {
+        f.write_all(tensor.data)?;
+    }
+    f.flush()?;
+    Ok(())
+}
+
+/// A structure owning some metadata to lookup tensors on a shared `data`
+/// byte-buffer (not owned).
+pub struct SafeTensors<'data> {
+    metadata: Metadata,
+    data: &'data [u8],
+}
+
+impl<'data> SafeTensors<'data> {
+    /// Given a byte-buffer representing the whole safetensor 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 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::InvalidHeaderDeserialization)?;
+        let data = &buffer[n + 8..];
+        Ok(Self { metadata, data })
+    }
+
+    /// 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.tensors {
+            let tensorview = TensorView {
+                dtype: info.dtype,
+                shape: info.shape.clone(),
+                data: &self.data[info.data_offsets.0..info.data_offsets.1],
+            };
+            tensors.push((name.to_string(), tensorview));
+        }
+        tensors
+    }
+
+    /// Allow the user to get a specific tensor within the SafeTensors.
+    /// The tensor returned is merely a view and the data is not owned by this
+    /// structure.
+    pub fn tensor(&self, tensor_name: &str) -> Result<TensorView<'_>, SafeTensorError> {
+        if let Some(info) = &self.metadata.tensors.get(tensor_name) {
+            Ok(TensorView {
+                dtype: info.dtype,
+                shape: info.shape.clone(),
+                data: &self.data[info.data_offsets.0..info.data_offsets.1],
+            })
+        } else {
+            Err(SafeTensorError::TensorNotFound)
+        }
+    }
+
+    /// Allow the user to get a specific tensor within the SafeTensors.
+    /// The tensor returned is merely a view and the data is not owned by this
+    /// structure.
+    pub fn names(&self) -> Vec<&'_ String> {
+        self.metadata.tensors.iter().map(|(name, _)| name).collect()
+    }
+}
+
+/// 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)]
+pub struct Metadata {
+    #[serde(skip_serializing_if = "Option::is_none")]
+    #[serde(rename = "__metadata__")]
+    metadata: Option<HashMap<String, String>>,
+    #[serde(flatten)]
+    tensors: HashMap<String, TensorInfo>,
+}
+
+impl Metadata {
+    fn new(
+        metadata: Option<HashMap<String, String>>,
+        tensors: HashMap<String, TensorInfo>,
+    ) -> Self {
+        Self { metadata, tensors }
+    }
+
+    /// Gives back the tensor metadata
+    pub fn tensors(&self) -> &HashMap<String, TensorInfo> {
+        &self.tensors
+    }
+
+    /// Gives back the tensor metadata
+    pub fn metadata(&self) -> &Option<HashMap<String, String>> {
+        &self.metadata
+    }
+}
+
+/// 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(crate) dtype: Dtype,
+    pub(crate) shape: Vec<usize>,
+    pub(crate) data: &'data [u8],
+}
+
+impl<'data> TensorView<'data> {
+    /// Create new tensor view
+    pub fn new(
+        dtype: Dtype,
+        shape: Vec<usize>,
+        data: &'data [u8],
+    ) -> Result<Self, SafeTensorError> {
+        let nelements: usize = shape.iter().product();
+        let nbytes = nelements * dtype.size();
+        if data.len() != nbytes {
+            println!("{:?} != {:?}", data.len(), nbytes);
+            Err(SafeTensorError::TensorInvalidInfo)
+        } else {
+            Ok(Self { dtype, shape, data })
+        }
+    }
+    /// The current tensor dtype
+    pub fn get_dtype(&self) -> Dtype {
+        self.dtype
+    }
+
+    /// The current tensor shape
+    pub fn get_shape(&'data self) -> &'data [usize] {
+        &self.shape
+    }
+
+    /// The current tensor byte-buffer
+    pub fn get_data(&self) -> &'data [u8] {
+        self.data
+    }
+
+    /// The various pieces of the data buffer according to the asked slice
+    pub fn get_sliced_data(
+        &'data self,
+        slices: Vec<TensorIndexer>,
+    ) -> Result<SliceIterator<'data>, InvalidSlice> {
+        SliceIterator::new(self, slices)
+    }
+}
+
+/// A single tensor information.
+/// Endianness is assumed to be little endian
+/// Ordering is assumed to be 'C'.
+#[derive(Debug, Deserialize, Serialize, Clone)]
+pub struct TensorInfo {
+    /// The type of each element of the tensor
+    pub dtype: Dtype,
+    /// The shape of the tensor
+    pub shape: Vec<usize>,
+    /// The offsets to find the data within the byte-buffer array.
+    pub data_offsets: (usize, usize),
+}
+
+/// The various available dtypes
+#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq)]
+#[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,
+}
+
+impl Dtype {
+    /// Gives out the size (in bytes) of 1 element of this dtype.
+    pub fn size(&self) -> usize {
+        match self {
+            Dtype::BOOL => 1,
+            Dtype::U8 => 1,
+            Dtype::I8 => 1,
+            Dtype::I16 => 2,
+            Dtype::U16 => 2,
+            Dtype::I32 => 4,
+            Dtype::U32 => 4,
+            Dtype::I64 => 8,
+            Dtype::U64 => 8,
+            Dtype::F16 => 2,
+            Dtype::BF16 => 2,
+            Dtype::F32 => 4,
+            Dtype::F64 => 8,
+        }
+    }
+}
+
+// /// 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: &'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 }
+//     }
+// }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::slice::IndexOp;
+
+    #[test]
+    fn test_serialization() {
+        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 shape = vec![1, 2, 3];
+        let attn_0 = TensorView::new(Dtype::F32, shape, &data).unwrap();
+        let metadata: HashMap<String, TensorView> =
+            [("attn.0".to_string(), attn_0)].into_iter().collect();
+
+        let out = serialize(&metadata, &None);
+        let _parsed = SafeTensors::deserialize(&out).unwrap();
+    }
+
+    #[test]
+    fn test_slicing() {
+        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 = TensorView {
+            dtype: Dtype::F32,
+            shape: vec![1, 2, 3],
+            data: &data,
+        };
+        let metadata: HashMap<String, TensorView> =
+            [("attn.0".to_string(), attn_0)].into_iter().collect();
+
+        let out = serialize(&metadata, &None);
+        let parsed = SafeTensors::deserialize(&out).unwrap();
+
+        let out_buffer: Vec<u8> = parsed
+            .tensor("attn.0")
+            .unwrap()
+            .slice((.., ..1))
+            .unwrap()
+            .flat_map(|b| b.to_vec())
+            .collect();
+        assert_eq!(out_buffer, vec![0u8, 0, 0, 0, 0, 0, 128, 63, 0, 0, 0, 64]);
+        assert_eq!(
+            out_buffer,
+            vec![0.0f32, 1.0, 2.0]
+                .into_iter()
+                .flat_map(|f| f.to_le_bytes())
+                .collect::<Vec<_>>()
+        );
+        let out_buffer: Vec<u8> = parsed
+            .tensor("attn.0")
+            .unwrap()
+            .slice((.., .., ..1))
+            .unwrap()
+            .flat_map(|b| b.to_vec())
+            .collect();
+        assert_eq!(out_buffer, vec![0u8, 0, 0, 0, 0, 0, 64, 64]);
+        assert_eq!(
+            out_buffer,
+            vec![0.0f32, 3.0]
+                .into_iter()
+                .flat_map(|f| f.to_le_bytes())
+                .collect::<Vec<_>>()
+        );
+    }
+
+    #[test]
+    fn test_gpt2() {
+        gpt2_like(12, "gpt2");
+    }
+
+    #[test]
+    fn test_gpt2_tiny() {
+        gpt2_like(6, "gpt2_tiny");
+    }
+
+    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_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_desc.push(("ln_f.weight".to_string(), vec![768]));
+        tensors_desc.push(("ln_f.bias".to_string(), vec![768]));
+
+        let dtype = Dtype::F32;
+        let n: usize = tensors_desc
+            .iter()
+            .map(|(_, shape)| shape.iter().product::<usize>())
+            .sum::<usize>()
+            * dtype.size(); // 4
+        let all_data = vec![0; n];
+        let mut metadata: HashMap<String, TensorView> = 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 * dtype.size()];
+            let tensor = TensorView::new(dtype, shape, buffer).unwrap();
+            metadata.insert(name, tensor);
+            offset += n;
+        }
+
+        let filename = format!("./out_{}.bin", model_id);
+
+        let out = serialize(&metadata, &None);
+
+        std::fs::write(&filename, out).unwrap();
+
+        let raw = std::fs::read(&filename).unwrap();
+        let _deserialized = SafeTensors::deserialize(&raw).unwrap();
+        std::fs::remove_file(&filename).unwrap();
+    }
+
+    #[test]
+    fn test_deserialization() {
+        let 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";
+
+        let loaded = SafeTensors::deserialize(serialized).unwrap();
+
+        assert_eq!(loaded.names(), vec!["test"]);
+        let tensor = loaded.tensor("test").unwrap();
+        assert_eq!(tensor.get_shape(), vec![2, 2]);
+        assert_eq!(tensor.get_dtype(), Dtype::I32);
+        // 16 bytes
+        assert_eq!(tensor.get_data(), b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
+    }
+}