From a23e810844ece32c0bebb50359492e24052044da Mon Sep 17 00:00:00 2001 From: ngodongnguyen Date: Wed, 25 Nov 2026 16:05:01 +0700 Subject: [PATCH 1/3] Fix percentile for integer and half-precision tensors `torch.quantile` only accepts float32/float64 inputs, so `percentile` raised a RuntimeError for integer (e.g. uint8 PNG, int16 CT) and float16/bfloat16 tensors with at most 1e6 elements. This made `ScaleIntensityRangePercentiles` and `ClipIntensityPercentiles` fail on integer images, including numpy inputs since those are converted to tensors first. The numpy path (numpy inputs and tensors above 1e6 elements) also cast the result back to the input dtype, truncating interpolated percentiles of integer inputs, e.g. the median of [0, 1, 2, 3] was 1 instead of 1.5. Integer inputs now give a float64 result as `np.percentile` does, and half-precision tensors are computed in float32 and keep their dtype. Signed-off-by: ngodongnguyen --- .../utils_pytorch_numpy_unification.py | 18 +++++++-- .../test_scale_intensity_range_percentiles.py | 11 ++++++ .../test_clip_intensity_percentiles.py | 17 ++++++++ .../test_utils_pytorch_numpy_unification.py | 39 ++++++++++++++++++- 4 files changed, 80 insertions(+), 5 deletions(-) diff --git a/monai/transforms/utils_pytorch_numpy_unification.py b/monai/transforms/utils_pytorch_numpy_unification.py index db6ebc26e61..cc9d2512332 100644 --- a/monai/transforms/utils_pytorch_numpy_unification.py +++ b/monai/transforms/utils_pytorch_numpy_unification.py @@ -120,7 +120,8 @@ 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(): @@ -129,10 +130,19 @@ def percentile( 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] 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 np.issubdtype(_x.dtype, np.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 diff --git a/tests/transforms/intensity/test_scale_intensity_range_percentiles.py b/tests/transforms/intensity/test_scale_intensity_range_percentiles.py index 20fe59246b0..db3d6ed72c7 100644 --- a/tests/transforms/intensity/test_scale_intensity_range_percentiles.py +++ b/tests/transforms/intensity/test_scale_intensity_range_percentiles.py @@ -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) diff --git a/tests/transforms/test_clip_intensity_percentiles.py b/tests/transforms/test_clip_intensity_percentiles.py index 12d93da47de..1627f63c992 100644 --- a/tests/transforms/test_clip_intensity_percentiles.py +++ b/tests/transforms/test_clip_intensity_percentiles.py @@ -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) diff --git a/tests/transforms/test_utils_pytorch_numpy_unification.py b/tests/transforms/test_utils_pytorch_numpy_unification.py index 76c378e2600..32f87a7e051 100644 --- a/tests/transforms/test_utils_pytorch_numpy_unification.py +++ b/tests/transforms/test_utils_pytorch_numpy_unification.py @@ -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 convert_to_dst_type, set_determinism from tests.test_utils import TEST_NDARRAYS, assert_allclose, skip_if_quick TEST_MODE = [] @@ -61,6 +61,43 @@ 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]) + self.assertEqual(result.dtype, convert_to_dst_type(np.zeros(1, dtype=dtype), result)[0].dtype) + assert_allclose(result, [2.25, 4.5], type_test=False) + + 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): From 4f4a09404e2c2c299500ced4af7c5def4231a104 Mon Sep 17 00:00:00 2001 From: ngodongnguyen Date: Wed, 25 Nov 2026 16:12:01 +0700 Subject: [PATCH 2/3] Compare percentile result dtype with the input dtype in test The previous assertion converted the expected value to the dtype of the result itself, so it passed even when float16 input gave float32 output. Signed-off-by: ngodongnguyen --- tests/transforms/test_utils_pytorch_numpy_unification.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/transforms/test_utils_pytorch_numpy_unification.py b/tests/transforms/test_utils_pytorch_numpy_unification.py index 32f87a7e051..a39728d1cb0 100644 --- a/tests/transforms/test_utils_pytorch_numpy_unification.py +++ b/tests/transforms/test_utils_pytorch_numpy_unification.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms.utils_pytorch_numpy_unification import max, min, mode, percentile -from monai.utils import convert_to_dst_type, 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 = [] @@ -90,7 +90,10 @@ 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]) - self.assertEqual(result.dtype, convert_to_dst_type(np.zeros(1, dtype=dtype), result)[0].dtype) + 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_bfloat16_tensor(self): From 81059a5b4bdfd02f42580faee9e53caebea5ffc7 Mon Sep 17 00:00:00 2001 From: ngodongnguyen Date: Wed, 25 Nov 2026 16:21:49 +0700 Subject: [PATCH 3/3] Support bfloat16 and boolean tensors above 1e6 elements in percentile Tensors with more than 1e6 elements are computed with `np.percentile`. `Tensor.numpy` does not support bfloat16, and `np.percentile` cannot interpolate between boolean values, so both raised an error. bfloat16 tensors are now computed in float32 and cast back to bfloat16, and boolean inputs are computed in float64 like integer inputs. Signed-off-by: ngodongnguyen --- monai/transforms/utils_pytorch_numpy_unification.py | 10 ++++++++-- .../test_utils_pytorch_numpy_unification.py | 13 +++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/monai/transforms/utils_pytorch_numpy_unification.py b/monai/transforms/utils_pytorch_numpy_unification.py index cc9d2512332..3ad9ed9f8ba 100644 --- a/monai/transforms/utils_pytorch_numpy_unification.py +++ b/monai/transforms/utils_pytorch_numpy_unification.py @@ -128,10 +128,16 @@ def percentile( 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) # keep the floating point dtype of the result for non-floating inputs, otherwise it would be truncated - out_dtype = None if np.issubdtype(_x.dtype, np.floating) else np.asarray(result).dtype + out_dtype = None if is_floating else np.asarray(result).dtype result = convert_to_dst_type(result, x, dtype=out_dtype)[0] else: # `torch.quantile` only supports float32 and float64 inputs diff --git a/tests/transforms/test_utils_pytorch_numpy_unification.py b/tests/transforms/test_utils_pytorch_numpy_unification.py index a39728d1cb0..9ff1ce29f7b 100644 --- a/tests/transforms/test_utils_pytorch_numpy_unification.py +++ b/tests/transforms/test_utils_pytorch_numpy_unification.py @@ -96,6 +96,19 @@ def test_percentile_floating_input_keeps_dtype(self): 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)