Skip to content

ops.clamp incorrectly clamps NaN to lower bound instead of preserving NaN #367

Description

@ALinrunrun

Environment

Hardware Environment(Ascend/GPU/CPU):

/device cpu

Software Environment:

  • MindSpore version (source or binary): MindSpore 2.9.0
  • Python version (e.g., Python 3.7.5): Python 3.11.15
  • OS platform and distribution (e.g., Linux Ubuntu 16.04): Ubuntu 24.04.1, Linux 6.17.0-29-generic, x86_64
  • GCC/Compiler version (if compiled from source): gcc (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0

Describe the current behavior

mindspore.ops.clamp appears to handle NaN incorrectly for float32 tensors.

When the input contains NaN, +Inf, and -Inf, calling:

ops.clamp(x, -1.0, 2.0)

returns -1.0 for the NaN element.

Actual result:

[[-1.0, 2.0, -1.0],
 [0.3003249168395996, -1.0, -0.0947190374135971]]

The NaN value is incorrectly converted to the lower bound -1.0.

Describe the expected behavior

NaN should be preserved by ops.clamp, while finite and infinite values should be clamped to the specified range.

Expected result:

[[nan, 2.0, -1.0],
 [0.3003249168395996, -1.0, -0.0947190374135971]]

Steps to reproduce the issue

  1. Install MindSpore 2.9.0 and NumPy 1.26.4.
  2. Save the following script as reproduce.py.
  3. Run python reproduce.py.
import numpy as np
import mindspore as ms
import mindspore.ops as ops

x = ms.Tensor(
    np.array(
        [
            [np.nan, np.inf, -np.inf],
            [0.3003249168395996, -1.1990708112716675, -0.0947190374135971],
        ],
        dtype=np.float32,
    )
)

wrong = ops.clamp(x, -1.0, 2.0).asnumpy()

correct = np.array(
    [
        [np.nan, 2.0, -1.0],
        [0.3003249168395996, -1.0, -0.0947190374135971],
    ],
    dtype=np.float32,
)

print("wrong:", wrong.tolist())
print("correct:", correct.tolist())

Related log / screenshot

Running the script produces:

wrong: [[-1.0, 2.0, -1.0], [0.3003249168395996, -1.0, -0.0947190374135971]]
correct: [[nan, 2.0, -1.0], [0.3003249168395996, -1.0, -0.0947190374135971]]

Environment output:

Python version: 3.11.15
OS platform: Linux-6.17.0-29-generic-x86_64-with-glibc2.39
Machine: x86_64
MindSpore version: 2.9.0
NumPy version: 1.26.4
GCC version: gcc (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0

Special notes for this issue

This looks like a NaN/Inf handling issue in ops.clamp.

For the input:

[[nan, inf, -inf],
 [0.3003249168395996, -1.1990708112716675, -0.0947190374135971]]

with min=-1.0 and max=2.0, +Inf is correctly clamped to 2.0, and -Inf is correctly clamped to -1.0. However, NaN is unexpectedly clamped to -1.0 instead of remaining NaN.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions