From 698dd6e137b9de9fc7a4ebea9adb6bb44ff6ddc1 Mon Sep 17 00:00:00 2001 From: Nicolas Patry Date: Thu, 17 Aug 2023 08:44:48 +0200 Subject: [PATCH] Fixing big endian. (#327) * Fixing big endian. - Many more tests, with numpy coverage. - Actually test values on disk. * Re-enabling bf16 (we piggy back f16 byteswap). * Fmt. * Black. --- .github/workflows/python.yml | 4 +- Dockerfile.s390x.test | 3 + bindings/python/py_src/safetensors/numpy.py | 16 ++-- bindings/python/py_src/safetensors/torch.py | 20 ++++- bindings/python/src/lib.rs | 89 +++++++++++++-------- bindings/python/tests/test_pt_comparison.py | 37 ++++++++- bindings/python/tests/test_pt_model.py | 31 ++++++- bindings/python/tests/test_simple.py | 15 ++++ 8 files changed, 168 insertions(+), 47 deletions(-) diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 7ee0bfb..3edfed1 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -114,5 +114,5 @@ jobs: 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 diff --git a/Dockerfile.s390x.test b/Dockerfile.s390x.test index ea18462..d1dc758 100644 --- a/Dockerfile.s390x.test +++ b/Dockerfile.s390x.test @@ -6,9 +6,12 @@ RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | bash -s -- -y 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 diff --git a/bindings/python/py_src/safetensors/numpy.py b/bindings/python/py_src/safetensors/numpy.py index 2ecc6ca..442270a 100644 --- a/bindings/python/py_src/safetensors/numpy.py +++ b/bindings/python/py_src/safetensors/numpy.py @@ -7,6 +7,12 @@ import numpy as np 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. @@ -32,10 +38,7 @@ def save(tensor_dict: Dict[str, np.ndarray], metadata: Optional[Dict[str, str]] 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 @@ -70,10 +73,7 @@ def save_file( 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) diff --git a/bindings/python/py_src/safetensors/torch.py b/bindings/python/py_src/safetensors/torch.py index 92af3f7..12d1f89 100644 --- a/bindings/python/py_src/safetensors/torch.py +++ b/bindings/python/py_src/safetensors/torch.py @@ -44,7 +44,6 @@ def storage_size(tensor: torch.Tensor) -> int: 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 @@ -378,6 +377,8 @@ def _view2torch(safeview) -> Dict[str, torch.Tensor]: 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 @@ -419,7 +420,22 @@ def _tobytes(tensor: torch.Tensor, name: str) -> bytes: 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() diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index d3decfa..a8c799b 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -377,34 +377,12 @@ impl Open { (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, @@ -509,18 +487,47 @@ impl Open { .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); @@ -809,11 +816,27 @@ impl PySafeSlice { .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__"))? diff --git a/bindings/python/tests/test_pt_comparison.py b/bindings/python/tests/test_pt_comparison.py index f8892c0..cb1a9f5 100644 --- a/bindings/python/tests/test_pt_comparison.py +++ b/bindings/python/tests/test_pt_comparison.py @@ -1,5 +1,5 @@ -import unittest import sys +import unittest import torch @@ -8,6 +8,40 @@ from safetensors.torch import load, load_file, save, save_file 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), @@ -15,6 +49,7 @@ class TorchTestCase(unittest.TestCase): "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"])) diff --git a/bindings/python/tests/test_pt_model.py b/bindings/python/tests/test_pt_model.py index 5862528..7614c33 100644 --- a/bindings/python/tests/test_pt_model.py +++ b/bindings/python/tests/test_pt_model.py @@ -15,6 +15,15 @@ from safetensors.torch import ( ) +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__() @@ -106,7 +115,7 @@ class TorchModelTestCase(unittest.TestCase): # 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) @@ -142,6 +151,26 @@ class TorchModelTestCase(unittest.TestCase): # 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") diff --git a/bindings/python/tests/test_simple.py b/bindings/python/tests/test_simple.py index 2283aa3..f121148 100644 --- a/bindings/python/tests/test_simple.py +++ b/bindings/python/tests/test_simple.py @@ -25,6 +25,14 @@ class TestCase(unittest.TestCase): 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}) @@ -33,6 +41,13 @@ class TestCase(unittest.TestCase): 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""" -- 2.43.0