Choose an optimizer

An optimizer turns the gradients of a training step into new parameter values. All six in sk.ainet.lang.nn.optim implement Optimizer, so they are interchangeable in the training { } DSL and in the Java TrainingLoop.

The snippets on this page are compiled and executed in CI from skainet-docs-samples (OptimizerChoice.kt), where each optimizer trains the same small model.

Factory What it does with the gradient Pick it when

sgd(lr, momentum, weightDecay)

Steps along the gradient; with momentum, along a running sum of gradients.

You want the simplest behaviour to reason about, or you have a tuned schedule.

adam(lr, …​), adamw(lr, …​)

Divides a running average of the gradient by the root of a running average of its square.

You want a good default. adamw applies weight decay to the weights directly.

rmsprop(lr, alpha, epsilon, momentum, weightDecay)

Divides the gradient by the root of a running average of its square.

Recurrent networks, or a recipe that was published with RMSProp.

adagrad(lr, lrDecay, initialAccumulatorValue, epsilon, weightDecay)

Divides the gradient by the root of the sum of all its squares so far.

Sparse inputs, where rarely seen features should keep a large step. The step only shrinks.

adadelta(lr, rho, epsilon, weightDecay)

Like RMSProp, with the step also scaled by a running average of past steps.

You do not want to tune a learning rate; lr = 1.0 is the method as published.

adamax(lr, beta1, beta2, epsilon, weightDecay)

Adam with the running maximum of the gradient’s magnitude in place of the average of squares.

Adam is unstable because single large gradients dominate its second moment.

Use one

    val optimizers: Map<String, () -> Optimizer> = mapOf(
        "sgd" to { sgd(lr = 0.1, momentum = 0.9) },
        "adam" to { adam(lr = 0.01) },
        "rmsprop" to { rmsprop(lr = 0.01) },
        "adagrad" to { adagrad(lr = 0.1) },
        "adadelta" to { adadelta() },          // no learning rate to tune
        "adamax" to { adamax(lr = 0.01) },
    )

An optimizer updates the parameters it was given. Register the model’s trainable parameters, then hand it to the training runner:

        val newOptimizer = optimizers.getValue(name)
        val runner = training<FP32, Float> {
            model { model }
            loss { MSELoss() }
            optimizer {
                // An optimizer updates the parameters it was given, so register the model's.
                newOptimizer().apply { model.trainableParameters().forEach { addParameter(it) } }
            }
        }

        var firstLoss = 0f
        var lastLoss = 0f
        repeat(steps) { step ->
            val loss = runner.step(trainCtx, x, y).data.get()
            if (step == 0) firstLoss = loss
            lastLoss = loss
        }

From Java the same six come from sk.ainet.java.Optimizers; see Train a model from Java.

The update rules

g is the gradient, θ a parameter, and every running value starts at zero.

Optimizer Rule

RMSProp

v = α·v + (1 − α)·g², then θ = θ − lr · g / (sqrt(v) + ε). With momentum μ the step is b = μ·b + g / (sqrt(v) + ε).

AdaGrad

s = s + g², then θ = θ − lr / (1 + (t − 1)·lrDecay) · g / (sqrt(s) + ε).

AdaDelta

v = ρ·v + (1 − ρ)·g², Δ = sqrt(u + ε) / sqrt(v + ε) · g, u = ρ·u + (1 − ρ)·Δ², then θ = θ − lr · Δ.

Adamax

m = β1·m + (1 − β1)·g, u = max(β2·u, |g| + ε), then θ = θ − lr / (1 − β1^t) · m / u.

With weightDecay these four add weightDecay · θ to the gradient first (an L2 penalty). A parameter registered with applyWeightDecay = false is exempt, which is the usual choice for biases and normalization parameters.

The rules and the default values are those of torch.optim.RMSprop, Adagrad, Adadelta and Adamax. The ground-truth suite TS-009 runs the real PyTorch optimizers over five steps with given gradients and records the value after every step; skainet-test-groundtruth holds every SKaiNET optimizer, SGD and Adam included, to those values.

Change the learning rate during training

Every optimizer class has a mutable lr. A schedule sets it between steps, and the optimizer keeps its running values:

        val optimizer = RmsPropOptimizer(lr = 0.01)
        val schedule = linearWarmupCosineDecay(totalSteps = 1_000, warmupSteps = 100, peakLr = 0.01)
        val seen = ArrayList<Double>()
        for (step in 0 until 1_000) {
            optimizer.lr = schedule.lrAt(step)   // before each training step
            seen += optimizer.lr
        }

References