]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Fixing big endian. (#327)
authorNicolas Patry <patry.nicolas@protonmail.com>
Thu, 17 Aug 2023 06:44:48 +0000 (08:44 +0200)
committerGitHub <noreply@github.com>
Thu, 17 Aug 2023 06:44:48 +0000 (08:44 +0200)
* 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
Dockerfile.s390x.test
bindings/python/py_src/safetensors/numpy.py
bindings/python/py_src/safetensors/torch.py
bindings/python/src/lib.rs
bindings/python/tests/test_pt_comparison.py
bindings/python/tests/test_pt_model.py
bindings/python/tests/test_simple.py

index 7ee0bfb2f3471afd73b1a9fe526677af2ec6fc1e..3edfed1a2bc80704a1705ce663216e124d924637 100644 (file)
@@ -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
index ea18462100c32aa49a837f665e71cb721c23cc95..d1dc75830bc5931f655b7836bbec7b0482caba01 100644 (file)
@@ -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
index 2ecc6ca6c7fedfd7d77e6f7c1e778015657f9600..442270a0ce623d9fc1e804fefef25ec2d35c2c07 100644 (file)
@@ -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)
 
 
index 92af3f7fd90a80f8f831b0bcf9a8700e23a8e45b..12d1f89316e9631fbc28a8fc2b73a5f39537a61b 100644 (file)
@@ -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()
 
 
index d3decfab24229221c8185ccde0e05e61e35a5f4b..a8c799b7531259d16e32b8f666c04ba674ffd5fa 100644 (file)
@@ -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__"))?
index f8892c0dc1fb0cecd6db647099cd1a58be081dee..cb1a9f577a62fed82e24d3845914e8b8107aa7e3 100644 (file)
@@ -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"]))
index 5862528881cc1d5bed4ff0875f5c7eea98e57cfe..7614c33b3e5b51533700173749234010f4740147 100644 (file)
@@ -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")
index 2283aa362d0b1a684266a9baa78c1245aeadd757..f1211483cd4353b8c438ab17de02749c28209139 100644 (file)
@@ -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"""