* Adding MLX backend.
* Apply suggestions from code review
Co-authored-by: Pedro Cuenca <pedro@huggingface.co>
* Update bindings/python/py_src/safetensors/mlx.py
Co-authored-by: Pedro Cuenca <pedro@huggingface.co>
* Update bindings/python/py_src/safetensors/mlx.py
Co-authored-by: Pedro Cuenca <pedro@huggingface.co>
---------
Co-authored-by: Pedro Cuenca <pedro@huggingface.co>
--- /dev/null
+import os
+import tempfile
+
+import mlx.core as mx
+from safetensors.mlx import load_file, save_file
+
+
+def create_gpt2(n_layers: int):
+ tensors = {}
+ tensors["wte"] = mx.zeros((50257, 768))
+ tensors["wpe"] = mx.zeros((1024, 768))
+ for i in range(n_layers):
+ tensors[f"h.{i}.ln_1.weight"] = mx.zeros((768,))
+ tensors[f"h.{i}.ln_1.bias"] = mx.zeros((768,))
+ tensors[f"h.{i}.attn.bias"] = mx.zeros((1, 1, 1024, 1024))
+ tensors[f"h.{i}.attn.c_attn.weight"] = mx.zeros((768, 2304))
+ tensors[f"h.{i}.attn.c_attn.bias"] = mx.zeros((2304))
+ tensors[f"h.{i}.attn.c_proj.weight"] = mx.zeros((768, 768))
+ tensors[f"h.{i}.attn.c_proj.bias"] = mx.zeros((768))
+ tensors[f"h.{i}.ln_2.weight"] = mx.zeros((768))
+ tensors[f"h.{i}.ln_2.bias"] = mx.zeros((768))
+ tensors[f"h.{i}.mlp.c_fc.weight"] = mx.zeros((768, 3072))
+ tensors[f"h.{i}.mlp.c_fc.bias"] = mx.zeros((3072))
+ tensors[f"h.{i}.mlp.c_proj.weight"] = mx.zeros((3072, 768))
+ tensors[f"h.{i}.mlp.c_proj.bias"] = mx.zeros((768))
+ tensors["ln_f.weight"] = mx.zeros((768))
+ tensors["ln_f.bias"] = mx.zeros((768))
+ return tensors
+
+
+def load(filename):
+ return mx.load(filename)
+
+
+def test_mlx_mlx_load(benchmark):
+ # benchmark something
+ weights = create_gpt2(12)
+ with tempfile.NamedTemporaryFile(delete=False) as f:
+ filename = f"{f.name}.npz"
+ mx.savez(filename, **weights)
+ result = benchmark(load, filename)
+ os.unlink(f.name)
+
+ for k, v in weights.items():
+ tv = result[k]
+ assert mx.allclose(v, tv)
+
+
+def test_mlx_sf_load(benchmark):
+ # benchmark something
+ weights = create_gpt2(12)
+ with tempfile.NamedTemporaryFile(delete=False) as f:
+ save_file(weights, f.name)
+ result = benchmark(load_file, f.name)
+ os.unlink(f.name)
+
+ for k, v in weights.items():
+ tv = result[k]
+ assert mx.allclose(v, tv)
--- /dev/null
+import os
+from typing import Dict, Optional, Union
+
+import numpy as np
+
+import mlx.core as mx
+from safetensors import numpy, safe_open
+
+
+def save(tensors: Dict[str, mx.array], metadata: Optional[Dict[str, str]] = None) -> bytes:
+ """
+ Saves a dictionary of tensors into raw bytes in safetensors format.
+
+ Args:
+ tensors (`Dict[str, mx.array]`):
+ 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.mlx import save
+ import mlx.core as mx
+
+ tensors = {"embedding": mx.zeros((512, 1024)), "attention": mx.zeros((256, 256))}
+ byte_data = save(tensors)
+ ```
+ """
+ np_tensors = _mx2np(tensors)
+ return numpy.save(np_tensors, metadata=metadata)
+
+
+def save_file(
+ tensors: Dict[str, mx.array],
+ filename: Union[str, os.PathLike],
+ metadata: Optional[Dict[str, str]] = None,
+) -> None:
+ """
+ Saves a dictionary of tensors into raw bytes in safetensors format.
+
+ Args:
+ tensors (`Dict[str, mx.array]`):
+ The incoming tensors. Tensors need to be contiguous and dense.
+ filename (`str`, or `os.PathLike`)):
+ 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.mlx import save_file
+ import mlx.core as mx
+
+ tensors = {"embedding": mx.zeros((512, 1024)), "attention": mx.zeros((256, 256))}
+ save_file(tensors, "model.safetensors")
+ ```
+ """
+ np_tensors = _mx2np(tensors)
+ return numpy.save_file(np_tensors, filename, metadata=metadata)
+
+
+def load(data: bytes) -> Dict[str, mx.array]:
+ """
+ Loads a safetensors file into MLX format from pure bytes.
+
+ Args:
+ data (`bytes`):
+ The content of a safetensors file
+
+ Returns:
+ `Dict[str, mx.array]`: dictionary that contains name as key, value as `mx.array`
+
+ Example:
+
+ ```python
+ from safetensors.mlx 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 _np2mx(flat)
+
+
+def load_file(filename: Union[str, os.PathLike]) -> Dict[str, mx.array]:
+ """
+ Loads a safetensors file into MLX format.
+
+ Args:
+ filename (`str`, or `os.PathLike`)):
+ The name of the file which contains the tensors
+
+ Returns:
+ `Dict[str, mx.array]`: dictionary that contains name as key, value as `mx.array`
+
+ Example:
+
+ ```python
+ from safetensors.flax import load_file
+
+ file_path = "./my_folder/bert.safetensors"
+ loaded = load_file(file_path)
+ ```
+ """
+ result = {}
+ with safe_open(filename, framework="mlx") as f:
+ for k in f.keys():
+ result[k] = f.get_tensor(k)
+ return result
+
+
+def _np2mx(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, mx.array]:
+ for k, v in numpy_dict.items():
+ numpy_dict[k] = mx.array(v)
+ return numpy_dict
+
+
+def _mx2np(mx_dict: Dict[str, mx.array]) -> Dict[str, np.array]:
+ new_dict = {}
+ for k, v in mx_dict.items():
+ new_dict[k] = np.asarray(v)
+ return new_dict
static NUMPY_MODULE: GILOnceCell<Py<PyModule>> = GILOnceCell::new();
static TENSORFLOW_MODULE: GILOnceCell<Py<PyModule>> = GILOnceCell::new();
static FLAX_MODULE: GILOnceCell<Py<PyModule>> = GILOnceCell::new();
+static MLX_MODULE: GILOnceCell<Py<PyModule>> = GILOnceCell::new();
fn prepare(tensor_dict: HashMap<String, &PyDict>) -> PyResult<HashMap<String, TensorView<'_>>> {
let mut tensors = HashMap::with_capacity(tensor_dict.len());
Numpy,
Tensorflow,
Flax,
+ Mlx,
}
impl<'source> FromPyObject<'source> for Framework {
"jax" => Ok(Framework::Flax),
"flax" => Ok(Framework::Flax),
+ "mlx" => Ok(Framework::Mlx),
name => Err(SafetensorError::new_err(format!(
"framework {name} is invalid"
))),
.getattr(intern!(py, "convert_to_tensor"))?
.call1((tensor,))?
}
+ Framework::Mlx => {
+ let module = Python::with_gil(|py| -> PyResult<&Py<PyModule>> {
+ let module = PyModule::import(py, intern!(py, "mlx"))?;
+ Ok(MLX_MODULE.get_or_init(py, || module.into()))
+ })?
+ .as_ref(py);
+ module
+ .getattr(intern!(py, "core"))?
+ .getattr(intern!(py, "array"))?
+ .call1((tensor,))?
+ }
Framework::Pytorch => {
if device != &Device::Cpu {
let device: PyObject = device.clone().into_py(py);
}
tensor
}
- _ => tensor,
+ Framework::Numpy => tensor,
};
let tensor = tensor.into_py(py);
Ok(tensor)
--- /dev/null
+import platform
+import unittest
+
+
+if platform.system() == "Darwin":
+ # This platform is not supported, we don't want to crash on import
+ # This test will be skipped anyway.
+ import mlx.core as mx
+ from safetensors import safe_open
+ from safetensors.mlx import load_file, save_file
+
+
+# MLX only exists on Mac
+@unittest.skipIf(platform.system() != "Darwin", "Mlx is not available on non Mac")
+class LoadTestCase(unittest.TestCase):
+ def setUp(self):
+ data = {
+ "test": mx.zeros((1024, 1024), dtype=mx.float32),
+ "test2": mx.zeros((1024, 1024), dtype=mx.float32),
+ "test3": mx.zeros((1024, 1024), dtype=mx.float32),
+ "test4": mx.zeros((1024, 1024), dtype=mx.bfloat16),
+ }
+ self.mlx_filename = "./tests/data/mlx_load.npz"
+ self.sf_filename = "./tests/data/mlx_load.safetensors"
+
+ serialized = mx.savez(self.mlx_filename, **data)
+ save_file(data, self.sf_filename)
+
+ def test_zero_sized(self):
+ data = {
+ "test": mx.zeros((2, 0), dtype=mx.float32),
+ }
+ local = "./tests/data/out_safe_flat_mmap_small2.safetensors"
+ save_file(data.copy(), local)
+ reloaded = load_file(local)
+ # Empty tensor != empty tensor on numpy, so comparing shapes
+ # instead
+ self.assertEqual(data["test"].shape, reloaded["test"].shape)
+
+ def test_deserialization_safe(self):
+ weights = load_file(self.sf_filename)
+
+ mlx_weights = mx.load(self.mlx_filename)
+
+ for k, v in weights.items():
+ tv = mlx_weights[k]
+ self.assertTrue(mx.allclose(v, tv))
+
+ def test_deserialization_safe_open(self):
+ weights = {}
+ with safe_open(self.sf_filename, framework="mlx") as f:
+ for k in f.keys():
+ weights[k] = f.get_tensor(k)
+
+ mlx_weights = mx.load(self.mlx_filename)
+
+ for k, v in weights.items():
+ tv = mlx_weights[k]
+ self.assertTrue(mx.allclose(v, tv))