Segmentation resampling, 17× faster
nnU-Net · batchgeneratorsv2 #28
Segmentation resampling, 17× faster
When nnU-Net rotates or scales a training patch, it also resamples its label map. This pull request makes that step nearly independent of the number of labels, with the same output, bit for bit.
1One pass per label
A label map cannot be interpolated directly: halfway between liver and kidney there is no “1.5”. So the old code resampled a 0/1 map of every label over the whole patch with PyTorch's grid_sample, and kept the label that scored highest.
→
grid_sample over the whole patchThe cost grows with the number of labels: with TotalSegmentator's ~56, over 2 seconds per sample, enough to make training wait on the CPU.
2Only the corners can win
Bilinear interpolation reads only the source voxels around each output point: 4 in 2D, 8 in 3D. A label absent from them scores zero, so however many labels the patch has, at most 8 compete at a voxel, read straight from those corners.
Move the point over the grid, or pick a case:
Scores at the point (out of 1,000)
- Label A700.0
- Label B300.0
- Label C0.0
Step 2Label A wins by 400. The corner weights settle it.
3Three steps, from cheap to exact
All corners agree
The output takes that label, with no arithmetic. About 98% of a 3D patch stops here.
A clear winner
On a boundary, the corner weights score each label. A lead of 2 out of 1,000 is far beyond any rounding difference, so the leader wins.
A near-tie
Whatever is left goes to PyTorch's own
grid_sample, run only at those points.
4Same output, much faster
Every decision that could depend on rounding is left to grid_sample itself, so the result cannot drift from the old code. An earlier version that copied its arithmetic instead differed in 1 voxel out of 12 million on an Apple M1; this one gave 0 on three PyTorch releases, x86 and Apple silicon.
The gain grows with the number of labels. Measured on a Ryzen 9 5950X with real nnU-Net patches; benchmark in the pull request.