Faster floating point math with Rust's new API
pythonspeed.com
pythonspeed.com
Well, kind of. It's currently documented to wrap in release mode by default, but it's just that - a default. You're free to enable overflow checks in release mode (or disable them in debug if you really like oddball configurations), and either way overflow is considered a logic error that devs shouldn't rely on (and basically can't rely on when not in control of the end binary since it's the end user who controls overflow checks).
The Rust devs are theoretically open to making signed overflow panic by default, but consider such a change unlikely unless "something materially changes" [0].
[0]: https://github.com/rust-lang/rust/issues/47739#issuecomment-...
It's true that since it's safe and faster, release builds default to wrapping rather than panic, but it's still wrong if you overflow any of Rust's default integer types, it's just that in a safe language it won't be Undefined Behaviour.
"I can't be bothered to do it correctly" speaks to the quality of the rest of the product, it's a Brown M&M [read about the Van Halen test if you don't know what a Brown M&M means]
edit - nevermind, I'm wrong lol
I've never really found this argument particularly convincing; as you say, sanitizers don't have to strictly adhere to the standard, and they do in fact take advantage of this flexibility to check behaviors that "are not undefined behavior, but are often unintentional" (e.g., -fsanitize=unsigned-integer-overflow).
Makes me wonder whether "sanitizers can't flag defined behavior" is meant to be shorthand for some more nuanced position ("the false positive rate for signed overflow sanitizer checks would be too high", maybe?) or something else.
Of course, -fsanitize=unsigned-integer-overflow isn't enabled by default, and few people use it (github code search gives 6K results for that, compared to 175K for "-fsanitize=undefined"; which to be fair is a lot higher than I expected, but still not a lot).
> Makes me wonder whether "sanitizers can't flag defined behavior" is meant to be shorthand for some more nuanced position
And signed overflow checking would have to be off-by-default too, if people were allowed to start relying on it. It'd be less "false positive rate too high", more "it disallows you to use a genuine language feature that is actually useful", defeating the point of defining signed overflow in the first place.
(imo defining signed overflow specifically for reducing attack surface from exploitable UB is a mostly-separate discussion, which should not affect core language semantics, and certainly not what users would be suggested to do)
Sure, but it's still a counterexample for "you can't define it because it means sanitizers can't warn for it". Sanitizers can warn for it; you "just" get a worse signal-to-noise ratio.
> It'd be less "false positive rate too high", more "it disallows you to use a genuine language feature that is actually useful"
I'm not sure I see the distinction? Flagging a correct use of a language feature as incorrect is more or less the definition of a false positive, so if intentional signed overflows get a reasonable amount of use then that'd presumably result in an unacceptably noisy check to be enabled by default.
> defeating the point of defining signed overflow in the first place.
As for unsigned overflow checks I'd imagine the intent is that one would enable that particular check if you think that the corresponding overflow is more likely to be unintentional than not, and in the cases where it actually is intentional you can suppress the check.
Sure, technically you can write a sanitizer for anything. It just becomes less a "sanitizer" you can always recommend everyone everywhere use, and more of just a heuristic thing that only really works if you design your code for its arbitrary desires.
> and in the cases where it actually is intentional you can suppress the check.
imo it'd be nice to have separate types for wrapping and non-wrapping integers for that, so that you have actual language-level semantics and an easy way to mix things (e.g. wrapping arith for hashing, mixed with non-wrapping arith for loop index or whatever) instead of suppressions.
Sure, and that's basically what I was wondering about with respect to "can't define it" being shorthand for something else
> imo it'd be nice to have separate types for wrapping and non-wrapping integers for that
I think I'd agree, though I'd imagine it's a bit late for such things to be deeply integrated into the language. At least making your own isn't horrendously difficult.
Eh, I'd say it's still the same thing; can't define a sanitizer for it if what you define isn't a sanitizer. Depends on a specific definition of "sanitizer" though.
> At least making your own isn't horrendously difficult.
In C++ perhaps, but impossible in C. (and there are still some funky edge-cases where multiplying two `uint16_t`s can overflow due to implicit promotion to signed int; C's _BitInt solves at least that)
Clang does actually have experimental support for these - https://clang.llvm.org/docs/OverflowBehaviorTypes.html
Hrm, I suppose a general definition would be something that you use to check for certain (unintended?) runtime behaviors? Though I also feel that could include hardened implementations and stuff like valgrind....
> In C++ perhaps, but impossible in C.
Oh, true I forgot about that.
Rust has two behaviours around overflow. In debug builds, it panics, in release builds it wraps.
IMO wrapping is a reasonable-enough behaviour to avoid UB in release builds, and panicking in debug is definitely the correct behaviour, because you're only avoiding UB by defaulting to something, but that's not nearly enough. In most applications where overflow is a risk you should make sure to choose what behaviour you consider correct.
Thankfully Rust has a pretty robust story around this:
fn add_behaviour() {
let small: i32 = 123;
let big: i32 = i32::MAX;
assert_eq!(small.wrapping_add(big), i32::MIN + 122);
assert_eq!(small.overflowing_add(big), (i32::MIN + 122, true));
assert_eq!(small.overflowing_add(small), (246, false));
assert_eq!(small.saturating_add(big), i32::MAX);
assert_panics!(a.strict_add(b)); // (nb: Not a real assertion)
}
And you could easily implement the default behaviour yourself with conditional compilation: impl Add for u32 {
type Output = u32;
fn add(self, rhs: u32) -> u32 {
#[cfg(debug_assertions)]
{
self.strict_add(rhs)
}
#[cfg(not(debug_assertions))]
{
self.wrapping_add(rhs)
}
}
}As a sidenote, if implemented as a macro, e.g.
fn fast_sum_f64(values: &[f64]) -> f64 {
let mut total = 0;
fp_opt!(associative, {
for value in values {
total += value;
}
});
return total;
}
A question arises what happens when operating on custom types that overload arithmetic operations. I think the cleanest approach here would be to let the custom type define optimised versions, or have another macro that automatically generates them based on the existing ones, i.e. propagate the optimisation flags.It's not strictly true to say that it's "being conservative". What is more correct is to say that floating point operations have different semantics to integer operations, and an optimisation that retains the semantics of an expression over integers may not do so when applied to an expression over integers. Hence, it may be possible to apply one optimisation to an integer expression, but applying that to a floating-point expression may result in a different program meaning.
C/C++ compilers give you a way out of this with the `--ffast-math` flag, which essentially allows compilers to relax the constraints on floating-point optimisation passes.
For an example of how this works in GCC, take a look here: https://gcc.gnu.org/wiki/FloatingPointMath
People should really use the individual optimization flags they want (no signed zeros, no trapping math, associative math, reciprocal math) and not -ffast-math because the other optimizations it enables leads to surprising code (for example, isinf and isnan may become noops, which will break production code).
Basically never use an optimization flag that changes the semantics of your code without understanding exactly what that means. I have had to fix this in a number of codebases because someone thought that flag was as innocuous as -O3.
And if you have to enable flush to zero/denormals are zero it should be explicit in your code and scoped.
They're much stranger than the machine integers. The machine integers are basically like the Integers you were taught in school, except for overflow. That's not nothing but it's a complexity you can ignore entirely so long as you never overflow. In Rust you can have the language keep you safe - if an overflow occurs we'll panic and we're done. However the floating point types are a weird thing entirely invented for the convenience of the machine. They're too often introduced as if, like the machine integers, they're almost familiar numbers from school. Some languages even call these types "real" - but they very much are not actually the Real numbers, not even the approximation that the machine integers were to actual Integers. The programming language can't help you cope today. You can use software like "Herbie" to help you a bit, but today's languages just leave you with it.
Here's an easy example you saw in school, a tenth, written 0.1 in decimal. The floating point types cannot represent this number. When you ask for the 32-bit floating point value 0.1 in a language like C or Rust, you actually get exactly 0.100000001490116119384765625 because that was a number the type can represent and it was deemed "close enough".
If you want "simple" rationals, you can use the numerator/denominator scheme. This has its own problems but if you avoid overflows, they are the rationals you were taught in school, just like the integers.
The problem is that people (and languages) default to floating-point without understanding the consequences. Many times it does not matter and then floating point are indeed better (if you know how to use them, e.g. not comparing for equality), but sometimes it does.
If you were to insist on there being only one numeric data type in a language, then floating-point turns out to be the best compromise, especially because someone who doesn't understand the pitfalls of floating-point are going to be less likely to have it blow up in their face than other options. Fixed-point has a problem when the numbers have very different scales. Rational numbers don't let you do basic things like "measure the distance between two points" (because functions like sqrt or exp aren't defined on rational numbers).
However the floating point types are just binary rationals, so if we took this "can't do basic things" at face value we couldn't do these operations on the floating point types either.
The reason they're so weird is a convenience to the implementation. I am not an EE so I can't tell you how much that saved, but it was a choice, obviously we can't implement the Reals because Almost All Reals aren't even Computable, but I think most software engineers really don't have an appropriate understanding of the floating point types and the result is buggy software.
Which is sort of the thing of floating-point: they may be weird, but it kind of turns out that they're ultimately less weird than all of their alternatives, if you try to do anything other than toy examples on them. It's almost like floating-point was designed by people who needed to do a lot of numerical work in computers instead of students in Programming 101!
In my (unpublished) toy calculator I added a mechanism to bring an f32 or f64 into existence and convert it to my Rational type and so that's why I had the exact value of the f32 we call 0.1 to hand earlier. But of course the API goes much further than that. Want to multiply the square root of 40 by the square root of 1000? No problem that's exactly 20. A bright teenager can figure that out, and so can a properly designed API for numbers. The ordinary human activities you talked about of course work just fine in this API, it has historically been how the calculator in an Android phone works for example.
Symbolic approaches also have value in this space.
In both cases, what you do not get is the problem where the programmer mistakenly believes these types will behave like the numbers in school but actually they behave in an entirely different way. You have to go really far off piste, by which point likely the programmer has appreciated that they do not understand what's going on, before you trip on a hazard we cannot manage with this approach - whereas in traditional floating point that happens without them realising.
const FOO: f32 = 0.75; // The 32-bit floating point value three quarters
If you try const UNTYPED = 0.75; // Does not compile, pick a type
I don't find the SO answer very convincing because it seems like it's trying to argue this is the Reals, and it just isn't, it's only a subset of the Rationals which happened to be convenient for Go to work with it. The Reals are much stranger.Joke's on you, in my programming language all numbers are written in phinary: https://en.wikipedia.org/wiki/Golden_ratio_base
But yes, you can absolutely represent irrational numbers (only a finite amount of them of course). You can even do it symbolically.
https://en.wikipedia.org/wiki/Computable_number
roughly represent each number as a turing machine, which on input i outputs the ith digit. it works fine (it's slower than floats, but that's a different concern).
the issue is that the computable numbers are relatively small. in particular, there are countably many turing machines, so they're a countable subset (in fact subfield) of the reals. so in a precise sense they only make up a vanishingly small fraction of the real numbers. but they still capture many important mathematical constants, e.g. e and pi.
Anyway adding this optimisation to CPython would be like putting active aero on a dandy horse.
As for change in semantics, apparently that isn't an issue on JS, Java and .NET JITs in adopting more modern architectures.
I think it'd be an issue irrespective of the architecture? Optimizations are generally expected to preserve semantics and those languages all specify IEEE 754 semantics which aren't necessarily associative. For instance, from the Java language spec [0]:
> Floating-point arithmetic is carried out in accordance with the rules of the IEEE 754 Standard, including for overflow and underflow (§15.4), with the exception of the remainder operator % (§15.17.3).
Or the .NET reference [1]:
> The Double type complies with the IEC 60559:1989 (IEEE 754) standard for binary floating-point arithmetic.
Or the ECMAScript 2027 spec [2]:
> Numeric operators such as +, ×, =, and ≥ refer to those operations as determined by the type of the operands. [] When applied to Numbers, the operators refer to the relevant operations within IEEE 754-2019.
[0]: https://docs.oracle.com/javase/specs/jls/se26/jls26.pdf
[1]: https://learn.microsoft.com/en-us/dotnet/csharp/language-ref...
RyuJIT target CPU modes, breaking change due to dropping support for older hardware,
https://github.com/dotnet/docs/issues/48045
> Native Image now targets x86-64-v3 architecture by default on AMD64 and provides a new -march option to specify target compatibility. Use -march=compatibility for best compatibility or -march=native for best performance if a native executable is deployed on the same machine or on a machine with the same CPU features. To list all available machine types, use -march=list.
I'd assume they aren't applied by default and/or without the programmer explicitly opting in to those altered semantics, though. Would you be able to show otherwise?
I don't see how changing targeted instruction sets is relevant here as the instructions you use is orthogonal to whether you assume floating point operations are associative.
I'm pretty sure this is wrong. No JS engine, RyuJIT or or HotSpot break IEE-754. Java does have intrinsics for algebraic floating point operations (but does not apply them by default and I don't think they're exposed), the other I don't think.
The tl;dr for the relevant languages here is:
* Java requires full IEEE 754 conformance (and bounds ULPs on java.lang.Math functions, although not fully correctly-rounded), although (now removed) strictfp permitted a slightly more relaxed mode to make it easier to implement using x87 FPU arithmetic.
* C# has license for excess precision mode and denormal flushing.
* JS is strict IEEE 754 conformance, except for math library functions (which can be more approximate).
* Go permits FMA contraction (but is otherwise silent).
* Most other interpreted/JIT'd languages pretty much go "you get your machine floating-point."
And, FWIW, all of those floating-point semantics are orthogonal to things enabled by -ffast-math or similar flags! The only languages that really discuss such things are C (in a TS nobody implements), Fortran (which lets you rearrange expressions as long as you preserve parentheses), Julia (which has a fast_fma-like function and a fast-math macro), and now Rust.