Skip to content

Handle sNaNs in {min,max}_precise on Neon - #441

Open
RunDevelopment wants to merge 3 commits into
linebender:mainfrom
RunDevelopment:min-max-precise
Open

RunDevelopment wants to merge 3 commits into
linebender:mainfrom
RunDevelopment:min-max-precise

Conversation

@RunDevelopment

Copy link
Copy Markdown
Contributor

Motivation

The _precise family of methods is supposed to return platform-independent precise results at the cost of speed. So it was very surprising to me when I read that max_precise didn't handle NaNs correctly. To quote the docs:

If a floating-point operand is a signaling NaN, the result is not just implementation-defined, but fully non-deterministic: it may be either NaN or the non-NaN operand. Signaling NaN values are not produced by floating-point math operations, only from manual initialization with specific bit patterns. You probably don’t need to worry about them.

In my case, the numbers I get are user input (they could be anything) so I can't just assume sNaNs aren't included. Plus, no other operation has this caveat around sNaNs and neither does the standard library with fN::max.

Changes

This PR removes the caveat around sNaN by bringing Neon in line. All other platforms already handled NaNs (signally or not) like the standard library.

To bring Neon in line, I'm using the same trick as the standard library. vmaxnmq_f32 is the element-wise max operation, and it also has the property of never returning sNaNs. So vmaxnmq_f32(x, x) will return a quiet NaN if x is any NaN value (signalling or not) and the numeric value of x otherwise. With this trick, sNaN disappears.

Example: max_precise(a, b) is implemented like this:

vmaxnmq_f32(
    vmaxnmq_f32(a, a),
    vmaxnmq_f32(b, b)
)

For consistency, I also adjusted reduce_{max,min}_precise to handle sNaN correctly using the same trick. However, the standard reduction from larger-than-native vectors would have resulted in a few unnecessary sNaN -> qNaN conversions. To avoid them, I also implemented a custom reduce logic to skip the unnecessary conversions.

@Shnatsel

Shnatsel commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

There is a much more significant problem with these methods:

If one floating-point operand is positive zero and the other is negative zero, the result is implementation-defined, and it could be either one.

It's a much bigger issue for determinism in practice than the theoretical possibility of signalling NaNs.

If you want fully IEEE compliant min/max that deals with all kinds of NaN and also signed zero, you need a much slower formulation. People have workshopped variants of it in this thread: https://news.ycombinator.com/item?id=49800085

I don't want to slow down the _precise variant for everyone because of signalling NaNs, but I am open to adding a min_ieee or some such that is fully deterministic at the cost of speed.

@RunDevelopment

Copy link
Copy Markdown
Contributor Author

My goal was to make them behave the same as the standard library by getting rid of the NaN caveat. Since the standard library doesn't care about non-deterministic +/-0, neither do I.

IMO, implementing IEEE 754's minimum/maximum should also follow the (unstable) standard library. But implementing those is a different issue from bringing the semantics of max_precise (and co.) in line with the standard library.

I don't want to slow down the _precise variant for everyone because of signalling NaNs

max_precise compiles to 3 instructions now. Same as WASM, AVX2, and SSE4.2. The slowdown is within what should be expected for the additional guarantees IMO.

Plus, the compiler can optimize away vmaxnmq_f32(x, x) when it knows x isn't NaN, so code like input.max_precise(0.0).min_precise(1.0) is 3 instructions. That's a lot better than other platforms (except AVX512), where max_precise could be implemented as a single instruction when one arg is known to be non-NaN, but the compiler isn't smart enough for that.

@Shnatsel

Copy link
Copy Markdown
Contributor

@LaurenzV could you check if this impacts important benchmarks in Vello?

@RunDevelopment

Copy link
Copy Markdown
Contributor Author

On that note: LLVM seems to think that vmaxnmq_f32(x, x) can be optimized away to just x.

Is this a miscompilation or am I doing something wrong? Does LLVM treat all NaNs as equivalent? Or does LLVM know something that I don't. Like making additional assumptions based on the target aarch64-unknown-linux-gnu .

@Shnatsel

Copy link
Copy Markdown
Contributor

Ah, this reminds me: Rust and LLVM do not preserve NaN bit patterns in arithmetic operations. I ran into this with miri previously, where it produced divergent bit patterns: rust-lang/miri#4995

std docs: https://doc.rust-lang.org/nightly/std/primitive.f32.html#nan-bit-patterns

I wouldn't be surprised if LLVM just looks at that op, decides that it only changes the NaN bit pattern, and discards it because the optimizer doesn't preserve NaN bit patterns.

@RunDevelopment

Copy link
Copy Markdown
Contributor Author

Yikes. So my fix doesn't even work...

Is there even a good way to fix this then? I just need one fast sNaN -> qNaN conversion that LLVM doesn't optimize away. But even if we find one, would the optimizer still leave it in the next Rust version...?

I think x.is_nan().select(QNAN, x) should work, because that's 3 instructions just to map all NaNs to qNaN (counting the load for the QNAN constant). If that is the only way to change the sNaN handling of {min,max}_precise, then I might even agree with you that the perf overhead isn't worth it.

@Shnatsel

Copy link
Copy Markdown
Contributor

Have you checked if signalling NaN inputs are even a problem in practice?

I think you need to load the values at runtime to check too, because LLVM constant propagation most likely won't match hardware semantics for NaN bit patterns.

@RunDevelopment

Copy link
Copy Markdown
Contributor Author

I don't have ARM hardware, so it's hard to test. In my use case, I get a &[f32] representing pixel data from the user, and the contract says that all NaNs are treated as zero. This was done in scalar using input.max(0.0).min(1.0) which maps NaN to zero. I don't control what NaNs the user gives me; I just have to deal with it.

I just asked Google Gemini and it suggested inline assembly (among a bunch of nonsense). Basically, have the sNaN -> qNaN conversion in a helper function implemented using asm!. This seems to work but I know nowhere near enough about any of this to judge whether this is a good solution. What do you think?

@Shnatsel

Copy link
Copy Markdown
Contributor

I'm afraid you'll need to turn NaNs into zeroes explicitly, if you want to be really sure, followed by .max(0.0).min(1.0)

I've looked into clamp(input, 0.0, 1.0) but that is slow on WASM with relaxed SIMD, where min/max are implementation-defined for NaNs, but clamp has to propagate the NaNs with extra instructions. Admittedly it's a niche platform.

Or you could rent an ARM server from a cloud for 30 minutes for like $1 to experiment and see if this is a problem in practice. You could even test all bit patterns exhaustively, if it's an f32.

@RunDevelopment

Copy link
Copy Markdown
Contributor Author

I've looked into clamp(input, 0.0, 1.0) but that is slow on WASM with relaxed SIMD, where min/max are implementation-defined for NaNs, but clamp has to propagate the NaNs with extra instructions.

I don't really understand what you're talking about here. Current SimdBase::clamp is 2 WASM instructions, and mapping NaN to min/max can be done with 2 instructions as well using f32x4.pmax and pmin. I.e. pmin(pmax(min, input), max) to map NaN to min.

Or you could rent an ARM server from a cloud for 30 minutes for like $1 to experiment and see if this is a problem in practice.

Unless that ARM CPU doesn't do what the ARM documentation says it should, then I don't really see the point in confirming what I already know from looking at the assembly 😐

Or did I misunderstand you?

@LaurenzV

Copy link
Copy Markdown
Collaborator

@Shnatsel So should I still benchmark anything?

@Shnatsel

Copy link
Copy Markdown
Contributor

No, this gets eliminated by LLVM anyway. Sorry!

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.

3 participants