Accuracy-optimized performance-neutral implementation of erfcxf()

The exponentially scaled complementary error function computes ex*x and is useful in preventing premature underflow when the complementary error function is combined with fast-growing terms, for example when computing the Mills ratio: M(x) = exp(x*x) * sqrt(π/2) * erfc (x/sqrt(2)). The single-precision implementation of it, erfcxf(), in CUDA 11 has a maximum error of 3.90275 ulps.

In my implementation below, my_erfcxf(), the maximum error is reduced to 2.4504 ulps. On my Quadro RTX 4000 (compute capability 7.5) it performs identically to CUDA’s built-in function within a measurement noise level of 2%. I would expect this to hold across all GPUs currently supported by CUDA.

/*
  Copyright (c) 2022, Norbert Juffa
  All rights reserved.

  Redistribution and use in source and binary forms, with or without 
  modification, are permitted provided that the following conditions
  are met:

  1. Redistributions of source code must retain the above copyright 
     notice, this list of conditions and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/* Compute exponential function with maximum error 0.86565 ulps */
__forceinline__ __device__ float my_expf (float a)
{
    float f, r, j, s, t;
    int i, ia;

    // exp(a) = 2**i * exp(f); i = rintf (a / log(2))
    j = fmaf (1.442695f, a, 12582912.f) - 12582912.f; // 0x1.715476p0, 0x1.8p23
    f = fmaf (j, -6.93145752e-1f, a); // -0x1.62e400p-1  // log_2_hi 
    f = fmaf (j, -1.42860677e-6f, f); // -0x1.7f7d1cp-20 // log_2_lo 
    i = (int)j;
    // approximate r = exp(f) on interval [-log(2)/2, +log(2)/2]
    r =             1.37805939e-3f;  // 0x1.694000p-10
    r = fmaf (r, f, 8.37312452e-3f); // 0x1.125edcp-7
    r = fmaf (r, f, 4.16695364e-2f); // 0x1.555b5ap-5
    r = fmaf (r, f, 1.66664720e-1f); // 0x1.555450p-3
    r = fmaf (r, f, 4.99999851e-1f); // 0x1.fffff6p-2
    r = fmaf (r, f, 1.00000000e+0f); // 0x1.000000p+0
    r = fmaf (r, f, 1.00000000e+0f); // 0x1.000000p+0
    // exp(a) = 2**i * r
    ia = (i > 0) ?  0 : 0x83000000;
    s = __int_as_float (0x7f000000 + ia);
    t = __int_as_float ((i << 23) - ia);
    r = r * s;
    r = r * t;
    // handle special cases: severe overflow / underflow
    if (fabsf (a) >= 104.0f) r = s * s;
    return r;
}

/*
  Compute the exponentially scaled complementary error function exp(x*x)*erfc(x)
  maximum error positive half-plane: 1.97521 ulps
  maximum error negative half-plane: 2.45040 ulps
*/
__inline__ __device__ float my_erfcxf (float x)
{
    float MY_INF = __int_as_float (0x7f800000);
    float a, d, e, p, q, r, s, t;

    a = fabsf (x);

    /* Compute q = (a-2)/(a+2) accurately. [0,INF) -> [-1,1] */
    p = a + 2.0f;
    asm ("rcp.approx.ftz.f32 %0,%1;" : "=f"(r) : "f"(p)); // r = 1.0f / p
    q = fmaf (-4.0f, r, 1.0f);
    t = fmaf (q + 1.0f, -2.0f, a); 
    e = fmaf (-a, q, t); 
    q = fmaf (r, e, q); 

    /* Approximate (1+2*a)*exp(a*a)*erfc(a) as p(q)+1 for q in [-1,1] */
    p =              5.92619181e-5f;  //  0x1.f12000p-15
    p = fmaf (p, q,  1.61231728e-4f); //  0x1.5220a0p-13
    p = fmaf (p, q, -3.46499495e-4f); // -0x1.6b54c0p-12
    p = fmaf (p, q, -1.39683776e-3f); // -0x1.6e2c32p-10
    p = fmaf (p, q,  1.20587996e-3f); //  0x1.3c1d3cp-10
    p = fmaf (p, q,  8.69013276e-3f); //  0x1.1cc21ep-7
    p = fmaf (p, q, -8.01389851e-3f); // -0x1.069974p-7
    p = fmaf (p, q, -5.42122647e-2f); // -0x1.bc1b5cp-5
    p = fmaf (p, q,  1.64048553e-1f); //  0x1.4ff8b0p-3
    p = fmaf (p, q, -1.66031078e-1f); // -0x1.54081ap-3
    p = fmaf (p, q, -9.27637145e-2f); // -0x1.7bf5cep-4
    p = fmaf (p, q,  2.76978403e-1f); //  0x1.1ba03ap-2

    /* Divide (1+p) by (1+2*a) ==> exp(a*a)*erfc(a) */
    d = fmaf (0.25f, a, 0.125f);
    asm ("rcp.approx.ftz.f32 %0,%1;" : "=f"(r) : "f"(d)); // r = 1.0f / d
    q = fmaf (p, r, r);
    e = fmaf (fmaf (-a, q, 4.0f), 0.25f, fmaf (-0.125f, q, p)); // residual
    r = 0.125f * fmaf (e, r, q);

    if (a == MY_INF) r = 0.0f;

    /* Handle negative arguments: erfcx(x) = 2*exp(x*x) - erfcx(|x|) */
    if (x < 0.0f) {
        s = x * x;
        d = fmaf (x, x, -s);
        e = my_expf (s);
        r = e - r;
        r = fmaf (e, d + d, r); 
        r = r + e;
        if (e == MY_INF) r = e; // avoid creating NaN
    }
    return r;
}
1 Like

I wonder how this compares to the spline-based logarithmically indexed table I came up with a few years ago. It’s not quite the same function, and if one were only computing exp(x * x) * erfc(x), I would expect the code above to go faster. When piling more computations on top of it all, I’d expect a spline table to go faster, although the applications grow more narrow unless one can create a much larger code base to translate the input function into a spline, encapsulate the access as a __device__ __forceinline__ function as above, and have some degree of assurance that the function will be used frequently enough to take advantage of the L1 caching of coefficients for regions of the spline where the function is commonly evaluated. The spline does have advantages in the way that its 32-bit floating point coefficients can have their ULPs tweaked to optimize the results with respect to 64-bit floating point arithmetic over the range in which those coefficients are valid.

It’s also noteworthy that you have your own exponential function–would you recommend that as a general substitute for float e_to_the_x = expf(x); ? I did not anticipate that the built-in expf function may be that costly.

@dscerutti I recall we had a discussion in this forum some years ago regarding a fast approximation to erfcf (not erfcx). As I recall, your requirements included a restricted domain (i.e. doesn’t need to work for all possible single-precision inputs) and lower than single-precision accuracy. Under those conditions, your approach (I don’t recall the use of splines) came out ahead.

This is basically a variant of general trade-offs between general-purpose implementation of mathematical functions as found in standard math libraries versus special-purpose implementations custom-tailored to a specific use case or particular field.

Although it is not part of C++, the erfcx() function is kind of standardized and various software environments offer it (the Fortran 2008 standard calls it ERFC_SCALED, for example).

I do not recall exactly why we (well, I :-) added erfcx() to the CUDA math library, but I think we got a request from a customer who pointed out that it is available in Matlab, and why it is useful. Similar story with erfinv() and erfcinv() (which are inexplicably absent from the C++ standard), although a different customer requested those.

Give it a try if you need a faithfully-rounded implementation. Seems unlikely in your application area. CUDA’s built-in expf() is less accurate since it is built around the MUFU.EX2 instruction. Last I checked, my own implementation of expf() is performance competitive with the built-in expf(), at least with -ftz=false. It would help if NVIDIA GPUs had ldexp() capability in hardware, like AMD’s GPUs, because getting correct and fast scaling in software eats up precious cycles.