Skip to content

percentile fails or truncates results for integer and float16 tensors #9321

Backlog

Description

@ngodongnguyen

Describe the bug

monai.transforms.utils_pytorch_numpy_unification.percentile fails or returns wrong values for non-float32/float64 inputs:

  1. Integer and float16/bfloat16 tensors with at most 1e6 elements raise
    RuntimeError: quantile() input tensor must be either float or double dtype, because torch.quantile only accepts float32/float64.
  2. On the numpy path (numpy inputs, and tensors above 1e6 elements, see pytorch#64947) the result is cast back to the input dtype, so interpolated percentiles of integer inputs are silently truncated.

As a consequence, ScaleIntensityRangePercentiles and ClipIntensityPercentiles (and their dict versions) fail on integer images such as uint8 PNGs or int16 CT volumes. Numpy inputs fail too, because these transforms convert to tensors first.

To Reproduce

import numpy as np
import torch
from monai.transforms import ClipIntensityPercentiles, ScaleIntensityRangePercentiles
from monai.transforms.utils_pytorch_numpy_unification import percentile

percentile(torch.tensor([0, 1, 2, 3]), 50)              # RuntimeError
percentile(torch.arange(4, dtype=torch.float16), 50)    # RuntimeError
percentile(np.array([0, 1, 2, 3]), 50)                  # 1, expected 1.5
percentile(torch.arange(2_000_000) % 4, 50)             # tensor(1), expected 1.5

img = torch.randint(-1024, 3000, (1, 32, 32), dtype=torch.int16)
ScaleIntensityRangePercentiles(1, 99, 0, 1)(img)        # RuntimeError
ClipIntensityPercentiles(1, 99)(img.numpy())            # RuntimeError

Expected behavior

Same result as np.percentile: integer inputs give a floating point percentile (1.5 above), and half-precision inputs are supported.

Environment

MONAI dev (89b1ce4), PyTorch 2.15.0, numpy 2.x, Python 3.13, macOS arm64.

Activity

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