Skip to content

Commit a26ab35

Browse files
committed
Fix ShiftIntensity safe integer offset overflow
Signed-off-by: Rifa Ferzana <78103780+Rifa-111@users.noreply.github.com>
1 parent c5bddb2 commit a26ab35

2 files changed

Lines changed: 89 additions & 2 deletions

File tree

‎monai/transforms/intensity/array.py‎

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -254,8 +254,47 @@ def __call__(self, img: NdarrayOrTensor, offset: float | None = None) -> Ndarray
254254

255255
img = convert_to_tensor(img, track_meta=get_track_meta())
256256
offset = self.offset if offset is None else offset
257-
out = img + offset
258-
out, *_ = convert_data_type(data=out, dtype=img.dtype, safe=self.safe)
257+
if self.safe and not img.is_floating_point() and isinstance(offset, float) and not np.isfinite(offset):
258+
raise ValueError("ShiftIntensity with safe=True requires finite offsets for integer inputs.")
259+
if self.safe and img.dtype == torch.bool:
260+
# Interpret bool as 0/1 and saturate to the representable range.
261+
out = (img.to(torch.float64) + offset).clamp(0, 1).to(img.dtype)
262+
elif self.safe and img.dtype == torch.uint64:
263+
# Neither int64 nor float64 can represent all uint64 values exactly.
264+
raise TypeError("ShiftIntensity with safe=True does not support torch.uint64 inputs.")
265+
elif (
266+
self.safe
267+
and not img.is_floating_point()
268+
and (isinstance(offset, int) or (isinstance(offset, float) and offset.is_integer()))
269+
):
270+
# Keep integral offsets in integer arithmetic to avoid float64 precision
271+
# loss for int64 values above 2**53.
272+
shift = int(offset)
273+
bounds = torch.iinfo(img.dtype)
274+
if shift >= bounds.max - bounds.min:
275+
out = torch.full_like(img, bounds.max)
276+
elif shift <= bounds.min - bounds.max:
277+
out = torch.full_like(img, bounds.min)
278+
else:
279+
# Clamp before adding so even int64 arithmetic cannot overflow.
280+
work = img.to(torch.int64)
281+
if shift > 0:
282+
work = work.clamp(max=bounds.max - shift)
283+
elif shift < 0:
284+
work = work.clamp(min=bounds.min - shift)
285+
# Large offsets may exceed the range of a PyTorch int64 scalar.
286+
# Split them into representable additions after clamping.
287+
int64_bounds = torch.iinfo(torch.int64)
288+
remaining = shift
289+
while remaining:
290+
step = min(remaining, int64_bounds.max) if remaining > 0 else max(remaining, int64_bounds.min)
291+
work = work + step
292+
remaining -= step
293+
out = work.to(img.dtype)
294+
else:
295+
computation_img = img.to(torch.float64) if self.safe and not img.is_floating_point() else img
296+
out = computation_img + offset
297+
out, *_ = convert_data_type(data=out, dtype=img.dtype, safe=self.safe)
259298

260299
return out
261300

‎tests/transforms/test_shift_intensity.py‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,60 @@
1414
import unittest
1515

1616
import numpy as np
17+
import torch
1718

1819
from monai.transforms import ShiftIntensity
1920
from tests.test_utils import NumpyImageTestCase2D
2021

2122

2223
class TestShiftIntensity(NumpyImageTestCase2D):
24+
def test_safe_integer_offset_clamps_unsigned_image(self):
25+
image = torch.tensor([0, 100, 255], dtype=torch.uint8)
26+
for offset, expected in ((1, [1, 101, 255]), (-1, [0, 99, 254]), (1.0, [1, 101, 255]), (-1.0, [0, 99, 254])):
27+
with self.subTest(offset=offset):
28+
result = ShiftIntensity(offset=offset, safe=True)(image)
29+
torch.testing.assert_close(result, torch.tensor(expected, dtype=torch.uint8))
30+
31+
def test_safe_integer_offset_clamps_signed_image(self):
32+
image = torch.tensor([-128, 0, 127], dtype=torch.int8)
33+
result = ShiftIntensity(offset=1, safe=True)(image)
34+
torch.testing.assert_close(result, torch.tensor([-127, 1, 127], dtype=torch.int8))
35+
result = ShiftIntensity(offset=-1, safe=True)(image)
36+
torch.testing.assert_close(result, torch.tensor([-128, -1, 126], dtype=torch.int8))
37+
38+
def test_safe_int64_preserves_large_integer_precision(self):
39+
image = torch.tensor([2**60 + 1, torch.iinfo(torch.int64).max], dtype=torch.int64)
40+
result = ShiftIntensity(offset=1, safe=True)(image)
41+
torch.testing.assert_close(result, torch.tensor([2**60 + 2, torch.iinfo(torch.int64).max], dtype=torch.int64))
42+
negative = torch.tensor([-(2**60 + 1), torch.iinfo(torch.int64).min], dtype=torch.int64)
43+
result = ShiftIntensity(offset=-1, safe=True)(negative)
44+
torch.testing.assert_close(
45+
result, torch.tensor([-(2**60 + 2), torch.iinfo(torch.int64).min], dtype=torch.int64)
46+
)
47+
48+
def test_safe_int64_offset_beyond_scalar_range(self):
49+
image = torch.tensor([2**62], dtype=torch.int64)
50+
result = ShiftIntensity(offset=float(-3 * 2**62), safe=True)(image)
51+
torch.testing.assert_close(result, torch.tensor([torch.iinfo(torch.int64).min], dtype=torch.int64))
52+
53+
def test_safe_bool_input(self):
54+
image = torch.tensor([False, True], dtype=torch.bool)
55+
for offset, expected in ((0, [False, True]), (1, [True, True]), (-1, [False, False])):
56+
with self.subTest(offset=offset):
57+
result = ShiftIntensity(offset=offset, safe=True)(image)
58+
torch.testing.assert_close(result, torch.tensor(expected, dtype=torch.bool))
59+
60+
def test_safe_uint64_rejected_explicitly(self):
61+
image = torch.tensor([2**63 + 1], dtype=torch.uint64)
62+
with self.assertRaisesRegex(TypeError, "does not support torch.uint64"):
63+
ShiftIntensity(offset=1, safe=True)(image)
64+
65+
def test_safe_integer_nonfinite_offsets_rejected(self):
66+
image = torch.tensor([1, 2], dtype=torch.int64)
67+
for offset in (float("inf"), float("-inf"), float("nan")):
68+
with self.subTest(offset=offset), self.assertRaisesRegex(ValueError, "finite offsets"):
69+
ShiftIntensity(offset=offset, safe=True)(image)
70+
2371
def test_value(self):
2472
shifter = ShiftIntensity(offset=1.0)
2573
result = shifter(self.imt)

0 commit comments

Comments
 (0)