]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Splitting up tests from benchmarks. (#50)
authorNicolas Patry <patry.nicolas@protonmail.com>
Tue, 1 Nov 2022 18:00:24 +0000 (19:00 +0100)
committerGitHub <noreply@github.com>
Tue, 1 Nov 2022 18:00:24 +0000 (19:00 +0100)
* Splitting up tests from benchmarks.

* Skipping if cuda is not available.

* Fix condition.

* Working directory.

* Different location.

* Auto-push on GH pages.

* Benching for real.

.github/workflows/python-bench.yml [new file with mode: 0644]
bindings/python/benches/test_flax.py [new file with mode: 0644]
bindings/python/benches/test_pt.py [new file with mode: 0644]
bindings/python/benches/test_tf.py [new file with mode: 0644]
bindings/python/tests/test_flax_comparison.py
bindings/python/tests/test_pt.py [new file with mode: 0644]
bindings/python/tests/test_pt_comparison.py
bindings/python/tests/test_tf_comparison.py

diff --git a/.github/workflows/python-bench.yml b/.github/workflows/python-bench.yml
new file mode 100644 (file)
index 0000000..1fd6e55
--- /dev/null
@@ -0,0 +1,64 @@
+name: Simple benchmarks
+on:
+  pull_request:
+    branches:
+      - main
+
+permissions:
+  # deployments permission to deploy GitHub pages website
+  deployments: write
+  # contents permission to update benchmark contents in gh-pages branch
+  contents: write
+
+jobs:
+  benchmark:
+    name: Performance regression check
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v2
+      - name: Install Rust
+        uses: actions-rs/toolchain@v1
+        with:
+          toolchain: stable
+          components: rustfmt, clippy
+
+      - name: Install Python
+        uses: actions/setup-python@v2
+        with:
+          python-version: 3.7
+          architecture: "x64"
+
+      - name: Install
+        working-directory: ./bindings/python
+        run: |
+          pip install -U pip
+          pip install pytest pytest-benchmark setuptools_rust
+          pip install torch tensorflow numpy
+          pip install jax jaxlib flax
+          python setup.py develop
+
+      - name: Run tests
+        working-directory: ./bindings/python
+        run: |
+          cargo test
+          pytest --benchmark-json output.json benches/
+      # Download previous benchmark result from cache (if exists)
+      - name: Download previous benchmark data
+        uses: actions/cache@v1
+        with:
+          path: ./cache
+          key: ${{ runner.os }}-benchmark
+      # Run `github-action-benchmark` action
+      - name: Store benchmark result
+        uses: benchmark-action/github-action-benchmark@v1
+        with:
+          # What benchmark tool the output.txt came from
+          tool: 'pytest'
+          # Where the output from the benchmark tool is stored
+          output-file-path: ./bindings/python/output.json
+          github-token: ${{ secrets.GITHUB_TOKEN }}
+          # Push and deploy GitHub pages branch automatically
+          auto-push: true
+          comment-on-alert: true
+          # Mention @rhysd in the commit comment
+          alert-comment-cc-users: '@Narsil'
diff --git a/bindings/python/benches/test_flax.py b/bindings/python/benches/test_flax.py
new file mode 100644 (file)
index 0000000..f7edc2c
--- /dev/null
@@ -0,0 +1,60 @@
+import tempfile
+
+import jax.numpy as jnp
+from flax.serialization import msgpack_restore, msgpack_serialize
+from safetensors.flax import load_file, save_file
+
+
+def create_gpt2(n_layers: int):
+    tensors = {}
+    tensors["wte"] = jnp.zeros((50257, 768))
+    tensors["wpe"] = jnp.zeros((1024, 768))
+    for i in range(n_layers):
+        tensors[f"h.{i}.ln_1.weight"] = jnp.zeros((768,))
+        tensors[f"h.{i}.ln_1.bias"] = jnp.zeros((768,))
+        tensors[f"h.{i}.attn.bias"] = jnp.zeros((1, 1, 1024, 1024))
+        tensors[f"h.{i}.attn.c_attn.weight"] = jnp.zeros((768, 2304))
+        tensors[f"h.{i}.attn.c_attn.bias"] = jnp.zeros((2304))
+        tensors[f"h.{i}.attn.c_proj.weight"] = jnp.zeros((768, 768))
+        tensors[f"h.{i}.attn.c_proj.bias"] = jnp.zeros((768))
+        tensors[f"h.{i}.ln_2.weight"] = jnp.zeros((768))
+        tensors[f"h.{i}.ln_2.bias"] = jnp.zeros((768))
+        tensors[f"h.{i}.mlp.c_fc.weight"] = jnp.zeros((768, 3072))
+        tensors[f"h.{i}.mlp.c_fc.bias"] = jnp.zeros((3072))
+        tensors[f"h.{i}.mlp.c_proj.weight"] = jnp.zeros((3072, 768))
+        tensors[f"h.{i}.mlp.c_proj.bias"] = jnp.zeros((768))
+    tensors["ln_f.weight"] = jnp.zeros((768))
+    tensors["ln_f.bias"] = jnp.zeros((768))
+    return tensors
+
+
+def load(filename):
+    with open(filename, "rb") as f:
+        data = f.read()
+        flax_weights = msgpack_restore(data)
+        return flax_weights
+
+
+def test_flax_flax_load(benchmark):
+    # benchmark something
+    weights = create_gpt2(12)
+    with tempfile.NamedTemporaryFile() as f:
+        serialized = msgpack_serialize(weights)
+        f.write(serialized)
+        result = benchmark(load, f.name)
+
+    for k, v in weights.items():
+        tv = result[k]
+        assert jnp.allclose(v, tv)
+
+
+def test_flax_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 jnp.allclose(v, tv)
diff --git a/bindings/python/benches/test_pt.py b/bindings/python/benches/test_pt.py
new file mode 100644 (file)
index 0000000..49827a5
--- /dev/null
@@ -0,0 +1,81 @@
+import tempfile
+
+import pytest
+import torch
+
+from safetensors.torch import load_file, save_file
+
+
+def create_gpt2(n_layers: int):
+    tensors = {}
+    tensors["wte"] = torch.zeros((50257, 768))
+    tensors["wpe"] = torch.zeros((1024, 768))
+    for i in range(n_layers):
+        tensors[f"h.{i}.ln_1.weight"] = torch.zeros((768,))
+        tensors[f"h.{i}.ln_1.bias"] = torch.zeros((768,))
+        tensors[f"h.{i}.attn.bias"] = torch.zeros((1, 1, 1024, 1024))
+        tensors[f"h.{i}.attn.c_attn.weight"] = torch.zeros((768, 2304))
+        tensors[f"h.{i}.attn.c_attn.bias"] = torch.zeros((2304))
+        tensors[f"h.{i}.attn.c_proj.weight"] = torch.zeros((768, 768))
+        tensors[f"h.{i}.attn.c_proj.bias"] = torch.zeros((768))
+        tensors[f"h.{i}.ln_2.weight"] = torch.zeros((768))
+        tensors[f"h.{i}.ln_2.bias"] = torch.zeros((768))
+        tensors[f"h.{i}.mlp.c_fc.weight"] = torch.zeros((768, 3072))
+        tensors[f"h.{i}.mlp.c_fc.bias"] = torch.zeros((3072))
+        tensors[f"h.{i}.mlp.c_proj.weight"] = torch.zeros((3072, 768))
+        tensors[f"h.{i}.mlp.c_proj.bias"] = torch.zeros((768))
+    tensors["ln_f.weight"] = torch.zeros((768))
+    tensors["ln_f.bias"] = torch.zeros((768))
+    return tensors
+
+
+def test_pt_pt_load_cpu(benchmark):
+    # benchmark something
+    weights = create_gpt2(12)
+    with tempfile.NamedTemporaryFile() as f:
+        torch.save(weights, f)
+        result = benchmark(torch.load, f.name)
+
+    for k, v in weights.items():
+        tv = result[k]
+        assert torch.allclose(v, tv)
+
+
+def test_pt_sf_load_cpu(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 torch.allclose(v, tv)
+
+
+@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires cuda")
+def test_pt_pt_load_gpu(benchmark):
+    # benchmark something
+    weights = create_gpt2(12)
+    with tempfile.NamedTemporaryFile() as f:
+        torch.save(weights, f)
+        result = benchmark(torch.load, f.name, map_location="cuda:0")
+
+    for k, v in weights.items():
+        v = v.cuda()
+        tv = result[k]
+        assert torch.allclose(v, tv)
+
+
+@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires cuda")
+def test_pt_sf_load_gpu(benchmark):
+    # benchmark something
+    weights = create_gpt2(12)
+    with tempfile.NamedTemporaryFile() as f:
+        save_file(weights, f.name)
+        result = benchmark(load_file, f.name, device="cuda:0")
+
+    for k, v in weights.items():
+        v = v.cuda()
+        tv = result[k]
+        assert torch.allclose(v, tv)
diff --git a/bindings/python/benches/test_tf.py b/bindings/python/benches/test_tf.py
new file mode 100644 (file)
index 0000000..a3fcc14
--- /dev/null
@@ -0,0 +1,75 @@
+import tempfile
+
+import h5py
+import numpy as np
+import tensorflow as tf
+
+from safetensors.tensorflow import load_file, save_file
+
+
+def _load(filename, tensors=None, prefix=""):
+    with h5py.File(filename, "r") as f:
+        if tensors is None:
+            tensors = {}
+        for k in f.keys():
+            if isinstance(f[k], h5py._hl.dataset.Dataset):
+                key = k if not prefix else f"{prefix}_{k}"
+                tensors[key] = tf.convert_to_tensor(np.array(f[k]))
+            else:
+                tensors.update(_load(f[k], tensors, prefix=f"{prefix}_{k}"))
+        return tensors
+
+
+def _save(filename, tensors, prefix=""):
+    with h5py.File(filename, "w") as f:
+        for name, tensor in tensors.items():
+            tensor = tensor.numpy()
+            dset = f.create_dataset(name, tensor.shape, dtype=tensor.dtype)
+            dset[:] = tensor
+
+
+def create_gpt2(n_layers: int):
+    tensors = {}
+    tensors["wte"] = tf.zeros((50257, 768))
+    tensors["wpe"] = tf.zeros((1024, 768))
+    for i in range(n_layers):
+        tensors[f"h.{i}.ln_1.weight"] = tf.zeros((768,))
+        tensors[f"h.{i}.ln_1.bias"] = tf.zeros((768,))
+        tensors[f"h.{i}.attn.bias"] = tf.zeros((1, 1, 1024, 1024))
+        tensors[f"h.{i}.attn.c_attn.weight"] = tf.zeros((768, 2304))
+        tensors[f"h.{i}.attn.c_attn.bias"] = tf.zeros((2304))
+        tensors[f"h.{i}.attn.c_proj.weight"] = tf.zeros((768, 768))
+        tensors[f"h.{i}.attn.c_proj.bias"] = tf.zeros((768))
+        tensors[f"h.{i}.ln_2.weight"] = tf.zeros((768))
+        tensors[f"h.{i}.ln_2.bias"] = tf.zeros((768))
+        tensors[f"h.{i}.mlp.c_fc.weight"] = tf.zeros((768, 3072))
+        tensors[f"h.{i}.mlp.c_fc.bias"] = tf.zeros((3072))
+        tensors[f"h.{i}.mlp.c_proj.weight"] = tf.zeros((3072, 768))
+        tensors[f"h.{i}.mlp.c_proj.bias"] = tf.zeros((768))
+    tensors["ln_f.weight"] = tf.zeros((768))
+    tensors["ln_f.bias"] = tf.zeros((768))
+    return tensors
+
+
+def test_tf_tf_load(benchmark):
+    # benchmark something
+    weights = create_gpt2(12)
+    with tempfile.NamedTemporaryFile() as f:
+        _save(f.name, weights)
+        result = benchmark(_load, f.name)
+
+    for k, v in weights.items():
+        tv = result[k]
+        assert np.allclose(v, tv)
+
+
+def test_tf_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 bf9f28d5bdbefe98cf6843da3ead94573e8d9cc7..fa0aac5e76ecf5cb3b5867857eb4a7e427d4eddf 100644 (file)
@@ -1,12 +1,8 @@
-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
@@ -15,65 +11,32 @@ if platform.system() != "Windows":
     from flax.serialization import msgpack_restore, msgpack_serialize
     from safetensors.flax import load_file, save_file
 
-MODEL_ID = os.getenv("MODEL_ID", "gpt2")
-
-
-def _load(nested, flat, prefix=""):
-    for k, v in nested.items():
-        if isinstance(v, dict):
-            _load(v, flat, prefix=f"{prefix}_{k}")
-        elif isinstance(v, np.ndarray):
-            flat[f"{prefix}_{k}"] = jnp.array(v)
-
-
-def load(nested_np_dicts):
-    tensors = {}
-    _load(nested_np_dicts, tensors)
-    return tensors
-
 
 # Jax doesn't not exist on Windows
 @unittest.skipIf(platform.system() == "Windows", "Jax is not available on Windows")
-class SafeTestCase(unittest.TestCase):
+class LoadTestCase(unittest.TestCase):
     def setUp(self):
-        self.filename = hf_hub_download(MODEL_ID, filename="flax_model.msgpack")
-        with open(self.filename, "rb") as f:
-            data = f.read()
-        self.data = load(msgpack_restore(data))
-        self.local = "./tests/data/out_safe_flax_mmap.safetensors"
-        save_file(self.data, self.local)
-
-    def test_deserialization_safe(self):
-        load_file(self.local)
+        data = {
+            "test": jnp.zeros((1024, 1024), dtype=jnp.float32),
+            "test2": jnp.zeros((1024, 1024), dtype=jnp.float32),
+            "test3": jnp.zeros((1024, 1024), dtype=jnp.float32),
+        }
+        self.flax_filename = "./tests/data/flax_load.msgpack"
+        self.sf_filename = "./tests/data/flax_load.safetensors"
+
+        serialized = msgpack_serialize(data)
+        with open(self.flax_filename, "wb") as f:
+            f.write(serialized)
 
-        start = datetime.datetime.now()
-        load_file(self.local)
-        safe_time = datetime.datetime.now() - start
+        save_file(data, self.sf_filename)
 
-        with open(self.filename, "rb") as f:
-            data = f.read()
+    def test_deserialization_safe(self):
+        weights = load_file(self.sf_filename)
 
-        start = datetime.datetime.now()
-        with open(self.filename, "rb") as f:
+        with open(self.flax_filename, "rb") as f:
             data = f.read()
-        msgpack_restore(data)
-        flax_time = datetime.datetime.now() - start
-
-        print()
-        print(f"Deserialization (Safe) took {safe_time}")
-        print(f"Deserialization (flax) took {flax_time} (Safe is {flax_time/safe_time} faster)")
+        flax_weights = msgpack_restore(data)
 
-    def test_serialization_safe(self):
-        outfilename = "./tests/data/out_safe.safetensors"
-        save_file(self.data, outfilename)
-        start = datetime.datetime.now()
-        save_file(self.data, outfilename)
-        safe_time = datetime.datetime.now() - start
-        start = datetime.datetime.now()
-        serialized = msgpack_serialize(self.data)
-        with open("./tests/data/out_flax.msgpack", "wb") as f:
-            f.write(serialized)
-        flax_time = datetime.datetime.now() - start
-        print()
-        print(f"Serialization (safe) took {safe_time}")
-        print(f"Serialization (flax) took {flax_time} (Safe is {flax_time/safe_time} faster)")
+        for k, v in weights.items():
+            tv = flax_weights[k]
+            self.assertTrue(np.allclose(v, tv))
diff --git a/bindings/python/tests/test_pt.py b/bindings/python/tests/test_pt.py
new file mode 100644 (file)
index 0000000..617a1e0
--- /dev/null
@@ -0,0 +1,83 @@
+import unittest
+
+import torch
+
+from safetensors.safetensors_rust import safe_open
+from safetensors.torch import load_file, save_file
+
+
+class TorchTestCase(unittest.TestCase):
+    def test_odd_dtype(self):
+        data = {
+            "test": torch.zeros((2, 2), dtype=torch.bfloat16),
+            "test2": torch.zeros((2, 2), dtype=torch.float16),
+            "test3": torch.zeros((2, 2), dtype=torch.bool),
+        }
+        local = "./tests/data/out_safe_pt_mmap_small.safetensors"
+        save_file(data, local)
+        reloaded = load_file(local)
+        self.assertTrue(torch.equal(data["test"], reloaded["test"]))
+        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_small.safetensors"
+        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.safetensors"
+        with self.assertRaises(ValueError):
+            save_file(data, local)
+
+
+class SliceTestCase(unittest.TestCase):
+    def setUp(self):
+        self.tensor = torch.arange(6, dtype=torch.float32).reshape((1, 2, 3))
+        self.data = {"test": self.tensor}
+        self.local = "./tests/data/out_safe_pt_mmap_slice.safetensors"
+        # 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.safetensors")
+
+    def test_deserialization_slice(self):
+        with safe_open(self.local, framework="pt") as f:
+            tensor = f.get_slice("test")[:, :, 1:2]
+
+        self.assertEqual(
+            tensor.numpy().tobytes(),
+            b"\x00\x00\x80?\x00\x00\x80@",
+        )
+
+        self.assertTrue(torch.equal(tensor, torch.Tensor([[[1.0], [4.0]]])))
+        self.assertTrue(torch.equal(tensor, self.tensor[:, :, 1:2]))
+
+    def test_deserialization_metadata(self):
+        with safe_open(self.local, framework="pt") as f:
+            metadata = f.metadata()
+        self.assertEqual(metadata, None)
+
+        # Save another one *with* metadata
+        tensor = torch.arange(6, dtype=torch.float32).reshape((1, 2, 3))
+        data = {"test": tensor}
+        local = "./tests/data/out_safe_pt_mmap2.safetensors"
+        # Need to copy since that call mutates the tensors to numpy
+        save_file(data, local, metadata={"Something": "more"})
+        with safe_open(local, framework="pt") as f:
+            metadata = f.metadata()
+        self.assertEqual(metadata, {"Something": "more"})
index 68a77cf78da57e3de7fd20aa2fadee87943a0349..8a91076a2ee754e73c2a95784c722fa7d648f37b 100644 (file)
@@ -1,17 +1,11 @@
-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")
-
-
 class TorchTestCase(unittest.TestCase):
     def test_odd_dtype(self):
         data = {
@@ -43,42 +37,25 @@ class TorchTestCase(unittest.TestCase):
             save_file(data, local)
 
 
-class SpeedTestCase(unittest.TestCase):
+class LoadTestCase(unittest.TestCase):
     def setUp(self):
-        self.filename = hf_hub_download(MODEL_ID, filename="pytorch_model.bin")
-        self.local = "./tests/data/out_safe_pt_mmap.safetensors"
-        if not os.path.exists(self.local):
-            data = torch.load(self.filename, map_location="cpu")
-            # Need to copy since that call mutates the tensors to numpy
-            save_file(data.copy(), self.local)
+        data = {
+            "test": torch.zeros((1024, 1024), dtype=torch.float32),
+            "test2": torch.zeros((1024, 1024), dtype=torch.float32),
+            "test3": torch.zeros((1024, 1024), dtype=torch.float32),
+        }
+        self.pt_filename = "./tests/data/pt_load.pt"
+        self.sf_filename = "./tests/data/pt_load.safetensors"
+
+        with open(self.pt_filename, "wb") as f:
+            torch.save(data, f)
+
+        save_file(data, self.sf_filename)
 
     def test_deserialization_safe(self):
-        W = 1
-        N = 1
-
-        for i in range(W):
-            torch.load(self.filename)
-        pt_timing = datetime.timedelta(0)
-        for i in range(N):
-            start = datetime.datetime.now()
-            tweights = torch.load(self.filename)
-            pt_time = datetime.datetime.now() - start
-            pt_timing += pt_time
-        pt_time = pt_timing / N
-
-        for i in range(W):
-            load_file(self.local)
-        safe_timing = datetime.timedelta(0)
-        for i in range(N):
-            start = datetime.datetime.now()
-            weights = load_file(self.local)
-            safe_time = datetime.datetime.now() - start
-            safe_timing += safe_time
-        safe_time = safe_timing / N
-
-        print()
-        print(f"Deserialization (Safe) took {safe_time}")
-        print(f"Deserialization (PT) took {pt_time} (Safe is {pt_time/safe_time} faster)")
+        tweights = torch.load(self.pt_filename)
+        weights = load_file(self.sf_filename)
+
         for k, v in weights.items():
             tv = tweights[k]
             self.assertTrue(torch.allclose(v, tv))
@@ -87,22 +64,11 @@ class SpeedTestCase(unittest.TestCase):
     @unittest.skipIf(not torch.cuda.is_available(), "Cuda is not available")
     def test_deserialization_safe_gpu(self):
         # First time to hit disk
-        torch.load(self.filename, map_location="cuda:0")
-        start = datetime.datetime.now()
-        tweights = torch.load(self.filename, map_location="cuda:0")
-        pt_time = datetime.datetime.now() - start
+        tweights = torch.load(self.pt_filename, map_location="cuda:0")
+
+        load_file(self.sf_filename, device=0)
+        weights = load_file(self.sf_filename, device="cuda:0")
 
-        # First time to hit disk
-        load_file(self.local, device=0)
-        load_file(self.local, device="cuda:0")
-        # Second time we should be in disk cache
-        start = datetime.datetime.now()
-        weights = load_file(self.local, device="cuda:0")
-        safe_time = datetime.datetime.now() - start
-
-        print()
-        print(f"Deserialization (Safe - GPU) took {safe_time}")
-        print(f"Deserialization (PT - GPU) took {pt_time} (Safe is {pt_time/safe_time} faster)")
         for k, v in weights.items():
             tv = tweights[k]
             self.assertTrue(torch.allclose(v, tv))
@@ -110,26 +76,12 @@ class SpeedTestCase(unittest.TestCase):
 
     @unittest.skipIf(not torch.cuda.is_available(), "Cuda is not available")
     def test_deserialization_safe_gpu_slice(self):
-        # First time to hit disk
-        load_file(self.local, device="cuda:0")
-        # Second time we should be in disk cache
-        start = datetime.datetime.now()
-
         weights = {}
-        with safe_open(self.local, framework="pt", device="cuda:0") as f:
+        with safe_open(self.sf_filename, framework="pt", device="cuda:0") as f:
             for k in f.keys():
                 weights[k] = f.get_slice(k)[:1]
-        safe_time = datetime.datetime.now() - start
-
-        # First time to hit disk
-        torch.load(self.filename, map_location="cuda:0")
-        start = datetime.datetime.now()
-        tweights = torch.load(self.filename, map_location="cuda:0")
+        tweights = torch.load(self.pt_filename, map_location="cuda:0")
         tweights = {k: v[:1] for k, v in tweights.items()}
-        pt_time = datetime.datetime.now() - start
-        print()
-        print(f"Deserialization (Safe - GPU) took {safe_time}")
-        print(f"Deserialization (PT - GPU) took {pt_time} (Safe is {pt_time/safe_time} faster)")
         for k, v in weights.items():
             tv = tweights[k]
             self.assertTrue(torch.allclose(v, tv))
@@ -137,44 +89,14 @@ class SpeedTestCase(unittest.TestCase):
 
     @unittest.skipIf(torch.cuda.device_count() < 2, "Only 1 device available")
     def test_deserialization_safe_device_1(self):
-        # First time to hit disk
-        load_file(self.local, device=1)
-        load_file(self.local, device="cuda:1")
-        # Second time we should be in disk cache
-        start = datetime.datetime.now()
-
-        weights = load_file(self.local, device="cuda:1")
-        safe_time = datetime.datetime.now() - start
-
-        # First time to hit disk
-        torch.load(self.filename, map_location="cuda:1")
-        start = datetime.datetime.now()
-        tweights = torch.load(self.filename, map_location="cuda:1")
-        pt_time = datetime.datetime.now() - start
-        print()
-        print(f"Deserialization (Safe - GPU) took {safe_time}")
-        print(f"Deserialization (PT - GPU) took {pt_time} (Safe is {pt_time/safe_time} faster)")
+        load_file(self.sf_filename, device=1)
+        weights = load_file(self.sf_filename, device="cuda:1")
+        tweights = torch.load(self.pt_filename, map_location="cuda:1")
         for k, v in weights.items():
             tv = tweights[k]
             self.assertTrue(torch.allclose(v, tv))
             self.assertEqual(v.device, torch.device("cuda:1"))
 
-    def test_serialization_safe(self):
-        data = torch.load(self.filename, map_location="cpu")
-        start = datetime.datetime.now()
-        outfilename = "./tests/data/out_safe.safetensors"
-        save_file(data, outfilename)
-        safe_time = datetime.datetime.now() - start
-
-        start = datetime.datetime.now()
-        with open("./tests/data/out_pt.safetensors", "wb") as f:
-            torch.save(data, f)
-        pt_time = datetime.datetime.now() - start
-
-        print()
-        print(f"Serialization (safe) took {safe_time}")
-        print(f"Serialization (PT) took {pt_time} (Safe is {pt_time/safe_time} faster)")
-
 
 class SliceTestCase(unittest.TestCase):
     def setUp(self):
index 41dc2e364b623a68f959cd67c3368db080a13058..db398da7259d04d21ac40d067f0c4e75862dcc35 100644 (file)
@@ -1,22 +1,19 @@
-import datetime
-import os
 import unittest
 
 import h5py
 import numpy as np
 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")
-
-
-def _load(f, tensors, prefix=""):
+def _load(f, tensors=None, prefix=""):
+    if tensors is None:
+        tensors = {}
     for k in f.keys():
         if isinstance(f[k], h5py._hl.dataset.Dataset):
-            tensors[f"{prefix}_{k}"] = tf.convert_to_tensor(np.array(f[k]))
+            key = k if not prefix else f"{prefix}_{k}"
+            tensors[key] = tf.convert_to_tensor(np.array(f[k]))
         else:
             tensors.update(_load(f[k], tensors, prefix=f"{prefix}_{k}"))
     return tensors
@@ -31,54 +28,24 @@ def _save(f, tensors, prefix=""):
 
 class SafeTestCase(unittest.TestCase):
     def setUp(self):
-        self.filename = hf_hub_download(MODEL_ID, filename="tf_model.h5")
-        tensors = {}
-        with h5py.File(self.filename, "r") as f:
-            self.data = _load(f, tensors)
-
-        # Weird copies are necessary because apparently calling
-        # tf.Tensor(..).numpy() converts inplace destroying the actual
-        # tf.Tensor.
-        data = self.data.copy()
-        self.local = "./tests/data/out_safe_tf_mmap.h5"
-        save_file(data, self.local)
+        data = {
+            "test": tf.zeros((1024, 1024), dtype=tf.float32),
+            "test2": tf.zeros((1024, 1024), dtype=tf.float32),
+            "test3": tf.zeros((1024, 1024), dtype=tf.float32),
+        }
+        self.tf_filename = "./tests/data/tf_load.h5"
+        self.sf_filename = "./tests/data/tf_load.safetensors"
+
+        with h5py.File(self.tf_filename, "w") as f:
+            _save(f, data)
+        save_file(data, self.sf_filename)
 
     def test_deserialization_safe(self):
-        load_file(self.local)
-
-        start = datetime.datetime.now()
-        load_file(self.local)
-        safe_time = datetime.datetime.now() - start
+        weights = load_file(self.sf_filename)
 
-        tensors = {}
-        with h5py.File(self.filename, "r") as f:
-            self.data = _load(f, tensors)
-
-        start = datetime.datetime.now()
-        tensors = {}
-        with h5py.File(self.filename, "r") as f:
-            self.data = _load(f, tensors)
-        tf_time = datetime.datetime.now() - start
-        print()
-        print(f"Deserialization (Safe) took {safe_time}")
-        print(f"Deserialization (TF) took {tf_time} (Safe is {tf_time/safe_time} faster)")
-
-    def test_serialization_safe(self):
-        outfilename = "./tests/data/out_safe.safetensors"
-        data = self.data.copy()
-        save_file(data, outfilename)
-
-        data = self.data.copy()
-        start = datetime.datetime.now()
-        save_file(data, outfilename)
-        safe_time = datetime.datetime.now() - start
-
-        data = self.data.copy()
-        start = datetime.datetime.now()
-        with h5py.File("./tests/data/out_tf_tf.h5", "w") as f:
-            _save(f, data)
-        tf_time = datetime.datetime.now() - start
+        with h5py.File(self.tf_filename, "r") as f:
+            tf_weights = _load(f)
 
-        print()
-        print(f"Serialization (Safe) took {safe_time}")
-        print(f"Serialization (TF) took {tf_time} (Safe is {tf_time/safe_time} faster)")
+        for k, v in weights.items():
+            tv = tf_weights[k]
+            self.assertTrue(np.allclose(v, tv))