From: Mishig Date: Wed, 2 Nov 2022 15:52:39 +0000 (+0100) Subject: Adding docs (#55) X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=a99b681851e0333033b7a6182e2998f0768cdb62;p=safetensors.git Adding docs (#55) * Initialize docs * Add build pr github action * Adding a bunch of documentation. Co-authored-by: Nicolas Patry --- diff --git a/.github/workflows/build_pr_documentation.yml b/.github/workflows/build_pr_documentation.yml new file mode 100644 index 0000000..b6b606a --- /dev/null +++ b/.github/workflows/build_pr_documentation.yml @@ -0,0 +1,18 @@ +name: Build PR Documentation + +on: + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + build: + uses: huggingface/doc-builder/.github/workflows/build_pr_documentation.yml@safetensors + with: + commit_sha: ${{ github.event.pull_request.head.sha }} + pr_number: ${{ github.event.number }} + package: safetensors + package_path: safetensors/bindings/python/ + install_rust: true diff --git a/bindings/python/py_src/safetensors/__init__.pyi b/bindings/python/py_src/safetensors/__init__.pyi new file mode 100644 index 0000000..a125e8d --- /dev/null +++ b/bindings/python/py_src/safetensors/__init__.pyi @@ -0,0 +1,73 @@ +# Generated content DO NOT EDIT +@staticmethod +def deserialize(bytes): + """ + Opens a safetensors lazily and returns tensors as asked + + Args: + data (:obj:`bytes`): + The byte content of a file + + Returns: + (:obj:`List[str, Dict[str, Dict[str, any]]]`): + The deserialized content is like: + [("tensor_name", {"shape": [2, 3], "dtype": "F32", "data": b"\0\0.." }), (...)] + """ + pass + +@staticmethod +def serialize(tensor_dict, metadata=None): + """ + Serializes raw data. + + Args: + tensor_dict (:obj:`Dict[str, Dict[Any]]`): + The tensor dict is like: + {"tensor_name": {"dtype": "F32", "shape": [2, 3], "data": b"\0\0"}} + metadata (:obj:`Dict[str, str]`, *optional*): + The optional purely text annotations + + Returns: + (:obj:`bytes`): + The serialized content. + """ + pass + +@staticmethod +def serialize_file(tensor_dict, filename, metadata=None): + """ + Serializes raw data. + + Args: + tensor_dict (:obj:`Dict[str, Dict[Any]]`): + The tensor dict is like: + {"tensor_name": {"dtype": "F32", "shape": [2, 3], "data": b"\0\0"}} + filename (:obj:`str`): + The name of the file to write into. + metadata (:obj:`Dict[str, str]`, *optional*): + The optional purely text annotations + + Returns: + (:obj:`bytes`): + The serialized content. + """ + pass + +class safe_open: + """ + Opens a safetensors lazily and returns tensors as asked + + Args: + filename (:obj:`str`): + The filename to open + + framework (:obj:`str`): + The framework you want you tensors in. Supported values: + `pt`, `tf`, `flax`, `numpy`. + + device (:obj:`str`, defaults to :obj:`"cpu"`): + The device on which you want the tensors. + """ + + def __init__(self, filename, framework, device="cpu"): + pass diff --git a/bindings/python/py_src/safetensors/flax.py b/bindings/python/py_src/safetensors/flax.py index 4984162..36909ea 100644 --- a/bindings/python/py_src/safetensors/flax.py +++ b/bindings/python/py_src/safetensors/flax.py @@ -6,19 +6,31 @@ import jax.numpy as jnp from safetensors import numpy -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 save(tensors: Dict[str, jnp.DeviceArray], metadata: Optional[Dict[str, str]] = None) -> bytes: + """ + Saves a dictionnary of tensors into raw bytes in safetensors format. + Args: + tensors (`Dict[str, jnp.DeviceArray]`): + The incoming tensors. Tensors need to be contiguous and dense. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. -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 + Returns: + `bytes`: The raw bytes representing the format + Example: -def save(tensors: Dict[str, jnp.DeviceArray], metadata: Optional[Dict[str, str]] = None) -> bytes: + ```python + from safetensors.flax import save + import flax + + tensors = {"embedding": jnp.zeros((512, 1024)), "attention": jnp.zeros((256, 256))} + byte_data = save(tensors) + ``` + """ np_tensors = _jnp2np(tensors) return numpy.save(np_tensors, metadata=metadata) @@ -28,15 +40,97 @@ def save_file( filename: str, metadata: Optional[Dict[str, str]] = None, ): + """ + Saves a dictionnary of tensors into raw bytes in safetensors format. + + Args: + tensors (`Dict[str, jnp.DeviceArray]`): + The incoming tensors. Tensors need to be contiguous and dense. + filename (`str`): + The filename we're saving into. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. + + Returns: + `None` + + Example: + + ```python + from safetensors.flax import save_file + import flax + + tensors = {"embedding": jnp.zeros((512, 1024)), "attention": jnp.zeros((256, 256))} + save(tensors, "model.safetensors") + ``` + """ np_tensors = _jnp2np(tensors) return numpy.save_file(np_tensors, filename, metadata=metadata) -def load(buffer: bytes) -> Dict[str, jnp.DeviceArray]: - flat = numpy.load(buffer) +def load(data: bytes) -> Dict[str, jnp.DeviceArray]: + """ + Loads a safetensors file into flax format from pure bytes. + + Args: + data (`bytes`): + The content of a safetensors file + + Returns: + `Dict[str, jnp.DeviceArray]`: dictionary that contains name as key, value as `jnp.DeviceArray` on cpu + + Example: + + ```python + from safetensors.flax import load + + file_path = "./my_folder/bert.safetensors" + with open(file_path, "rb") as f: + data = f.read() + + loaded = load(data) + ``` + """ + flat = numpy.load(data) return _np2jnp(flat) def load_file(filename: str) -> Dict[str, jnp.DeviceArray]: + """ + Loads a safetensors file into flax format. + + Args: + filename (`str`): + The name of the file which contains the tensors + device (`Dict[str, any]`, *optional*, defaults to `cpu`): + The device where the tensors need to be located after load. + available options are all regular flax device locations + + Returns: + `Dict[str, jnp.DeviceArray]`: dictionary that contains name as key, value as `jnp.DeviceArray` + + Example: + + ```python + from safetensors.flax import load_file + + file_path = "./my_folder/bert.safetensors" + loaded = load_file(file_path) + ``` + """ flat = numpy.load_file(filename) return _np2jnp(flat) + + +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]: + for k, v in jnp_dict.items(): + jnp_dict[k] = np.asarray(v) + return jnp_dict diff --git a/bindings/python/py_src/safetensors/numpy.py b/bindings/python/py_src/safetensors/numpy.py index 1f8c04d..63a208d 100644 --- a/bindings/python/py_src/safetensors/numpy.py +++ b/bindings/python/py_src/safetensors/numpy.py @@ -6,18 +6,117 @@ from .safetensors_rust import deserialize, safe_open, serialize, serialize_file def save(tensor_dict: Dict[str, np.ndarray], metadata: Optional[Dict[str, str]] = None) -> bytes: + """ + Saves a dictionnary of tensors into raw bytes in safetensors format. + + Args: + tensors (`Dict[str, np.ndarray]`): + The incoming tensors. Tensors need to be contiguous and dense. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. + + Returns: + `bytes`: The raw bytes representing the format + + Example: + + ```python + from safetensors.numpy import save + import numpy as np + + tensors = {"embedding": np.zeros((512, 1024)), "attention": np.zeros((256, 256))} + byte_data = save(tensors) + ``` + """ flattened = {k: {"dtype": v.dtype.name, "shape": v.shape, "data": v.tobytes()} for k, v in tensor_dict.items()} serialized = serialize(flattened, metadata=metadata) result = bytes(serialized) return result -def load(filename: str) -> Dict[str, np.ndarray]: - flat = deserialize(filename) +def save_file(tensor_dict: Dict[str, np.ndarray], filename: str, metadata: Optional[Dict[str, str]] = None): + """ + Saves a dictionnary of tensors into raw bytes in safetensors format. + + Args: + tensors (`Dict[str, np.ndarray]`): + The incoming tensors. Tensors need to be contiguous and dense. + filename (`str`): + The filename we're saving into. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. + + Returns: + `None` + + Example: + + ```python + from safetensors.numpy import save_file + import numpy as np + + tensors = {"embedding": np.zeros((512, 1024)), "attention": np.zeros((256, 256))} + save(tensors, "model.safetensors") + ``` + """ + flattened = {k: {"dtype": v.dtype.name, "shape": v.shape, "data": v.tobytes()} for k, v in tensor_dict.items()} + serialize_file(flattened, filename, metadata=metadata) + + +def load(data: bytes) -> Dict[str, np.ndarray]: + """ + Loads a safetensors file into numpy format from pure bytes. + + Args: + data (`bytes`): + The content of a safetensors file + + Returns: + `Dict[str, np.ndarray]`: dictionary that contains name as key, value as `np.ndarray` on cpu + + Example: + + ```python + from safetensors.numpy import load + + file_path = "./my_folder/bert.safetensors" + with open(file_path, "rb") as f: + data = f.read() + + loaded = load(data) + ``` + """ + flat = deserialize(data) return _view2np(flat) def load_file(filename: str) -> Dict[str, np.ndarray]: + """ + Loads a safetensors file into numpy format. + + Args: + filename (`str`): + The name of the file which contains the tensors + device (`Dict[str, any]`, *optional*, defaults to `cpu`): + The device where the tensors need to be located after load. + available options are all regular numpy device locations + + Returns: + `Dict[str, np.ndarray]`: dictionary that contains name as key, value as `np.ndarray` + + Example: + + ```python + from safetensors.numpy import load_file + + file_path = "./my_folder/bert.safetensors" + loaded = load_file(file_path) + ``` + """ result = {} with safe_open(filename, framework="np") as f: for k in f.keys(): @@ -25,11 +124,6 @@ def load_file(filename: str) -> Dict[str, np.ndarray]: 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, filename, metadata=metadata) - - _TYPES = { "F64": np.float64, "F32": np.float32, diff --git a/bindings/python/py_src/safetensors/tensorflow.py b/bindings/python/py_src/safetensors/tensorflow.py index aaaf05c..76fbf81 100644 --- a/bindings/python/py_src/safetensors/tensorflow.py +++ b/bindings/python/py_src/safetensors/tensorflow.py @@ -6,19 +6,31 @@ import tensorflow as tf from safetensors import numpy -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 save(tensors: Dict[str, tf.Tensor], metadata: Optional[Dict[str, str]] = None) -> bytes: + """ + Saves a dictionnary of tensors into raw bytes in safetensors format. + Args: + tensors (`Dict[str, tf.Tensor]`): + The incoming tensors. Tensors need to be contiguous and dense. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. -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 + Returns: + `bytes`: The raw bytes representing the format + Example: -def save(tensors: Dict[str, tf.Tensor], metadata: Optional[Dict[str, str]] = None) -> bytes: + ```python + from safetensors.tensorflow import save + import tensorflow as tf + + tensors = {"embedding": tf.zeros((512, 1024)), "attention": tf.zeros((256, 256))} + byte_data = save(tensors) + ``` + """ np_tensors = _tf2np(tensors) return numpy.save(np_tensors, metadata=metadata) @@ -28,15 +40,97 @@ def save_file( filename: str, metadata: Optional[Dict[str, str]] = None, ): + """ + Saves a dictionnary of tensors into raw bytes in safetensors format. + + Args: + tensors (`Dict[str, tf.Tensor]`): + The incoming tensors. Tensors need to be contiguous and dense. + filename (`str`): + The filename we're saving into. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. + + Returns: + `None` + + Example: + + ```python + from safetensors.tensorflow import save_file + import tensorflow as tf + + tensors = {"embedding": tf.zeros((512, 1024)), "attention": tf.zeros((256, 256))} + save(tensors, "model.safetensors") + ``` + """ np_tensors = _tf2np(tensors) return numpy.save_file(np_tensors, filename, metadata=metadata) -def load(buffer: bytes) -> Dict[str, tf.Tensor]: - flat = numpy.load(buffer) +def load(data: bytes) -> Dict[str, tf.Tensor]: + """ + Loads a safetensors file into tensorflow format from pure bytes. + + Args: + data (`bytes`): + The content of a safetensors file + + Returns: + `Dict[str, tf.Tensor]`: dictionary that contains name as key, value as `tf.Tensor` on cpu + + Example: + + ```python + from safetensors.tensorflow import load + + file_path = "./my_folder/bert.safetensors" + with open(file_path, "rb") as f: + data = f.read() + + loaded = load(data) + ``` + """ + flat = numpy.load(data) return _np2tf(flat) def load_file(filename: str) -> Dict[str, tf.Tensor]: + """ + Loads a safetensors file into tensorflow format. + + Args: + filename (`str`): + The name of the file which contains the tensors + device (`Dict[str, any]`, *optional*, defaults to `cpu`): + The device where the tensors need to be located after load. + available options are all regular tensorflow device locations + + Returns: + `Dict[str, tf.Tensor]`: dictionary that contains name as key, value as `tf.Tensor` + + Example: + + ```python + from safetensors.tensorflow import load_file + + file_path = "./my_folder/bert.safetensors" + loaded = load_file(file_path) + ``` + """ flat = numpy.load_file(filename) return _np2tf(flat) + + +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.Tensor]) -> Dict[str, np.array]: + for k, v in tf_dict.items(): + tf_dict[k] = v.numpy() + return tf_dict diff --git a/bindings/python/py_src/safetensors/torch.py b/bindings/python/py_src/safetensors/torch.py index 7a86882..2c4740e 100644 --- a/bindings/python/py_src/safetensors/torch.py +++ b/bindings/python/py_src/safetensors/torch.py @@ -1,38 +1,36 @@ -from typing import Any, Dict, Optional from collections import defaultdict +from typing import Any, Dict, Optional import torch from .safetensors_rust import deserialize, safe_open, serialize, serialize_file -def _flatten(tensors: Dict[str, torch.Tensor]) -> Dict[str, Dict[str, Any]]: - ptrs = defaultdict(set) - for k, v in tensors.items(): - if v.layout == torch.strided: - ptrs[v.data_ptr()].add(k) - - failing = [] - for ptr, names in ptrs.items(): - if len(names) > 1: - failing.append(names) - - if failing: - raise RuntimeError( - f"""Some tensors share memory, this will lead to duplicate memory on disk and potential differences when loading them again: {failing}""" - ) - - return { - k: { - "dtype": str(v.dtype).split(".")[-1], - "shape": v.shape, - "data": _tobytes(v, k), - } - for k, v in tensors.items() - } - - def save(tensors: Dict[str, torch.Tensor], metadata: Optional[Dict[str, str]] = None) -> bytes: + """ + Saves a dictionnary of tensors into raw bytes in safetensors format. + + Args: + tensors (`Dict[str, torch.Tensor]`): + The incoming tensors. Tensors need to be contiguous and dense. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. + + Returns: + `bytes`: The raw bytes representing the format + + Example: + + ```python + from safetensors.torch import save + import torch + + tensors = {"embedding": torch.zeros((512, 1024)), "attention": torch.zeros((256, 256))} + byte_data = save(tensors) + ``` + """ serialized = serialize(_flatten(tensors), metadata=metadata) result = bytes(serialized) return result @@ -43,10 +41,58 @@ def save_file( filename: str, metadata: Optional[Dict[str, str]] = None, ): + """ + Saves a dictionnary of tensors into raw bytes in safetensors format. + + Args: + tensors (`Dict[str, torch.Tensor]`): + The incoming tensors. Tensors need to be contiguous and dense. + filename (`str`): + The filename we're saving into. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. + + Returns: + `None` + + Example: + + ```python + from safetensors.torch import save_file + import torch + + tensors = {"embedding": torch.zeros((512, 1024)), "attention": torch.zeros((256, 256))} + save(tensors, "model.safetensors") + ``` + """ serialize_file(_flatten(tensors), filename, metadata=metadata) def load_file(filename: str, device="cpu") -> Dict[str, torch.Tensor]: + """ + Loads a safetensors file into torch format. + + Args: + filename (`str`): + The name of the file which contains the tensors + device (`Dict[str, any]`, *optional*, defaults to `cpu`): + The device where the tensors need to be located after load. + available options are all regular torch device locations + + Returns: + `Dict[str, torch.Tensor]`: dictionary that contains name as key, value as `torch.Tensor` + + Example: + + ```python + from safetensors.torch import load_file + + file_path = "./my_folder/bert.safetensors" + loaded = load_file(file_path) + ``` + """ result = {} with safe_open(filename, framework="pt", device=device) as f: for k in f.keys(): @@ -54,8 +100,30 @@ def load_file(filename: str, device="cpu") -> Dict[str, torch.Tensor]: return result -def load(filename: str) -> Dict[str, torch.Tensor]: - flat = deserialize(filename) +def load(data: bytes) -> Dict[str, torch.Tensor]: + """ + Loads a safetensors file into torch format from pure bytes. + + Args: + data (`bytes`): + The content of a safetensors file + + Returns: + `Dict[str, torch.Tensor]`: dictionary that contains name as key, value as `torch.Tensor` on cpu + + Example: + + ```python + from safetensors.torch import load + + file_path = "./my_folder/bert.safetensors" + with open(file_path, "rb") as f: + data = f.read() + + loaded = load(data) + ``` + """ + flat = deserialize(data) return _view2torch(flat) @@ -132,11 +200,32 @@ def _tobytes(tensor: torch.Tensor, name: str) -> bytes: ptr = tensor.data_ptr() newptr = ctypes.cast(ptr, ctypes.POINTER(ctypes.c_ubyte)) - try: - data = np.ctypeslib.as_array(newptr, (total_bytes,)) # no internal copy - except Exception: - import ipdb - - ipdb.set_trace() + data = np.ctypeslib.as_array(newptr, (total_bytes,)) # no internal copy return data.tobytes() + + +def _flatten(tensors: Dict[str, torch.Tensor]) -> Dict[str, Dict[str, Any]]: + ptrs = defaultdict(set) + for k, v in tensors.items(): + if v.layout == torch.strided: + ptrs[v.data_ptr()].add(k) + + failing = [] + for ptr, names in ptrs.items(): + if len(names) > 1: + failing.append(names) + + if failing: + raise RuntimeError( + f"""Some tensors share memory, this will lead to duplicate memory on disk and potential differences when loading them again: {failing}""" + ) + + return { + k: { + "dtype": str(v.dtype).split(".")[-1], + "shape": v.shape, + "data": _tobytes(v, k), + } + for k, v in tensors.items() + } diff --git a/bindings/python/setup.py b/bindings/python/setup.py index a62e4ca..9174f16 100644 --- a/bindings/python/setup.py +++ b/bindings/python/setup.py @@ -7,6 +7,7 @@ with open("requirements-dev.txt", "r") as f: extras = {} extras["testing"] = testing +extras["dev"] = testing setup( name="safetensors", diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index 9fb49c7..91f8eee 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -60,7 +60,20 @@ fn prepare(tensor_dict: HashMap) -> PyResult( py: Python<'b>, tensor_dict: HashMap, @@ -75,7 +88,22 @@ fn serialize<'a, 'b>( Ok(pybytes) } +/// Serializes raw data. +/// +/// Args: +/// tensor_dict (:obj:`Dict[str, Dict[Any]]`): +/// The tensor dict is like: +/// {"tensor_name": {"dtype": "F32", "shape": [2, 3], "data": b"\0\0"}} +/// filename (:obj:`str`): +/// The name of the file to write into. +/// metadata (:obj:`Dict[str, str]`, *optional*): +/// The optional purely text annotations +/// +/// Returns: +/// (:obj:`bytes`): +/// The serialized content. #[pyfunction] +#[pyo3(text_signature = "(tensor_dict, filename, metadata=None)")] fn serialize_file( tensor_dict: HashMap, filename: &str, @@ -89,7 +117,18 @@ fn serialize_file( Ok(()) } +/// Opens a safetensors lazily and returns tensors as asked +/// +/// Args: +/// data (:obj:`bytes`): +/// The byte content of a file +/// +/// Returns: +/// (:obj:`List[str, Dict[str, Dict[str, any]]]`): +/// The deserialized content is like: +/// [("tensor_name", {"shape": [2, 3], "dtype": "F32", "data": b"\0\0.." }), (...)] #[pyfunction] +#[pyo3(text_signature = "(bytes)")] fn deserialize(py: Python, bytes: &[u8]) -> PyResult)>> { let safetensor = SafeTensors::deserialize(bytes).map_err(|e| { exceptions::PyException::new_err(format!("Error while deserializing: {:?}", e)) @@ -204,8 +243,21 @@ impl IntoPy for Device { } } +/// Opens a safetensors lazily and returns tensors as asked +/// +/// Args: +/// filename (:obj:`str`): +/// The filename to open +/// +/// framework (:obj:`str`): +/// The framework you want you tensors in. Supported values: +/// `pt`, `tf`, `flax`, `numpy`. +/// +/// device (:obj:`str`, defaults to :obj:`"cpu"`): +/// The device on which you want the tensors. #[pyclass] #[allow(non_camel_case_types)] +#[pyo3(text_signature = "(self, filename, framework, device=\"cpu\")")] struct safe_open { metadata: Metadata, offset: usize, @@ -261,16 +313,44 @@ impl safe_open { }) } + /// Return the special non tensor information in the header + /// + /// Returns: + /// (:obj:`Dict[str, str]`): + /// The freeform metadata. pub fn metadata(&self) -> Option> { self.metadata.metadata().clone() } + /// Returns the names of the tensors in the file. + /// + /// Returns: + /// (:obj:`List[str]`): + /// The name of the tensors contained in that file pub fn keys(&self) -> PyResult> { let mut keys: Vec<_> = self.metadata.tensors().keys().cloned().collect(); keys.sort(); Ok(keys) } + /// Returns a full tensor + /// + /// Args: + /// name (:obj:`str`): + /// The name of the tensor you want + /// + /// Returns: + /// (:obj:`Tensor`): + /// The tensor in the framework you opened the file for. + /// + /// Example: + /// ```python + /// from safetensors import safe_open + /// + /// with safe_open("model.safetensors", framework="pt", device=0) as f: + /// tensor = f.get_tensor("embedding") + /// + /// ``` pub fn get_tensor(&self, name: &str) -> PyResult { let info = self.metadata.tensors().get(name).ok_or_else(|| { exceptions::PyException::new_err(format!("File does not contain tensor {name}",)) @@ -291,6 +371,23 @@ impl safe_open { }) } + /// Returns a full slice view object + /// + /// Args: + /// name (:obj:`str`): + /// The name of the tensor you want + /// + /// Returns: + /// (:obj:`PySafeSlice`): + /// A dummy object you can slice into to get a real tensor + /// Example: + /// ```python + /// from safetensors import safe_open + /// + /// with safe_open("model.safetensors", framework="pt", device=0) as f: + /// tensor_part = f.get_slice("embedding")[:, ::8] + /// + /// ``` pub fn get_slice(&self, name: &str) -> PyResult { if let Some(info) = self.metadata.tensors().get(name) { Ok(PySafeSlice { @@ -332,6 +429,22 @@ enum Slice<'a> { #[pymethods] impl PySafeSlice { + /// Returns the shape of the full underlying tensor + /// + /// Returns: + /// (:obj:`List[int]`): + /// The shape of the full tensor + /// + /// Example: + /// ```python + /// from safetensors import safe_open + /// + /// with safe_open("model.safetensors", framework="pt", device=0) as f: + /// tslice = f.get_slice("embedding") + /// shape = tslice.get_shape() + /// dim = shape // 8 + /// tensor = tslice[:, :dim] + /// ``` pub fn get_shape(&self, py: Python) -> PyResult { let shape = self.info.shape.clone(); let shape: PyObject = shape.into_py(py); diff --git a/bindings/python/stub.py b/bindings/python/stub.py new file mode 100644 index 0000000..340fda5 --- /dev/null +++ b/bindings/python/stub.py @@ -0,0 +1,187 @@ +import argparse +import inspect +import os + +import black + + +INDENT = " " * 4 +GENERATED_COMMENT = "# Generated content DO NOT EDIT\n" + + +def do_indent(text: str, indent: str): + return text.replace("\n", f"\n{indent}") + + +def function(obj, indent, text_signature=None): + if text_signature is None: + text_signature = obj.__text_signature__ + string = "" + string += f"{indent}def {obj.__name__}{text_signature}:\n" + indent += INDENT + string += f'{indent}"""\n' + string += f"{indent}{do_indent(obj.__doc__, indent)}\n" + string += f'{indent}"""\n' + string += f"{indent}pass\n" + string += "\n" + string += "\n" + return string + + +def member_sort(member): + if inspect.isclass(member): + value = 10 + len(inspect.getmro(member)) + else: + value = 1 + return value + + +def fn_predicate(obj): + value = inspect.ismethoddescriptor(obj) or inspect.isbuiltin(obj) + if value: + return obj.__doc__ and obj.__text_signature__ and not obj.__name__.startswith("_") + if inspect.isgetsetdescriptor(obj): + return obj.__doc__ and not obj.__name__.startswith("_") + return False + + +def get_module_members(module): + members = [ + member + for name, member in inspect.getmembers(module) + if not name.startswith("_") and not inspect.ismodule(member) + ] + members.sort(key=member_sort) + return members + + +def pyi_file(obj, indent=""): + string = "" + if inspect.ismodule(obj): + string += GENERATED_COMMENT + members = get_module_members(obj) + for member in members: + string += pyi_file(member, indent) + + elif inspect.isclass(obj): + indent += INDENT + mro = inspect.getmro(obj) + if len(mro) > 2: + inherit = f"({mro[1].__name__})" + else: + inherit = "" + string += f"class {obj.__name__}{inherit}:\n" + + body = "" + if obj.__doc__: + body += f'{indent}"""\n{indent}{do_indent(obj.__doc__, indent)}\n{indent}"""\n' + + fns = inspect.getmembers(obj, fn_predicate) + + # Init + if obj.__text_signature__: + body += f"{indent}def __init__{obj.__text_signature__}:\n" + body += f"{indent+INDENT}pass\n" + body += "\n" + + for (name, fn) in fns: + body += pyi_file(fn, indent=indent) + + if not body: + body += f"{indent}pass\n" + + string += body + string += "\n\n" + + elif inspect.isbuiltin(obj): + string += f"{indent}@staticmethod\n" + string += function(obj, indent) + + elif inspect.ismethoddescriptor(obj): + string += function(obj, indent) + + elif inspect.isgetsetdescriptor(obj): + # TODO it would be interesing to add the setter maybe ? + string += f"{indent}@property\n" + string += function(obj, indent, text_signature="(self)") + else: + raise Exception(f"Object {obj} is not supported") + return string + + +def py_file(module, origin): + members = get_module_members(module) + + string = GENERATED_COMMENT + string += f"from .. import {origin}\n" + string += "\n" + for member in members: + name = member.__name__ + string += f"{name} = {origin}.{name}\n" + return string + + +def do_black(content, is_pyi): + mode = black.Mode( + target_versions={black.TargetVersion.PY35}, + line_length=119, + is_pyi=is_pyi, + string_normalization=True, + experimental_string_processing=False, + ) + try: + return black.format_file_contents(content, fast=True, mode=mode) + except black.NothingChanged: + return content + + +def write(module, directory, origin, check=False): + submodules = [(name, member) for name, member in inspect.getmembers(module) if inspect.ismodule(member)] + + filename = os.path.join(directory, "__init__.pyi") + pyi_content = pyi_file(module) + pyi_content = do_black(pyi_content, is_pyi=True) + os.makedirs(directory, exist_ok=True) + if check: + with open(filename, "r") as f: + data = f.read() + assert data == pyi_content, f"The content of {filename} seems outdated, please run `python stub.py`" + else: + with open(filename, "w") as f: + f.write(pyi_content) + + filename = os.path.join(directory, "__init__.py") + py_content = py_file(module, origin) + py_content = do_black(py_content, is_pyi=False) + os.makedirs(directory, exist_ok=True) + + is_auto = False + if not os.path.exists(filename): + is_auto = True + else: + with open(filename, "r") as f: + line = f.readline() + if line == GENERATED_COMMENT: + is_auto = True + + if is_auto: + if check: + with open(filename, "r") as f: + data = f.read() + assert data == py_content, f"The content of {filename} seems outdated, please run `python stub.py`" + else: + with open(filename, "w") as f: + f.write(py_content) + + for name, submodule in submodules: + write(submodule, os.path.join(directory, name), f"{name}", check=check) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--check", action="store_true") + + args = parser.parse_args() + import safetensors + + write(safetensors.safetensors_rust, "py_src/safetensors/", "safetensors", check=args.check) diff --git a/docs/source/_toctree.yml b/docs/source/_toctree.yml new file mode 100644 index 0000000..c0bfb5c --- /dev/null +++ b/docs/source/_toctree.yml @@ -0,0 +1,14 @@ +- sections: + - local: index + title: 🤗 Safetensors + title: Getting started +- sections: + - local: api/torch + title: Torch API + - local: api/tensorflow + title: Tensorflow API + - local: api/flax + title: Flax API + - local: api/numpy + title: Numpy API + title: API diff --git a/docs/source/api/flax.mdx b/docs/source/api/flax.mdx new file mode 100644 index 0000000..d6b24aa --- /dev/null +++ b/docs/source/api/flax.mdx @@ -0,0 +1,6 @@ +# Flax API + +[[autodoc]] safetensors.flax.load_file +[[autodoc]] safetensors.flax.load +[[autodoc]] safetensors.flax.save_file +[[autodoc]] safetensors.flax.save diff --git a/docs/source/api/numpy.mdx b/docs/source/api/numpy.mdx new file mode 100644 index 0000000..42957fb --- /dev/null +++ b/docs/source/api/numpy.mdx @@ -0,0 +1,6 @@ +# Numpy API + +[[autodoc]] safetensors.numpy.load_file +[[autodoc]] safetensors.numpy.load +[[autodoc]] safetensors.numpy.save_file +[[autodoc]] safetensors.numpy.save diff --git a/docs/source/api/tensorflow.mdx b/docs/source/api/tensorflow.mdx new file mode 100644 index 0000000..4bb9331 --- /dev/null +++ b/docs/source/api/tensorflow.mdx @@ -0,0 +1,6 @@ +# Tensorflow API + +[[autodoc]] safetensors.tensorflow.load_file +[[autodoc]] safetensors.tensorflow.load +[[autodoc]] safetensors.tensorflow.save_file +[[autodoc]] safetensors.tensorflow.save diff --git a/docs/source/api/torch.mdx b/docs/source/api/torch.mdx new file mode 100644 index 0000000..dbeffcf --- /dev/null +++ b/docs/source/api/torch.mdx @@ -0,0 +1,6 @@ +# Torch API + +[[autodoc]] safetensors.torch.load_file +[[autodoc]] safetensors.torch.load +[[autodoc]] safetensors.torch.save_file +[[autodoc]] safetensors.torch.save diff --git a/docs/source/index.mdx b/docs/source/index.mdx new file mode 100644 index 0000000..7af7f19 --- /dev/null +++ b/docs/source/index.mdx @@ -0,0 +1,42 @@ + + +# Safetensors + +Safetensors is a new simple format for storing tensors safely (as opposed to pickle) and that is still fast (zero-copy). + + +## Load tensors + +```python +from safetensors import safe_open + +tensors = {} +with safe_open("model.safetensors", framework="pt", device=0) as f: + for k in f.keys(): + tensors[k] = f.get_tensor(k) +``` + +Loading only part of the tensors (interesting when running on multiple GPU) + +```python +from safetensors import safe_open + +tensors = {} +with safe_open("model.safetensors", framework="pt", device=0) as f: + tensor_slice = f.get_slice("embedding") + vocab_size, hidden_dim = tensor_slice.get_shape() + tensor = tensor_slice[:, :hidden_dim] +``` + +## Save tensors + +```python +import torch +from safetensors.torch import save_file + +tensors = { + "embedding": torch.zeros((2, 2)), + "attention": torch.zeros((2, 3)) +} +save_file(tensors, "model.safetensors") +```