Skip to content

Perf regression for Math.Min and Math.Max #12159

Closed

Description

@tannergooding

The Math.Min and Math.Max functions that take double/float were updated to be IEEE compliant in dotnet/coreclr#20912. However, the JIT does not do a great job optimizing this code and it has resulted in a regression.

For example, in the Ray Tracer that Matt Warren ported to C# as part of https://mattwarren.org/2019/03/01/Is-CSharp-a-low-level-language/#using-mathf-functions-instead-of-math, I see the following locally:

  • C++ 19.16: 26sec
  • C# netcoreapp2.2: 36sec
  • C# netcoreapp3.0: 57sec

Reverting the change back to the original implementation gives:

  • C# netcoreapp3.0: 31sec

The function could likely be intrinsified in order to help with the codegen here. This can't be done using exclusively minss as that always returns the second operand if either of the operands is NaN, so we could emulate this branchlessly using the recommendation in the architecture manual:

If only one value is a NaN (SNaN or QNaN) for this instruction, the second source operand, either a NaN or a valid floating-point value, is written to the result. If instead of this behavior, it is required that the NaN in either source operand be returned, the action of MINSD can be emulated using a sequence of instructions, such as, a comparison followed by AND, ANDN and OR.

I believe that should be something similar to the following:

if (Sse.IsSupported)
{
    var lhs = Vector128.CreateScalarUnsafe(val1);
    var rhs = Vector128.CreateScalarUnsafe(val2);

    var tmp1 = Sse.MinScalar(rhs, lhs);
    var tmp2 = Sse.CompareUnorderedScalar(lhs, lhs);

    if (Avx.IsSupported)
    {
        return Avx.BlendVariable(tmp1, rhs, tmp2).ToScalar();
    }
    else
    {
        var tmp3 = Sse.And(tmp2, rhs);
        tmp2 = Sse.AndNot(tmp2, tmp1);
        return Sse.Or(tmp2, tmp3).ToScalar();
    }
}

Activity

  1. self-assigned this
    on Mar 1, 2019
  2. tannergooding commented on Mar 1, 2019

    @tannergooding
    MemberAuthor

    The above suggested fix brings the time back down to:

    • C# netcoreapp3.0: 30sec

    Will need to finish validating that it is also correct.

  3. jkotas commented on Mar 1, 2019

    @jkotas
    Member

    Please make sure to fix this regression on all supported platforms, not just x64.

  4. tannergooding commented on Mar 1, 2019

    @tannergooding
    MemberAuthor

    Please make sure to fix this regression on all supported platforms, not just x64.

    Fixing it for x86 and x64 is just the above. Fixing it for ARM/ARM64 will likely require the JIT to treat the method as intrinsic until the HWIntrinsic support actually becomes available.

    The root problem is the JIT doesn't handle NaN comparisons very well, which results in a bunch of branches in a small window of code. I'll try to give some more thought on if I can also improve the software fallback case.

  5. jkotas commented on Mar 1, 2019

    @jkotas
    Member

    What is the implementation strategy used for this by other environments, e.g. C/C++ compilers? Does the compiler handles it, or is the max implementation handcrafted in library code?

  6. tannergooding commented on Mar 1, 2019

    @tannergooding
    MemberAuthor

    GCC and MSVC both forward down to the CRT software implementation (fmin and fmax). Clang (when optimizations are enabled) emits some assembly similar to my prototype above.

    All of them have a "fast floating-point math" switch and just emit minss when that is enabled.

  7. jkotas commented on Mar 1, 2019

    @jkotas
    Member

    GCC and MSVC both forward down to the CRT software implementation (fmin and fmax).

    I think we should do the same here like we do for majority of the other Math operations. Would that fix the regression?

  8. tannergooding commented on Mar 1, 2019

    @tannergooding
    MemberAuthor

    Would that fix the regression?

    I'll check, but I find it doubtful as the CRT implementations are roughly what we already have in the C# implementation.

    From previous analysis on related functions, the cost of the two calls (one to our COMSingle::Min and one from that to fminf) ends up being more expensive than the actual assembly being run.

    For reference: just aggressively inlining the current "correct" implementation cuts the time down from 57sec to 48sec, showing that the call is a significant portion of the current cost.

  9. tannergooding commented on Mar 1, 2019

    @tannergooding
    MemberAuthor

    @jkotas, Unfortunately, my suspicion was correct. Changing these to FCALL into the CRT fmin and fmax regresses the time from 57sec to 78sec.

    I'll continue looking at the software fallback case to see if I can improve it standalone as well. I expect we might be able to just emulate the cmp, and, andnot, or sequence using bit manipulation to get a speedup.

  10. mikedn commented on Mar 1, 2019

    @mikedn
    Contributor

    The root problem is the JIT doesn't handle NaN comparisons very well, which results in a bunch of branches in a small window of code

    I can improve NaN comparisons in the JIT. Though last time I tried it didn't seem to make a difference.

  11. mikedn commented on Mar 1, 2019

    @mikedn
    Contributor

    Though it looks to me that the C++ version of the raytracer is using

    float min(float l, float r) { return l < r ? l : r; }

    and that has nothing to do with Math.Min. And it's not uncommon for this kind of code to not care about NaN-accuracy and I don't see why the C# version would do it differently.

    Still, it's probably worth taking a look at what can be done to improve Math.Min/Max, even though it will probably never match x < y ? x : y.

  12. tannergooding commented on Mar 2, 2019

    @tannergooding
    MemberAuthor

    I have a PR up which resolves this for x86/x64: dotnet/coreclr#22965. The prototype I wrote in the original post was nearly correct, but didn't handle -0.0 vs +0.0 correctly; where-as the PR has the additional checks to do that.

    The software fallback implementation has a few problems.

    First, the codegen for IsNaN is pretty bad. This is because the implementation for IsNaN is doing a strict bit-comparison. The fix is actually fairly trivial in that we could change the implementation to bool IsNaN(float x) => x != x and the JIT correctly emits a ucomiss instruction followed by jp.

    • BitConverter.SingleToInt32Bits also currently goes through the stack, rather than using movd, which might be nice to fix as a separate issue

    Second, the IsNaN checks are being done first; when they could be handled last since they are the uncommon case and either operand being NaN causes every other comparison to return false.

    Third, the JIT treats x < y as commutative with y >= x. This is normally great, since the IEEE spec says that -0.0 and +0.0 are equal, and this is the only case that could matter. However, it makes it very difficult to "efficiently" handle cases where this difference does matter; and so we end up having to do 2 separate comparisons (first the equality and then the less than comparison) to get this working correctly.

  13. mikedn commented on Mar 2, 2019

    @mikedn
    Contributor

    I see the following locally:
    C++ 19.16: 26ms
    C# netcoreapp2.2: 36ms
    C# netcoreapp3.0: 57ms

    Can you tell me what exactly are you measuring? I've been looking other that blog post but I don't see such values. And attempting to run the raytracer takes a lot longer, minutes on my machine.

  14. tannergooding commented on Mar 2, 2019

    @tannergooding
    MemberAuthor

    Can you tell me what exactly are you measuring?

    The execution of the entire program using the time-windows tool listed in the blog post (which is a port of the unix time command).

    The programs are exactly as given in the blog post, with the C++ code modified to be 2 samples (also specified in th blog post).

    The times I gave above should be seconds though, not sure why I typed ms (probably just habit, editing them now).

  15. tannergooding commented on Mar 2, 2019

    @tannergooding
    MemberAuthor

    Times should be updated to be in the correct unit (seconds not ms). Sorry for the confusion.

  16. mikedn commented on Mar 2, 2019

    @mikedn
    Contributor

    Thanks. I also discovered that I was using a debug corelib and that's why it was taking minutes for me. Now I get 58s (and 33s for the C++ version, compiled with VS2019). So the results are comparable and I can play a bit with it.

    First observation is that changing min to return l < r ? l : r; like in the C++ version brings down the C# time to 35s.

  17. mikedn commented on Mar 2, 2019

    @mikedn
    Contributor

    This Math.Min comment is kind of misleading:

    Doing (val1 < val2) first could get transformed into (val2 >= val1) by the JIT

    The JIT will transform val1 < val2 into val2 > val1 pretty much always. The JIT may sometimes transform val1 < val2 into !(val1 >= val2), or in the specific case of Min code - return (val1 < val2) ? val1 : val2; into return (val1 >= val2) ? val2 : val1;.

  18. mikedn commented on Mar 2, 2019

    @mikedn
    Contributor
    • Using movd saves 2-3s, around 6%. Might worth doing it but it is not enough.
    • Using x != x rather than IsNaN doesn't seem to make a difference performance wise but it does generate smaller code

    But the current Min code seems pretty bad, it doesn't take advantage of facts like x < NaN = false. I need to stare at it a bit more but the following should be equivalent and generates far less code:

    public static float Min31(float val1, float val2)
    {
        if (((val1 == val2) && float.IsNegative(val2)) ||
            (val1 > val2) ||
            (val1 != val1))
        {
            val1 = val2;
        }
    
        return val1;
    }

    runs in ~47s and generates

    G_M14706_IG01:
           C5F877               vzeroupper
           6690                 nop
    G_M14706_IG02:
           C5F82EC1             vucomiss xmm0, xmm1
           7A0C                 jp       SHORT G_M14706_IG03
           750A                 jne      SHORT G_M14706_IG03
           C5F97EC8             vmovd    eax, xmm1
           85C0                 test     eax, eax
           7C10                 jl       SHORT G_M14706_IG04
    G_M14706_IG03:
           C5F82EC1             vucomiss xmm0, xmm1
           7708                 ja       SHORT G_M14706_IG04
           C5F82EC0             vucomiss xmm0, xmm0
           7B07                 jnp      SHORT G_M14706_IG05
    G_M14706_IG04:
           C5F828C1             vmovaps  xmm0, xmm1
    G_M14706_IG05:
           C3                   ret
    ; Total bytes of code 38, prolog size 5 for method Program:Min31(float,float):float

    There may be an way to eliminate one of the vucomiss xmm0, xmm1 but I don't see it right now, the negative 0 check is in the way.

    It's a bit large to force inline it but doing that brings the time down to 39s.

  19. CarolEidt commented on Apr 23, 2019

    @CarolEidt
    Contributor

    @tannergooding - is https://github.com/dotnet/corefx/issues/36925 the plan for addressing this? If so, should this be moved out from 3.0 to future (since it seems that proposal won't make it into 3.0)?

  20. tannergooding commented on Apr 23, 2019

    @tannergooding
    MemberAuthor

    This was reduced to a 3-6ms regression after https://github.com/dotnet/corefx/issues/36931 was merged.

    I think this can probably be closed for now.

  21. CarolEidt commented on Apr 24, 2019

    @CarolEidt
    Contributor
  22. transferred this issue fromdotnet/coreclron Jan 31, 2020
  23. added this to the 3.0 milestone on Jan 31, 2020
  24. removed their assignment
    on May 26, 2020
  25. ghost locked as resolved and limited conversation to collaborators on Dec 14, 2020
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

    area-CodeGen-coreclrbug

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions