Skip to content

Fix NaN propagation in CPU cummax and cummin for float16 and bfloat16 - #4912

Merged
zcbenz merged 1 commit into
ml-explore:mainfrom
luciusacarr:cpu-scan-half-nan
Nov 24, 2026
Merged

zcbenz merged 1 commit into
ml-explore:mainfrom
luciusacarr:cpu-scan-half-nan

Conversation

@luciusacarr

Copy link
Copy Markdown
Contributor

Description:

On the CPU backend mx.cummax and mx.cummin on float16 and bfloat16 turn NaN into 0, so the NaN no longer propagates. float32 and GPU are correct. This is because scan.cpp returns std::numeric_limits<U>::quiet_NaN(). Since numeric_limits isn't specialized for the half types on CPU, it returns 0. We instead build NaN from float and cast to U as the file does for infinity. test_cummax_cummin_nan now also covers float16 and bfloat16.
Currently the code snippet

Reproduction:

import mlx.core as mx
mx.set_default_device(mx.cpu)
for dt in (mx.float32, mx.float16, mx.bfloat16):
    a = mx.array([1.0, float("nan"), 2.0]).astype(dt)
    print(dt, mx.cummax(a).tolist(), mx.cummin(a).tolist())

outputs

mlx.core.float32 [1.0, nan, nan] [1.0, nan, nan]
mlx.core.float16 [1.0, 0.0, 2.0] [1.0, 0.0, 0.0]
mlx.core.bfloat16 [1.0, 0.0, 2.0] [1.0, 0.0, 0.0]

but it should be

mlx.core.float32 [1.0, nan, nan] [1.0, nan, nan]
mlx.core.float16 [1.0, nan, nan] [1.0, nan, nan]
mlx.core.bfloat16 [1.0, nan, nan] [1.0, nan, nan]
  • ☑️ I understand it is strictly prohibited to use AI to write PR description
  • AI usage disclosure: AI used to probe discrepancy and aid in test coverage.

@zcbenz zcbenz closed this Nov 24, 2026
@zcbenz zcbenz reopened this Nov 24, 2026
@zcbenz
zcbenz merged commit 5598dfa into ml-explore:main Nov 24, 2026
48 checks passed
rcfa pushed a commit to cubiculum-ai/mlx that referenced this pull request Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants