]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Improve error message when saving bogus object. (#106)
authorNicolas Patry <patry.nicolas@protonmail.com>
Wed, 23 Nov 2022 14:41:36 +0000 (15:41 +0100)
committerGitHub <noreply@github.com>
Wed, 23 Nov 2022 14:41:36 +0000 (15:41 +0100)
bindings/python/py_src/safetensors/torch.py
bindings/python/tests/test_pt_comparison.py

index 4d39bc871ef19ec86cc1b9f2ba20196163433cd2..1a59f47b0bf2900ca803256827daf7b5c4cf86ab 100644 (file)
@@ -213,8 +213,13 @@ def _tobytes(tensor: torch.Tensor, name: str) -> bytes:
 def _flatten(tensors: Dict[str, torch.Tensor]) -> Dict[str, Dict[str, Any]]:
     if sys.byteorder == "big":
         raise ValueError("Big endian is not supported, serialization need to be in little endian")
+    if not isinstance(tensors, dict):
+        raise ValueError(f"Expected a dict of [str, torch.Tensor] but received {type(tensors)}")
     ptrs = defaultdict(set)
     for k, v in tensors.items():
+        if not isinstance(v, torch.Tensor):
+            raise ValueError(f"Key `{k}` is invalid, expected torch.Tensor but received {type(v)}")
+
         if v.layout == torch.strided:
             ptrs[v.data_ptr()].add(k)
 
index 10f3148a5f9329b1f00891972c90c2fd78c8fc78..bd640d0f1624273540a82a987553c9c6d82cb84a 100644 (file)
@@ -45,8 +45,29 @@ class TorchTestCase(unittest.TestCase):
     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):
+        with self.assertRaises(ValueError) as ctx:
+            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.",
+        )
+
+    def test_bogus(self):
+        data = {"test": {"some": "thing"}}
+        local = "./tests/data/out_safe_pt_sparse.safetensors"
+        with self.assertRaises(ValueError) as ctx:
             save_file(data, local)
+        self.assertEqual(
+            str(ctx.exception),
+            "Key `test` is invalid, expected torch.Tensor but received <class 'dict'>",
+        )
+
+        with self.assertRaises(ValueError) as ctx:
+            save_file("notadict", local)
+        self.assertEqual(
+            str(ctx.exception),
+            "Expected a dict of [str, torch.Tensor] but received <class 'str'>",
+        )
 
 
 class LoadTestCase(unittest.TestCase):