Function minimization with dfx

We are slowly approaching the holiday season, which means two things: it is a time for gifts, and the yearly return of the F# Advent Calendar! Thank you Sergey Tihon for organizing this once again.

Santa was good to me, with a very nice early surprise: the release of dfx. dfx, an F# automatic differentiation library, did not appear in a vacuum: it is the continuation of DiffSharp, the wonderful work of Dr. Atılım Güneş Baydin. As such, it uses the same core concepts as DiffSharp, making it easy to pick up if you are familiar with it, but brings renewed energy into the project, which is awesome news.

So for this F# Advent post, I figured I would take a look at dfx, from the perspective of “simple” function minimization. This is a very narrow angle on what dfx has to offer. In particular, dfx includes very elegant building blocks geared towards specifying and training neural networks. However, minimizing a bog-standard function is a problem I encounter regularly, and a problem where dfx shines, because one classic technique - gradient descent - relies on differentiation.

Note: this post is revisiting and updating an older post of mine.

Why care about function minimization

For since the fabric of the universe is most perfect, and is the work of a most wise Creator, nothing whatsoever takes place in the universe in which some relation of maximum and minimum does not appear.
Leonhard Euler

The universe being most perfect is what the kids today would call a hot take by Leonhard Euler. However, many interesting problems can indeed be seen through the lens of minimization or maximization.

Function minimization is concerned with finding input values that make a given function (the objective function) as small as possible. This type of problem arises in numerous fields, when one is interested in selecting the best solution from a set of alternatives to optimize some criterion.

In my particular case, I encounter that problem regularly, in 2 different contexts. The first one is finding the optimum stategy to use resources - things like tuning production equipment to maximize throughput, investing to minimize risk, and the like. The second is curve-fitting - things like finding parameters for a model to match predictions and observations as closely as possible, that is, minimizing their distance.

Function minimization comes in various flavors. Depending on the type of function, and the type of inputs and outputs, different algorithms may be relevant. The case I am interested in here is unconstrained functions where both the inputs and outputs are real values (float).

The Beale function

Rather than work through a real-world example, I will use a test function, the beale function, which I pulled from a collection of well-studied test functions for optimization. While a real-world example could be more interesting, using such a test function is convenient: we know what the correct answer is, and the function has interesting characteristics.

The beale function is defined like so:

let beale (x: float, y: float) =
    (1.5 - x + x * y) ** 2.0
    +
    (2.25 - x + x * y ** 2.0) ** 2.0
    +
    (2.625 - x + x * y ** 3.0) ** 2.0

Three things make this function interesting:

Seen from the top down, here is how the function surface looks like:

Top down view of the Beale function surface

Our goal here is to automatically find the values (x, y) such that the beale function is minimized.

Gradient descent

We will first use Gradient Descent to approach that problem.

One strategy to minimize our function goes along these lines: start somewhere (an initial value (x0, y0)), and take a step towards a direction that reduces the value of the function. Rinse and repeat, and when you can’t go further down, you have found a local minimum.

How can we find a direction that goes down?

Let’s consider the variable x. If we increase x “a little” from its initial value of x0, the value of the beale function will change, at a rate given by its (partial) derivative evaluated at x0. So if that derivative is positive, in order to reduce the value of the function, we should decrease x. Conversely, if the derivative is negative, we should increase x.

Denoting that partial derivative f'x, we can achieve a decrease by updating x like so:

x1 = x0 - alpha * f'x(x0).

Setting alpha to a small positive value will produce the desired effect. If f'x is positive, x will decrease; if f'x is negative, x will increase. In either case, the function value will decrease.

Applying the same reasoning to y gives us a strategy: compute all the partial derivatives of the function, which will give us the rate of change if we increase each value, and move each value towards a decrease. As it turns out, the vector of all these partial derivatives has the name - the gradient. So our strategy boils down to the following:

Simple gradient descent in dfx

Version used:
#r “nuget: dfx-cpu, 1.0.12”

Implementing this strategy is (almost) a one-liner in dfx:

open Dfx

let step
    (alpha: float) // step size, aka learning rate
    (f: Tensor -> Tensor) // function to minimize
    (current: Tensor) // current value
    =
    let gradient = dfx.grad f current
    current - alpha * gradient

Let’s try it out on the beale function. To match the signature, we need to convert it to use tensors (more on that in a minute), like so:

// tensor version of the beale function
let beale (xy: Tensor) =
    let x = xy[0]
    let y = xy[1]
    (1.5 - x + x * y) ** 2.0
    +
    (2.25 - x + x * y ** 2.0) ** 2.0
    +
    (2.625 - x + x * y ** 3.0) ** 2.0

Let’s test it out:

// starting point x0, y0
let init = dfx.tensor [ 1.0; 1.0 ]
> val init: Tensor = tensor([1., 1.])

// initial value
beale init |> float
> val it: float = 14.203125

// updated x1, y1 after 1 step
let updated = init |> step 0.01 beale
> val updated: Tensor = tensor([1.0000, 0.7225])

// value after the update
updated |> beale |> float
> val it: float = 8.643115997

We start at (x0 = 1.0, y0 = 1.0), where we compute the initial value, beale(1.0, 1.0), which equals 14.2. We apply one update, and observe that after one step, we moved to (x1 = 1.0, y1 = 0.7), where the function value decreased from 14.2 to 8.6. Things appear to work as expected.

We can now do the Rinse & Repeat part, repeating updates to generate a sequence of decreasing values:

    init
    |> Seq.unfold (fun xy ->
        let x, y = xy[0] |> float, xy[1] |> float
        let f = beale xy |> float
        let next = step 0.01 beale xy
        Some ((x, y, f), next)
        )
    |> Seq.take 10
    |> Array.ofSeq
[|
    (1.0, 1.0, 14.203125); 
    (1.0, 0.7224999666, 8.643115997);
    (1.048665881, 0.5841308832, 6.750264168);
    (1.106647849, 0.4852854908, 5.54221487);
    (1.166829109, 0.4088133574, 4.655265331);
    (1.226356149, 0.3475235999, 3.965607405);
    (1.283878446, 0.2974966466, 3.41397047);
    (1.338739634, 0.2562693655, 2.96565485);
    (1.390648007, 0.2221497744, 2.597605705);
    (1.439516902, 0.1939031929, 2.293242455)
|]

Over 10 iterations, we see the value of the function regularly decreasing. All good, let’s let it run longer then! Because we happen to know that the minimum is 0, we can let it run until we are close enough to 0, say, 0.000_001. If you do so, after about 1600 iterations, you will end up with a value of (x = 2.997497559, y = 0.4993747175), reasonably close to the correct answer, (x = 3, y = 0.5).

What is a Tensor?

One change we had to make to our initial function

beale (x: float, y: float): float

was to turn it into this version:

beale (xy: Tensor): Tensor

So what is a Tensor? From a software engineer perspective, I think the easiest way to think about a tensor is as an array of arbitrary dimensions. A tensor can be a single value (a scalar), an array of values (1 dimension / vector), a 2-dimensional array (matrix), or any dimension you would want.

Let’s illustrate by creating tensors of various dimensions:

let t0 = dfx.scalar 1.0
> val t0: Tensor = tensor(1.)

let t1 = dfx.tensor [ 1.0; 2.0 ]
> val t1: Tensor = tensor([1., 2.])

let t2 =
    dfx.tensor
        [
            [ 1.0; 2.0 ]
            [ 3.0; 4.0 ]
            [ 5.0; 6.0 ]
        ]
> val t2: Tensor = 
    tensor([[1., 2.],
            [3., 4.],
            [5., 6.]])

Tensors have a dimension, a shape, and indexers:

t2.dim
> val it: int = 2
t2.shape
> val it: Shape = [|3; 2|]
t2[2,0]
> val it: Tensor = tensor(5.)

More interestingly, tensors support various operators and functions, possibly involving tensors of different dimensions (broadcasting):

10.0 * t1 + t2
> val it: Tensor =
    tensor([[11., 22.],
            [13., 24.],
            [15., 26.]])

I have mixed feelings about tensors.

On one hand, they are a powerful abstraction, allowing the combination of scalars, vectors, matrices, and more, in a unified manner. As an example, the step function we wrote earlier expects a function (f: Tensor -> Tensor). This works on functions where inputs are vectors, as in our earlier example, for vectors of any size. It works also on functions that take scalars:

let square (x: Tensor): Tensor =
    x ** 2.0
step 0.1 square (dfx.scalar 10.0)
> val it: Tensor = tensor(8.)

This is great. On the other hand, it will fail at runtime on this example:

step 0.1 square (dfx.tensor [ 10.0; 10.0 ])
> System.Exception: f must be a scalar-valued function of a vector or scalar, encountered f:[|2|]->[|2|]

The failure is logical: because we are computing a gradient, step requires a function that takes in a scalar or a vector, and returns a scalar. This is exactly what the error message states. But all the step function tells me is the very general signature for f, Tensor -> Tensor. I wish there was a way to annotate step, to clarify that what is expected is (Vector -> Scalar).

Stated differently, tensors everywhere is a powerful abstraction, but also makes for code that can be hard to decypher, and could lead to unpleasant debugging time.

Adam optimizer

As we saw earlier, dfx makes it trivial to implement a simple gradient descent algorithm. This is nice, but gradient descent is finicky. In particular, it often requires tuning the alpha parameter, the learning rate.

Using a small value of alpha means taking small steps at each iteration. This helps making sure the direction we are following is sensible, because we stay close to the position where the gradient was evaluated, but will also result in a slower progress. Conversely, a larger learning rate means taking larger steps, which can speed up convergence, but can also completely derail the algorithm by taking overly aggressive steps, moving to a new position that could actually be worse than the previous one.

As an illustration, let’s take our original example, and vary alpha, first bumping it up to 0.05 instead of 0.01:

init
|> Seq.unfold (fun xy ->
    let x, y = xy[0] |> float, xy[1] |> float
    let f = beale xy |> float
    let next = step 0.05 beale xy
    Some ((x, y, f), next)
    )
|> Seq.take 10
|> Array.ofSeq
(1.0, 1.0, 14.203125)
(1.0, -0.3875000477, 4.428001404)
// omitted for brevity
(1.997552633, 0.1093213856, 0.5512651205)
(2.062912226, 0.1485078186, 0.4434992075)

After 10 steps, our earlier version reached a value of 2.29, at x = 1.45, y = 0.19. With alpha = 0.05, in the same number of iterations, we are already at 0.44, much better than 2.29, for x = 2.06, y = 0.15.

However, bumping alpha to 0.1 produces the following sequence:

(1.0, 1.0, 14.203125)
(1.0, -1.775000095, 36.7310791)
(-6.831298828, 9.104244232, 26790710.0)
(784779.5, -1762079.875, infinity)
(-infinity, infinity, nan)
(nan, nan, nan)

This is bad. Instead of a nicely decreasing sequence, our algorithm now takes wild swings, and diverges rapidly to something unusable.

The point here is that Gradient Descent works, but often requires tuning alpha manually, to strike a balance between speed and stability.

Fortunately, this issue can be mitigated by making modifications to Gradient Descent, and dfx includes such a variant, the Adam optimizer. Without going into the details, Adam modifies Gradient Descent by keeping a learning rate alpha for each parameter individually, and updating that learning rate dynamically, based on momentum, the changes observed in previous iterations.

Using Adam on our function is as simple as this:

open Dfx.Optim
optim.adam (beale, init, iters = 10)
Duration   |Iters| Value
0.00:00:00 |   1 | 1.420312e+001 - New min
0.00:00:00 |   2 | 1.417541e+001 - New min
0.00:00:00 |   3 | 1.414772e+001 - New min
0.00:00:00 |   4 | 1.412006e+001 - New min
0.00:00:00 |   5 | 1.409241e+001 - New min
0.00:00:00 |   6 | 1.406479e+001 - New min
0.00:00:00 |   7 | 1.403719e+001 - New min
0.00:00:00 |   8 | 1.400960e+001 - New min
0.00:00:00 |   9 | 1.398203e+001 - New min
0.00:00:00 |  10 | 1.395448e+001 Iters=10 reached
val it: Tensor * Tensor = (tensor(13.9545), tensor([1.0072, 0.9910]))

The optim.adam method requires only 2 arguments, f, the function to minimize, and x0, the initial starting point.

As far as I can tell, unless you specify a number of iterations (iters) or a target value (threshold), the optimizer will run forever, which is why I also included iters = 10 in this example.

On the plus side, using only default values worked. On the downside, this is slow. Let’s change some of the parameters:

optim.adam (
    beale, init,
    lr = dfx.scalar 0.5,
    threshold = 0.000_001,
    printEvery = 25
    )
Duration   |Iters| Value
0.00:00:00 |   1 | 1.420312e+001 - New min
0.00:00:00 |  25 | 8.056664e-002 +
0.00:00:00 |  50 | 4.686180e-002 +
0.00:00:00 |  75 | 1.022825e-003 - New min
0.00:00:00 | 100 | 6.089718e-005 -
0.00:00:00 | 125 | 4.785069e-006 -
0.00:00:00 | 129 | 1.178749e-007 Converged (value < 1e-06)
val it: Tensor * Tensor =
  (tensor(0.0000),
   tensor([3.0007, 0.5002])

I used a large learning rate alpha of 0.5, which would have caused Gradient Descent to diverge. Adam handles it just fine, converging in 129 iterations to the correct solution. This is nice.

Adam is much less sensitive than Gradient Descent to the initial choice of learning rate. However, that initial choice will still impact the speed of convergence, and could cause unstability, so tuning is still recommended!

Parting thoughts

First, I am delighted to see DiffSharp get re-energized via dfx! And a big hat tip to Adrian Sieradski for re-igniting that project.

To this day, I am still in awe whenever I see automatic differentiation at work. I understand conceptually why and how it works, but still - calculus is something I was never really good at, so seeing dfx handle fairly complicated-looking expressions and “just work” always gives me the feeling that I am witnessing an act of Dark Magic.

This post gave me an excuse to dig into the built-in optimizers, something I always wanted to do but kept postponing. I am glad I did! Having a built-in Adam optimizer (as well as a SGD optimizer) is handy. That being said, the API seems less polished than other parts of the library. As a small example, the optimization will run forever unless you set a number of iterations or a threshold, even though neither is required. I was also a bit surprised to see how the threshold value was used as a termination criterion. In most cases, you wouldn’t know what the minimum of the objective function is beforehand. Checking how small the derivatives are would make more sense to me. Perhaps this is assuming that the function being minimized is some form of distance, as is common in curve fitting? That being said, these are nitpicks: the core building blocks are there, and the optimizers live in a layer above, which should make it easy to improve.

One thing I still need to dig into is the notion of Model. My understanding so far is that a Model allows the composition of functions, using parameters of various shapes, and the optimization of these parameters - the type of thing you would need to, for instance, train a neural network. Probably something I will revisit in a later post.

That’s where I will leave things for today! Hopefully there was something for you in this post, and it will perhaps motivate you to take a look at dfx! In the meantime, happy holidays :)

Do you have a comment or a question?
Ping me on Mastodon!