Skip to content

Commit 368b1eb

Browse files
committed
Support multiple outputs in buffered sliding-window inference
Signed-off-by: TomasGuija <tomasguija@gmail.com>
1 parent a7904ae commit 368b1eb

2 files changed

Lines changed: 76 additions & 51 deletions

File tree

‎monai/inferers/utils.py‎

Lines changed: 32 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ def sliding_window_inference(
234234
importance_map_ = convert_data_type(importance_map_, torch.Tensor, device=sw_device, dtype=compute_dtype)[0]
235235

236236
# stores output and count map
237-
output_image_list, count_map_list, sw_device_buffer, b_s, b_i = [], [], [], 0, 0 # type: ignore
237+
output_image_list, count_map_list, sw_device_buffer, buffer_scales, b_s, b_i = [], [], [], [], 0, 0 # type: ignore
238238
# for each patch
239239
for slice_g in tqdm(windows_range) if progress else windows_range:
240240
slice_range = range(slice_g, min(slice_g + sw_batch_size, b_slices[b_s][0] if buffered else total_slices))
@@ -274,15 +274,28 @@ def sliding_window_inference(
274274
if buffered:
275275
c_start, c_end = b_slices[b_s][1:]
276276
if not sw_device_buffer:
277-
k = seg_tuple[0].shape[1] # len(seg_tuple) > 1 is currently ignored
278-
sp_size = list(image_size)
279-
sp_size[buffer_dim] = c_end - c_start
280-
sw_device_buffer = [torch.zeros(size=[1, k, *sp_size], dtype=compute_dtype, device=sw_device)]
281-
for p, s in zip(seg_tuple[0], unravel_slice):
282-
offset = s[buffer_dim + 2].start - c_start
283-
s[buffer_dim + 2] = slice(offset, offset + roi_size[buffer_dim])
284-
s[0] = slice(0, 1)
285-
sw_device_buffer[0][ensure_tuple(s)] += p * w_t
277+
for seg in seg_tuple:
278+
seg_shape = seg.shape[2:]
279+
z_scale = [out_w_i / in_w_i for out_w_i, in_w_i in zip(seg_shape, roi_size)]
280+
sp_size = [int(size * scale) for size, scale in zip(image_size, z_scale)]
281+
sp_size[buffer_dim] = int((c_end - c_start) * z_scale[buffer_dim])
282+
sw_device_buffer.append(
283+
torch.zeros([1, seg.shape[1], *sp_size], dtype=compute_dtype, device=sw_device)
284+
)
285+
buffer_scales.append(z_scale)
286+
for ss, seg in enumerate(seg_tuple):
287+
seg_shape = seg.shape[2:]
288+
w_t_ss = F.interpolate(w_t, seg_shape, mode=_nearest_mode) if seg_shape != roi_size else w_t
289+
for p, s in zip(seg, unravel_slice):
290+
output_slice = [slice(0, 1), slice(None)]
291+
for dim, scale in enumerate(buffer_scales[ss]):
292+
start = int(s[dim + 2].start * scale)
293+
stop = int(s[dim + 2].stop * scale)
294+
if dim == buffer_dim:
295+
start -= int(c_start * scale)
296+
stop -= int(c_start * scale)
297+
output_slice.append(slice(start, stop))
298+
sw_device_buffer[ss][ensure_tuple(output_slice)] += p * w_t_ss
286299
b_i += len(unravel_slice)
287300
if b_i < b_slices[b_s][0]:
288301
continue
@@ -292,37 +305,39 @@ def sliding_window_inference(
292305
for ss in range(len(sw_device_buffer)):
293306
b_shape = sw_device_buffer[ss].shape
294307
seg_chns, seg_shape = b_shape[1], b_shape[2:]
295-
z_scale = None
308+
z_scale = buffer_scales[ss] if buffered else None
296309
if not buffered and seg_shape != roi_size:
297310
z_scale = [out_w_i / float(in_w_i) for out_w_i, in_w_i in zip(seg_shape, roi_size)]
298-
w_t = F.interpolate(w_t, seg_shape, mode=_nearest_mode)
311+
weight_shape = tuple(int(size * scale) for size, scale in zip(roi_size, z_scale)) if z_scale else seg_shape
312+
w_t_ss = w_t if weight_shape == roi_size else F.interpolate(w_t, weight_shape, mode=_nearest_mode)
299313
if len(output_image_list) <= ss:
300314
output_shape = [batch_size, seg_chns]
301315
output_shape += [int(_i * _z) for _i, _z in zip(image_size, z_scale)] if z_scale else list(image_size)
302316
# allocate memory to store the full output and the count for overlapping parts
303317
new_tensor: Callable = torch.empty if non_blocking else torch.zeros # type: ignore
304318
output_image_list.append(new_tensor(output_shape, dtype=compute_dtype, device=device))
305319
count_map_list.append(torch.zeros([1, 1] + output_shape[2:], dtype=compute_dtype, device=device))
306-
w_t_ = w_t.to(device)
320+
w_t_ = w_t_ss.to(device)
307321
for __s in slices:
308322
if z_scale is not None:
309323
__s = tuple(slice(int(_si.start * z_s), int(_si.stop * z_s)) for _si, z_s in zip(__s, z_scale))
310324
count_map_list[-1][(slice(None), slice(None), *__s)] += w_t_
311325
if buffered:
312326
o_slice = [slice(None)] * len(inputs.shape)
313-
o_slice[buffer_dim + 2] = slice(c_start, c_end)
327+
o_slice[buffer_dim + 2] = slice(int(c_start * z_scale[buffer_dim]), int(c_end * z_scale[buffer_dim]))
314328
img_b = b_s // n_per_batch # image batch index
315329
o_slice[0] = slice(img_b, img_b + 1)
316330
o_slice_idx = ensure_tuple(o_slice)
317331
if non_blocking:
318-
output_image_list[0][o_slice_idx].copy_(sw_device_buffer[0], non_blocking=non_blocking)
332+
output_image_list[ss][o_slice_idx].copy_(sw_device_buffer[ss], non_blocking=non_blocking)
319333
else:
320-
output_image_list[0][o_slice_idx] += sw_device_buffer[0].to(device=device)
334+
output_image_list[ss][o_slice_idx] += sw_device_buffer[ss].to(device=device)
321335
else:
322-
sw_device_buffer[ss] *= w_t
336+
sw_device_buffer[ss] *= w_t_ss
323337
sw_device_buffer[ss] = sw_device_buffer[ss].to(device)
324338
_compute_coords(unravel_slice, z_scale, output_image_list[ss], sw_device_buffer[ss])
325339
sw_device_buffer = []
340+
buffer_scales = []
326341
if buffered:
327342
b_s += 1
328343

‎tests/inferers/test_sliding_window_inference.py‎

Lines changed: 44 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -323,42 +323,52 @@ def compute(data):
323323
def compute_dict(data):
324324
return {1: data + 1, 2: data[:, ::3, ::2, ::2] + 2, 3: data[:, ::2, ::4, ::4] + 3}
325325

326-
result = sliding_window_inference(
327-
inputs,
328-
roi_shape,
329-
sw_batch_size,
330-
compute,
331-
0.5,
332-
"constant",
333-
1.0,
334-
"constant",
335-
0.0,
336-
device,
337-
device,
338-
has_tqdm,
339-
None,
340-
)
341-
result_dict = sliding_window_inference(
342-
inputs,
343-
roi_shape,
344-
sw_batch_size,
345-
compute_dict,
346-
0.5,
347-
"constant",
348-
1.0,
349-
"constant",
350-
0.0,
351-
device,
352-
device,
353-
has_tqdm,
354-
None,
355-
)
356326
expected = (np.ones((1, 6, 20, 20)) + 1, np.ones((1, 2, 10, 10)) + 2, np.ones((1, 3, 5, 5)) + 3)
357327
expected_dict = {1: np.ones((1, 6, 20, 20)) + 1, 2: np.ones((1, 2, 10, 10)) + 2, 3: np.ones((1, 3, 5, 5)) + 3}
358-
for rr, ee in zip(result, expected):
359-
np.testing.assert_allclose(rr.cpu().numpy(), ee, rtol=1e-4)
360-
for rr, _ in zip(result_dict, expected_dict):
361-
np.testing.assert_allclose(result_dict[rr].cpu().numpy(), expected_dict[rr], rtol=1e-4)
328+
329+
for buffer_steps in (None, 2):
330+
result = sliding_window_inference(
331+
inputs,
332+
roi_shape,
333+
sw_batch_size,
334+
compute,
335+
0.5,
336+
"constant",
337+
1.0,
338+
"constant",
339+
0.0,
340+
device,
341+
device,
342+
has_tqdm,
343+
None,
344+
buffer_steps=buffer_steps,
345+
buffer_dim=0,
346+
)
347+
result_dict = sliding_window_inference(
348+
inputs,
349+
roi_shape,
350+
sw_batch_size,
351+
compute_dict,
352+
0.5,
353+
"constant",
354+
1.0,
355+
"constant",
356+
0.0,
357+
device,
358+
device,
359+
has_tqdm,
360+
None,
361+
buffer_steps=buffer_steps,
362+
buffer_dim=0,
363+
)
364+
self.assertIsInstance(result, tuple)
365+
self.assertEqual(len(result), len(expected))
366+
self.assertIsInstance(result_dict, dict)
367+
self.assertEqual(set(result_dict), set(expected_dict))
368+
for rr, ee in zip(result, expected):
369+
np.testing.assert_allclose(rr.cpu().numpy(), ee, rtol=1e-4)
370+
for rr in result_dict:
371+
np.testing.assert_allclose(result_dict[rr].cpu().numpy(), expected_dict[rr], rtol=1e-4)
362372

363373
result = SlidingWindowInferer(
364374
roi_shape, sw_batch_size, overlap=0.5, mode="constant", cval=-1, progress=has_tqdm

0 commit comments

Comments
 (0)