With compute capability 7.5 NVIDIA added hardware support for the computation of tanhf() to the GPU’s multifunction unit (MUFU). Various publications and multiple questions on Mathematics Stackexchange discuss how to use the hyperbolic tangent tanh to compute the error function erf, motivated by similarity of the graphs of the two functions. The simplest such scheme I am aware of (due to Vedder) uses a simple cubic polynomial to translate the argument of erf to the argument of tanh and achieves an accuracy of 0.039%.
For the implementation of fast_erff() below I tuned the coefficients of Vedder’s proposed cubic polynomial specifically for best results with the MUFU.TANH instruction. This implementation requires just five machine instructions.
/*
Copyright 2023, Norbert Juffa
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.
*/
__forceinline__ __device__ float raw_tanhf (float a)
{
#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 750)
#error unsupported __CUDA_ARCH__
#else // __CUDA_ARCH__
asm ("tanh.approx.f32 %0,%1; \n\t" : "+f"(a) : "f"(a));
#endif // __CUDA_ARCH__
return a;
}
/*
Based on John D. Vedder, "Simple approximations for the error function and its
inverse." American Journal of Physics, Vol. 55, No. 8, Aug. 1987, pp. 762-763.
maximum ulp error: 5735.81, maximum relative error: 3.8735e-4
*/
__forceinline__ __device__ float fast_erff (float x)
{
float x2 = x * x;
x = fmaf (fmaf (0.100646973f, x2, 0.128759325f), x, x); // 0x1.9c4000p-4, 0x1.07b2f8p-3
return raw_tanhf (x);
}