/reactantnitro-jl:reactantnitro-metricsfrom reactantnitro-jl
Guides writing metrics for ReactantNitro experiments: value-to-mode contract (count, sum, max, min, concat), why the framework omits denominators, group and mode mixing, fixed key sets, finalize_metrics for non-mean values, concat for rank-based metrics like AUROC, logging validation loss, metrics vs train_metrics, and metric residency (host vs…
Ships in reactantnitro-jl. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Two hooks, both optional. metrics runs on an evaluation split, once per eval batch, each epoch.
train_metrics runs on the training batch, once per micro-batch, and returns plain scalars.
metrics(e, outputs; y) -> NamedTuple of `value => mode`
With no metrics method at all, the framework reports the validation loss as loss, so a bare
experiment still validates. Names carry no split: acc, never val_acc; the split is the
context the logger receives, and monitor reads the validation metrics by these keys. The full reference is the Metrics page of the docs (docs/src/metrics.md).
value => mode contractThe mode says how the framework combines a value across the batches of a split.
| Mode | Across batches | finalize_metrics receives |
|---|---|---|
| a count | values summed, counts summed | value / count |
:sum | summed | the total |
:max, :min | elementwise max or min | the extreme |
:concat | joined along the last axis | an (…, N) array, one entry per sample |
function ReactantNitro.metrics(::MyExp, ŷ; y)
err = abs.(ŷ .- y)
return (;
mae = sum(err) => length(err), # divided at the end
accuracy = count_correct(ŷ, y) => size(y, 2),
worst = maximum(err) => :max, # the batch's own extreme
confusion = confusion_matrix(ŷ, y) => :sum, # summed, never divided
)
end
Why not a framework-supplied sample count. Different metrics have different natural denominators: per sample, per image, per object, per present class. One framework count would be the wrong denominator for most of them, silently. A bare number with no mode raises with the metric named rather than being accumulated as though it were a numerator.
=> binds tighter than a ternary. c ? a : b => :sum gives a no mode; write
(c ? a : b) => :sum. A count is any real number, so a weighted mean is sum(w .* err) => sum(w).
The older spellings still work at the top of a key: (value, count) for value => count and
nothing for :sum. Write new metrics with =>.
A key can hold a NamedTuple or Tuple of values. A mode on the group covers every value in it; a
mode on one value covers that value, so a group can mix modes:
ranking = (; score = p, label = y) => :concat
ranking = (; score = p => :concat, label = y => :concat, n_pos = count(y) => :sum)
Every value needs exactly one mode, from itself or a group above it. finalize_metrics receives the
same shape with the modes removed.
The metric set and every value's mode are fixed by the first batch. A later batch that adds or drops a key, or changes a mode, is an error, because a value measured on only some batches has no honest denominator.
So emit every key on every batch, with 0.0 => 0 where the stratum is empty. The natural way to
write a per-class metric is to skip the empty ones (count(sel) == 0 && continue), which is correct
when you own a Dict and fatal here. It also survives testing: synthetic data usually populates
every stratum, and the first batch that misses one is real data.
An empty count reaches you as NaN, because nothing guards 0 / 0. That flows to the logger,
the phase monitors, and the checkpoint metric, which must be finite. Scrub it in finalize_metrics:
ReactantNitro.finalize_metrics(e, acc, split) =
map(v -> v isa Real && !isfinite(v) ? 0.0 : v, acc)
finalize_metrics for anything that is not a meanF1 is not the mean of per-batch F1s. Accumulate the parts with :sum and combine at the end:
ReactantNitro.metrics(::MyExp, ŷ; y) = (; f1 = (; tp = tp(ŷ, y), fp = fp(ŷ, y), fn = fn(ŷ, y)) => :sum)
ReactantNitro.finalize_metrics(e, acc, split) =
(; f1 = 2acc.f1.tp / (2acc.f1.tp + acc.f1.fp + acc.f1.fn))
The default is identity. What finalize_metrics returns is what reaches the run history, the
logger, the phase monitors, and the checkpoint metric, so the key you select a checkpoint on has to
appear here.
A function of sums over samples is exact with counts and :sum: MSE, MAE, R², Pearson correlation,
precision, recall, F1, global Dice and IoU, fixed-bin calibration error. A split-wide extreme is
:max or :min. A metric that depends on ranks or order needs :concat, or a binned :sum
histogram when the split is large: AUROC, average precision, Spearman correlation, medians,
quantiles.
:concat rulespermutedims.i of every :concat value is the same sample, but dataset order
is not promised. Concatenate an id field and sort by it if you need order.finalize_metrics. A :concat array returned unreduced is refused, because it
would be stored in the run history, logged, and written into every checkpoint. Per-sample outputs
for analysis come from predict.:concat holds the split's per-sample values in host memory for one evaluation pass.
The other modes hold one value per key.loss may return (l, terms), a flat NamedTuple of scalars. Each term is logged as
loss/<term>: on the train line straight from the gradient program, and wherever the validation
loss is reported. Only l is differentiated.
ReactantNitro.loss(e::MyExp, ŷ; y) = (ce = crossent(ŷ, y); kl = kldiv(ŷ); (ce + 0.1f0 * kl, (; ce, kl)))
Validation reports the loss without metrics, and with them only under eval_loss = true,
which runs loss in its own small program on the device, as in training, and adds loss and every
loss/<term> after finalize_metrics. A key both sources report is an error naming both.
Do not call loss from a :host metrics. There it runs on the CPU over host arrays, with
e's Device fields still on the device: eager per-op compiles or an error, Reactant-only code
failing, and a number that is not quite the trained objective. Use eval_loss = true.
With metrics defined and eval_loss off, there is no monitor default: declare
monitor(e) = :key => :min | :max, or a ranking checkpointer, EarlyStopping or Plateau is
refused at setup.
:host or :devicemetrics_residency(e, hook::Symbol) -> :host | :device
Defaults: :host for metrics, :device for train_metrics. The default follows the cadence.
train_metrics runs per micro-batch, so host residency there transfers a full output batch every
micro-batch. metrics runs once per eval batch per epoch, after an epoch of thousands of steps, so
the same transfer is noise.
The flexibility runs toward :host. A traced metric has to be expressible as a traced program,
and evaluation code often is not: data-dependent control flow, matching, connected components,
sorting with tie-breaking, any library that knows nothing about Reactant.
What changes for you is only what the arguments are: device arrays under :device, host arrays
under :host. Keyword routing, the modes, and the guarantee that a metric never sees a padded row
are identical either way.
"Host" means every argument, not just outputs. Under :host the framework converts the outputs
and the routed batch fields before calling you, and asserts the conversion was total. You do not
need Array(...) in your hook. An error naming a device-resident path at this boundary is a
framework gap; see reactantnitro-device-boundary.
Residency also decides whether editing the hook recompiles. A :host hook is part of no
compiled program; a :device hook is, and editing it re-pays the compile. Prefer :host while
iterating on a metric.
Do not keep a mutable accumulator on the experiment. The modes are the accumulator, and the framework owns the reduction; a field you mutate per batch is invisible to the tracer and does not survive the run the way you expect.
If you are porting a metric from another framework, check this first. A metric object with
update! and finalize lets you accumulate anything, so a ported metric usually arrives with
keys emitted only when their stratum is non-empty, and with its own running state. Map the state
to modes: running sums to a count or :sum, running extremes to :max or :min, collected
predictions to :concat.
Do not unpack outputs again. If forward returns a single array, metrics receives that
array. first(outputs) gets you element one of the prediction matrix, and every operation after
it stays broadcast-legal, so the run reports a metric over one sample without raising.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
11 skills in this plugin
/reactantnitro-acceleratorsChoosing and configuring the accelerator a ReactantNitro run executes on: CPU, CUDA, ROCm, TPU, and how many devices it shards over. The one-process-one-XLA model, `setup_devices!` (REPL) and its tool form `nitro_setup` (Kaimon) as one shared code path, the `n_devs` pin and its precedence, and `CUDA_VISIBLE_DEVICES` for restricting GPUs. Invoke when starting a run on a specific accelerator, when a run unexpectedly uses the wrong backend or the wrong number of devices, or when deciding what `n_devs` means for a session.
/reactantnitro-checkpoint-resumeCheckpoint and resume a ReactantNitro run: `Checkpointer(; keep)` and its selectors (`Best`, `Last`, `Epochs`, `Every`; retention is their union), `scope = :run | :dir`, current-metric-only selection, the deprecated `TopKCheckpointer`, the `run => checkpoint` source grammar shared by `weights` and `resume`, checkpoint averaging (`Average`, `Best(k; among)`, `average_checkpoints`, `averaged_from`), `resume = :auto`, `restore_optimizer`, `restore_best` (including `restore_best = Average(...)`), finding run ids with `runs()` and `checkpoint_run()`, what a checkpoint record holds and why every value in it is a host value, the four refusals behind a resume, and what is recomputed rather than restored. Invoke when configuring checkpointing, resuming or continuing a run, debugging a refused or failed resume, or deciding which artifact to load for evaluation or export, or configuring an early stop.
/reactantnitro-device-boundaryDebug and prevent CPU/GPU divergence in ReactantNitro: why a fully green CPU test suite can pass while code has never once worked on a device, what a model author must and must not do at the boundary, what scalar indexing does differently on each backend, how to read a residency assertion, and the rule to apply to any new contract ("would this raise on CPU?"). Invoke when code that passes on CPU fails on a GPU; when anything raises "Scalar indexing is disallowed" or "still holds DEVICE-resident values"; when a resume dies on `buffer.buffer !== C_NULL`; or when adding a contract that promises host or device residency.
/reactantnitro-experimentAuthor or read a ReactantNitro experiment: the four required hooks, the three field markers (Device, Host, GraphConst) and which one a field wants, why every knob is a FLAT field and never a configuration struct held in one, the batch contract and keyword routing, what a hook may return and why a batch-reduced scalar may not be an output leaf, derived values, and what `Nitro(e)` does. Also the canonical model shape (one `@compact`, the experiment passed in by `forward`, never captured) and the rule for `@trace` loops that read the experiment or a captured activation (`track_numbers = false`). Start here for any ReactantNitro task; this skill also indexes the rest. Invoke when writing a new experiment or model, porting a training loop onto ReactantNitro, adding a knob to an existing one, writing a `@trace` loop, or reading one you did not write.
/reactantnitro-exportExport a trained ReactantNitro model to a servable artifact: the six export hooks and which are optional, why the exported graph is not the graph that trained, the wire convention, what the framework derives and verifies versus what you declare, and what provenance it stamps versus what you must supply. Invoke when exporting a model, writing the export hooks for a new experiment, or reading a bundle that does not behave the way its manifest says it should.
/reactantnitro-kaimonDrive ReactantNitro runs from a Kaimon-hosted session: the `nitro_*` GateTools the KaimonGate extension registers (train, validate, evaluate, predict, export, runs, status, stop), when the tools appear, why every tool returns immediately and the run runs in the background, how to name an experiment and split run knobs from experiment fields, and how the tools map to the framework verbs `train!`, `validate`, `evaluate`, `predict`, and `export_model`. Invoke whenever a session is hosted by Kaimon, when a workflow says "train the model", or when writing a harness-specific skill that will assume the tool surface.
npx claudepluginhub enzymead/reactantnitro.jl --plugin reactantnitro-jlOther plugins' skills for the same job