SKEEP-010: The training run as a sequence of reports
Status: Draft
Audience: SKaiNET maintainers and contributors; users who train models; users who come from Keras or KotlinDL
Created: 2026-12-04
Tracking issue: #1643
Origin: the work to fill the gap KotlinDL left. KotlinDL users expect fit with callbacks, early stopping, a history and evaluate. SKaiNET has trainStep and TrainingRunner.train, which reports nothing.
Summary
TrainingRunner.train(ctx, dataset, epochs) runs a loop and returns Unit. A program cannot see
the loss, cannot stop the run, and cannot evaluate between epochs without writing the loop itself.
The usual answer is a callback interface: the loop calls onEpochEnd, and polls a flag a
callback may set. This proposal does not add one. Instead:
-
A run is a lazy sequence of reports:
run.steps(ctx, data)gives aStepReportper step,run.epochs(ctx, train, validation)anEpochReportper epoch. A report is immutable data. -
A reaction is an operator on the sequence. The epoch limit is
take, logging isonEach, the history istoList(). Two operators are added:stopWhen(reason) { }anduntilNoImprovement(patience) { }. -
Why a run ended is data too: the operator that ends a run writes its reason on the last report,
stoppedBy. -
evaluateruns a model over a data set with a loss and the existingMetricinterface. -
Gradient clipping is an optimizer,
optimizer.clipGradNorm(1.0), because it is part of the step and not a reaction to it.
val history = run.epochs(ctx, train, validation)
.onEach { println(it) }
.stopWhen("the loss is not finite") { !it.loss.isFinite() }
.untilNoImprovement(patience = 3) { it.validation!!.loss!! }
.take(50)
.toList()
Motivation
What the code does today
| Part | Behaviour |
|---|---|
|
One step: forward, backward, optimizer step, release of the step. Returns the loss tensor. |
|
|
|
A loop over epochs and batches. Returns |
|
|
Java |
The same loop. Returns the epoch count and the last step’s loss. |
Why not a callback interface
A callback interface inverts control. The loop owns the run and calls out, so every new need is
a new method on the interface (onEpochBegin, onBatchEnd, onTrainEnd), stopping needs a
mutable flag the loop must remember to poll, and the history is an object a special callback
fills. Two callbacks that both want to stop, or one that needs the result of another, need an
ordering rule.
SKaiNET’s DSLs are declarative: a network, a pipeline or a tensor is described, and the description is data. A callback interface would be the one imperative, loop-owned corner. With a sequence the same separation holds for training: what happened is data, what to do about it is an operator. The operators compose in the order they are written, each is a few lines, a user writes a new one without touching the engine, and the Kotlin standard library already supplies most of them.
Goals
-
A program can see every step or epoch of a run, stop the run for a reason, and know the reason.
-
Stopping leaves the model in a consistent state.
-
No new interface for a user to implement.
-
Additive:
trainStep,TrainingRunner.stepandTrainingRunner.traindo not change. -
Common code, every target.
Non-Goals
-
A
fitmethod with a parameter for every policy. -
Restoring the best weights. It needs a snapshot of the parameters and is a follow-up (see Open Questions).
-
A
Flowor any coroutine API. See Proposed Design, "Sequence, not Flow". -
Metrics computed during the training steps.
trainStepdoes not expose the predictions. -
Shuffling and batching. They belong to the data set.
Proposed Design
All of it is in skainet-lang-core, package sk.ainet.lang.nn.training, except the clipping
optimizers, which are in sk.ainet.lang.nn.optim.
Reports
public interface TrainingReport<out R> {
public val stoppedBy: String?
public fun stopped(reason: String): R
}
public data class StepReport(
val epoch: Int, val step: Int, val loss: Double, val endsEpoch: Boolean,
override val stoppedBy: String? = null,
) : TrainingReport<StepReport>
public data class EpochReport(
val epoch: Int, val steps: Int, val loss: Double,
val validation: Evaluation? = null, val complete: Boolean = true,
override val stoppedBy: String? = null,
) : TrainingReport<EpochReport>
public data class Evaluation(val loss: Double?, val metrics: Map<String, Double>, val batches: Int)
epoch and step count from 1. An epoch’s loss is the mean of its steps' losses. A loss is a
Double, read from the scalar loss tensor, so a report holds no tensor and keeps nothing of the
step alive.
The sequences
public fun <T : DType, V> TrainingRunner<T, V>.steps(ctx, data): Sequence<StepReport>
public fun Sequence<StepReport>.epochs(validate: (() -> Evaluation)? = null): Sequence<EpochReport>
public fun <T : DType, V> TrainingRunner<T, V>.epochs(ctx, train, validation = null, metrics = emptyList()): Sequence<EpochReport>
-
stepsis the source. It iteratesdataonce per epoch, has no end of its own, and yields a report after the step is complete. So wherever the consumer stops pulling, the parameters are updated and the context has released the step. -
Epochs are an aggregation of steps, not a second loop. That is what lets a condition on a step end a long epoch: the epoch that was cut short is reported with
complete = false, is not evaluated, and carries the reason. -
run.epochs(ctx, train, validation, metrics)is the short form ofsteps(ctx, train).epochs { evaluate(ctx, validation, metrics) }. -
The sequences are
constrainOnce(). Pulling them changes the model, so a second pass would not repeat the first one, and failing is better than doing that silently.
The operators
public fun <R : TrainingReport<R>> Sequence<R>.stopWhen(reason: String, condition: (R) -> Boolean): Sequence<R>
public fun <R : TrainingReport<R>> Sequence<R>.untilNoImprovement(patience: Int, minDelta: Double = 0.0, value: (R) -> Double): Sequence<R>
stopWhen ends the sequence with the first report the condition holds for and writes the reason
on it. untilNoImprovement is early stopping, built on stopWhen: lower is better, a value that
is not a number does not improve, and the report that used up the patience is the last one.
| Need | Expression |
|---|---|
Epoch limit |
|
Logging, checkpoint, learning-rate change |
|
History |
|
Early stopping |
|
Divergence, time budget, cancel request |
|
Why the run ended |
|
Stopping and its handling
There is no stop flag in the engine and no cancellation protocol, because the consumer drives the run. Three cases:
-
A condition on the reports:
stopWhen. -
A request from outside (a user, another thread): the request is a value the condition reads,
stopWhen("cancelled") { cancelled.get() }. The run ends after the step or epoch in progress. A step is not interrupted. -
An error in a step: the exception propagates out of the terminal operator.
trainStepstops the recording in afinally, so the context can be used again. The reports already consumed byonEachare not lost; atoList()that did not return gives no list, so a program that needs the history of a failed run collects it inonEach.
Handling is the code after the terminal operator. It has the last report, the reason, and a model in a consistent state.
Evaluate
public fun <T : DType, V> evaluate(model, ctx, data, loss: Loss? = null, metrics: List<Metric> = emptyList()): Evaluation
public fun <T : DType, V> TrainingRunner<T, V>.evaluate(ctx, data, metrics = emptyList()): Evaluation
The model runs in the evaluation phase (eval(ctx) { }), whatever the phase of ctx is. Every
metric is reset first. The loss is the mean of the batches' losses.
Gradient clipping
public fun Optimizer.clipGradNorm(maxNorm: Double): Optimizer
public fun Optimizer.clipGradValue(limit: Double): Optimizer
Clipping changes the gradient between the backward pass and the update. It is part of the step,
so it is not an operator on reports. It follows the optimizer pattern: a decorator that keeps the
parameters registered through it, replaces their gradients in step(), and delegates. The rules
are those of torch.nn.utils.clip_grad_norm_ (one norm over all parameters, factor
maxNorm / (norm + 1e-6) when below 1) and clip_grad_value_.
Cost: the decorator is an Optimizer, so a property of the wrapped class, such as a mutable
lr for a schedule, is reached through a reference to the wrapped optimizer that the caller
keeps.
Sequence, not Flow
Training is synchronous in SKaiNET, skainet-lang-core has no coroutines dependency, and
Sequence with the sequence { } builder is in the standard library on every target. A Flow
would add a dependency and a suspension point to every step for no gain today. An adapter
(asFlow()) is one line in user code and can become API when asynchronous training exists.
Validation
By the DARC rule "Assess means ground truth", what has a numerical reference is held to it, and what is behaviour is tested as behaviour.
-
Clipping has a reference.
TS-009ofskainet-ground-truthgains five optimizer cases withop.clip_grad_normorop.clip_grad_value(SGD, SGD with momentum, Adam, RMSprop). Each asserts that the bound changes some gradients and leaves others.OptimizerExecutorwraps the optimizer when a case has one of the parameters. An optimizer case has one parameter tensor, so the norm over several parameters is tested as a property incommonTest: the length of the clipped step is the bound and its direction is unchanged. -
The sequences and operators have no numerical reference; they are control flow.
TrainingRunTestincommonTestchecks laziness, the epoch limit, the reason, the partial epoch, patience,minDelta, the single pass, the phase of validation and thatevaluateleaves the model unchanged. It runs on the JVM and on native targets. -
The update rules a run applies are those
TS-009already holds.
Compatibility and Migration
Additive. No existing declaration changes. TrainingRunner.train stays and could be deprecated
in favour of epochs(…).take(n).last() once this is accepted; that is not part of this
proposal.
For a user who comes from Keras or KotlinDL:
| There | Here |
|---|---|
|
|
|
the list |
|
|
|
|
|
|
|
|
|
|
|
|
Rollout Plan
-
This document and the implementation in one change: reports, sequences, operators,
evaluate, clipping, Javafit, how-to page, sample compiled in CI. -
The clipping cases of
TS-009inskainet-ground-truth, merged first. -
Follow-ups, each its own DARC feature: best weights, a checkpoint operator.
Acceptance Criteria
-
run.epochs(…)trains nothing until pulled, and one pull trains one epoch. -
A run ended by
stopWhenoruntilNoImprovementhas the reason on its last report and on no other. -
A stop inside an epoch gives a partial epoch that is not evaluated.
-
Validation runs in the evaluation phase and resets the metrics.
-
The five clipping cases of
TS-009pass in the ground-truth job. -
The API dump of
skainet-lang-coreholds the new declarations and no changed one.
Risks
-
A sequence without an end.
run.epochs(…).toList()without a bound does not return. The KDoc and the how-to page say so. A requiredepochsparameter would prevent it, at the price of two ways to say the same thing. -
Operators with memory.
untilNoImprovementholds the best value, so the sequence it returns belongs to one run.constrainOnce()on the source makes a second pass fail. -
Side effects in a sequence. Pulling trains. This is unusual for a
Sequenceand is the point of the design; the single-pass constraint and the documentation carry it.
Open Questions
-
Best weights.
keepBest(model) { value }needs a snapshot and a restore of the parameters. Proposed as a follow-up, because the snapshot is a question of its own (where the copy lives, what it costs on a device). -
A bound on
steps/epochs. Whether an optionalepochs: Inton the source is worth the second spelling. -
Deprecating
TrainingRunner.train.
References
-
SKEEP-009, amendment "the same path for optimizers"
-
torch.nn.utils.clip_grad_norm_,torch.nn.utils.clip_grad_value_ -
Keras
Callback,EarlyStopping,History; KotlinDLCallback