Julius Ikkala

Fitting: How to approximate difficult functions efficiently on the GPU

In computer graphics, you quite often run into really annoying functions that are difficult or impossible to evaluate efficiently. This is usually related to functions that cannot be integrated analytically, requiring time-consuming numerical integration.

Let's use F(x)F(x) as a stand-in for such a difficult function in this article. This hypothetical function completely sucks. It takes minutes of computer time to evaluate it at any value of xx, and the derivative is unknown but can be computed with finite differences.

Unfortunately, your game looks bad unless you evaluate this F(x)F(x) for millions of pixels on the screen, at least 60 times per second (and may even need the derivative, pronto). What to do?

Options for approximating F(x)F(x)

When you have a function that is difficult or impossible to evaluate efficiently, you will have to approximate it instead. There are two choices for that:

  1. Pre-compute a lookup table (LUT).
  2. Approximate with a simpler, fitted function.

On a GPU, option 1 usually means a lookup texture and 2 is a function with no memory accesses.

There is some nuance in picking which one to go with: if the LUT is small or it is exceedingly difficult to find a good fit, then that is the right way to go. On the other hand, a fitted function avoids the cost of texture taps, can have C∞C^{\infty} continuity? and is usually amenable to very efficient auto-differentiation (e.g., in Slang).

This article is specifically about approach 2. But how should we choose the simpler function fc(x)≈F(x)f_{\mathbf{c}}(x) \approx F(x)? Here, we denote the fittable parameters with the vector c\mathbf{c}.

Consider shape of F(x)F(x)

Firstly, consider the shape of your F(x)F(x). Does it have some special features that must be preserved?

If lim⁡x→0F(x)=∞\lim_{x\to0} F(x) = \infty, you probably shouldn't use a polynomial function for the fit, because they can't do that. Similarly, if it is important that lim⁡x→∞F(x)=C\lim_{x\to\infty} F(x) = C (where C is some constant), a polynomial function is also not fit for the job.

You have to choose the simplified function such that it is able to represent the most important behaviors of F(x)F(x).

GPU efficiency and a⋅b+ca\cdot b + c

In literature, it is common to encounter fits made using a "gaussian mixture model" (GMM), i.e. a linear combination of bell curves. But is that actually a good idea on the GPU?

From the CUDA best practices guide, we can find instruction throughput details on Nvidia's hardware. Interestingly, most newer hardware on the table can do 4 fused multiply-add (FMA, a⋅b+ca\cdot b + c) operations per cycle per lane. This is the main primitive for polynomial functions; any polynomial can be expressed as successive FMA operations:

gn(x)=gn−1(x)⋅x+cng_n(x) = g_{n-1}(x) \cdot x + c_{n}

where g0(x)=c0g_0(x) = c_0 and nn is the degree of the polynomial.

Reciprocals, square roots, exponentials, logarithms, and trigonometric functions all have a throughput of 0.5 operations per cycle per lane. You can do an 8th degree polynomial fit in the same time as computing just 1x\frac{1}{x}.

These slow operations do have a silver lining. They are executed somewhat asynchronously on the Special Function Unit (SFU). Therefore, you can issue a square root instruction and compute an 8th degree polynomial on the ALU while waiting for the result of the square root. The story is similar on AMD's side as well.

So while it is probably a really bad idea to spam a ton of special functions (side-eye at GMMs), they can still be a good idea if used judiciously and in conjunction with FMAs. This means that rational functions are often efficient as they do one reciprocal per ton of FMAs. They can also reach infinity or express desirable asymptotic behavior if needed. The main con is that finding globally optimal parameters is non-trivial compared to polynomials.

Of course, there are also cases where just one special function provides a better fit than the 8th degree polynomial. Choosing the right approach can be a bit of an art form.

Imposing simple constraints on the fit

For example, F(x)F(x) could represent the albedo of a surface. I know that F(x)∈[0,1]F(x) \in [0, 1], anything beyond that range is going to cause major artifacts. But least squares doesn't know that, and may make concessions with the precision at key points.

This is why when I produce a fit for some function, I usually enforce that the fit hits some specific values. For example, I might require f(0)=F(0)=0f(0) = F(0) = 0, or even that f′(1)=0f'(1) = 0. This is often surprisingly simple to do. As an example, let's use:

f(x)=c0x2+c1x+c2f(x) = c_0 x^2 + c_1 x + c_2

Now, we know that f(0)=c2=0f(0) = c_2 = 0. Next, f′(1)=2c0+c1=0f'(1) = 2 c_0 + c_1 = 0. We just solve either of the two coefficients in terms of the other, c1=−2c0c_1 = -2 c_0. Finally, we have

f(x)=c0x2−2c0xf(x) = c_0 x^2 - 2c_0 x

which always fulfills both constraints. We can now freely fit c0c_0 to F(x)F(x).

Gnuplot Produced by GNUPLOT 6.0 patchlevel 5 0 0.25 0.5 0.75 0 0.25 0.5 0.75 1 unconstrained fit unconstrained fit constrained fit constrained fit f(x) x
Constrained polynomial: f(x)=c0x2−2c0xf(x) = c_0 x^2 - 2c_0 x, always satisfies f(0)=0f(0)=0, f′(1)=0f'(1)=0

Of course, imposing any constraints is not going to make the mean squared error of the fit smaller, so you shouldn't place constraints unless they're actually an important detail for the function to operate correctly. Typically, the boundaries of the domain of F(x)F(x) are good places to pin down with a constraint.

Because I love polynomial and rational fits and forcing specific key values and derivatives, I wrote a tool, RationalFitter, to do just that a while back. The tool can do both fitting and constraining, but you can also use it for just one or the other. I often "pin" some values in a polynomial, then print it out and plug it into a scipy script.

A typical RationalFitter script looks something like this:

# Third degree polynomial, input is x and output is y, so the function this
# defines is "y = a + b * x + c * x^2 + d * x^3"
polynomial 3 x y

# The print instruction can be used to print out the current state of the
# function.
print

load-csv dataset=xvalues path="dataset.csv" column=0
load-csv dataset=yvalues path="dataset.csv" column=1

# Force y=1 at x=0. This instruction _eliminates_ coefficients! After this,
# y = 1 + b * x + c * x^2 + d * x^3
pin x=0 y=1

# Derivative dy/dx = 0 at x=1. Again, this eliminates coefficients, so now
# we're at:
# y = 1 + b * x + (- 0.5 * b - 1.5 * d) * x^2 + d * x^3
pin x=1 'x=0

# There's a bunch of options for "print" that we can set, this one prints out
# the equation as a C function.
print c

# This performs the fitting. It has some parameters to automatically remove
# the least important coefficients until we hit a target loss. This can be
# useful with multidimensional or high-degree polynomials, where there may be
# a large number of near-useless coefficients
fit x=xvalues y=yvalues maxloss=0.01

# Prints the function as a C function with primarily FMA operations.
print c fma

If you don't perform the fitting in RationalFitter but still want to enforce constraints with it, you can use print python to print the equation in Python-compatible syntax and copy-paste it to a Scipy fitting script.

from scipy.optimize import curve_fit

xvalues = []
yvalues = []

# load dataset to xvalues and yvalues somehow

def func(x, b, d):
    return 1 + b * x + (- 0.5 * b - 1.5 * d) * x ** 2 + d * x ** 3

popt, pcov = curve_fit(func, xvalues, yvalues)
print(popt)

Conclusion

If you can make a lookup table for a function, you should also try to make a decent analytical fit for it as well. Otherwise, you cannot compare your options. The fit may even be more accurate and faster to evaluate.

Unfortunately, beyond just a couple of input dimensions, the curse of dimensionality strikes. Both lookup tables and fitted polynomials become increasingly impractical at higher dimensions.

Neural networks also belong in this category of fitting approaches. One can use a multi-layer perceptron as the fc(x)f_{\mathbf{c}}(x) instead of a polynomial. These can can manage a huge number of parameters much better than simple polynomials or rational functions, so they can scale to higher-dimensional problems quite well.

Organizing the efficient evaluation of neural networks can mess with the SIMT/SPMD programming model a bit, so they can be somewhat more difficult to use in typical shading tasks. You usually shouldn't reach for them until it becomes apparent that you really cannot just use a lookup table or make any decent fit with a simpler fc(x)f_{\mathbf{c}}(x).