-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathtest_persistentdataset.py
More file actions
315 lines (260 loc) · 14.1 KB
/
Copy pathtest_persistentdataset.py
File metadata and controls
315 lines (260 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import contextlib
import os
import tempfile
import unittest
from pathlib import Path
import nibabel as nib
import numpy as np
import torch
from parameterized import parameterized
from monai.data import MetaTensor, PersistentDataset, json_hashing
from monai.transforms import Compose, Flip, Identity, LoadImaged, SimulateDelayd, Transform
TEST_CASE_1 = [
Compose(
[
LoadImaged(keys=["image", "label", "extra"]),
SimulateDelayd(keys=["image", "label", "extra"], delay_time=[1e-7, 1e-6, 1e-5]),
]
),
(128, 128, 128),
]
TEST_CASE_2 = [
[
LoadImaged(keys=["image", "label", "extra"]),
SimulateDelayd(keys=["image", "label", "extra"], delay_time=[1e-7, 1e-6, 1e-5]),
],
(128, 128, 128),
]
TEST_CASE_3 = [None, (128, 128, 128)]
TEST_CASE_4 = [True, False, False, MetaTensor]
TEST_CASE_5 = [True, True, True, None]
TEST_CASE_6 = [False, False, False, torch.Tensor]
TEST_CASE_7 = [False, True, False, torch.Tensor]
class _InplaceXform(Transform):
def __call__(self, data):
if data:
data[0] = data[0] + np.pi
else:
data.append(1)
return data
class TestDataset(unittest.TestCase):
def test_cache(self):
"""testing no inplace change to the hashed item"""
items = [[list(range(i))] for i in range(5)]
with tempfile.TemporaryDirectory() as tempdir:
ds = PersistentDataset(
data=items,
transform=_InplaceXform(),
cache_dir=tempdir,
pickle_module="pickle",
# TODO: was pickle.HIGHEST_PROTOCOL but this wasn't compatible with torch.load, need to improve compatibility
pickle_protocol=torch.serialization.DEFAULT_PROTOCOL,
)
self.assertEqual(items, [[[]], [[0]], [[0, 1]], [[0, 1, 2]], [[0, 1, 2, 3]]])
ds1 = PersistentDataset(items, transform=_InplaceXform(), cache_dir=tempdir)
self.assertEqual(list(ds1), list(ds))
self.assertEqual(items, [[[]], [[0]], [[0, 1]], [[0, 1, 2]], [[0, 1, 2, 3]]])
ds = PersistentDataset(items, transform=_InplaceXform(), cache_dir=tempdir, hash_func=json_hashing)
self.assertEqual(items, [[[]], [[0]], [[0, 1]], [[0, 1, 2]], [[0, 1, 2, 3]]])
ds1 = PersistentDataset(items, transform=_InplaceXform(), cache_dir=tempdir, hash_func=json_hashing)
self.assertEqual(list(ds1), list(ds))
self.assertEqual(items, [[[]], [[0]], [[0, 1]], [[0, 1, 2]], [[0, 1, 2, 3]]])
@parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3])
def test_shape(self, transform, expected_shape):
test_image = nib.Nifti1Image(np.random.randint(0, 2, size=[128, 128, 128]).astype(float), np.eye(4))
with tempfile.TemporaryDirectory() as tempdir:
nib.save(test_image, os.path.join(tempdir, "test_image1.nii.gz"))
nib.save(test_image, os.path.join(tempdir, "test_label1.nii.gz"))
nib.save(test_image, os.path.join(tempdir, "test_extra1.nii.gz"))
nib.save(test_image, os.path.join(tempdir, "test_image2.nii.gz"))
nib.save(test_image, os.path.join(tempdir, "test_label2.nii.gz"))
nib.save(test_image, os.path.join(tempdir, "test_extra2.nii.gz"))
test_data = [
{
"image": os.path.join(tempdir, "test_image1.nii.gz"),
"label": os.path.join(tempdir, "test_label1.nii.gz"),
"extra": os.path.join(tempdir, "test_extra1.nii.gz"),
},
{
"image": os.path.join(tempdir, "test_image2.nii.gz"),
"label": os.path.join(tempdir, "test_label2.nii.gz"),
"extra": os.path.join(tempdir, "test_extra2.nii.gz"),
},
]
cache_dir = os.path.join(os.path.join(tempdir, "cache"), "data")
dataset_precached = PersistentDataset(data=test_data, transform=transform, cache_dir=cache_dir)
data1_precached = dataset_precached[0]
data2_precached = dataset_precached[1]
dataset_postcached = PersistentDataset(data=test_data, transform=transform, cache_dir=cache_dir)
data1_postcached = dataset_postcached[0]
data2_postcached = dataset_postcached[1]
data3_postcached = dataset_postcached[0:2]
if transform is None:
self.assertEqual(data1_precached["image"], os.path.join(tempdir, "test_image1.nii.gz"))
self.assertEqual(data2_precached["label"], os.path.join(tempdir, "test_label2.nii.gz"))
self.assertEqual(data1_postcached["image"], os.path.join(tempdir, "test_image1.nii.gz"))
self.assertEqual(data2_postcached["extra"], os.path.join(tempdir, "test_extra2.nii.gz"))
else:
self.assertTupleEqual(data1_precached["image"].shape, expected_shape)
self.assertTupleEqual(data1_precached["label"].shape, expected_shape)
self.assertTupleEqual(data1_precached["extra"].shape, expected_shape)
self.assertTupleEqual(data2_precached["image"].shape, expected_shape)
self.assertTupleEqual(data2_precached["label"].shape, expected_shape)
self.assertTupleEqual(data2_precached["extra"].shape, expected_shape)
self.assertTupleEqual(data1_postcached["image"].shape, expected_shape)
self.assertTupleEqual(data1_postcached["label"].shape, expected_shape)
self.assertTupleEqual(data1_postcached["extra"].shape, expected_shape)
self.assertTupleEqual(data2_postcached["image"].shape, expected_shape)
self.assertTupleEqual(data2_postcached["label"].shape, expected_shape)
self.assertTupleEqual(data2_postcached["extra"].shape, expected_shape)
for d in data3_postcached:
self.assertTupleEqual(d["image"].shape, expected_shape)
# update the data to cache
test_data_new = [
{
"image": os.path.join(tempdir, "test_image1_new.nii.gz"),
"label": os.path.join(tempdir, "test_label1_new.nii.gz"),
"extra": os.path.join(tempdir, "test_extra1_new.nii.gz"),
},
{
"image": os.path.join(tempdir, "test_image2_new.nii.gz"),
"label": os.path.join(tempdir, "test_label2_new.nii.gz"),
"extra": os.path.join(tempdir, "test_extra2_new.nii.gz"),
},
]
dataset_postcached.set_data(data=test_data_new)
# test new exchanged cache content
if transform is None:
self.assertEqual(dataset_postcached[0]["image"], os.path.join(tempdir, "test_image1_new.nii.gz"))
self.assertEqual(dataset_postcached[0]["label"], os.path.join(tempdir, "test_label1_new.nii.gz"))
self.assertEqual(dataset_postcached[1]["extra"], os.path.join(tempdir, "test_extra2_new.nii.gz"))
def test_different_transforms(self):
"""
Different instances of `PersistentDataset` with the same cache_dir,
same input data, but different transforms should give different results.
"""
shape = (1, 10, 9, 8)
im = np.arange(0, np.prod(shape)).reshape(shape)
with tempfile.TemporaryDirectory() as path:
im1 = PersistentDataset([im], Identity(), cache_dir=path, hash_transform=json_hashing)[0]
im2 = PersistentDataset([im], Flip(1), cache_dir=path, hash_transform=json_hashing)[0]
l2 = ((im1 - im2) ** 2).sum() ** 0.5
self.assertGreater(l2, 1)
@parameterized.expand([TEST_CASE_4, TEST_CASE_5, TEST_CASE_6, TEST_CASE_7])
def test_track_meta_and_weights_only(self, track_meta, weights_only, expected_error, expected_type):
"""
Ensure expected behavior for all combinations of `track_meta` and `weights_only`.
"""
test_image = nib.Nifti1Image(np.random.randint(0, 2, size=[128, 128, 128]).astype(float), np.eye(4))
with tempfile.TemporaryDirectory() as tempdir:
nib.save(test_image, os.path.join(tempdir, "test_image.nii.gz"))
test_data = [{"image": os.path.join(tempdir, "test_image.nii.gz")}]
transform = Compose([LoadImaged(keys=["image"])])
cache_dir = os.path.join(os.path.join(tempdir, "cache"), "data")
cm = self.assertRaises(ValueError) if expected_error else contextlib.nullcontext()
with cm:
test_dataset = PersistentDataset(
data=test_data,
transform=transform,
cache_dir=cache_dir,
track_meta=track_meta,
weights_only=weights_only,
)
im = test_dataset[0]["image"]
self.assertIsInstance(im, expected_type)
def test_in_memory_cache(self):
"""Test in_memory caching feature that combines persistent storage with RAM caching."""
items = [[list(range(i))] for i in range(5)]
with tempfile.TemporaryDirectory() as tempdir:
# First, create the persistent cache
ds1 = PersistentDataset(data=items, transform=_InplaceXform(), cache_dir=tempdir, in_memory=False)
# Access all items to populate disk cache
_ = list(ds1)
# Now create a new dataset with in_memory=True
ds2 = PersistentDataset(data=items, transform=_InplaceXform(), cache_dir=tempdir, in_memory=True)
# Memory cache should be empty initially
self.assertEqual(ds2.memory_cache_size, 0)
# Access items - they should be loaded from disk and cached in memory
_ = ds2[0]
self.assertEqual(ds2.memory_cache_size, 1)
_ = ds2[1]
self.assertEqual(ds2.memory_cache_size, 2)
# Access all items
_ = list(ds2)
self.assertEqual(ds2.memory_cache_size, 5)
# Accessing same item again should use memory cache (same result)
result1 = ds2[0]
result2 = ds2[0]
self.assertEqual(result1, result2)
# Test set_data clears in-memory cache
ds2.set_data(items[:3])
self.assertEqual(ds2.memory_cache_size, 0)
def test_in_memory_without_cache_dir(self):
"""Test in_memory caching works even without a cache_dir (pure RAM cache)."""
items = [[list(range(i))] for i in range(3)]
ds = PersistentDataset(data=items, transform=_InplaceXform(), cache_dir=None, in_memory=True)
# Memory cache should be empty initially
self.assertEqual(ds.memory_cache_size, 0)
# Access items - they should be cached in memory
_ = ds[0]
self.assertEqual(ds.memory_cache_size, 1)
_ = list(ds)
self.assertEqual(ds.memory_cache_size, 3)
def test_automatic_hybrid_caching(self):
"""
Test that in_memory=True provides automatic hybrid caching:
- ALL samples automatically persist to disk
- ALL samples automatically cache to RAM after first access
- No manual specification of which samples go where (unlike torchdatasets)
- Simulates restart scenario: disk cache survives, RAM cache rebuilds automatically
"""
items = [[list(range(i))] for i in range(5)]
with tempfile.TemporaryDirectory() as tempdir:
# === First "session": populate both disk and RAM cache ===
ds1 = PersistentDataset(data=items, transform=_InplaceXform(), cache_dir=tempdir, in_memory=True)
# Access all items - should automatically cache to BOTH disk AND RAM
for i in range(len(items)):
_ = ds1[i]
# Verify: ALL samples are in RAM (automatic, no manual specification)
self.assertEqual(ds1.memory_cache_size, 5)
# Verify: ALL samples are on disk (count .pt files)
cache_files = list(Path(tempdir).glob("*.pt"))
self.assertEqual(len(cache_files), 5)
# === Simulate "restart": new dataset instance, same cache_dir ===
# This is the key benefit over CacheDataset - disk cache survives restart
ds2 = PersistentDataset(data=items, transform=_InplaceXform(), cache_dir=tempdir, in_memory=True)
# RAM cache starts empty (simulating fresh process)
self.assertEqual(ds2.memory_cache_size, 0)
# Access all items - should load from disk and automatically cache to RAM
results = [ds2[i] for i in range(len(items))]
# Verify: ALL samples now in RAM again (automatic rebuild from disk)
self.assertEqual(ds2.memory_cache_size, 5)
# Verify: Results are correct (transformed by _InplaceXform)
for i, result in enumerate(results):
if i == 0:
expected = [[1]] # empty list -> append 1
else:
expected = [[np.pi] + list(range(1, i))] # data[0] = 0 + np.pi
self.assertEqual(result, expected)
# === Verify RAM cache provides fast repeated access ===
# Accessing same items again should hit RAM cache (same objects)
for i in range(len(items)):
result1 = ds2[i]
result2 = ds2[i]
# Should return equivalent results
self.assertEqual(result1, result2)
# RAM cache size unchanged (no duplicate entries)
self.assertEqual(ds2.memory_cache_size, 5)
if __name__ == "__main__":
unittest.main()