diff --git a/lib/intrinsics/ext/SPIRVIntrinsicsSpecialFunctionsExt.jl b/lib/intrinsics/ext/SPIRVIntrinsicsSpecialFunctionsExt.jl index 9c28d947..8a90af52 100644 --- a/lib/intrinsics/ext/SPIRVIntrinsicsSpecialFunctionsExt.jl +++ b/lib/intrinsics/ext/SPIRVIntrinsicsSpecialFunctionsExt.jl @@ -17,6 +17,79 @@ for gentype in SPIRVIntrinsics.generic_types end end +# OpenCL has no `erfcx`, and the host method calls into a C library, so it is computed here. +# +# The implementation is based on +# Shepherd & Laframboise, "Chebyshev approximation of (1+2x)exp(x²)erfc x in 0 ≤ x < ∞", +# Math. Comp. 36 (1981), 249–253). +# +# Write `a = |x|`, and split the `a` axis into two pieces, `0 <= a <= K` and `a > K`. +# The authors take `K = 4`. Also let `q = (a-K)/(a+K) ∈ [-1, 1]` for the entire `a` axis. +# `(1+2a)·erfcx(a) - 1` is a smooth function of `q`. It vanishes at `q = -1`, so it is +# approximated as `(1+q)·P(q)`, where `P` is polynomial fitted by Chebyshev interpolation: +# - for a ≤ K, as a polynomial in q ∈ [-1, 0] (degree 18 for Float64, 10 for Float32); +# - for a > K, as a polynomial in t = 1-q = 2K/(a+K) ∈ (0, 1] (degree 17 and 9), which +# avoids the cancellation that a polynomial in q suffers as q → 1. +# lib/intrinsics/gen/erfcx.jl generates the coefficients. +# +# For x < 0, erfcx(x) = 2exp(x²) - erfcx(-x) = 1 + ((1 - erfcx(-x)) + 2expm1(x²)), with +# x² carried as an unevaluated sum so that its rounding error does not get amplified by the +# exponential. +# +# Compared with a 256-bit reference, the error is below 1.5 ulp for x ≥ 0, which uses only +# basic arithmetic, and below 2 ulp for x < 0 given an `expm1` accurate to 1 ulp. +erfcx_poly_lo(::Type{Float64}) = + (0.2329951186255525, -0.37261623546611494, 0.38799588756874076, -0.3198988333137835, + 0.2188597672839452, -0.12512693218928395, 0.05879656732052493, -0.021629045370725797, + 0.005431342528262366, -0.00039926226315619145, -0.0003582303309479649, + 0.00015946483849941777, -8.354599711832533e-6, -1.6133452615258434e-5, + 3.6324363745202897e-6, -3.8518233794940066e-7, -2.10317272373958e-6, + -7.666054035753991e-7, -9.085596365874973e-8) +erfcx_poly_hi(::Type{Float64}) = + (0.0641895835477563, 0.06735664074561228, 0.04690151373727461, 0.027583004792131924, + 0.014583516646458685, 0.007091601684450108, 0.0031963432952589275, 0.001334492195726002, + 0.0005124600023022253, 0.00017710097024967172, 5.559239420169759e-5, + 1.0204429104398777e-5, 6.068248442349178e-6, -4.339792780021579e-6, + 2.485952526642677e-6, -1.4124744527659699e-6, 2.6485866341044387e-7, + -2.6073739147144374e-9) +erfcx_poly_lo(::Type{Float32}) = + (0.23299512f0, -0.37261623f0, 0.3879964f0, -0.31989133f0, 0.21891595f0, -0.12488772f0, + 0.059404545f0, -0.020717392f0, 0.0061394596f0, -0.0003129252f0, -0.0006353962f0) +erfcx_poly_hi(::Type{Float32}) = + (0.06418958f0, 0.06735668f0, 0.046900213f0, 0.027599718f0, 0.014474609f0, 0.0074985293f0, + 0.0022740331f0, 0.0026177485f0, -0.00054437976f0, 0.00062838406f0) + +function erfcx_impl(x::T) where {T<:Union{Float32,Float64}} + a = abs(x) + b = a + T(4) + s = ifelse(isinf(a), T(2), 2 * (a / b)) # 1 + q + # `@inline` keeps the coefficients as immediates: otherwise the Float64 tuples become a + # global passed by pointer through an address-space cast that the Khronos translator + # rejects. + P = a <= 4 ? @inline(evalpoly(s - one(T), erfcx_poly_lo(T))) : # q + @inline(evalpoly(8 / b, erfcx_poly_hi(T))) # 1 - q + p = s * P # (1+2a)·erfcx(a) - 1 + # erfcx(a) = (1+p)/(1+2a). Dividing by a+1/2 rather than 1+2a avoids overflow; the + # residual (1+p) - r·(1+2a) then corrects r. + rd = T(0.5) / (a + T(0.5)) + r = fma(p, rd, rd) + e = (p - r) + fma(r + r, -a, one(T)) + r = ifelse(isinf(a), zero(T), fma(e, rd, r)) + if x < 0 + x2 = x * x + δ = fma(x, x, -x2) # x² = x2 + δ exactly + em = expm1(x2) + u = em + fma(em, δ, δ) # expm1(x2 + δ) to first order in δ + r = isinf(em) ? em : 1 + ((1 - r) + 2 * u) + end + return r +end + +@device_override SpecialFunctions.erfcx(x::Float64) = erfcx_impl(x) +@device_override SpecialFunctions.erfcx(x::Float32) = erfcx_impl(x) +# via Float32, unlike the host method, so that Float16 does not need Float64 support +@device_override SpecialFunctions.erfcx(x::Float16) = Float16(erfcx_impl(Float32(x))) + # compilers only consult the package's list of builtins, and additions to it made while # precompiling this extension are not saved, so register them when the extension loads __init__() = append!(SPIRVIntrinsics.known_intrinsics, known_intrinsics) diff --git a/lib/intrinsics/gen/Project.toml b/lib/intrinsics/gen/Project.toml new file mode 100644 index 00000000..40ab5b27 --- /dev/null +++ b/lib/intrinsics/gen/Project.toml @@ -0,0 +1,5 @@ +[deps] +SpecialFunctions = "276daf66-3868-5448-9aa4-cd146d93841b" + +[compat] +SpecialFunctions = "2" diff --git a/lib/intrinsics/gen/erfcx.jl b/lib/intrinsics/gen/erfcx.jl new file mode 100644 index 00000000..a085c795 --- /dev/null +++ b/lib/intrinsics/gen/erfcx.jl @@ -0,0 +1,63 @@ +# Generates the polynomial coefficients used by `erfcx_impl` in +# lib/intrinsics/ext/SPIRVIntrinsicsSpecialFunctionsExt.jl. See that +# file for mathematical details. +# +# From lib/intrinsics, run +# +# julia --project=gen -e 'using Pkg; Pkg.instantiate()' +# julia --project=gen gen/erfcx.jl +# + +using SpecialFunctions + +setprecision(BigFloat, 512) + +const K = big(4) + +function g(q::BigFloat) + q == -1 && return (2 - 2 / sqrt(big(π))) * K / 2 # limit as a → 0 + q == 1 && return (2 / sqrt(big(π)) - 1) / 2 # limit as a → ∞ + a = K * (1 + q) / (1 - q) + return ((1 + 2a) * erfcx(a) - 1) / (1 + q) +end + +function chebcoefs(f, N) + nodes = [cos(big(π) * (j + big(1) / 2) / N) for j in 0:N-1] + fv = f.(nodes) + return [(k == 0 ? 1 : 2) / big(N) * + sum(fv[j+1] * cos(big(π) * k * (j + big(1) / 2) / N) for j in 0:N-1) for k in 0:N-1] +end + +function cheb2mono(c) + n = length(c) + T = [zeros(BigFloat, n) for _ in 1:n] + T[1][1] = 1 + n > 1 && (T[2][2] = 1) + for k in 3:n + T[k][2:end] .= 2 .* T[k-1][1:end-1] + T[k] .-= T[k-2] + end + return sum(c[k] .* T[k] for k in 1:n) +end + +# Monomial coefficients in v of the degree-`deg` Chebyshev interpolant of f on [lo, hi]. +function fit_mono(f, lo, hi, deg; N = 64) + lo, hi = big(lo), big(hi) + c = chebcoefs(u -> f((hi - lo) / 2 * u + (hi + lo) / 2), N) + mu = cheb2mono(c[1:deg+1]) # in u = α v + β + α = 2 / (hi - lo) + β = -(hi + lo) / (hi - lo) + m = zeros(BigFloat, deg + 1) + for i in 0:deg, j in 0:i + m[j+1] += mu[i+1] * binomial(big(i), big(j)) * α^j * β^(i - j) + end + return m +end + +lo(deg) = fit_mono(g, -1, 0, deg) # in q +hi(deg) = fit_mono(t -> g(1 - t), 0, 1, deg) # in t + +for (T, dlo, dhi) in ((Float64, 18, 17), (Float32, 10, 9)) + println("erfcx_poly_lo(::Type{$T}) = (", join(repr.(T.(lo(dlo))), ", "), ")") + println("erfcx_poly_hi(::Type{$T}) = (", join(repr.(T.(hi(dhi))), ", "), ")") +end diff --git a/test/intrinsics.jl b/test/intrinsics.jl index 62a8f8a4..6a9030ed 100644 --- a/test/intrinsics.jl +++ b/test/intrinsics.jl @@ -151,6 +151,36 @@ end end end +# SpecialFunctions' BigFloat `erfcx` evaluates exp(x²)·erfc(x) for x ≤ 2^15 when `long` is +# 32 bits (Windows), which exceeds MPFR's exponent range and yields NaN for x ≳ 27300. For +# x > 2^14 this uses the asymptotic series (DLMF 7.12.1) instead; its terms shrink by a +# factor of at least 2^28 there, and the error is below the first omitted term. +function erfcx_reference(x::BigFloat) + (isfinite(x) && x > 0x1p14) || return SpecialFunctions.erfcx(x) + v = 1 / (2 * x * x) + s = w = one(x) + k = 1 + while abs(w) > eps(BigFloat) / 4 + w *= -k * v + s += w + k += 2 + end + return s / (x * sqrt(BigFloat(π))) +end + +# `erfcx` is implemented in Julia rather than by an OpenCL builtin, so check it against a +# 256-bit reference across the whole range, including overflow for negative arguments. +@testset "SpecialFunctions.erfcx - $T" for T in float_types + mags = filter(isfinite, T.(exp2.(range(log2(floatmin(T)), log2(floatmax(T)); length=500)))) + lin = T.(range(0, 30; length=301)) + xs = [mags; -mags; lin; -lin; T(Inf); -T(Inf); T(NaN)] + ys = Array(SpecialFunctions.erfcx.(CLArray(xs))) + refs = setprecision(() -> T.(erfcx_reference.(big.(xs))), BigFloat, 256) + # the bound allows for the device's `expm1`, which OpenCL requires to be within 3 ulp + agrees(y, r) = isequal(y, r) || (isfinite(r) && abs(big(y) - big(r)) <= 4 * eps(r)) + @test isempty(xs[.!agrees.(ys, refs)]) +end + # Regression test for #428: `^(::Float, ::Int64)` must not truncate the # exponent through Int32, since `y % Int32` wraps for |y| ≥ 2^31 and would # flip the sign of the exponent (producing 0 instead of Inf, etc.).