Skip to content

Commit b7d14c8

Browse files
Enabling MetaTensor Persistent Caching (#8940)
Addresses [GHSA-636w-j999-g7x5](GHSA-636w-j999-g7x5). ### Description This modifies the `PersistentDataset` class to permit storing `MetaTensor` objects. This is done by relying on the `torch.load` functionality to load only safe object types and those white-listed with `torch.serialization.add_safe_globals`. This also uses sha256 hashing in place of md5 in case of security concerns. ### Types of changes <!--- Put an `x` in all the boxes that apply, and remove the not applicable items --> - [x] Non-breaking change (fix or new feature that would not break existing functionality). - [ ] Breaking change (fix or new feature that would cause existing functionality to change). - [x] New tests added to cover the changes. - [ ] Integration tests passed locally by running `./runtests.sh -f -u --net --coverage`. - [ ] Quick tests passed locally by running `./runtests.sh --quick --unittests --disttests`. - [x] In-line docstrings updated. - [ ] Documentation updated, tested `make html` command in the `docs/` folder. --------- Signed-off-by: Eric Kerfoot <17726042+ericspod@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 4ba89bd commit b7d14c8

3 files changed

Lines changed: 154 additions & 41 deletions

File tree

‎monai/data/dataset.py‎

Lines changed: 19 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -210,8 +210,12 @@ class PersistentDataset(Dataset):
210210
211211
Cached data is expected to be tensors, primitives, or dictionaries keying to these values. Numpy arrays will
212212
be converted to tensors, however any other object type returned by transforms will not be loadable since
213-
`torch.load` will be used with `weights_only=True` to prevent loading of potentially malicious objects.
214-
Legacy cache files may not be loadable and may need to be recomputed.
213+
`torch.load` will be used with `weights_only=True` by default to prevent loading of potentially malicious
214+
objects. Legacy cache files may not be loadable and may need to be recomputed. MetaTensor objects can be saved
215+
and loaded with their metadata preserved if `track_meta` is True, however the objects stored in the metadata
216+
must be acceptable as serialisable by `torch.load` by default or if they have been white-listed with
217+
`torch.serialization.add_safe_globals`. Any other object type may be stored but will fail to load and force
218+
a cache recompute.
215219
216220
Lazy Resampling:
217221
If you make use of the lazy resampling feature of `monai.transforms.Compose`, please refer to
@@ -245,8 +249,8 @@ def __init__(
245249
may share a common cache dir provided that the transforms pre-processing is consistent.
246250
If `cache_dir` doesn't exist, will automatically create it.
247251
If `cache_dir` is `None`, there is effectively no caching.
248-
hash_func: a callable to compute hash from data items to be cached.
249-
defaults to `monai.data.utils.pickle_hashing`.
252+
hash_func: a callable to compute hash from data items to be cached, defaults to
253+
`monai.data.utils.pickle_hashing` which uses sha256 (previously md5 so old caches will not work).
250254
pickle_module: string representing the module used for pickling metadata and objects,
251255
default to `"pickle"`. due to the pickle limitation in multi-processing of Dataloader,
252256
we can't use `pickle` as arg directly, so here we use a string name instead.
@@ -266,17 +270,12 @@ def __init__(
266270
When this is enabled, the traced transform instance IDs will be removed from the cached MetaTensors.
267271
This is useful for skipping the transform instance checks when inverting applied operations
268272
using the cached content and with re-created transform instances.
269-
track_meta: whether to track the meta information, if `True`, will convert to `MetaTensor`.
270-
default to `False`. Cannot be used with `weights_only=True`.
273+
track_meta: whether to track the meta information, defaults to False. If `True`, converts to `MetaTensor`.
271274
weights_only: keyword argument passed to `torch.load` when reading cached files.
272-
default to `True`. When set to `True`, `torch.load` restricts loading to tensors and
273-
other safe objects. Setting this to `False` is required for loading `MetaTensor`
274-
objects saved with `track_meta=True`, however this creates the possibility of remote
275-
code execution through `torch.load` so be aware of the security implications of doing so.
276-
277-
Raises:
278-
ValueError: When both `track_meta=True` and `weights_only=True`, since this combination
279-
prevents cached MetaTensors from being reloaded and causes perpetual cache regeneration.
275+
default to `True`. When `True`, `torch.load` restricts loading to tensors and other safe objects.
276+
Setting to `False` should only be done if it's absolutely necessary to load unsafe pickled data,
277+
eg. MetaTensor objects with unsafe objects in their metadata. Users must verify the safety of the data
278+
they intend to load before doing so.
280279
"""
281280
super().__init__(data=data, transform=transform)
282281
self.cache_dir = Path(cache_dir) if cache_dir is not None else None
@@ -292,11 +291,6 @@ def __init__(
292291
if hash_transform is not None:
293292
self.set_transform_hash(hash_transform)
294293
self.reset_ops_id = reset_ops_id
295-
if track_meta and weights_only:
296-
raise ValueError(
297-
"Invalid argument combination: `track_meta=True` cannot be used with `weights_only=True`. "
298-
"To cache and reload MetaTensors, set `track_meta=True` and `weights_only=False`."
299-
)
300294
self.track_meta = track_meta
301295
self.weights_only = weights_only
302296

@@ -390,9 +384,9 @@ def _cachecheck(self, item_transformed):
390384
"""
391385
hashfile = None
392386
if self.cache_dir is not None:
393-
data_item_md5 = self.hash_func(item_transformed).decode("utf-8")
394-
data_item_md5 += self.transform_hash
395-
hashfile = self.cache_dir / f"{data_item_md5}.pt"
387+
data_item_hash = self.hash_func(item_transformed).decode("utf-8")
388+
data_item_hash += self.transform_hash
389+
hashfile = self.cache_dir / f"{data_item_hash}.pt"
396390

397391
if hashfile is not None and hashfile.is_file(): # cache hit
398392
try:
@@ -1624,9 +1618,9 @@ def _cachecheck(self, item_transformed):
16241618
hashfile = None
16251619
# compute a cache id
16261620
if self.cache_dir is not None:
1627-
data_item_md5 = self.hash_func(item_transformed).decode("utf-8")
1628-
data_item_md5 += self.transform_hash
1629-
hashfile = self.cache_dir / f"{data_item_md5}.pt"
1621+
data_item_hash = self.hash_func(item_transformed).decode("utf-8")
1622+
data_item_hash += self.transform_hash
1623+
hashfile = self.cache_dir / f"{data_item_hash}.pt"
16301624

16311625
if hashfile is not None and hashfile.is_file(): # cache hit
16321626
with cp.cuda.Device(self.device):

‎monai/data/utils.py‎

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
import math
1818
import os
1919
import pickle
20-
import sys
2120
from collections import abc, defaultdict
2221
from collections.abc import Generator, Iterable, Mapping, Sequence, Sized
2322
from copy import deepcopy
@@ -1370,13 +1369,8 @@ def json_hashing(item) -> bytes:
13701369
13711370
"""
13721371
# TODO: Find way to hash transforms content as part of the cache
1373-
cache_key = ""
1374-
if sys.version_info.minor < 9:
1375-
cache_key = hashlib.md5(json.dumps(item, sort_keys=True).encode("utf-8")).hexdigest()
1376-
else:
1377-
cache_key = hashlib.md5(
1378-
json.dumps(item, sort_keys=True).encode("utf-8"), usedforsecurity=False # type: ignore
1379-
).hexdigest()
1372+
dump = json.dumps(item, sort_keys=True).encode("utf-8")
1373+
cache_key = hashlib.sha256(dump, usedforsecurity=False).hexdigest() # type: ignore
13801374
return f"{cache_key}".encode()
13811375

13821376

@@ -1391,13 +1385,8 @@ def pickle_hashing(item, protocol=pickle.HIGHEST_PROTOCOL) -> bytes:
13911385
Returns: the corresponding hash key
13921386
13931387
"""
1394-
cache_key = ""
1395-
if sys.version_info.minor < 9:
1396-
cache_key = hashlib.md5(pickle.dumps(sorted_dict(item), protocol=protocol)).hexdigest()
1397-
else:
1398-
cache_key = hashlib.md5(
1399-
pickle.dumps(sorted_dict(item), protocol=protocol), usedforsecurity=False # type: ignore
1400-
).hexdigest()
1388+
dump = pickle.dumps(sorted_dict(item), protocol=protocol)
1389+
cache_key = hashlib.sha256(dump, usedforsecurity=False).hexdigest() # type: ignore
14011390
return f"{cache_key}".encode()
14021391

14031392

‎tests/data/test_persistentdataset.py‎

Lines changed: 131 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,11 @@
1313

1414
import contextlib
1515
import os
16+
import pickle
1617
import tempfile
1718
import unittest
19+
from pathlib import Path
20+
from unittest.mock import patch
1821

1922
import nibabel as nib
2023
import numpy as np
@@ -46,7 +49,7 @@
4649

4750
TEST_CASE_4 = [True, False, False, MetaTensor]
4851

49-
TEST_CASE_5 = [True, True, True, None]
52+
TEST_CASE_5 = [True, True, False, MetaTensor]
5053

5154
TEST_CASE_6 = [False, False, False, torch.Tensor]
5255

@@ -200,6 +203,133 @@ def test_track_meta_and_weights_only(self, track_meta, weights_only, expected_er
200203
im = test_dataset[0]["image"]
201204
self.assertIsInstance(im, expected_type)
202205

206+
def test_metatensor_loading(self):
207+
"""
208+
Thorough test of metadata loading correctly with MetaTensor. This will store a MetaTensor with safe object types
209+
in its metadata dictionary, test the cache file exists and can be safely loaded with weights only, and that the
210+
loaded object is another MetaTensor with the correct information
211+
"""
212+
meta = {"test_meta": 123, "foo": "bar", "test_tuple": (1, 2, 3)}
213+
imt = MetaTensor(torch.rand(1, 128, 128, 128), meta=dict(meta), affine=torch.rand(4, 4))
214+
215+
with tempfile.TemporaryDirectory() as tempdir:
216+
cache_dir = Path(tempdir, "cache", "data")
217+
218+
test_data = [{"image": imt}]
219+
220+
test_dataset = PersistentDataset(
221+
data=test_data,
222+
transform=Compose([Identity()]),
223+
cache_dir=str(cache_dir),
224+
track_meta=True,
225+
weights_only=True,
226+
)
227+
228+
im = test_dataset[0]["image"]
229+
self.assertIsInstance(im, MetaTensor, "MetaTensor not stored in dataset.")
230+
231+
for k, v in meta.items():
232+
self.assertIn(k, im.meta, f"Metadata key {k} missing from loaded object.")
233+
self.assertEqual(im.meta[k], v, f"Metadata key {k} not equal ({im.meta[k]}!={v}).")
234+
235+
torch.testing.assert_close(imt.affine, im.affine)
236+
237+
cache_files = list(cache_dir.glob("*"))
238+
self.assertEqual(len(cache_files), 1, "Cached file not present.")
239+
240+
cache_im = torch.load(cache_files[0], weights_only=True)["image"]
241+
242+
self.assertIsInstance(cache_im, MetaTensor, "MetaTensor not stored in dataset.")
243+
244+
for k, v in meta.items():
245+
self.assertIn(k, cache_im.meta, f"Metadata key {k} missing from loaded object.")
246+
self.assertEqual(cache_im.meta[k], v, f"Metadata key {k} not equal ({cache_im.meta[k]}!={v}).")
247+
248+
# create a new dataset to be sure
249+
test_dataset2 = PersistentDataset(
250+
data=test_data,
251+
transform=Compose([Identity()]),
252+
cache_dir=str(cache_dir),
253+
track_meta=True,
254+
weights_only=True,
255+
)
256+
257+
# Replace torch.load with a function returning the same thing wrapped in a tuple, this is used to indicate
258+
# the dataset loaded the cached data rather than recomputed.
259+
old_load = torch.load
260+
261+
def _mock_load(f, weights_only):
262+
self.assertTrue(weights_only, f"torch.load called with {weights_only=}.")
263+
return (old_load(f, weights_only=weights_only),)
264+
265+
# check the returned object is a tuple containing the expected dict, if not then _mock_load wasn't called
266+
with patch("torch.load", _mock_load):
267+
im2_t = test_dataset2[0]
268+
self.assertIsInstance(im2_t, tuple, "Special tuple not returned, so mock not used.")
269+
self.assertIsInstance(im2_t[0]["image"], MetaTensor, "MetaTensor not stored in dataset.")
270+
271+
def test_metatensor_badcache(self):
272+
"""
273+
Test attempting to save then load a MetaTensor with an unsafe metadata item raises an exception. This creates
274+
a MetaTensor with an object in its metadata using unsafe code in __reduce__ which gets stored in the pickle.
275+
When attempting to load this through torch.load, pickle.UnpicklingError should be raised to force a recompute
276+
of the cached data rather than attempting to load something unsafe.
277+
"""
278+
with tempfile.TemporaryDirectory() as tempdir:
279+
cache_dir = Path(tempdir) / "cache" / "data"
280+
281+
class _BadType:
282+
def __reduce__(self):
283+
# something more insecure than this could be done with os.system
284+
return (os.system, (f'echo "Code injected!" > {Path(tempdir)/"out.txt"!s}',))
285+
286+
meta = {"test_meta": 123, "foo": "bar", "bad_item": _BadType()}
287+
imt = MetaTensor(torch.rand(1, 128, 128, 128), meta=dict(meta), affine=torch.rand(4, 4))
288+
test_data = [{"image": imt}]
289+
290+
test_dataset = PersistentDataset(
291+
data=test_data,
292+
transform=Compose([Identity()]),
293+
cache_dir=str(cache_dir),
294+
track_meta=True,
295+
weights_only=True,
296+
)
297+
298+
# This will trigger the _BadType class code injection because deepcopy will use __reduce__, but will still
299+
# write the cache file as needed for the test. The alternative was to write the cache file directly with a
300+
# computed hash value, but computing that hash without using pickle_hashing isn't trivial.
301+
im = test_dataset[0]["image"]
302+
303+
self.assertIsInstance(im, MetaTensor, "MetaTensor not stored in dataset.")
304+
305+
cache_files = list(cache_dir.glob("*"))
306+
self.assertEqual(len(cache_files), 1, "Cached file not present.")
307+
308+
# loading the cache file directly will raise the pickle exception as expected
309+
with self.assertRaises(pickle.UnpicklingError):
310+
torch.load(cache_files[0], weights_only=True)
311+
312+
# create a new dataset object just to be sure. When loading, a cache hit will occur but this will raise
313+
# the pickle exception again and force a recompute of the cached data as well as a warning, this indicates
314+
# the unsafe data was correctly rejected.
315+
test_dataset2 = PersistentDataset(
316+
data=test_data,
317+
transform=Compose([Identity()]),
318+
cache_dir=str(cache_dir),
319+
track_meta=True,
320+
weights_only=True,
321+
)
322+
323+
# warning raised about recomputing the corrupted cache file which raised UnpicklingError
324+
with self.assertWarns(UserWarning):
325+
im = test_dataset2[0]["image"]
326+
327+
self.assertIsInstance(im, MetaTensor, "MetaTensor not stored in dataset.")
328+
329+
cache_files2 = list(cache_dir.glob("*"))
330+
331+
self.assertEqual(cache_files[0], cache_files2[0], "Hashes for cached data differ.")
332+
203333

204334
if __name__ == "__main__":
205335
unittest.main()

0 commit comments

Comments
 (0)