From 9ebf05848467f2fb255039a83649c462875c3b95 Mon Sep 17 00:00:00 2001 From: Nicolas Patry Date: Wed, 5 Oct 2022 10:18:56 +0200 Subject: [PATCH] Refusing to save non contiguous tensors now. (#17) * Refusing to save non contiguous tensors now. Refusing to save non contiguous tensors now. It causes weird issues. 1/ It is hard to make it play well with lazy-loading since you would have 2 call sites, 1 needing to refer to some mother tensor (and potentially a whole graph of them) that might not yet exist. ```python x = torch.zeros((20, 20)) y = x[:, 0] torch.save([x, y], filename) x1, y1 = torch.load(filename) y1.fill_(1) ``` This exists because some two different tensors can refer to the same buffer with different striding, and pytorch save can persist them. This library and format doesn't enable that so we should just discard them. 2/ There was a bug when saving from something else than `cpu` because the pointer would point to a GPU address for instance so every tensor needs to be brought back before saving (Unless there's a better way). 3/ Disable saving sparse tensors. Forcing contiguous tensors from PT. * Black. * Fixing sparse. * Skip if no gpu. * X * Y. * Update bindings/python/py_src/safetensors/torch.py Co-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com> * Updating quality. * Rewrite warning multiline. * Remove `doc-builder` not there yet. * Factor out flattening. * Forgot the workflows. Co-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com> --- .github/workflows/python.yml | 4 +- .pre-commit-config.yaml | 51 ++++++++++++++++++ bindings/python/Makefile | 35 ++++++++++++ .../python/py_src/safetensors/__init__.py | 2 +- bindings/python/py_src/safetensors/flax.py | 6 ++- bindings/python/py_src/safetensors/numpy.py | 16 +++--- .../python/py_src/safetensors/tensorflow.py | 6 ++- bindings/python/py_src/safetensors/torch.py | 50 ++++++++++++----- bindings/python/pyproject.toml | 3 ++ bindings/python/setup.cfg | 54 +++++++++++++++++++ bindings/python/setup.py | 8 +-- bindings/python/tests/test_flax_comparison.py | 13 +++-- bindings/python/tests/test_pt_comparison.py | 38 +++++++++++-- bindings/python/tests/test_simple.py | 7 ++- bindings/python/tests/test_tf_comparison.py | 11 ++-- 15 files changed, 255 insertions(+), 49 deletions(-) create mode 100644 .pre-commit-config.yaml create mode 100644 bindings/python/Makefile create mode 100644 bindings/python/pyproject.toml create mode 100644 bindings/python/setup.cfg diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 3867df1..8ebcc34 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -62,8 +62,8 @@ jobs: - name: Check style working-directory: ./bindings/python run: | - pip install black==20.8b1 click==8.0.4 - black --check --line-length 100 --target-version py36 py_src/safetensors tests + pip install black==22.3 click==8.0.4 + black --check --line-length 119 --target-version py35 py_src/safetensors tests - name: Run tests working-directory: ./bindings/python diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..a37f05c --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,51 @@ +repos: + - repo: https://github.com/Narsil/pre-commit-rust + rev: 0c016cee78144d06d906fccc7715d607a946ca5c + hooks: + - id: fmt + name: "Rust (fmt)" + args: ["--manifest-path", "safetensors/Cargo.toml", "--"] + - id: clippy + name: "Rust (clippy)" + args: + [ + "--manifest-path", + "safetensors/Cargo.toml", + "--all-features", + "--all-targets", + "--", + "-Dwarnings", + ] + - repo: https://github.com/Narsil/pre-commit-rust + rev: 0c016cee78144d06d906fccc7715d607a946ca5c + hooks: + - id: fmt + name: "Python (fmt)" + args: ["--manifest-path", "bindings/python/Cargo.toml", "--"] + - id: clippy + name: "Python (clippy)" + args: + [ + "--manifest-path", + "bindings/python/Cargo.toml", + "--all-features", + "--all-targets", + "--", + "-Dwarnings", + ] + - repo: https://github.com/psf/black + rev: 22.3.0 + hooks: + - id: black + name: "Python (black)" + args: ["--line-length", "119", "--target-version", "py35"] + types: ["python"] + - repo: https://gitlab.com/pycqa/flake8 + rev: 3.8.3 + hooks: + - id: flake8 + args: ["--config", "bindings/python/setup.cfg"] + - repo: https://github.com/pre-commit/mirrors-isort + rev: v5.7.0 # Use the revision sha / tag you want to point at + hooks: + - id: isort diff --git a/bindings/python/Makefile b/bindings/python/Makefile new file mode 100644 index 0000000..0a4bcba --- /dev/null +++ b/bindings/python/Makefile @@ -0,0 +1,35 @@ +.PHONY: deps_table_update modified_only_fixup extra_style_checks quality style fixup fix-copies test test-examples + +# make sure to test the local checkout in scripts and not the pre-installed one (don't use quotes!) +export PYTHONPATH = src + +check_dirs := tests py_src + +modified_only_fixup: + $(eval modified_py_files := $(shell python utils/get_modified_files.py $(check_dirs))) + @if test -n "$(modified_py_files)"; then \ + echo "Checking/fixing $(modified_py_files)"; \ + black --preview $(modified_py_files); \ + isort $(modified_py_files); \ + flake8 $(modified_py_files); \ + else \ + echo "No library .py files were modified"; \ + fi + + +quality: + black --check --preview $(check_dirs) + isort --check-only $(check_dirs) + flake8 $(check_dirs) + # doc-builder style src/transformers docs/source --max_len 119 --check_only --path_to_docs docs/source + +style: + black --preview $(check_dirs) + isort $(check_dirs) + +# Super fast fix and check target that only works on relevant modified files since the branch was made + +fixup: modified_only_fixup + +test: + python -m pytest -n auto --dist=loadfile -s -v ./tests/ diff --git a/bindings/python/py_src/safetensors/__init__.py b/bindings/python/py_src/safetensors/__init__.py index dae903a..c2480d1 100644 --- a/bindings/python/py_src/safetensors/__init__.py +++ b/bindings/python/py_src/safetensors/__init__.py @@ -1,4 +1,4 @@ __version__ = "0.2.1.dev0" # Re-export this -from .safetensors_rust import safe_open +from .safetensors_rust import safe_open # noqa: F401 diff --git a/bindings/python/py_src/safetensors/flax.py b/bindings/python/py_src/safetensors/flax.py index 7ad527c..da91bea 100644 --- a/bindings/python/py_src/safetensors/flax.py +++ b/bindings/python/py_src/safetensors/flax.py @@ -1,7 +1,9 @@ -from safetensors import numpy -import numpy as np from typing import Dict, Optional + +import numpy as np + import jax.numpy as jnp +from safetensors import numpy def _np2jnp(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, jnp.DeviceArray]: diff --git a/bindings/python/py_src/safetensors/numpy.py b/bindings/python/py_src/safetensors/numpy.py index bbce500..da99b1a 100644 --- a/bindings/python/py_src/safetensors/numpy.py +++ b/bindings/python/py_src/safetensors/numpy.py @@ -1,13 +1,12 @@ -import numpy as np -from .safetensors_rust import serialize, serialize_file, safe_open, deserialize from typing import Dict, Optional +import numpy as np + +from .safetensors_rust import deserialize, safe_open, serialize, serialize_file + def save(tensor_dict: Dict[str, np.ndarray], metadata: Optional[Dict[str, str]] = None) -> bytes: - 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": v.tobytes()} for k, v in tensor_dict.items()} serialized = serialize(flattened, metadata=metadata) result = bytes(serialized) return result @@ -27,10 +26,7 @@ def load_file(filename: str) -> Dict[str, np.ndarray]: def save_file(tensor_dict: Dict[str, np.ndarray], filename: str): - 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": v.tobytes()} for k, v in tensor_dict.items()} serialize_file(flattened, filename) diff --git a/bindings/python/py_src/safetensors/tensorflow.py b/bindings/python/py_src/safetensors/tensorflow.py index a47293d..df98475 100644 --- a/bindings/python/py_src/safetensors/tensorflow.py +++ b/bindings/python/py_src/safetensors/tensorflow.py @@ -1,8 +1,10 @@ -from safetensors import numpy -import numpy as np from typing import Dict, Optional + +import numpy as np import tensorflow as tf +from safetensors import numpy + def _np2tf(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, tf.Tensor]: for k, v in numpy_dict.items(): diff --git a/bindings/python/py_src/safetensors/torch.py b/bindings/python/py_src/safetensors/torch.py index 8e36a93..ac234e0 100644 --- a/bindings/python/py_src/safetensors/torch.py +++ b/bindings/python/py_src/safetensors/torch.py @@ -1,16 +1,23 @@ -from .safetensors_rust import serialize_file, serialize, safe_open, deserialize -import math -from typing import Dict, Optional +from typing import Any, Dict, Optional import torch +from .safetensors_rust import deserialize, safe_open, serialize, serialize_file -def save(tensors: Dict[str, torch.Tensor], metadata: Optional[Dict[str, str]] = None) -> bytes: - flattened = { - k: {"dtype": str(v.dtype).split(".")[-1], "shape": v.shape, "data": _tobytes(v)} + +def _flatten(tensors: Dict[str, torch.Tensor]) -> Dict[str, Dict[str, Any]]: + return { + k: { + "dtype": str(v.dtype).split(".")[-1], + "shape": v.shape, + "data": _tobytes(v, k), + } for k, v in tensors.items() } - serialized = serialize(flattened, metadata=metadata) + + +def save(tensors: Dict[str, torch.Tensor], metadata: Optional[Dict[str, str]] = None) -> bytes: + serialized = serialize(_flatten(tensors), metadata=metadata) result = bytes(serialized) return result @@ -20,11 +27,7 @@ def save_file( filename: str, metadata: Optional[Dict[str, str]] = None, ): - flattened = { - k: {"dtype": str(v.dtype).split(".")[-1], "shape": v.shape, "data": _tobytes(v)} - for k, v in tensors.items() - } - serialize_file(flattened, filename, metadata=metadata) + serialize_file(_flatten(tensors), filename, metadata=metadata) def load_file(filename: str) -> Dict[str, torch.Tensor]: @@ -80,8 +83,29 @@ def _view2torch(safeview) -> Dict[str, torch.Tensor]: result[k] = arr -def _tobytes(tensor: torch.Tensor) -> bytes: +def _tobytes(tensor: torch.Tensor, name: str) -> bytes: + + try: + if not tensor.is_contiguous(): + raise ValueError( + f"You are trying to save a non contiguous tensor: `{name}` which is not allowed. It either means you" + " are trying to save tensors which are reference of each other in which case it's recommended to save" + " only the full tensors, and reslice at load time, or simply call `.contiguous()` on your tensor to" + " pack it before saving." + ) + except RuntimeError: + # This occurs with sparse tensors + raise ValueError( + f"You are trying to save a sparse tensor: `{name}` which this library does not support." + " You can make it a dense tensor before saving with `.to_dense()` but be aware this might" + " make a much larger file than needed." + ) + if tensor.device.type != "cpu": + # Moving tensor to cpu before saving + tensor = tensor.to("cpu") + import ctypes + import numpy as np length = np.prod(tensor.shape).item() diff --git a/bindings/python/pyproject.toml b/bindings/python/pyproject.toml new file mode 100644 index 0000000..291558c --- /dev/null +++ b/bindings/python/pyproject.toml @@ -0,0 +1,3 @@ +[tool.black] +line-length = 119 +target-version = ['py35'] diff --git a/bindings/python/setup.cfg b/bindings/python/setup.cfg new file mode 100644 index 0000000..2d605cc --- /dev/null +++ b/bindings/python/setup.cfg @@ -0,0 +1,54 @@ +[isort] +default_section = FIRSTPARTY +ensure_newline_before_comments = True +force_grid_wrap = 0 +include_trailing_comma = True +known_first_party = transformers +known_third_party = + absl + conllu + datasets + elasticsearch + fairseq + faiss-cpu + fastprogress + fire + fugashi + git + h5py + matplotlib + nltk + numpy + packaging + pandas + PIL + psutil + pytest + pytorch_lightning + rouge_score + sacrebleu + seqeval + sklearn + streamlit + tensorboardX + tensorflow + tensorflow_datasets + timeout_decorator + torch + torchaudio + torchtext + torchvision + torch_xla + tqdm + +line_length = 119 +lines_after_imports = 2 +multi_line_output = 3 +use_parentheses = True + +[flake8] +ignore = E203, E501, E741, W503, W605 +max-line-length = 119 + +[tool:pytest] +doctest_optionflags=NUMBER NORMALIZE_WHITESPACE ELLIPSIS \ No newline at end of file diff --git a/bindings/python/setup.py b/bindings/python/setup.py index d7cdec7..17589ce 100644 --- a/bindings/python/setup.py +++ b/bindings/python/setup.py @@ -1,8 +1,12 @@ from setuptools import setup from setuptools_rust import Binding, RustExtension + extras = {} extras["testing"] = [ + "black==22.3", # after updating to black 2023, also update Python version in pyproject.toml to 3.7 + "isort>=5.5.4", + "flake8>=3.8.3", "pytest", "numpy", ] @@ -19,9 +23,7 @@ setup( author_email="", url="https://github.com/huggingface/safetensors", license="Apache License 2.0", - rust_extensions=[ - RustExtension("safetensors.safetensors_rust", binding=Binding.PyO3, debug=False) - ], + rust_extensions=[RustExtension("safetensors.safetensors_rust", binding=Binding.PyO3, debug=False)], extras_require=extras, classifiers=[ "Development Status :: 5 - Production/Stable", diff --git a/bindings/python/tests/test_flax_comparison.py b/bindings/python/tests/test_flax_comparison.py index 4329bbc..1595641 100644 --- a/bindings/python/tests/test_flax_comparison.py +++ b/bindings/python/tests/test_flax_comparison.py @@ -1,16 +1,19 @@ -import unittest -from huggingface_hub import hf_hub_download -import numpy as np import datetime import os import platform +import unittest + +import numpy as np + +from huggingface_hub import hf_hub_download + if platform.system() != "Windows": # This platform is not supported, we don't want to crash on import # This test will be skipped anyway. - from safetensors.flax import save_file, load_file - from flax.serialization import msgpack_restore, msgpack_serialize import jax.numpy as jnp + from flax.serialization import msgpack_restore, msgpack_serialize + from safetensors.flax import load_file, save_file MODEL_ID = os.getenv("MODEL_ID", "gpt2") diff --git a/bindings/python/tests/test_pt_comparison.py b/bindings/python/tests/test_pt_comparison.py index e3c7f1e..319839b 100644 --- a/bindings/python/tests/test_pt_comparison.py +++ b/bindings/python/tests/test_pt_comparison.py @@ -1,10 +1,12 @@ -import unittest -from safetensors.torch import save_file, load_file -from safetensors.safetensors_rust import safe_open -from huggingface_hub import hf_hub_download -import torch import datetime import os +import unittest + +import torch + +from huggingface_hub import hf_hub_download +from safetensors.safetensors_rust import safe_open +from safetensors.torch import load_file, save_file MODEL_ID = os.getenv("MODEL_ID", "gpt2") @@ -24,6 +26,22 @@ class TorchTestCase(unittest.TestCase): self.assertTrue(torch.equal(data["test2"], reloaded["test2"])) self.assertTrue(torch.equal(data["test3"], reloaded["test3"])) + @unittest.skipIf(not torch.cuda.is_available(), "Cuda is not available") + def test_gpu(self): + data = { + "test": torch.arange(4).view((2, 2)).to("cuda:0"), + } + local = "./tests/data/out_safe_pt_mmap.bin" + save_file(data, local) + reloaded = load_file(local) + self.assertTrue(torch.equal(torch.arange(4).view((2, 2)), reloaded["test"])) + + def test_sparse(self): + data = {"test": torch.sparse_coo_tensor(size=(2, 3))} + local = "./tests/data/out_safe_pt_sparse.bin" + with self.assertRaises(ValueError): + save_file(data, local) + class SpeedTestCase(unittest.TestCase): def setUp(self): @@ -73,6 +91,16 @@ class SliceTestCase(unittest.TestCase): # Need to copy since that call mutates the tensors to numpy save_file(self.data.copy(), self.local) + def test_cannot_serialize_a_non_contiguous_tensor(self): + tensor = torch.arange(6, dtype=torch.float32).reshape((1, 2, 3)) + x = tensor[:, :, 1] + data = {"test": x} + self.assertFalse( + x.is_contiguous(), + ) + with self.assertRaises(ValueError): + save_file(data, "./tests/data/out.bin") + def test_deserialization_slice(self): with safe_open(self.local, framework="pt") as f: tensor = f.get_slice("test")[:, :, 1:2] diff --git a/bindings/python/tests/test_simple.py b/bindings/python/tests/test_simple.py index abd6b6b..c92cebd 100644 --- a/bindings/python/tests/test_simple.py +++ b/bindings/python/tests/test_simple.py @@ -1,9 +1,12 @@ import unittest -from safetensors.numpy import save, load, save_file, load_file -from safetensors.torch import load_file as load_file_pt, save_file as save_file_pt + import numpy as np import torch +from safetensors.numpy import load, load_file, save, save_file +from safetensors.torch import load_file as load_file_pt +from safetensors.torch import save_file as save_file_pt + class TestCase(unittest.TestCase): def test_serialization(self): diff --git a/bindings/python/tests/test_tf_comparison.py b/bindings/python/tests/test_tf_comparison.py index 6d9fbb9..2acca90 100644 --- a/bindings/python/tests/test_tf_comparison.py +++ b/bindings/python/tests/test_tf_comparison.py @@ -1,12 +1,15 @@ -import unittest -from safetensors.tensorflow import save_file, load_file -from huggingface_hub import hf_hub_download import datetime +import os +import unittest + import h5py import numpy as np -import os import tensorflow as tf +from huggingface_hub import hf_hub_download +from safetensors.tensorflow import load_file, save_file + + MODEL_ID = os.getenv("MODEL_ID", "gpt2") -- 2.43.0