* Fixing big endian.
- Many more tests, with numpy coverage.
- Actually test values on disk.
* Re-enabling bf16 (we piggy back f16 byteswap).
* Fmt.
* Black.
file: Dockerfile.s390x.test
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
- cache-from: type=registry,ref=registry.internal.huggingface.tech/safetensors/s390x:cache,mode=max
- cache-to: type=registry,ref=registry.internal.huggingface.tech/safetensors/s390x:cache,mode=max
+ cache-from: type=registry,ref=registry.internal.huggingface.tech/safetensors/s390x:cache,mode=min
+ cache-to: type=registry,ref=registry.internal.huggingface.tech/safetensors/s390x:cache,mode=min
RUN /root/miniconda3/bin/conda install pytorch cpuonly -c pytorch -y
WORKDIR /safetensors/
RUN /root/miniconda3/bin/pip install -U pip pytest
+# RUN /root/miniconda3/bin/pip install -U huggingface_hub
+# RUN /root/miniconda3/bin/python -c 'from huggingface_hub import hf_hub_download; filename = hf_hub_download("roberta-base", "model.safetensors")'
COPY . .
SHELL ["/bin/bash", "-c"]
WORKDIR /safetensors/bindings/python/
RUN source /root/.cargo/env && /root/miniconda3/bin/pip install -e .
RUN /root/miniconda3/bin/pytest -sv tests/test_pt_* tests/test_simple.py
+# RUN /root/miniconda3/bin/python -c 'from huggingface_hub import hf_hub_download; filename = hf_hub_download("roberta-base", "model.safetensors"); from safetensors.torch import load_file; weights = load_file(filename); assert weights["roberta.embeddings.position_embeddings.weight"][0][0].abs().item() > 1e-10'
ENTRYPOINT /bin/bash
from safetensors import deserialize, safe_open, serialize, serialize_file
+def _tobytes(tensor: np.ndarray) -> bytes:
+ if not _is_little_endian(tensor):
+ tensor = tensor.byteswap(inplace=False)
+ return tensor.tobytes()
+
+
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.
byte_data = save(tensors)
```
"""
- for tensor in tensor_dict.values():
- if not _is_little_endian(tensor):
- tensor.byteswap(inplace=True)
- flattened = {k: {"dtype": v.dtype.name, "shape": v.shape, "data": v.tobytes()} for k, v in tensor_dict.items()}
+ flattened = {k: {"dtype": v.dtype.name, "shape": v.shape, "data": _tobytes(v)} for k, v in tensor_dict.items()}
serialized = serialize(flattened, metadata=metadata)
result = bytes(serialized)
return result
save(tensors, "model.safetensors")
```
"""
- for tensor in tensor_dict.values():
- if not _is_little_endian(tensor):
- tensor.byteswap(inplace=True)
- flattened = {k: {"dtype": v.dtype.name, "shape": v.shape, "data": v.tobytes()} for k, v in tensor_dict.items()}
+ flattened = {k: {"dtype": v.dtype.name, "shape": v.shape, "data": _tobytes(v)} for k, v in tensor_dict.items()}
serialize_file(flattened, filename, metadata=metadata)
def _filter_shared_not_shared(tensors: List[Set[str]], state_dict: Dict[str, torch.Tensor]) -> List[Set[str]]:
filtered_tensors = []
for shared in tensors:
-
if len(shared) < 2:
filtered_tensors.append(shared)
continue
for k, v in safeview:
dtype = _getdtype(v["dtype"])
arr = torch.frombuffer(v["data"], dtype=dtype).reshape(v["shape"])
+ if sys.byteorder == "big":
+ arr = torch.from_numpy(arr.numpy().byteswap(inplace=False))
result[k] = arr
return result
newptr = ctypes.cast(ptr, ctypes.POINTER(ctypes.c_ubyte))
data = np.ctypeslib.as_array(newptr, (total_bytes,)) # no internal copy
if sys.byteorder == "big":
- data.byteswap(inplace=True)
+ NPDTYPES = {
+ torch.int64: np.int64,
+ torch.float32: np.float32,
+ torch.int32: np.int32,
+ # XXX: This is ok because both have the same width
+ torch.bfloat16: np.float16,
+ torch.float16: np.float16,
+ torch.int16: np.int16,
+ torch.uint8: np.uint8,
+ torch.int8: np.int8,
+ torch.bool: bool,
+ torch.float64: np.float64,
+ }
+ npdtype = NPDTYPES[tensor.dtype]
+ # Not in place as that would potentially modify a live running model
+ data = data.view(npdtype).byteswap(inplace=False)
return data.tobytes()
(intern!(py, "size"), intern!(py, "ByteStorage"))
};
- let sys = PyModule::import(py, intern!(py, "sys"))?;
- let byteorder: String = sys.getattr(intern!(py, "byteorder"))?.extract()?;
-
- let storage = if byteorder == "big" {
- let torch_uint8: PyObject = get_pydtype(module, Dtype::U8)?;
- let kwargs = [
- (intern!(py, "dtype"), torch_uint8),
- (intern!(py, "byte_order"), "big".into_py(py)),
- ]
- .into_py_dict(py);
- let builtins = PyModule::import(py, intern!(py, "builtins"))?;
- let py_buffer = builtins
- .getattr(intern!(py, "open"))?
- .call1((py_filename, intern!(py, "rb")))?
- .getattr(intern!(py, "read"))?
- .call0()?;
- module
- .getattr(storage_name)?
- .getattr(intern!(py, "from_buffer"))?
- .call((py_buffer,), Some(kwargs))?
- } else {
- let kwargs =
- [(intern!(py, "shared"), shared), (size_name, size)].into_py_dict(py);
- module
- .getattr(storage_name)?
- .getattr(intern!(py, "from_file"))?
- .call((py_filename,), Some(kwargs))?
- };
+ let kwargs =
+ [(intern!(py, "shared"), shared), (size_name, size)].into_py_dict(py);
+ let storage = module
+ .getattr(storage_name)?
+ .getattr(intern!(py, "from_file"))?
+ .call((py_filename,), Some(kwargs))?;
let untyped: &PyAny = match storage.getattr(intern!(py, "untyped")) {
Ok(untyped) => untyped,
.get(py)
.ok_or_else(|| SafetensorError::new_err("Could not find storage"))?;
let storage: &PyAny = storage.as_ref(py);
-
let storage_slice = storage
.getattr(intern!(py, "__getitem__"))?
.call1((slice,))?;
+ let sys = PyModule::import(py, intern!(py, "sys"))?;
+ let byteorder: String = sys.getattr(intern!(py, "byteorder"))?.extract()?;
+
let mut tensor = torch
.getattr(intern!(py, "asarray"))?
.call((storage_slice,), Some(kwargs))?
.getattr(intern!(py, "view"))?
- .call((), Some(view_kwargs))?
- .getattr(intern!(py, "reshape"))?
- .call1((shape,))?;
+ .call((), Some(view_kwargs))?;
+
+ if byteorder == "big" {
+ let inplace_kwargs =
+ [(intern!(py, "inplace"), false.into_py(py))].into_py_dict(py);
+ if info.dtype == Dtype::BF16 {
+ let torch_f16: PyObject = get_pydtype(torch, Dtype::F16)?;
+ tensor = tensor.getattr(intern!(py, "to"))?.call(
+ (),
+ Some([(intern!(py, "dtype"), torch_f16)].into_py_dict(py)),
+ )?;
+ }
+
+ let numpy = tensor
+ .getattr(intern!(py, "numpy"))?
+ .call0()?
+ .getattr("byteswap")?
+ .call((), Some(inplace_kwargs))?;
+ tensor = torch.getattr(intern!(py, "from_numpy"))?.call1((numpy,))?;
+
+ if info.dtype == Dtype::BF16 {
+ let torch_bf16: PyObject = get_pydtype(torch, Dtype::BF16)?;
+ tensor = tensor.getattr(intern!(py, "to"))?.call(
+ (),
+ Some([(intern!(py, "dtype"), torch_bf16)].into_py_dict(py)),
+ )?;
+ }
+ }
+
+ tensor = tensor.getattr(intern!(py, "reshape"))?.call1((shape,))?;
if self.device != Device::Cpu {
let device: PyObject = self.device.clone().into_py(py);
let kwargs = PyDict::new(py);
.call1((slice,))?;
let slices = slices.into_py(py);
+
+ let sys = PyModule::import(py, intern!(py, "sys"))?;
+ let byteorder: String = sys.getattr(intern!(py, "byteorder"))?.extract()?;
+
let mut tensor = torch
.getattr(intern!(py, "asarray"))?
.call((storage_slice,), Some(kwargs))?
.getattr(intern!(py, "view"))?
- .call((), Some(view_kwargs))?
+ .call((), Some(view_kwargs))?;
+ if byteorder == "big" {
+ let inplace_kwargs =
+ [(intern!(py, "inplace"), false.into_py(py))].into_py_dict(py);
+
+ let numpy = tensor
+ .getattr(intern!(py, "numpy"))?
+ .call0()?
+ .getattr("byteswap")?
+ .call((), Some(inplace_kwargs))?;
+ tensor = torch.getattr(intern!(py, "from_numpy"))?.call1((numpy,))?;
+ }
+ tensor = tensor
.getattr(intern!(py, "reshape"))?
.call1((shape,))?
.getattr(intern!(py, "__getitem__"))?
-import unittest
import sys
+import unittest
import torch
class TorchTestCase(unittest.TestCase):
+ def test_serialization(self):
+ data = torch.zeros((2, 2), dtype=torch.int32)
+ out = save({"test": data})
+
+ self.assertEqual(
+ out,
+ b'@\x00\x00\x00\x00\x00\x00\x00{"test":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]}} '
+ b" \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ )
+
+ save_file({"test": data}, "serialization.safetensors")
+ out = open("serialization.safetensors", "rb").read()
+ self.assertEqual(
+ out,
+ b'@\x00\x00\x00\x00\x00\x00\x00{"test":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]}} '
+ b" \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ )
+
+ data[1, 1] = 1
+ out = save({"test": data})
+
+ self.assertEqual(
+ out,
+ b'@\x00\x00\x00\x00\x00\x00\x00{"test":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]}} '
+ b" \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00",
+ )
+ save_file({"test": data}, "serialization.safetensors")
+ out = open("serialization.safetensors", "rb").read()
+ self.assertEqual(
+ out,
+ b'@\x00\x00\x00\x00\x00\x00\x00{"test":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]}} '
+ b" \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00",
+ )
+
def test_odd_dtype(self):
data = {
"test": torch.zeros((2, 2), dtype=torch.bfloat16),
"test3": torch.zeros((2, 2), dtype=torch.bool),
}
local = "./tests/data/out_safe_pt_mmap_small.safetensors"
+
save_file(data, local)
reloaded = load_file(local)
self.assertTrue(torch.equal(data["test"], reloaded["test"]))
)
+class OnesModel(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.a = torch.nn.Linear(4, 4)
+ self.a.weight = torch.nn.Parameter(torch.ones((4, 4)))
+ self.a.bias = torch.nn.Parameter(torch.ones((4,)))
+ self.b = self.a
+
+
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
# Then add the size of the datapoint 4 bytes
self.assertEqual(end - start, 16 * 3 + 4)
- ## FLOAT16
+ # FLOAT16
A = torch.zeros((4,), dtype=torch.float16)
start = A.data_ptr()
end = _end_ptr(A)
# save_model(model, "tmp4.safetensors")
# self.assertIn(".Refusing to save/load the model since you could be storing much more memory than needed.", str(ctx.exception))
+ def test_save(self):
+ # Just testing the actual saved file to make sure we're ok on big endian
+ model = OnesModel()
+ save_model(model, "tmp_ones.safetensors")
+ with safe_open("tmp_ones.safetensors", framework="pt") as f:
+ self.assertEqual(f.metadata(), {"b.bias": "a.bias", "b.weight": "a.weight"})
+
+ # 192 hardcoded to skip the header, metadata order is random.
+ self.assertEqual(
+ open("tmp_ones.safetensors", "rb").read()[192:],
+ b"""\x00\x00\x80?\x00\x00\x80?\x00\x00\x80?\x00\x00\x80?\x00\x00\x80?\x00\x00\x80?\x00\x00\x80?\x00\x00\x80?\x00\x00\x80?\x00\x00\x80?\x00\x00\x80?\x00\x00\x80?\x00\x00\x80?\x00\x00\x80?\x00\x00\x80?\x00\x00\x80?\x00\x00\x80?\x00\x00\x80?\x00\x00\x80?\x00\x00\x80?""",
+ )
+
+ model2 = OnesModel()
+ load_model(model2, "tmp_ones.safetensors")
+
+ state_dict = model.state_dict()
+ for k, v in model2.state_dict().items():
+ torch.testing.assert_close(v, state_dict[k])
+
def test_workaround(self):
model = Model()
save_model(model, "tmp.safetensors")
b" \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
)
+ save_file({"test": data}, "serialization.safetensors")
+ out = open("serialization.safetensors", "rb").read()
+ self.assertEqual(
+ out,
+ b'@\x00\x00\x00\x00\x00\x00\x00{"test":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]}} '
+ b" \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
+ )
+
data[1, 1] = 1
out = save({"test": data})
b'@\x00\x00\x00\x00\x00\x00\x00{"test":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]}} '
b" \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00",
)
+ save_file({"test": data}, "serialization.safetensors")
+ out = open("serialization.safetensors", "rb").read()
+ self.assertEqual(
+ out,
+ b'@\x00\x00\x00\x00\x00\x00\x00{"test":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]}} '
+ b" \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00",
+ )
def test_deserialization(self):
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"""