Skip to content

Add method to disable fast-math on a per-shader basis. #2076

Open

Description

@mrshannon

Add the ability to disable fast-math.

Currently there is no way to enable/disable fast-math for a shader. This has caused severe numerical inconsistencies across platforms for us, sometimes producing errors of several thousand percent. See https://jsfiddle.net/mrshannon/mudLvz17/ for an example. In particular the algorithm implemented in that demo delivers the same results on CPU and GPU on both Windows (DX12 backend) and Linux (Vulkan backend) but is 8 orders of magnitude off on Mac OS (Metal backend). The algorithm in that example is extremely sensitive to changes in operation order (associative and distributive rules cannot be used). Therefore, I suspect fast-math is the issue. The algorithm in the example above is emulated double precision (subtraction operations) which is used by some renderers to achieve increased resolution where doubles are not available. In particular it is used in the rendering of planets in Elite Dangerous.

Enabling/disabling fast-math could be handled via either some sort of option in WGSL (as it is with SPIR-V) or at the compilation level as an option in createShaderModule (similar to Metal).

How this relates to each backend is covered below.

DirectX 12

There does not appear to be any fast-math option in DirectX, but I am not that familiar with DX12 so correct me if this is not correct.

According to Floating Point Rules it appears that associative and distributive properties are never used in DirectX outside of explicitly fused operations such as mad.

In general DirectX is very close to IEEE with the primary difference being rounding denorms to zero.

Vulkan (SPIR-V)

SPIR-V treats vertex/fragment shaders and compute shaders differently.

Shader

From the Vulkan spec

By default, the implementation may perform optimizations on half, single, or double-precision
floating-point instructions that ignore sign of a zero, or assume that arguments and results are
not NaNs or infinities. If the entry point is declared with the SignedZeroInfNanPreserve execution
mode, then NaNs, infinities, and the sign of zero must not be ignored.

As for rearrangement of operations, this is only allowed inside builtin functions (like DirectX).

Kernel - compute shader

SPIR-V has a fast-math mode called FP Fast Math Mode which allows enabling/disabling the following fast-math features individually by setting a bitfield in the shader:

  • Assume no NaNs
  • Assume no Inf
  • No signed 0
  • Multiplication of reciprocal instead of division
  • Allow algebraic transformations according to associative and distribute properties.

Metal

According to the Metal Shading Language Specification fast-math is enabled by default but can be disabled with -fno-fast-math option on the compiler. With fast-math enabled (the default) the following optimizations are made:

  • Assume no NaNs
  • Assume no Inf
  • No signed 0
  • Multiplication of reciprocal instead of division
  • Allow algebraic transformations according to associative and distribute properties.

Summary

Of all the backends Metal is the only one that does not allow disabling associative/distributive optimizations without disabling all fast-math operations. Also, from my testing Metal seems to be the only backend for which associative/distributive optimizations are on by default.

While the ability to enable/disable different optimizations individually as in SPIR-V compute shaders would be nice, since it is usually associative/distributive optimizations which cause the most trouble, the only cross platform solution is to enable/disable all fast-math optimizations on a whole shader basis.

Specifically disabling fast-math should:

  • Do nothing on DX12
  • Add SignedZeroInfNanPreserve to the entry point of vertex/fragment shaders or set the FP Fast Math Mode bitfield of compute shaders to 0x0.
  • Use -fno-fast-math on Metal.

NOTE: Sometimes the invariant qualifier can disable associative/distributive optimizations in other APIs but in WGSL this is limited to the built-in position variable.

Activity

  1. added
    wgsl
    on Aug 31, 2021
  2. kainino0x commented on Aug 31, 2021

    @kainino0x
    Contributor

    The Metal shader compiler is Clang. According to Clang docs:
    https://clang.llvm.org/docs/UsersManual.html#cmdoption-ffast-math

    This option implies:

    • -fno-honor-infinities
    • -fno-honor-nans
    • -fno-math-errno
    • -ffinite-math-only
    • -fassociative-math
    • -freciprocal-math
    • -fno-signed-zeros
    • -fno-trapping-math
    • -ffp-contract=fast

    It's likely that all of these flags can be used individually in MSL as well, even if they're undocumented by the MSL spec.

  3. kainino0x commented on Aug 31, 2021

    @kainino0x
    Contributor
  4. kvark commented on Aug 31, 2021

    @kvark
    Contributor

    Thank you for putting this together!

    Note that #1743 already describes the desired precision of the operations, and I believe it has a more comprehensive investigation. It has been decided there to follow the relaxed precision rules for MVP.

    If we want an ability to turn off the math optimizations, I think it needs to be done at the shader module level, since both MTLLibrary and a SPIR-V module can be generated from the shader source before the entry point is known.

    Kernel - compute shader

    This isn't something we use in WebGPU. We only care about the "Shader" capability, which supports compute shaders.

  5. kainino0x commented on Aug 31, 2021

    @kainino0x
    Contributor

    Kernel - compute shader

    This isn't something we use in WebGPU. We only care about the "Shader" capability, which supports compute shaders.

    Ah yup, "Kernel" is for OpenCL (and newer Vulkan maybe?), not usual compute shaders.

  6. munrocket commented on Sep 1, 2021

    @munrocket
    Contributor

    Agree with mrshannon that -ffast-math can be optional because it breaks IEEE-754 1985. This is a very clever standard that with hardware fma gives full kit for floating point expansion. In other words strict calculation can be useful for arbitrary precision arithmetic. But even if you keep basic operations (*/+-) correct, without reordering and without implicit MAD instruction (which is used in fast-math) sky is the limit and you can construct float256 from float32.

    So I believe that criteria to turn-on/turn-off compiler flags in strict mode is: “will it break finite version of IEEE-754”? And here practical criteria: “will it break kahan summation?” or “will it break double-double arithmetic?”.

  7. kvark commented on Sep 1, 2021

    @kvark
    Contributor

    Took a stab at it with #2077

  8. dneto0 commented on Sep 1, 2021

    @dneto0
    Contributor

    Sorry, I don't think this is reasonable.

    For graphics APIs like OpenGL, DirectX (I believe) and Vulkan (definitely), floating point operates as if it is always fast-math. There is no widespread support for the accuracy and edge case behaviours of IEEE-754.
    These implementations would not pass a carefully constructed test suite

    OpenCL originally had High Performance Computing (a.k.a. traditional "scientific") as a target market, so it requires the more complete IEEE 754 support. Its CTS does a good job testing those edge cases.

    The graphics APIs would fail the math tests in the OpenCL suite

    (I don't speak for Metal.)

    You may ask yourself: But the same GPUs implement OpenCL and Vulkan (say). True! But they are often different compiler/library stacks, with different target markets. Game developers need speed over the accuracy/edge-cases that full IEEE offers.

    If you add a flag saying "fast-math" and it can be false, i.e. require more complete IEEE 754, then (1) you would have to write that test suite, and (2) many many implementations would fail.

  9. kvark commented on Sep 1, 2021

    @kvark
    Contributor

    I don't think anybody feels really strongly about us exposing the strict IEEE-754. Instead, we care about getting access to Metal's "fast-math" option, since it's a deal breaker for a lot of practical scenarios, like KhronosGroup/MoltenVK#1209.
    So instead of exposing "Strict vs Relaxed" we can say it's "Less Relaxed vs More Relaxed" - names aren't important here, it would still be very useful.

    In terms of CTS, we can probably test that Inf and Nan are respected, at least. If we can't test everything, doesn't mean there is no value in exposing it. It could be even defined as "implementations do best effort in trying to preserve the accuracy" or something like this.

  10. mrshannon commented on Sep 1, 2021

    @mrshannon
    ContributorAuthor

    If you add a flag saying "fast-math" and it can be false, i.e. require more complete IEEE 754, then (1) you would have to write that test suite, and (2) many many implementations would fail.

    I was not arguing for exact IEEE-754 support. Only a mode more akin to what DirectX always promises and what Vulkan delivers with SignedZeroInfNanPreserve. There are existing engines that if ported from DirectX or Vulkan would require this, as MoltenVK found out.

    In our use case, disabling of reassociation (a Metal only optimization) of fundamental operations would be enough to enable algorithms such as Kahman summation and arbitrary precision. Though I am sure there are those that make use of Inf, NaN, and signed zero as these are commonly available in DirectX and Vulkan.

    Game developers need speed over the accuracy/edge-cases that full IEEE offers.

    While we do favor speed over accuracy (as we intend to use this in both compute and certain vertex shaders) there are cases where accuracy must be maintained in order to maintain visual smoothness. Therefore, in our specific case we are only trying to get the same behavior on the Metal backend that we can already count on for DirectX and Vulkan backends (kind of a shame this would require an option at all).

    It's likely that all of these flags can be used individually in MSL as well, even if they're undocumented by the MSL spec.

    If there was a way to disable reassociation in Metal without disabling all optimizations I would argue that it should be disabled by default in order to bring it inline with the other backends.

    EDIT: Seems kvark already beat me to most of this.

  11. kvark commented on Sep 1, 2021

    @kvark
    Contributor

    Second try in #2080

  12. dneto0 commented on Sep 1, 2021

    @dneto0
    Contributor

    Thanks @kvark for linking that issue. It's very informative.

    Also, from my testing Metal seems to be the only backend for which associative/distributive optimizations are on by default.

    I suspect that for Vulkan, it only covered the (big-area) desktop GPUs, and not mobile.
    As for DirectX, I think that's dominated by desktop. (Qualcomm apparently has DirectX but I don't know how popular it is.)

    In our use case, disabling of reassociation (a Metal only optimization) of fundamental operations would be enough to enable algorithms such as Kahman summation and arbitrary precision.

    GLSL addresses this use case with the "precise" qualifier. (Discussed offline with @kvark about this).

    Some algorithms require floating-point computations to exactly follow the order of operations specified in
    the source code and to treat all operations consistently, even if the implementation supports optimizations
    that could produce nearly equivalent results with higher performance. ....

    When translating that to SPIR-V, that's propagated through expressions and becomes the NoContract decoration on value-producing SPIR-V instructions.

    The Metal compiler's control is fairly coarse grain, and affects the entire module.

    So those are two extremes about how to specify.

    Some obvious options are:

    • whole module (like Metal; also, SPIR 1.2 has FP_CONTRACT)
    • C99 has an FP_CONTRACT pragma which can be turned on or off at specific points in the source. (C99 7.12.2)
    • per entry point (and its static call tree)
      • this has a bit of "action at a distance" feel which is unsettling. For example if two entry points have different options, but call the same helper function, then either you duplicate the helper, or one entry point influences the other
    • per user-defined function.
      • still quite coarse grain
      • this allows the programmer to explicitly capture their intent, and avoids the action-at-a-distance problem.

    I argue that the last option (attribute on a user-defined function) is a good balance.

    A motivating example: An application might combine two chunks of code with different needs. For example, one is arithmetic-sensitive like described by @mrshannon. Another chunk is an ML library that really wants very fast-math-y behaviours. The application may want to glue those WGSL chunks together for transport and presentation to createShaderModule. I would be sad if the adding one changed the perf/accuracy behaviour of the other. That would be bad action-at-a-distance.

  13. munrocket commented on Sep 7, 2021

    @munrocket
    Contributor

    Sorry, if David Neto was against this at first, maybe in practice GPUs computations not robust for lot of devices or there are some issues with user dtection? Can this feature be useful only for PC version of WebGPU?

    Fair enough to say that this technique not so popular. It is used in scientific stuff and galaxy simulators. This example exist in shadertoy and it works even with WebGL on iPhone 11, but not on macbook Air 2017 not sure why. (If example will crash, change iTime to iTime+70.)

  14. pow2clk commented on Sep 8, 2021

    @pow2clk

    There is a setting for DX, "REFACTORING_ALLOWED" that is per-entry and determines what the default behavior is. The documentation cited is from the DX11 era as the parenthetical implies and references a time when the default for it was false. In SM5.0+, the default is true, which makes all operations fast math except where variables qualified with precise are concerned.

    Depending on the details of the resolution here, the per-entry setting might be toggled or the precise keywords could be applied where needed. Regardless, there are solutions for DX backends, but DX12 is definitely not a no-op.

  15. kainino0x commented on Sep 10, 2021

    @kainino0x
    Contributor

    It's likely that all of these flags can be used individually in MSL as well, even if they're undocumented by the MSL spec.

    The flags I pointed to can probably only be used when invoking an MSL compiler via command line, but not via newLibraryWithSource. However I found the associated clang pragmas:
    https://clang.llvm.org/docs/LanguageExtensions.html#extensions-to-specify-floating-point-flags

  16. added this to the V1.0 milestone on Feb 3, 2022
  17. modified the milestones: V1.0, post-V1 on Feb 8, 2022
  18. raphlinus commented on Jun 7, 2023

    @raphlinus

    I have a specific use case for this feature or a related one. As part of a line rasterization algorith, I am writing floor(a * f32(i) + b) quite a bit, and I rely on the behavior being consistent, ie this always returning the same value for the same input. Ideally I would like a way to specify this. It's similar to the invariant attribute but with different scope.

    Either of these behaviors is completely acceptable for me:

    • It gets compiled as a fused multiply-add operation. This is available in MSL (fma) and HLSL (mad, especially in combination with precise), but I think not Vulkan.
    • It gets compiled as a multiply, rounded to IEEE, then an add. This is "no-contract" behavior as discussed above.

    The following behaviors are undesirable:

    • Sometimes compiled as multiply and add, sometimes fused.
    • The optimization of floor(a * f32(i + 1) + b) to floor(t + a) where t = a * f32(i) + b is likely to have been computed elsewhere.

    I understand it's tricky to design something that's both portable and performant, so in this comment am stating my wish-list item rather than proposing a mechanism.

  19. mikialex commented on Jul 3, 2025

    @mikialex

    I'm implementing the high-precision large world rendering support in my renderer using methods such as https://godotengine.org/article/emulating-double-precision-gpu-render-large-worlds/ or https://www.youtube.com/watch?v=HdIVSwdXQQM&list=PLLaly9x9rqjsXLW1tMFruyh_657sh8epk&index=7, which is as same as the above demo link issue. As far as I know, this is the best way to do large world rendering. The ability to disable fast math is crucial to support this feature.

  20. isghe commented on Aug 15, 2026

    @isghe

    Another concrete data point for this: a double-single (Dekker) emulation used to extend zoom depth in a WebGPU Mandelbrot/Julia renderer shows the same reassociation/fusion breakage described here, browser-dependent on identical hardware.

    Standalone file:// reproduction (WebGPU compute, no build step): https://github.com/isghe/mandelbrot/blob/master/scripts/precision-portability-probe.html (also runnable live, served over https: https://isghe.github.io/mandelbrot/scripts/precision-portability-probe.html)

    Setup: a two_sum/quick_two_sum-based ds_add (hi/lo f32 pair) computing 32 adjacent-pixel offsets at a fixed deep-zoom view (probe SCALE ≈ 2.9e-6; in-app visual gap past roughly mscale 1e-5 / blocks ~8–11px wide by 1e-6). The correctness-critical property is that the algebraically-zero error term in two_sum survives compilation — per §15.7.5 Reassociation and Fusion, the compiler is free to simplify it away.

    Result on the same machine/GPU:

    • Plain f32 offset (no double-single): 32/32 distinct coordinates on both Chromium and Firefox — as expected, this path has no error term to lose.
    • Post-ds_add double-single offset: 32/32 distinct on Chromium (Dawn), only 4/32 distinct on Firefox (naga/wgpu) — i.e. Firefox collapses ~28 of the 32 pixels into flat blocks (~8–11px wide) at this zoom level.

    This isn't a bug in either implementation under the current spec text — both are conforming — but it means double-single emulation is not portable across WGSL implementations today, and there's no way in WGSL to request the literal semantics the algorithm depends on. A fast-math opt-out (or an explicit "preserve associativity" annotation on a scope/expression) would fix this class of algorithm without requiring it project-wide.

  21. beaufortfrancois commented on Aug 19, 2026

    @beaufortfrancois
    Contributor
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

    wgsl

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions