* 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>
- 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
--- /dev/null
+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
--- /dev/null
+.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/
__version__ = "0.2.1.dev0"
# Re-export this
-from .safetensors_rust import safe_open
+from .safetensors_rust import safe_open # noqa: F401
-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]:
-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
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)
-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():
-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
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]:
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()
--- /dev/null
+[tool.black]
+line-length = 119
+target-version = ['py35']
--- /dev/null
+[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
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",
]
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",
-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")
-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")
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):
# 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]
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):
-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")