Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 21 additions & 5 deletions monai/transforms/utils_pytorch_numpy_unification.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,19 +120,35 @@ def percentile(
https://numpy.org/doc/stable/reference/generated/numpy.percentile.html.

Returns:
Resulting value (scalar)
Resulting value (scalar). As with `np.percentile`, integer inputs give a floating point result (float64),
so interpolated percentiles are not truncated to the input dtype, and floating point inputs keep their dtype.
"""
q_np = convert_data_type(q, output_type=np.ndarray, wrap_sequence=True)[0]
if ((q_np < 0) | (q_np > 100)).any():
raise ValueError(f"q values must be in [0, 100], got values: {q}.")
result: NdarrayOrTensor | float | int
if isinstance(x, np.ndarray) or (isinstance(x, torch.Tensor) and torch.numel(x) > 1_000_000): # pytorch#64947
_x = convert_data_type(x, output_type=np.ndarray)[0]
# `.numpy()` does not support bfloat16, compute in float32 and cast back below
_x = convert_data_type(
x.float() if isinstance(x, torch.Tensor) and x.dtype == torch.bfloat16 else x, output_type=np.ndarray
)[0]
is_floating = np.issubdtype(_x.dtype, np.floating)
if _x.dtype == np.bool_:
_x = _x.astype(np.float64) # `np.percentile` cannot interpolate between boolean values
result = np.percentile(_x, q_np, axis=dim, keepdims=keepdim, **kwargs)
result = convert_to_dst_type(result, x)[0]
# keep the floating point dtype of the result for non-floating inputs, otherwise it would be truncated
out_dtype = None if is_floating else np.asarray(result).dtype
result = convert_to_dst_type(result, x, dtype=out_dtype)[0]
else:
q = convert_to_dst_type(q_np / 100.0, x)[0]
result = torch.quantile(x, q, dim=dim, keepdim=keepdim)
# `torch.quantile` only supports float32 and float64 inputs
if x.dtype in (torch.float32, torch.float64):
_xt = x
else:
_xt = x.to(torch.float32 if x.is_floating_point() else torch.float64)
q = convert_to_dst_type(q_np / 100.0, _xt)[0]
result = torch.quantile(_xt, q, dim=dim, keepdim=keepdim)
if x.is_floating_point():
result = result.to(x.dtype) # e.g. float16 inputs give float16 results, as with `np.percentile`
return result


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,17 @@ def test_relative_scaling(self):
result, p(np.clip(expected_img, expected_b_min, expected_b_max)), type_test="tensor", rtol=0.1
)

def test_integer_input(self):
# integer images (e.g. uint8 PNG or int16 CT) should be scaled as their floating point equivalents
for dtype in (np.uint8, np.int16):
img = (self.imt[0] * 200).astype(dtype)
scaler = ScaleIntensityRangePercentiles(lower=10, upper=90, b_min=0, b_max=1)
expected = scaler(img.astype(np.float32))
for p in TEST_NDARRAYS:
result = scaler(p(img))
self.assertEqual(result.dtype, torch.float32)
assert_allclose(result, p(expected), type_test="tensor", rtol=1e-5, atol=1e-6)

def test_invalid_instantiation(self):
self.assertRaises(ValueError, ScaleIntensityRangePercentiles, lower=-10, upper=99, b_min=0, b_max=255)
self.assertRaises(ValueError, ScaleIntensityRangePercentiles, lower=101, upper=99, b_min=0, b_max=255)
Expand Down
17 changes: 17 additions & 0 deletions tests/transforms/test_clip_intensity_percentiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,23 @@ def test_channel_wise(self, p):
expected = clip(c, lower, upper)
assert_allclose(result[i], p(expected), type_test="tensor", rtol=1e-4, atol=0)

@parameterized.expand([[p, dtype] for p in TEST_NDARRAYS for dtype in (torch.uint8, torch.int16)])
def test_hard_clipping_integer_input(self, p, dtype):
# integer images (e.g. uint8 PNG or int16 CT) are clipped at their percentiles and keep their dtype
im = torch.arange(100, dtype=dtype).reshape(1, 10, 10)
result = ClipIntensityPercentiles(upper=95, lower=5)(p(im))
self.assertEqual(convert_to_tensor(result).dtype, dtype)
assert_allclose(result, torch.clamp(im, 4, 94), type_test=False)

@parameterized.expand([[p] for p in TEST_NDARRAYS])
def test_soft_clipping_integer_input(self, p):
# the output keeps the integer dtype of the input, so compare with the floating point result cast back
im = torch.arange(100, dtype=torch.int16).reshape(1, 10, 10)
soft_clipper = ClipIntensityPercentiles(upper=95, lower=5, sharpness_factor=1.0)
result = soft_clipper(p(im))
expected = soft_clipper(im.float()).to(torch.int16)
assert_allclose(result, expected, type_test=False)

def test_ill_sharpness_factor(self):
with self.assertRaises(ValueError):
ClipIntensityPercentiles(upper=95, lower=5, sharpness_factor=0.0)
Expand Down
55 changes: 54 additions & 1 deletion tests/transforms/test_utils_pytorch_numpy_unification.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from parameterized import parameterized

from monai.transforms.utils_pytorch_numpy_unification import max, min, mode, percentile
from monai.utils import set_determinism
from monai.utils import dtype_numpy_to_torch, set_determinism
from tests.test_utils import TEST_NDARRAYS, assert_allclose, skip_if_quick

TEST_MODE = []
Expand Down Expand Up @@ -61,6 +61,59 @@ def test_many_elements_quantile(self): # pytorch#64947
self.assertIsInstance(q, torch.Tensor)
assert_allclose(q.shape, [2], type_test=False)

@parameterized.expand([[p, dtype] for p in TEST_NDARRAYS for dtype in (np.uint8, np.int16, np.int32, np.int64)])
def test_percentile_integer_input(self, p, dtype):
# interpolated percentiles of integer inputs must not raise or be truncated
data = np.array([[0, 1, 2, 3], [1, 0, 1, 0]]).astype(dtype)
for kwargs in ({}, {"dim": 1}):
result = percentile(p(data), [25, 50], **kwargs)
expected = np.percentile(data, [25, 50], axis=kwargs.get("dim"))
if isinstance(result, torch.Tensor):
self.assertTrue(result.is_floating_point())
else:
self.assertTrue(np.issubdtype(result.dtype, np.floating))
assert_allclose(result, expected, type_test=False, atol=1e-6)

def test_percentile_bool_tensor(self):
result = percentile(torch.tensor([True, False, True, False]), 50)
self.assertTrue(result.is_floating_point())
assert_allclose(result, 0.5, type_test=False)

def test_percentile_integer_input_many_elements(self):
# tensors above 1e6 elements go through `np.percentile` (pytorch#64947), the result must not be truncated
data = np.arange(1_000_004, dtype=np.int32) % 4
for p in TEST_NDARRAYS:
result = percentile(p(data), 50)
assert_allclose(result, 1.5, type_test=False)

def test_percentile_floating_input_keeps_dtype(self):
for p in TEST_NDARRAYS:
for dtype in (np.float16, np.float32, np.float64):
result = percentile(p(np.arange(10, dtype=dtype)), [25, 50])
if isinstance(result, torch.Tensor):
self.assertEqual(result.dtype, dtype_numpy_to_torch(np.dtype(dtype)))
else:
self.assertEqual(result.dtype, np.dtype(dtype))
assert_allclose(result, [2.25, 4.5], type_test=False)

def test_percentile_bool_many_elements(self):
# booleans are not interpolated by `np.percentile`, which is used for numpy inputs and large tensors
data = np.arange(1_000_004) % 2 == 0
for p in TEST_NDARRAYS:
result = percentile(p(data), 50)
assert_allclose(result, 0.5, type_test=False)

def test_percentile_bfloat16_many_elements(self):
# `Tensor.numpy` does not support bfloat16, tensors above 1e6 elements are computed with numpy
result = percentile((torch.arange(1_000_004) % 4).to(torch.bfloat16), [25, 50])
self.assertEqual(result.dtype, torch.bfloat16)
assert_allclose(result.float(), [0.75, 1.5], type_test=False, atol=1e-2)

def test_percentile_bfloat16_tensor(self):
result = percentile(torch.arange(10, dtype=torch.bfloat16), [25, 50])
self.assertEqual(result.dtype, torch.bfloat16)
assert_allclose(result.float(), [2.25, 4.5], type_test=False, atol=1e-2)

def test_fails(self):
for p in TEST_NDARRAYS:
for q in (-1, 101):
Expand Down