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:

  1. A run is a lazy sequence of reports: run.steps(ctx, data) gives a StepReport per step, run.epochs(ctx, train, validation) an EpochReport per epoch. A report is immutable data.

  2. A reaction is an operator on the sequence. The epoch limit is take, logging is onEach, the history is toList(). Two operators are added: stopWhen(reason) { } and untilNoImprovement(patience) { }.

  3. Why a run ended is data too: the operator that ends a run writes its reason on the last report, stoppedBy.

  4. evaluate runs a model over a data set with a loss and the existing Metric interface.

  5. 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

trainStep(model, loss, optimizer, ctx, x, y)

One step: forward, backward, optimizer step, release of the step. Returns the loss tensor.

TrainingRunner.step

trainStep with the runner’s model, loss and optimizer.

TrainingRunner.train(ctx, dataset, epochs)

A loop over epochs and batches. Returns Unit. No loss, no validation, no way to stop.

Metric

update, compute, reset. Nothing in the engine feeds a metric from a data set.

Java TrainingLoop.train

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.

Why this needs a SKEEP

It adds public API in skainet-lang-core, and every later training feature (checkpoints, best weights, learning-rate policies, progress display) inherits the shape decided here.

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.step and TrainingRunner.train do not change.

  • Common code, every target.

Non-Goals

  • A fit method 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 Flow or any coroutine API. See Proposed Design, "Sequence, not Flow".

  • Metrics computed during the training steps. trainStep does 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>
  • steps is the source. It iterates data once 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 of steps(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

take(n)

Logging, checkpoint, learning-rate change

onEach { }

History

toList()

Early stopping

untilNoImprovement(patience) { }

Divergence, time budget, cancel request

stopWhen(reason) { }

Why the run ended

history.last().stoppedBy; null when the sequence ended without an operator’s reason

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. trainStep stops the recording in a finally, so the context can be used again. The reports already consumed by onEach are not lost; a toList() that did not return gives no list, so a program that needs the history of a failed run collects it in onEach.

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.

Java

Java does not see the sequence. TrainingLoop.fit(train, epochs) and fit(train, validation, epochs, patience) build the same chain and return List<EpochReport>. train and trainAsync stay.

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-009 of skainet-ground-truth gains five optimizer cases with op.clip_grad_norm or op.clip_grad_value (SGD, SGD with momentum, Adam, RMSprop). Each asserts that the bound changes some gradients and leaves others. OptimizerExecutor wraps 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 in commonTest: 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. TrainingRunTest in commonTest checks laziness, the epoch limit, the reason, the partial epoch, patience, minDelta, the single pass, the phase of validation and that evaluate leaves the model unchanged. It runs on the JVM and on native targets.

  • The update rules a run applies are those TS-009 already 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

fit(epochs = 50)

epochs(…​).take(50).toList()

History

the list

Callback.onEpochEnd

onEach { }

EarlyStopping(patience = 3)

untilNoImprovement(3) { it.validation!!.loss!! }

TerminateOnNaN

stopWhen("the loss is not finite") { !it.loss.isFinite() }

model.stopTraining = true

stopWhen(reason) { }

evaluate

evaluate

clipnorm, clipvalue on the optimizer

optimizer.clipGradNorm(), clipGradValue()

Rollout Plan

  1. This document and the implementation in one change: reports, sequences, operators, evaluate, clipping, Java fit, how-to page, sample compiled in CI.

  2. The clipping cases of TS-009 in skainet-ground-truth, merged first.

  3. 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 stopWhen or untilNoImprovement has 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-009 pass in the ground-truth job.

  • The API dump of skainet-lang-core holds 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 required epochs parameter would prevent it, at the price of two ways to say the same thing.

  • Operators with memory. untilNoImprovement holds 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 Sequence and is the point of the design; the single-pass constraint and the documentation carry it.

Open Questions

  1. 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).

  2. A bound on steps/epochs. Whether an optional epochs: Int on the source is worth the second spelling.

  3. Deprecating TrainingRunner.train.

References