Train a model and decide when to stop
A training run is a lazy sequence of reports. run.epochs(…) gives one EpochReport per
epoch and run.steps(…) one StepReport per step. Nothing is trained until the sequence is
pulled, and what you do with a report is an operator on the sequence. There is no callback
interface to implement and no flag for the loop to poll (SKEEP-010).
The snippets on this page are compiled and executed in CI from skainet-docs-samples
(TrainingRunSample.kt).
The run
A run is the model, the loss and the optimizer, as before:
training<FP32, Float> {
model { model }
loss { MSELoss() }
optimizer {
// Clipping is part of the step, so it wraps the optimizer.
adam(lr = 0.01).clipGradNorm(1.0)
.apply { model.trainableParameters().forEach { addParameter(it) } }
}
}
Epochs, validation, early stopping, history
val history: List<EpochReport> = run
.epochs(ctx, train, validation) // nothing is trained yet
.onEach { println("epoch ${it.epoch}: loss ${it.loss}, validation ${it.validation?.loss}") }
.stopWhen("the loss is not finite") { !it.loss.isFinite() }
.untilNoImprovement(patience = 5) { it.validation!!.loss!! }
.take(300) // the epoch limit
.toList() // trains, and is the history
val last = history.last()
println("ended after ${last.epoch} epochs: ${last.stoppedBy ?: "the epoch limit"}")
| You want | You write |
|---|---|
A limit of 50 epochs |
|
A log line, a checkpoint, a learning-rate change after every epoch |
|
Early stopping |
|
A stop for a reason of your own |
|
The history |
|
The reason the run ended for |
|
Evaluation without training |
|
Stopping a run before its end
A report is handed out only after its step or its epoch is complete: the optimizer has updated the parameters and the context has released the step. So wherever the run ends, the model is in a consistent state, and the code after the terminal operator is the place to save it, log the reason or report to the user.
Three cases:
-
A condition on the numbers, such as a loss that is not finite or a time budget:
stopWhen. -
A request from outside, such as a user who cancels: a flag another thread sets, read in
stopWhen("cancelled") { cancelled.get() }. The run ends after the step or epoch in progress. -
An error in a step: the exception leaves the sequence as it would leave a loop. The step stops its recording on the way out, so the context can be used again.
epochs can react only when an epoch has ended. To end a run inside an epoch, put the condition
on the steps and make the epochs from them:
val epochs = run
.steps(ctx, train)
.stopWhen("the step budget is used up") { it.epoch == 3 && it.step == 2 }
.onEach { seen += it }
.epochs { run.evaluate(ctx, train) } // a partial epoch is not evaluated
.toList()
The epoch that was cut short is reported with complete = false, has no validation, and carries
the reason.
Gradient clipping
Clipping changes the gradient before the update, so it is part of the step and not a reaction to it. It is an optimizer that wraps another one:
| Factory | What it does |
|---|---|
|
Takes the norm of all gradients as one vector. When it is larger than |
|
Clips every element of every gradient to |
Register the parameters on the optimizer that clipGradNorm or clipGradValue returns. Both
rules are those of torch.nn.utils and are held to it by the ground-truth suite TS-009.
What to know
-
The sequence has no end of its own. Bound it with
take,stopWhenoruntilNoImprovementbefore a terminal operator such astoList(). -
The sequence can be consumed once, because consuming it trains the model. A second pass fails.
-
An operator with a memory, such as
untilNoImprovement, belongs to one run. -
The training data is iterated once per epoch. Shuffle in its
iterator()if every epoch should see another order. -
From Java,
TrainingLoop.fit(…)runs the same sequence and returns the history as a list (Train a model from Java).