/reactantnitro-jl:reactantnitro-experimentfrom reactantnitro-jl
Author or read a ReactantNitro experiment: four required hooks, three field markers (Device, Host, GraphConst), batch contract, keyword routing, canonical model shape, and @trace loop rules. Start here for any ReactantNitro task.
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.
An experiment is a struct plus hooks. The framework owns the compiled programs, the device
transfers, the optimizer, the schedules, and the lifecycle. Nitro(e) runs setup and nothing else,
so evaluation and serving never require a train! to have happened; train!(nitro) runs the loop.
Everything else has a default. These do not.
build_model(e, rng) -> (model, ps, st) # standard Lux setup
build_data(e, dist) -> NamedTuple of splits # (; train, val, test); `dist` is nothing today
forward(e, model, ps, st; <batch fields>) -> (outputs, st_new)
loss(e, outputs; <batch fields>) -> scalar
An experiment defining only these four trains, validates, and checkpoints with nothing else passed. When you are unsure whether something needs a hook, assume it does not and check the default first.
forward is the exportable program and is what predict calls, which is why the three-function
split exists: forward sees only inputs, loss and metrics see the outputs plus the label fields.
Do not fold the loss into forward.
@experiment struct MyExp
"Structural: changes the emitted graph, so it bakes and is in the compile key."
width::GraphConst{Int} = 128
"A traced INPUT: sweep it or schedule it without recompiling."
smoothing::Device{Float32} = 0.05f0
"Unmarked, therefore Host: driver-only and invisible to the tracer."
max_epochs::Int = 20
end
Unmarked means Host, and that is the default on purpose. The first real model ported to this
framework was 83% Host by field count, so the category you get by saying nothing is the one you
almost always want. Writing Host{T} explicitly is legal and worth it only where a field's
host-ness would otherwise surprise a reader.
| Marker | Reaches traced code as | In the compile key? | Reach for it when |
|---|---|---|---|
GraphConst{T} | a baked literal, ordinary Julia semantics | yes, so changing it recompiles | the value changes the graph: a shape, a class count, a layer width, a variant selector |
Device{T} | a device-resident traced input; baked at its current value on export | no, by construction | a numeric knob you might sweep or schedule, or a buffer set the graph reads and nothing trains (see below) |
unmarked / Host{T} | not at all | no | everything else, including anything dataset-sized |
Getting it wrong is loud, in both directions. Reading an unmarked field from traced code raises
with the field named and all three fixes spelled out. Over-marking GraphConst costs a recompile per
distinct value, which is visible in the cache counters. Neither mistake produces a plausible-looking
run. See reactantnitro-recompiles for what the key actually contains.
Keep dataset-sized state unmarked, or off the experiment entirely. Reactant and Enzyme traverse
the whole experiment while tracing, so anything dataset-sized reachable from it is walked element by
element, on one thread, every time a program compiles. It does not raise and does not change the
emitted graph: compile time simply grows with your data, which reads like a data-loading problem and
is not one. Host is the fix, and it is now the default, so this bites only a field someone marked
GraphConst by hand.
A Device knob read in forward needs no export handling. Export traces against a view of the
experiment with every Device value copied to the host, so the knob is baked into the bundle at the
export handle's value. Do not make a sweepable knob GraphConst for export's sake, and do not invent
a marker for "traced in training, constant at export": that is what Device already does.
Match GraphConst floats to the model's element type. A GraphConst{Float64} scalar broadcast
against a Float32 array promotes the result to Float64; write T(e.scale) or Float32(e.scale). A
Device{Float32} field arrives as a Float32 in training and at export, so it needs no conversion
and no helper.
The generated accessors are device_fields(T), host_fields(T), and config_metadata(T). There is
deliberately no graphconst_fields: two traits determine three categories and the third is the
setdiff. The macro is optional; define those three yourself and a hand-written struct works.
Device field may hold BUFFERS, not just a knobThe marker table above is written around numeric knobs, and that undersells it. A Device field may
hold a buffer set: arrays the graph reads and nothing differentiates, which is what PyTorch calls
buffers. The worked case is a FROZEN PRETRAINED NETWORK that a model calls inside its own forward,
through Reactant.Ops.hlo_call on an exported StableHLO module:
@experiment struct MyProbe
feat_dim::GraphConst{Int} = 4096
backbone_code::GraphConst{String} = "" # the module text IS the graph: baked, and in the key
backbone_w::Device{Any} = () # its weight buffers: traced inputs, never differentiated
end
ReactantNitro.derive(e::MyProbe, data) = (; backbone_code = ..., backbone_w = ...) # host arrays
function ReactantNitro.forward(e::MyProbe, model, ps, st; img)
feats = Reactant.Ops.hlo_call(e.backbone_code, img, e.backbone_w...)[2]
return Lux.apply(model, feats, ps, st)[1], st
end
Why the field and not ps. Nothing trains them, so they do not belong in the parameter tree:
put them there and the optimizer carries state for every one of them, make_zero allocates a
gradient tree the size of the backbone, and the checkpoint records it all. Freezing with
Optimisers.freeze! does not fix that: it stops the UPDATE, not the differentiation.
Why not GraphConst. That bakes the values into the graph and the cache key. For a knob that is
the point; for tens of millions of weights it is a compile-time disaster.
Why it is cheap to differentiate around, which is the part that makes the pattern work: the
experiment reaches the gradient program as Enzyme.Const(ev), so everything on it is constant to
the gradient. Enzyme has nothing to propagate through the backbone, keeps no tape for its forward,
and the only Duplicated argument in the program is the head's ps. A large frozen backbone in
front of a small head costs only the head.
And it transfers once. to_device_config converts Device leaves at setup; the per-step rebuild
re-converts the SCHEDULED entries only, and nothing converts inside the traced step. A buffer set is
not schedulable, so it crosses the bus once at setup and is passed by reference every step
thereafter. That is worth knowing before anyone "optimizes" it: at hundreds of megabytes, a
regression that started converting per step would present as an inexplicably slow epoch rather than
as an error.
derive is usually the right place to fill it rather than a field default, because a default is
eager: every from_preset would then read the weights off disk to answer a question about a preset.
derive runs once per Nitro, before device conversion, so it returns HOST arrays and the framework
places them.
Then keep the backbone out of your dataloader. The alternative shape, running the frozen
network in build_data and yielding features, puts a device program where the framework cannot
account for it, and the framework's prefetch fan-out will then run as many copies of it as there
are producer tasks. Many producers each holding a copy of the backbone's workspace exhaust device
memory within minutes, and the run ends in RESOURCE_EXHAUSTED.
@compact, the experiment passed in by forwardThe canonical shape. forward hands the experiment to the model as an input, and the model reads
GraphConst and Device fields from it directly:
function ReactantNitro.build_model(e::MyExp, rng)
model = @compact(enc = encoder(e.width), block = Dense(e.width => e.width, tanh)) do (x, e)
@return iterate_block(e, block, enc(x)) # reads e.n_iters, e.alpha, ...
end
return model, Lux.setup(rng, model)...
end
ReactantNitro.forward(e::MyExp, model, ps, st; x) = Lux.apply(model, (x, e), ps, st)
Read e at call time; never capture it. build_model may read fields to size layers, and an
initializer may close over a number taken from e. The model itself must not store e or a value
taken from a Device field. build_model receives the converted experiment, so a captured copy:
set_device! and schedules never reach;Host fields, which the tracer then walks and traced code can read silently;Reading e passed in by forward has none of these problems: the traced code sees the compile view
(Host stripped, Device traced) in training and the export view (Device baked) at export.
No config struct on the model. A struct that mirrors experiment fields so the model can carry
them duplicates the single declaration of each value, and is the "flat struct" rule below applied to
the model. Pass e instead.
@trace loops: track_numbers = false when the body reads e or a captured activationfunction iterate_block(e, block, x)
h = zero(x) # traced, since x is
@trace track_numbers = false checkpointing = true for _ in 1:(e.n_iters)
h = block_step(e, block, x, h) # reads e.alpha directly
end
return h
end
A @trace loop makes every variable its body references into loop state and retraces it. With the
default track_numbers = true, every plain Int or Float64 inside that state becomes a traced
number, and a struct whose field types are not type parameters cannot hold one. Compiling fails with
NoFieldMatchError: Cannot convert type ..., naming the struct but not the variable. Two common
cases:
GraphConst fields keep their concrete declared types;ReshapedArray that GroupNorm returns, whose
dims field is a tuple of Ints.track_numbers = false leaves those numbers as constants, which is what a GraphConst is meant to
be; traced values such as Device fields stay traced. Three consequences:
@trace for promotes its bounds itself;Vector{Float64} captured under the default would become an array of traced scalars, one
loop operand per element; under track_numbers = false it stays a constant.Write the loop body as a top-level function that takes what it reads as arguments, so the captures are exactly the call's arguments. Hoisting constant arrays out of the loop is then an optimization, not a requirement.
Every knob is a flat field on the experiment. Do not group knobs into a configuration struct and hold it in a field.
# YES
@experiment struct MyExp
width::GraphConst{Int} = 128
depth::GraphConst{Int} = 8
smoothing::Device{Float32} = 0.05f0
end
# NO
@experiment struct MyExp
model::GraphConst{ModelCfg} = ModelCfg()
end
If a model builder wants a config struct as its argument, assemble one inside build_model from the
flat fields, or have the builder take the experiment. Either keeps one declaration of each value.
The reason that bites first: you cannot override one field of a nested struct. from_preset
validates every key against fieldnames(E), and the generated keyword constructor takes one keyword
per field. Neither reaches inside a struct. So a recipe wanting one different number has to name the
whole struct, and that fills every field it did not name from the CONFIG's @kwdef defaults rather
than from the EXPERIMENT's default for that field:
# experiment declares: model::GraphConst{ModelCfg} = ModelCfg(width = 256, depth = 8)
# a preset writes: (; model = ModelCfg(width = 512))
# and the run trains at depth = 4, the CONFIG's default. Nothing raises.
A call-site override has the same shape, since MyExp(; model = ModelCfg(width = 512)) replaces the
field rather than merging into it. The workaround people reach for is a _with(cfg; kw...) merge
helper, which is a second mechanism to keep in sync and a second place to forget. Flat fields need
none: from_preset(MyExp, :recipe; width = 512) works and says exactly what it changes.
A nested config is safe only by coincidence. If the experiment's default for the field happens to
be a bare ModelCfg(), the fallback lands on the same values and nothing looks wrong. It stops being
true the day that default gains an argument, and then every partial preset silently reverts every
field it did not name.
Three more reasons, in the order they matter:
GraphConst struct can be Device, and Device is what makes a value sweepable
and schedulable with no recompile. Burying a loss weight in a config struct decides, without
meaning to, that changing it recompiles the gradient program.GraphConst field is a hashing hazard, and the WRAPPER is the whole defect.
Julia's fallback hash for a struct with no method of its own is hash(objectid(x), h), and
objectid reaches a mutable field such as a Vector by identity rather than descending into it.
Two identical constructions then key differently (a recompile per handle, and a resume refused with
a diff whose sides print identically), and one mutated in place keys the SAME, which serves a
program compiled for the old value while the resume check passes. The same vector held directly as
a GraphConst{Vector{Int}} field is content-hashed in both directions by Base, with nothing
written by hand. assert_graphconst_hashable refuses the struct case at setup and recommends
flattening first.config_metadata and the logged hyperparameter table are per FIELD. A non-scalar field logs as
the bare string of its type name, so a nested config contributes one useless entry and none of its
values reach the table or any run comparison. Flat fields each log by name.What not to flatten. A Host field holding dataset-sized state (samplers, in-memory frames,
handles) stays one field: it is not a group of knobs, and the point is that compile_view replaces
the whole field with a sentinel so the tracer never walks it. A config type that is some other
function's signature stays a type, but assemble it at the call site rather than storing it. And note
the cost is asymmetric: @experiment generates one type parameter per Device and per Host field
and none per GraphConst, so flattening an architecture config is free in that respect while
flattening a large Host config is not.
Keep the named recipes in their own file. Once the fields are flat, presets is a table of
partial NamedTuples, and it reads better beside the experiment than inside it, organized by
whatever your recipes vary over.
Write the table as METHODS, and anchor it to no const. Revise updates a method body and
cannot rebind a const, so a shared base held in one pins the whole table to whatever it contained
when the session loaded: an edited preset keeps serving the old numbers, silently, until the
process restarts. That is worse here than in ordinary code, because a restart also gives up
whatever the process was holding: on a shared accelerator host, the GPU goes back when the process
exits, so a one-character preset edit turns into acquiring a card again and paying the package load
a second time.
# The shared base as a function, so editing it takes effect on the next call.
my_preset_base() = (; width = 256, max_epochs = 40, batch_size = 64)
ReactantNitro.presets(::Type{MyExp}) = (
smoke = (; my_preset_base()..., max_epochs = 1, batch_size = 8),
current = (; my_preset_base()..., dataset = :full),
)
const MY_PRESET_BASE = (; width = 256, ...) # DON'T: Revise cannot rebind it
The cost is one allocation per from_preset, on a call made once per run. Restarting to pick up a
preset edit also releases and reacquires any leased accelerator, which is expensive on a shared
host.
(A @config macro that generated the three hashing methods existed briefly and was withdrawn.
Do not look for it: shipping a convenience for the discouraged shape worked against the layout the
rest of the framework assumes.)
A data source is anything iterable yielding concrete NamedTuples of host arrays and supporting
length. The framework never looks inside your data and ships no batching or shuffling.
That is the whole contract, and it is deliberately small enough to adapt to rather than adopt.
Three requirements: iterate, yield NamedTuples of host arrays with concrete element types, and
answer length.
If you have no loader, use the ecosystem's. MLUtils.jl supplies batching and shuffling, and
MLUtils.DataLoader satisfies the contract directly once its tuples are named. Reach for it rather
than writing a sampler, unless you have a reason not to.
If you already have a loader, adapt it; do not replace it. Three requirements is usually less
work than porting a data pipeline, and a loader that already knows your storage, your augmentation,
and your sampling is not something to rewrite for the sake of a batching helper. A wrapper that maps
the loader's item to a NamedTuple and forwards length is the whole adapter.
Prefetch is a framework default, and it changes nothing about the contract. Setup wraps every
split, eval included, in a PrefetchIterator at workers = Threads.nthreads(:default),
device_batches = 1 (staged on the device), host_batches = 2 * workers (existing on the host) and
ordered delivery, unless the source is already a PrefetchIterator or a NoPrefetch. The wrapper
forwards length and its iterate is a passthrough, so the three requirements above are the whole
contract. NoPrefetch declines; ordered = false trades a bitwise-reproducible epoch order for
immunity to a straggling batch. Real concurrency needs the two-method trait, batch_at(source, i)
and begin_epoch!(source). The handle's display shows each split's resolved workers,
device_batches, host_batches and path.
The source trait, in full, and who implements it. Five functions, all owned by ReactantNitro
and extended on the source type: begin_epoch!(source) (the per-epoch plan; return it, or
nothing when the source stores it), batch_at(source, i) or batch_at(source, i, plan)
(the two storage choices; i is a BATCH index), epoch_token(source) (a counter the fan-out
asserts advances once per epoch), check_source_options(source, name, cfg) (setup-time refusal
of options the resolved pipeline cannot honour), and release!(source) (close what the source
holds open, called once per handle at Done or Failed, or by release!(nitro) for a handle
that only evaluated or exported). All but the first two are unexported and written qualified.
One implementer per source type: the framework carries the extension for a public loader it
chooses to support (ReactantNitroMLUtilsExt); any other loader's package declares
ReactantNitro as a weak dependency and ships the extension itself. Defining the trait on a type
you do not own is the last resort.
Runs leave the interactive thread, and ^C is a graceful stop. Every entry point
(train!, validate, evaluate, predict, export_model) runs its body on a default-pool
worker thread when one exists, so a long XLA compile or execute never starves your logger tasks
or the REPL; the caller's task parks, and the REPL keeps working while the loop runs. ^C then
requests the graceful stop: train! finishes the epoch, validates, checkpoints, and returns
with stop_reason = :requested (the request_stop! wind-down), and the eval entry points stop
at the next batch boundary. Single-threaded Julia runs inline, unchanged.
A field no hook declares reaches nobody, so a bookkeeping field costs nothing and is allowed to ride along, which means an adapter usually does not have to strip anything either.
Hooks are routed by their keyword names. forward(e, model, ps, st; x) declares it wants x;
loss(e, ŷ; y) declares y. Only the fields some hook declares are transferred to device, so a
bookkeeping field nothing declares costs nothing and is allowed. A required keyword the batch does
not provide is an error naming the hook, the keyword, and the batch's fields.
Every array leaf must have a concrete element type. A batch field like Vector{NamedTuple} fails
inside the tracer with an error that names neither the field nor the batch, so the framework rejects
it first.
forward may return any tree: an array, a tuple, a NamedTuple of several outputs. The batch
dimension must be last on every array leaf of it, exactly as it is on every batch field, because
the framework slices a short final evaluation batch back to its real width and slices the last
dimension to do it.
So a reduction over the batch cannot be an output leaf. A total, a mean, an accumulated penalty,
anything of shape (): each has no batch dimension, and each is rejected. Broadcast it to a (1, N)
row and reduce it again wherever you consume it.
Two reasons that rule is worth knowing before you meet it:
(1, N) row satisfies both rules at once.derive(e, data) -> NamedTuple is merged into the experiment, for anything that genuinely depends on
the dataset (class weights from label counts, a normalization constant). It runs before device
conversion, so it always returns host values, and it is recomputed rather than restored on resume.
Prefer constants for anything structural. Deriving a shape makes the compiled program a function of your data, so a different split silently changes the graph.
reactantnitro-metrics: the value => mode contract, finalize_metrics, residencyreactantnitro-optimizer: parameter groups, decay, clipping, schedulesreactantnitro-manual: manual training mode, where the experiment owns the stepreactantnitro-recompiles: the compile key, cache_stats(), why an edit did not take effectreactantnitro-checkpoint-resume: top-K retention, what resume refusesreactantnitro-device-boundary: why a green CPU test suite says nothing about GPU behaviourreactantnitro-visualization: the two hooks and the render driver, and what to draw at allreactantnitro-export: shipping forward as an artifact, and why what ships is not what trainedreactantnitro-kaimon: driving runs from a Kaimon-hosted session, where an experiment is named as a type stringWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
reactantnitro, experiment-framework, training-loops, lux-jl, julia-ml
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-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.
/reactantnitro-manualTrain a ReactantNitro experiment in manual mode, where the experiment owns the whole optimizer step: `train_step` and how defining it selects the mode, `setup_optimizers`, the checked return contract, `backward` with the objective discipline (a closure capture of a traced value silently zeroes the gradient), `step_optimizer`, path-bound `opt` schedules, and what the automatic loop still does for you. Invoke when the automatic loop cannot express an algorithm, the canonical case being a GAN with two optimizers, or when reading or writing a `train_step`.
npx claudepluginhub enzymead/reactantnitro.jl --plugin reactantnitro-jlOther plugins' skills for the same job