Winning at the n-body benchmark

There is this n-body benchmark at n-body - Which programs are fastest? (Benchmarks Game), right now C/C++ is winning, Fortran is 6th, 60% slower. I figured, why don’t we fix it?

Here is an example of the “C++” winner on my machine (full code here):

    template<size_t k = 0>
    inline void KernelLoop1() {
        __m256d x0 = _mm256_mul_pd(r[k], r[k]);
        __m256d x1 = _mm256_mul_pd(r[k + 1], r[k + 1]);
        __m256d x2 = _mm256_mul_pd(r[k + 2], r[k + 2]);
        __m256d x3 = _mm256_mul_pd(r[k + 3], r[k + 3]);

        __m256d t0 = _mm256_hadd_pd(x0, x1);
        __m256d t1 = _mm256_hadd_pd(x2, x3);
        __m256d y0 = _mm256_permute2f128_pd(t0, t1, 0x21);
        __m256d y1 = _mm256_blend_pd(t0, t1, 0b1100);

        __m256d z = _mm256_add_pd(y0, y1);
        z = _mm256_rsqrt_pd(z);
        _mm256_store_pd(&w[k], z);
        if constexpr ((k + 4) < PAIRS) KernelLoop1<k+4>();
    }

I don’t know how many of you can tell right away what is going on there. Plus it doesn’t even run on my Apple M4, since it’s hand-optimized in assembly for x86. But winner is a winner, so that has to be respected.

So the first thing we do is to write it in readable Fortran (full code here):

    do k = 1, npair
       d2 = r(1,k)*r(1,k) + r(2,k)*r(2,k) + r(3,k)*r(3,k)
       w(k) = 1 / sqrt(real(d2))
       w(k) = w(k) * (1.5_dp - 0.5_dp * d2 * w(k) * w(k))
       w(k) = tstep * w(k) * w(k) * w(k)
    end do

The C++ code is doing the same four lines in the body, but spread over several functions. Overall the code is equivalent, the same result. The Fortran code can be simplified more I think, but it’s a start, at 150 lines. The C++ code is 237 lines.

Let’s benchmark on AMD Ryzen 9 9955HX:

$ time ./nbody.cxx 50000000
-0.169075164
-0.169059907

real    0m1.027s
user    0m1.024s
sys     0m0.003s
$ time ./nbody.lfortran-opt 50000000
-0.169075164
-0.169059907

real    0m1.018s
user    0m1.017s
sys     0m0.001s

Wait, is LFortran faster? Well it is on my machine!

Let’s see how other Fortran compilers are doing:

$ time ./nbody.flang 50000000
-0.169075164
-0.169059907

real    0m1.488s
user    0m1.485s
sys     0m0.002s
$ time ./nbody.gfortran 50000000
-0.169075164
-0.169059907

real    0m2.264s
user    0m2.263s
sys     0m0.001s

Not too bad.

Now let’s benchmark on Apple M4:

$ time ./nbody.lfortran23 50000000
-0.169075164
-0.169059907

real    1.306s
user    1.297s
sys     0.006s
cpu     99.8%
$ time ./nbody.flang 50000000
-0.169075164
-0.169059907

real    1.346s
user    1.338s
sys     0.005s
cpu     99.8%
$ time ./nbody.gfortran 50000000
-0.169075164
-0.169059907

real    2.594s
user    2.587s
sys     0.006s
cpu     99.9%

The C++ code doesn’t even run on my M4, since it’s hardwired with assembly intrinsics for x86.

I think the result is about right, the frequency of the single M4 core is slightly lower than the AMD Ryzen core, so it seems we are getting a pretty good performance. I would say that’s true performance portability.

I used --fast for LFortran and -O3 -march=native -ffast-math for Flang/GFortran. I used these versions:

$ lfortran --version
LFortran version: 0.68.0-977-g01dce0b346
Status: alpha (expected to fail on third-party codes)
Platform: Linux
LLVM: 11.1.0
Default target: x86_64-unknown-linux-gnu
$ flang --version
flang version 23.1.4 (https://github.com/conda-forge/clangdev-feedstock babf9b0ec04c97fffe9fc24ec045deeb91a2c910)
Target: x86_64-conda-linux-gnu
Thread model: posix
InstalledDir: /home/ondrej/.pixi/envs/flang/bin
Configuration file: /home/ondrej/.pixi/envs/flang/bin/x86_64-conda-linux-gnu-flang.cfg
$ gfortran --version
GNU Fortran (conda-forge gcc 16.2.0-7) 16.2.0

Btw, I was using LLVM 11 on AMD Ryzen, and LLVM 23 on Apple M4. Usually newer LLVM is better, but on the Ryzen I was able to get state-of-the-art performance with very old LLVM 11 (released in 2020), showing that we are not doing anything fancy, just standard compiler optimizations.

And yes, we started implementing some optimizations into LFortran, just to get some decent performance before we release beta.

This is obviously all quite new and likely doesn’t translate to every code yet, but we’ll get there. I just wanted to let you know about this little (or big?) win, and put across the idea that we should be writing these high-performance algorithms in readable Fortran, not low level C++ with assembly instrinsics, and have the compiler optimize the code well on every platform.

29 Likes

Nice work!

1 Like

Is the intention here really to convert to real32?

Yes, that’s what the C++ code does here:

static inline __m256d _mm256_rsqrt_pd(__m256d s)
{
    __m128 q = _mm256_cvtpd_ps(s);
    q = _mm_rsqrt_ps(q);
    __m256d x = _mm256_cvtps_pd(q);
    __m256d y = s * x * x;
    __m256d a = _mm256_mul_pd(y, _mm256_set1_pd(0.375));
    a = _mm256_mul_pd(a, y);
    __m256d b = _mm256_mul_pd(y, _mm256_set1_pd(1.25));
    b = _mm256_sub_pd(b, _mm256_set1_pd(1.875));
    y = _mm256_sub_pd(a, b);
    x = _mm256_mul_pd(x, y);
    return x;
}

The _mm256_cvtpd_ps(s) converts the double precision argument to single precision.

So we just do exactly the same in Fortran.

P.S. To be exact, the C++ code uses linear Newton and a quadratic Taylor expansion after the hardware 1/sqrt(q) approximation, while the Fortran code first computes 1/sqrt(q) using hardware+linear Netwon (LFortran takes care of this), and then we do one more linear Newton in Fortran. So overall the Fortran code is actually more accurate (about 1e-14), while the C++ code is only 1e-9. Both are within the accuracy that the benchmark requires. We presumably could remove the Newton iteration from Fortran and just use double precision 1/sqrt(x) and let LFortran take care of these little details. In general there are various ways we can write the Fortran code, as long as it is coupled with good compiler optimizations.

P.P.S. This shows a very important point: the C++ code is “benchmaxxed” to just deliver on this one benchmark on a specific platform to the exact accuracy the benchmark requires and nothing more. The Fortran code, on the other hand, is a general code that computes everything to double precision (1e-14) and works on every platform (and it’s still as fast!). I think we should remove the single precision sqrt + Newton in Fortran and just replace it with just double precision sqrt. Then LFortran should handle how to most efficiently compute that on every platform. We could possibly add either some extensions or compiler options or pragmas to direct LFortran which implementation to choose, whether hardware+two Newton iterations (like the Fortran code above), or the possibly faster but less accurate hardware+Newton+quadratic Taylor term (like the C++ code above). In practice, given that the full double precision accuracy seems to be competitive on my machine above, it seems it might be enough for the user to simply choose either double or single and the compiler delivers full accuracy that the user requested (either 1e-7 or 1e-14). The intermediate accuracy 1e-9 that the C++ code uses could be done in LFortran as a mode, but it seems that in practice it might not really be needed. Because I don’t care about a particular contrived benchmark, I care about actual production maintainable codes and I think there either full single or full double will be enough as a “choice” for users. But of course, we still want to win on all benchmarks, and above I think I showed that we can.

7 Likes

That got me to take a trip down memory lane. Long ago in a land far away an inverse square root was so expensive that if you only needed an approximation (this method could be up to a percent off!) there was an old trick called the Quake III bit-hack that was much faster, but it only worked with 32-bit values. So quite a kludge, good for just a few cases but so much faster it still got used if the accuracy could be tolerated and the call was being made enough. Anyway it got me reminiscing and I am glad to report that using todays hardware it was an insignificant speedup. Not accurate enough anyway. Another old trick that is obsolete, but reassuring to know it does not help ! It was mostly useful for low-accuracy computations like drawing pixels to a screen back when everyone did their own low-level graphics and pixels were a new idea but it was a big speedup in its time. It truly is great seeing good speed with high accuracy from readable code; but some of that old stuff was actually kind of fun to use, like knowing an insider trick. You can guess from the name it was most famously implemented in game graphics but it did get used before that in special high-performance cases.

1 Like

Tricks like that are still used, but I am proposing they should be used inside compiler optimizations. User’s code should focus on the intent and readability, and a compiler should focus on nailing the performance on every platform.

5 Likes

Another possible reason for this might be hardware restrictions. For example, Apple cpus and vector units support real64 arithmetic, but Apple gpus only support 32-bit and 16-bit floating point formats. So one might code specifically to take advantage of the gpu hardware.

1 Like

Did you submit this to the site? I do not see it in the list.

@sumseq no, they have very specific requirements I think and various policies about what is and is not allowed. I figured, let’s make Fortran win all the benchmarks, and then we can submit it all at once. In the meantime, I really wanted to win on the machines that I have access to (and implement all the optimizations into LFortran), which I achieved, so my main job is done. :slight_smile:

1 Like