Skip to content

Lazy resampling ignores mode="nearest", turning binary labels into soft labels #9224

Description

@ThomasKierski

Describe the bug

When a pipeline is run with Compose(..., lazy=True), the interpolation mode requested on a spatial transform
(e.g. Spacingd(..., mode="nearest"), Rotated(..., mode="nearest")) is not used when the pending operations
are finally applied. The fused resample falls back to the default bilinear mode, so binary/integer
segmentation labels come out with fractional ("soft") values along object boundaries. The same pipeline with
lazy=False correctly produces a binary label.

Two things combine to cause this:

  1. monai.transforms.lazy.utils.kwargs_from_pending reads LazyAttr.INTERP_MODE / LazyAttr.PADDING_MODE
    from the pending item, but spatial transforms such as Spacing, Rotate, Zoom, Resize and Affine
    record the user's mode / padding_mode only in the pending item's extra_info. The requested mode is
    therefore never passed to the resampler.
  2. In monai.transforms.lazy.functional.apply_pending, kwargs are merged with cur_kwargs.update(new_kwargs),
    so a later pending item with no mode (e.g. from SpatialPad / CenterSpatialCrop) overwrites an earlier
    mode with None.

This silently corrupts labels in any lazy pipeline that resamples segmentations, e.g. the standard
Spacingd -> Rotated/RandAffined -> SpatialPadd/Crop preprocessing.

To Reproduce
Self-contained script below: it builds a 64³ volume containing a 32³ binary foreground cube, then runs
Spacingd -> Rotated -> SpatialPadd (all mode="nearest") both eagerly and lazily, prints value statistics,
and saves a figure with a mid-slice imshow and a histogram for each output.

lazy_soft_labels_demo.py
"""Demo: lazy resampling ignores `mode="nearest"` and turns binary labels into soft labels."""

import sys

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import torch

import monai
from monai.data import MetaTensor
from monai.transforms import Compose, Rotated, Spacingd, SpatialPadd

print(f"MONAI {monai.__version__} loaded from {monai.__file__}")

# binary 64^3 label: a 32^3 foreground cube on an empty background
size = 64
label = torch.zeros(1, size, size, size)
label[:, 16:48, 16:48, 16:48] = 1.0
label = MetaTensor(label, affine=torch.eye(4))


def make_pipeline(lazy):
    return Compose(
        [
            Spacingd("label", pixdim=1.3, mode="nearest"),
            Rotated("label", angle=(0.0, 0.0, 0.4), mode="nearest", keep_size=True),
            SpatialPadd("label", spatial_size=72),
        ],
        lazy=lazy,
    )


results = {}
for name, lazy in [("eager (lazy=False)", False), ("lazy (lazy=True)", True)]:
    out = make_pipeline(lazy)({"label": label.clone()})["label"].array.squeeze()
    soft = np.count_nonzero((out > 0) & (out < 1))
    print(f"\n{name}: shape={out.shape}")
    print(f"  #unique values: {len(np.unique(out))}  (first few: {np.unique(out)[:6]})")
    print(f"  #soft (0 < v < 1) voxels: {soft}")
    results[name] = out

eager, lazy = results.values()
binary_ok = set(np.unique(lazy).tolist()) <= {0.0, 1.0}
print(f"\nlazy output is binary: {binary_ok}")
# lazy fuses all transforms into one resample, so a few boundary voxels may legitimately differ from eager
print(f"voxels where lazy != eager: {np.mean(eager != lazy):.2%}")

fig, axes = plt.subplots(2, 2, figsize=(10, 9))
for row, (name, out) in enumerate(results.items()):
    z = out.shape[-1] // 2
    im = axes[row, 0].imshow(out[..., z], cmap="viridis", vmin=0, vmax=1)
    axes[row, 0].set_title(f"{name}: slice z={z}")
    fig.colorbar(im, ax=axes[row, 0])
    axes[row, 1].hist(out.ravel(), bins=50, range=(0, 1), log=True)
    axes[row, 1].set_title(f"{name}: histogram ({len(np.unique(out))} unique values)")
    axes[row, 1].set_xlabel("voxel value")
    axes[row, 1].set_ylabel("count (log)")
tag = sys.argv[1] if len(sys.argv) > 1 else "output"
fig.suptitle(f'MONAI {monai.__version__} [{tag}]: Spacingd -> Rotated -> SpatialPadd, all mode="nearest"')
fig.tight_layout()
fig.savefig(f"lazy_soft_labels_{tag}.png", dpi=100)
print(f"saved lazy_soft_labels_{tag}.png")

Save the script as lazy_soft_labels_demo.py, then copy-paste one of the blocks below. Each block uses its own
virtual environment so the versions don't interfere. (Commands shown for bash; on Windows PowerShell replace
source <env>/bin/activate with <env>\Scripts\Activate.ps1.)

Latest release (pip install monai):

python -m venv venv-release && source venv-release/bin/activate
pip install torch --index-url https://download.pytorch.org/whl/cpu
pip install monai matplotlib
python lazy_soft_labels_demo.py release
deactivate

dev branch:

python -m venv venv-dev && source venv-dev/bin/activate
pip install torch --index-url https://download.pytorch.org/whl/cpu
pip install matplotlib "monai @ git+https://github.com/Project-MONAI/MONAI.git@dev"
python lazy_soft_labels_demo.py dev
deactivate
eager (lazy=False): shape=(72, 72, 72)
  #unique values: 2  (first few: [0. 1.])
  #soft (0 < v < 1) voxels: 0

lazy (lazy=True): shape=(72, 72, 72)
  #unique values: 85  (first few: [0.         0.02201395 0.02387741 0.03668991 0.03979568 0.04362671])
  #soft (0 < v < 1) voxels: 2469

lazy output is binary: False
voxels where lazy != eager: 0.67%

Expected behavior

Compose(..., lazy=True) should honour each transform's mode / padding_mode, so a binary label resampled
with mode="nearest" stays binary, just like with lazy=False. (Small differences on boundary voxels are
expected because lazy mode fuses all transforms into a single resample, but no new values should appear.)

Screenshots

Image

Environment
See above for reproduction on dev branch and 1.6.1 release branch

Additional context
I originally found this issue while debugging some unexpectedly poor training runs. This behavior was severely impacting model performance in cases where the foreground label had small islands / structures

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions