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.

2,217 → 130 msper sample, TotalSegmentator
9.9×whole training augmentation
0voxels that differ

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.

The 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.

A grid of source voxels in three labels, one output point and the four voxels it reads

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

  1. All corners agree

    The output takes that label, with no arithmetic. About 98% of a 3D patch stops here.

  2. 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.

  3. 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.

Segmentation resampling, median ms per sample before after
TotalSegmentator~56 labels
2,217
130
17×
MSD BrainTumour5 labels
329
140
2.4×
MSD Spleen2 labels
173
119
1.5×
MSD Hippocampus4 labels
10.0
9.2
1.1×

The gain grows with the number of labels. Measured on a Ryzen 9 5950X with real nnU-Net patches; benchmark in the pull request.