From 2bb7ace99104da75fd7bc53465c81a5521d1900c Mon Sep 17 00:00:00 2001 From: Nicolas Patry Date: Fri, 18 Nov 2022 10:19:27 +0100 Subject: [PATCH] Preventing big endian files to be saved. (#82) --- bindings/python/py_src/safetensors/numpy.py | 15 +++++++++++++++ bindings/python/py_src/safetensors/torch.py | 3 +++ bindings/python/tests/test_simple.py | 6 ++++++ 3 files changed, 24 insertions(+) diff --git a/bindings/python/py_src/safetensors/numpy.py b/bindings/python/py_src/safetensors/numpy.py index 63a208d..e91ed3e 100644 --- a/bindings/python/py_src/safetensors/numpy.py +++ b/bindings/python/py_src/safetensors/numpy.py @@ -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 diff --git a/bindings/python/py_src/safetensors/torch.py b/bindings/python/py_src/safetensors/torch.py index 2c4740e..55814b7 100644 --- a/bindings/python/py_src/safetensors/torch.py +++ b/bindings/python/py_src/safetensors/torch.py @@ -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: diff --git a/bindings/python/tests/test_simple.py b/bindings/python/tests/test_simple.py index e079acc..18b1290 100644 --- a/bindings/python/tests/test_simple.py +++ b/bindings/python/tests/test_simple.py @@ -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): -- 2.43.0