Repository navigation
Description
Describe the bug
Several intensity transforms write their result into the caller's array instead of returning a new one. convert_to_tensor shares memory with a float32 numpy array or tensor, and these transforms then assign into it (img[slices] = ... or img[i] = ...):
StdShiftIntensity/RandStdShiftIntensity(always)NormalizeIntensitywithnonzero=Trueorchannel_wise=True(the default settings are out-of-place)RandRicianNoisewithchannel_wise=TrueRandCoarseDropout/RandCoarseShuffle
Most other intensity transforms, such as ShiftIntensity, ScaleIntensity and NormalizeIntensity() with default settings, leave the input alone. Two things break in practice:
- With a plain
monai.data.Datasetover in-memory arrays, the stored data changes on every access. Each epoch re-normalizes data that was already normalized. - Multi-sample crops such as
RandSpatialCropSamplesdreturn views of the source image. An in-place transform after the crop then writes into the source and into the other, overlapping samples.
To Reproduce
import numpy as np
from monai.data import Dataset
from monai.transforms import NormalizeIntensity, NormalizeIntensityd, RandStdShiftIntensityd
rng = np.random.default_rng(0)
vol = rng.normal(100.0, 20.0, size=(2, 8, 8, 8)).astype(np.float32)
a = vol.copy()
NormalizeIntensity(subtrahend=[100.0, 100.0], divisor=[20.0, 20.0], channel_wise=True)(a)
print(vol.mean(), a.mean()) # 99.016 -0.049, the caller's array was overwritten
ds = Dataset([{"img": vol.copy()}], transform=NormalizeIntensityd(
"img", subtrahend=[100.0, 100.0], divisor=[20.0, 20.0], channel_wise=True))
for epoch in range(3):
x = ds[0]["img"]
print(epoch, float(x.mean()), float(x.std()))
# 0 -0.0492 0.9723
# 1 -5.0025 0.0486
# 2 -5.2501 0.0024
ds = Dataset([{"img": vol.copy()}], transform=RandStdShiftIntensityd("img", factors=(1.0, 1.0), prob=1.0))
print([round(float(ds[0]["img"].mean()), 2) for _ in range(3)]) # [118.45, 137.89, 157.33], drifts up every epochWith crops:
import numpy as np, torch
from monai.transforms import RandSpatialCropSamplesd, StdShiftIntensityd
vol = torch.as_tensor(np.random.default_rng(0).normal(100.0, 20.0, size=(1, 16, 16, 16)).astype(np.float32))
src = vol.clone()
crop = RandSpatialCropSamplesd("img", roi_size=(12, 12, 12), num_samples=4, random_size=False)
crop.set_random_state(0)
out = [StdShiftIntensityd("img", factor=0.5)(s) for s in crop({"img": src})]
print(int((src != vol).sum())) # 2842 of 4096 source voxels changed
# each sample differs from "crop, then shift" on a clean copy by up to ~31.5Expected behavior
The transform returns a new array and the input is unchanged, as with ShiftIntensity or the default NormalizeIntensity. Running the same pipeline twice on the same data should give the same result.
Environment
MONAI 1.6.2+ (dev at 1502b8a; monai/transforms/intensity/array.py is unchanged from there), PyTorch 2.15.0+cpu, NumPy 2.5.4, Python 3.12.13, Windows 11.
Additional context
CacheDataset with the default copy_cache=True hides this for the random part of a pipeline, which may be why it hasn't been reported. It still shows with Dataset, copy_cache=False, multi-sample crops, and anyone calling the array transforms directly.
A possible fix is to clone once at the top of each affected __call__ (or _normalize / _stdshift) before the masked or per-channel assignment, and add a test that the input is unchanged. That costs one copy per call. If you'd rather keep the in-place path for speed, an alternative is to document it on these transforms. I'm happy to send a PR for whichever you prefer.
I used Claude Code to help find this.
Activity
Kietnehi commentedon Nov 30, 2026
Hi, I'd like to work on this. I've prepared a fix that makes these transforms write their result into a new array instead of the caller's input, with regression tests, and will open a PR shortly.