From: Nicolas Patry Date: Wed, 23 Nov 2022 14:41:36 +0000 (+0100) Subject: Improve error message when saving bogus object. (#106) X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=0a4eb42bb1b98e41f442a94425075d358366e0ae;p=safetensors.git Improve error message when saving bogus object. (#106) --- diff --git a/bindings/python/py_src/safetensors/torch.py b/bindings/python/py_src/safetensors/torch.py index 4d39bc8..1a59f47 100644 --- a/bindings/python/py_src/safetensors/torch.py +++ b/bindings/python/py_src/safetensors/torch.py @@ -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) diff --git a/bindings/python/tests/test_pt_comparison.py b/bindings/python/tests/test_pt_comparison.py index 10f3148..bd640d0 100644 --- a/bindings/python/tests/test_pt_comparison.py +++ b/bindings/python/tests/test_pt_comparison.py @@ -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 ", + ) + + 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 LoadTestCase(unittest.TestCase):