]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Preventing big endian files to be saved. (#82)
authorNicolas Patry <patry.nicolas@protonmail.com>
Fri, 18 Nov 2022 09:19:27 +0000 (10:19 +0100)
committerGitHub <noreply@github.com>
Fri, 18 Nov 2022 09:19:27 +0000 (10:19 +0100)
bindings/python/py_src/safetensors/numpy.py
bindings/python/py_src/safetensors/torch.py
bindings/python/tests/test_simple.py

index 63a208d687ed2e72fc4294d946aca3f641a71d8c..e91ed3e94b1285f93a0f497475a1e510dbbd7fdb 100644 (file)
@@ -1,3 +1,4 @@
+import sys
 from typing import Dict, Optional
 
 import numpy as np
@@ -30,6 +31,10 @@ def save(tensor_dict: Dict[str, np.ndarray], metadata: Optional[Dict[str, str]]
     byte_data = save(tensors)
     ```
     """
+    for tensor in tensor_dict.values():
+        byte_order = _byte_order(tensor)
+        if byte_order != "<":
+            raise ValueError("Safetensor format only accepts little endian")
     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)
@@ -151,3 +156,13 @@ def _view2np(safeview) -> Dict[str, np.ndarray]:
         arr = np.frombuffer(v["data"], dtype=dtype).reshape(v["shape"])
         result[k] = arr
     return result
+
+
+def _byte_order(tensor: np.ndarray) -> str:
+    byteorder = tensor.dtype.byteorder
+    if byteorder == "=":
+        if sys.byteorder == "little":
+            return "<"
+        else:
+            return ">"
+    return byteorder
index 2c4740ec2502e08d86eb9ddbde50c568c11797ea..55814b70ac1ddb1c6c7328cd9a18a00954d6546a 100644 (file)
@@ -1,3 +1,4 @@
+import sys
 from collections import defaultdict
 from typing import Any, Dict, Optional
 
@@ -206,6 +207,8 @@ def _tobytes(tensor: torch.Tensor, name: str) -> bytes:
 
 
 def _flatten(tensors: Dict[str, torch.Tensor]) -> Dict[str, Dict[str, Any]]:
+    if sys.byteorder == "big":
+        raise ValueError("Big endian is not supported, serialization need to be in little endian")
     ptrs = defaultdict(set)
     for k, v in tensors.items():
         if v.layout == torch.strided:
index e079acc2098392464c25a64fc5529e78d1beb79e..18b1290386972ec5c6a3970c015010995c1c9925 100644 (file)
@@ -40,6 +40,12 @@ class TestCase(unittest.TestCase):
 
         self.assertEqual(out1, out2)
 
+    def test_serialization_no_big_endian(self):
+        # Big endian tensor
+        data = np.zeros((2, 2), dtype=">u4")
+        with self.assertRaises(ValueError):
+            save({"test1": data})
+
 
 class ReadmeTestCase(unittest.TestCase):
     def assertTensorEqual(self, tensors1, tensors2, equality_fn):