Skip to content

StdShiftIntensity, NormalizeIntensity(nonzero/channel_wise) and others modify the input array in place #9334

Backlog

Description

@harshil-sri

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)
  • NormalizeIntensity with nonzero=True or channel_wise=True (the default settings are out-of-place)
  • RandRicianNoise with channel_wise=True
  • RandCoarseDropout / RandCoarseShuffle

Most other intensity transforms, such as ShiftIntensity, ScaleIntensity and NormalizeIntensity() with default settings, leave the input alone. Two things break in practice:

  1. With a plain monai.data.Dataset over in-memory arrays, the stored data changes on every access. Each epoch re-normalizes data that was already normalized.
  2. Multi-sample crops such as RandSpatialCropSamplesd return 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 epoch

With 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.5

Expected 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

  1. Kietnehi commented on Nov 30, 2026

    @Kietnehi

    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.

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

Metadata

Metadata

Assignees

No one assigned

    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