SKEEP-009: Ground-truth validation for stateful metrics
Status: Implemented
Audience: SKaiNET maintainers and contributors; authors of new metrics; maintainers of skainet-ground-truth and gradienttracer
Created: 2026-11-23
Tracking issue: #1223
Origin: the Precision / Recall / F1 feature (#1222) shipped with unit tests only, because the ground-truth harness can only run stateless tensor operations. The tracking issue was filed as "SKEEP-005"; that number was already taken by the schedules proposal, so this document is SKEEP-009.
Summary
The ground-truth harness (skainet-test/skainet-test-groundtruth) compares SKaiNET with a
reference library. Today it can do that for one shape of thing only: a stateless TensorOps
call that takes tensors and returns one tensor. A Metric does not have that shape. It is fed
batch by batch with update(), returns one Double from compute(), and has a reset().
This proposal adds a second, parallel path for metrics:
-
A fixture convention inside the existing GGUF contract: a metric case is a normal fixture file whose operation name starts with
metric., whose inputs are a sequence of (predictions, targets) batches, and whose result is one scalar. -
A
MetricExecutorbesideOperationExecutor. It builds the metric from the fixture’s parameters, feeds the batches in order, and returns the value. It also checks the stateful contract (reset()) that no reference value can express. -
scikit-learn as the reference for classification metrics, added to the fixture image.
Nothing changes for tensor operations: OperationExecutor, the existing fixtures and the
existing contract keys are untouched.
Motivation
What the code does today
| Part | Behaviour |
|---|---|
|
Maps |
|
Reads |
|
Writes all tensors as F32. Writes |
|
|
Fixture image ( |
Installs |
So five things do not fit: the executor (stateless), the return type (tensor, not scalar), the targets (the loader has no integer tensors), the parameters (an averaging mode is a word, not a number), and the reference (nothing in the image computes a metric).
Why this needs a SKEEP
Every future metric inherits whatever is decided here, and the decision spans three
repositories (SKaiNET, skainet-ground-truth, gradienttracer) joined by a written fixture
contract. Settling it inside the first metric pull request that needs it would fix the
contract by accident.
Goals
-
Any
Metriccan be checked against a reference library in the same CI job as tensor operations. -
One case can exercise accumulation over several
update()calls. -
The fixture stays inside the existing GGUF contract and file layout.
-
Adding a metric to the harness is one line in the executor plus fixtures.
Non-Goals
-
Gradient validation and wider operation coverage (the Phase 2 roadmap, #984).
-
A fixture format version field. The contract has none today; this proposal stays additive so it does not need one.
-
Rendering a "ground-truth validated" badge for metrics. Metrics have no generated reference page yet.
-
Metrics that do not return one scalar (a per-class vector, a confusion matrix). See Open Questions.
Proposed Design
The four questions of the tracking issue
| Question | Decision |
|---|---|
New decorator, or reuse |
Reuse |
One batch or a sequence? |
A sequence. The inputs are pairs: |
Scalar tolerance? |
Absolute |
Own format, or GGUF? |
GGUF, same layout and naming. The only producer change is that |
Fixture convention
| Item | Convention |
|---|---|
|
|
|
Predictions of batch |
|
Targets of batch |
|
One element: the reference value over all batches together. |
|
|
|
|
|
Passed to the metric’s constructor when present; the metric’s defaults otherwise. |
A case is written like this on the Python side:
@Executable("F1 macro, three classes, two batches",
op_type="metric.f1",
op_params={"average": "macro", "target_encoding": "index"})
def f1_macro_two_batches():
scores_0, y_0 = torch.randn(32, 3), torch.randint(0, 3, (32,))
scores_1, y_1 = torch.randn(32, 3), torch.randint(0, 3, (32,))
y_true = torch.cat([y_0, y_1])
y_pred = torch.cat([scores_0, scores_1]).argmax(dim=1)
expected = f1_score(y_true, y_pred, average="macro", zero_division=0)
return [scores_0, y_0, scores_1, y_1], torch.tensor([expected])
The reference value is computed once over the concatenation of the batches. The SKaiNET side feeds the batches one at a time. A case with more than one batch therefore checks the value and the accumulation in one comparison.
Reference library
scikit-learn is the reference for classification metrics. Its conventions are the ones the
metrics were built to: macro averaging runs over the labels present in the targets or the
predictions, and a zero denominator gives 0 (with zero_division=0 passed explicitly, so no
warning is involved). torchmetrics is stateful like SKaiNET’s Metric, but that is not needed:
accumulation is checked by comparing with the concatenated batches. It also needs the number
of classes fixed up front, and it would be a second dependency for no extra coverage.
A later metric uses whatever library defines it best. The fixture does not record the library; the test suite’s README does.
Kotlin side
/** A metric case: batches in feed order, one expected value. */
public data class GroundTruthMetricCase(
val metricName: String, // "f1" for general.name = "metric.f1"
val batches: List<Batch>,
val expected: Double,
val params: Map<String, Any>, // op.* values, strings included
val source: GroundTruthTestCase,
) {
public data class Batch(val predictions: GroundTruthTensor, val targets: GroundTruthTensor)
}
/** Null when the case is not a metric case. Fails on an odd input count or a non-scalar result. */
public fun GroundTruthTestCase.toMetricCase(): GroundTruthMetricCase?
public class MetricExecutor(private val ctx: ExecutionContext) {
/** Builds the metric, feeds every batch in order, returns compute(). */
public fun execute(case: GroundTruthMetricCase): Double
}
-
Registry.
MetricExecutorholds a map from metric name to a factory that takes the parameters. Adding a metric is one entry. An unknown name fails the case with a message that names it; it is not skipped. -
Loader.
GroundTruthLoaderkeeps string values ofop.*keys.rawOpParamsalready has the typeMap<String, Any>, so this is not an API change. -
Validator.
GroundTruthValidatorgetsvalidateMetric(case, tolerance = 1e-6). The existingvalidate(testCase)is unchanged, and ametric.*case passed to it fails with a message that points tovalidateMetric. -
Stateful contract. After comparing the value, the executor calls
reset(), requirescompute()to return what a new instance returns, feeds the batches again and requires the same value as before. A reference library cannot express this, so the harness checks it on every case. -
Unknown parameters. A parameter in
op.*that the factory does not know fails the case. A fixture that sets an option SKaiNET ignores would otherwise pass by luck.
Producer side
| Repository | Change |
|---|---|
|
The writer stores a |
|
|
CI
ground-truth.yml already generates all fixtures and runs the module’s jvmTest. Two changes:
-
The integration test gets a
TS-008test that fails on any failed case, likeTS-001. -
The workflow’s path filter adds
skainet-lang/skainet-lang-core/src/commonMain/kotlin/sk/ainet/lang/nn/metrics/**. Today a change to a metric does not start the ground-truth job; only the weekly run would catch it.
Compatibility and Migration
-
Additive in all three repositories. No existing fixture, key or Kotlin signature changes.
-
Order of merges. The producer goes first. A consumer that does not know metric cases is safe with the new fixtures: the per-suite tests name their suites, and the "all suites" test reports an unknown operation without failing.
-
The fixture image installs
gradienttracerfrom its default branch and CI checks outskainet-ground-truthat its default branch. Neither is pinned, so a merge there takes effect in SKaiNET’s CI at once. This is how it works today and is not changed here.
Rollout Plan
| Phase | Content |
|---|---|
0 — spike |
String |
1 — harness |
|
2 — Precision, Recall, F1 |
Cases for the three metrics × macro / micro / binary, multi-batch, one-hot targets, a class that never occurs, a zero denominator, binary with a threshold. The note in the metrics how-to that says ground truth is pending is removed. |
Implementation status
| Phase | State |
|---|---|
0 — spike |
Done: |
1 — harness |
Done (#1562). One difference from the sketch above: |
2 — Precision, Recall, F1 |
Done ( |
Found on the way and fixed afterwards: the loader’s useCase was always null, because the
files are named TS_<NNN>_UC_<MMM>.<function>.gguf and the loader looked for a path part that
starts with UC-. It affected all suites, not only metric cases.
Acceptance Criteria
All six are met. The right column says what shows it.
| Criterion | Met by |
|---|---|
A |
The |
Accuracy, Precision, Recall and F1 each have at least one multi-batch case. |
Asserted by the |
A case with a metric name or a parameter the executor does not know fails with a message that names it. |
|
|
|
|
The "Metric cases" section of |
A change under |
The path filter in |
Risks
-
Three repositories. A metric case needs a merge in up to three places. The spike phase exists to find ordering problems while only one case depends on them.
-
Random data and ties. Predictions are random class scores; two equal scores in a row would make the predicted class depend on tie-breaking. With
torch.randnthis does not happen in practice, and binary threshold cases use fixed scores away from the threshold. -
F32 expected value. The reference computes in 64 bit and the file holds 32 bit. The tolerance covers it for values in
[0, 1]; a later unbounded metric (a sum of errors) needs a relative tolerance. See Open Questions. -
Reference drift. A new scikit-learn release could change a default. The cases pass
averageandzero_divisionexplicitly, and the image should pin the version.
Open Questions
-
Non-scalar metrics. A per-class result or a confusion matrix does not fit
compute(): Double. That is a question for theMetricinterface first; the fixture’sresulttensor could already hold more than one element. -
Regression metrics. Targets that are real values need a third
target_encoding(value) and a relative tolerance. Left until the first such metric exists. -
Recording the reference. Should the fixture name the library and version that produced the value (
op.reference = "scikit-learn 1.5")? Useful when a value is disputed; not needed for the comparison. -
Other targets. The ground-truth module builds for JVM and Android only (#1301). Metric values are already pinned bit for bit on every tested target by
MetricsPlatformParityTest, so running the fixtures on the JVM is enough for metrics.
References
-
#1223 — tracking issue.
-
#1222 — Precision, Recall and F1Score; Worked example: F1Score via DARC.
-
gradienttracer— the@Executabledecorator and the GGUF writer. -
sklearn.metrics.precision_recall_fscore_support— label set andzero_division.