16. Architecture¶
1. Package and lifecycle overview¶
NNx is organized around two public entry points (NNModel / Trainer), a
training-hook family (train_step_fn, eval_step_fn, and
trainer_step_fn), and content-addressed persistence under runs/<id>/.
Hook-producing modules inject behavior into the orchestrators; model transforms,
exporters, inference helpers, and diagnostics compose around them.
The inference branch, nnx.decisions, sits beside the training path. Typed
questions go to a DecisionProvider and come back as validated results
(Typed decisions). For a trained classifier, the provider is
FixedHeadProvider over NNModel.predict_proba.
The training loop owns callback dispatch, scheduler updates, phase checkpoint
cadence, and incremental NNRun persistence. A scheduler updates once per
epoch by default. A clock="optimizer_update" scheduler updates once per
committed optimizer update.
See Concepts §1 for the full written breakdown.
2. Lifecycle order¶
For each successfully started training run, NNx calls on_train_begin, then
dispatches epoch and batch work. A completed epoch aggregates validation through
the built-in path or eval_step_fn, updates each epoch-clock scheduler once,
and dispatches on_epoch_end.
An optimizer_update-clock scheduler is stepped instead right after each
committed update of its optimizer. It is never stepped per microbatch, masked
window or skipped step. One of these reports the committed update:
- the update engine;
default_train_step;finalize_step(the built-in paradigm steps);- a step function calling
ctx.report_update(...).
An objective's on_optimizer_update callbacks see every optimizer's event of
a commit before any clock steps.
A run that declares metrics or a named monitor also records the whole-epoch
training summary and the monitor's decision before the scheduler update. That
one decision drives the plateau scheduler, BEST and any EarlyStopping given
the same monitor
(Concepts §6.4).
In an objective run the shared update engine accumulates each microbatch's
loss terms. At the end of every update window it runs unscale → clip → step.
It dispatches on_optimizer_update once per committed update, before the
epoch's validation and the durable commit order
(Concepts §6.5).
Durable state then commits in order: run history, LAST, phase/BEST, and
deferred callback checkpoints. Finalization calls on_train_end in reverse
callback order. Both NNModel and Trainer refresh LAST after finalization.
Callback mutations and topology-transform metadata are therefore present in
the persisted checkpoint.
The exception is an NNModel stop at an update
boundary (ctx.stop_at_update): LAST then stays at the last committed epoch.
The refreshed LAST's RNG streams are the ones from before on_train_end, so
a draw there never reaches a resume.
On failure, callbacks whose begin hook completed are still finalized. Every cleanup hook is attempted; cleanup errors do not mask an exception already raised by training. A failed LAST commit rolls history back; failures after LAST retain the durable history/checkpoint pair. On load, history newer than LAST is truncated, while an empty or corrupt LAST is rejected rather than treated as a request to erase history.
Each text file is replaced on its own through an owned temporary file. A
failed write leaves that destination's previous bytes and removes its
temporary. The history files are not one multi-file transaction, however, and
a hard kill can still leave a stale temporary behind. An interrupt between a
first save's run.yaml and its idps.csv leaves a run with nothing
committed, which loads with an empty history
(Concepts §4, §4.2).
With an opt-in history journal (history=HistoryJournal(...),
Concepts §4.5) the
loop keeps a bounded window of records in memory. The "run history" step
appends the epoch's records as immutable chunks, indexes them and publishes
the journal manifest. This still happens before LAST, which stays the commit
marker.
Readers show records up to LAST's epoch only. A crash between the manifest
and LAST therefore leaves an uncommitted tail that is ignored. A failed LAST
republishes the previous manifest. Callbacks see the window as ctx.idps
unless they declare history_access = "full". A continuation writes its own
run and chunk files, never its source's.
3. Single-node data parallelism (nnx.distributed)¶
train(params, distributed=DDP()) runs inside the process group
torchrun started — NNx adds no runtime of its own:
torchrun --standalone --nproc_per_node=2 train.py
├── rank 0 (writer) ── init_process_group() ── train_loader / validation_loader ── model.train(distributed=DDP()) ── shutdown()
└── rank 1 ── init_process_group() ── train_loader / validation_loader ── model.train(distributed=DDP()) ── shutdown()
(gloo on CPU, nccl with one GPU per rank)
init_process_group() selects cuda:LOCAL_RANK under nccl only. To train a
CUDA model over gloo, call torch.cuda.set_device(local_rank) before
building the model; otherwise every rank's model sits on cuda:0 and the
preflight refuses the other ranks.
Teardown. nnx.distributed.shutdown(timeout_seconds=60) ends the
recipe. Every rank meets at a teardown barrier, then the group is destroyed.
No rank therefore tears down its connections while a peer still uses them.
The wait is bounded with Gloo; with NCCL on older torch, it is bounded by the
group's own timeout. A rank that does not arrive in time makes the others
raise RuntimeError instead of blocking in the call. The group is then left
for process exit.
On Linux CPU builds of torch 2.13.0, 2.14.0 and 2.14.1 the
process waits at exit until the missing rank arrives or the group's timeout
expires. The test suite pins that per torch minor
(tests/test_ddp_adapter.py, test_shutdown_is_bounded_when_a_rank_never_arrives).
A macOS run on torch 2.14.1 exited at once; that difference is not explained.
torch does not promise either behaviour. Without a process group, or after a successful call, it does
nothing.
In a process that called init_process_group(), the Gloo default group
still initialized at interpreter exit is destroyed then, before the interpreter
finalizes. A failed train() or shutdown() leaves it that way. Exit then
waits for a collective still in flight. Otherwise a Gloo worker thread could
release that collective during finalization and abort the process with
std::terminate (exit -6).
Partitions. nnx.distributed.train_loader(dataset, batch_size, policy=, seed=)
deals each epoch's permutation (seeded by (seed + epoch) % 2**64, for a
seed in [0, 2**64 - 1]) to the ranks. It
first pads ("pad" repeats leading rows) or drops ("drop") the tail, so
every rank takes the same number of steps. A mismatch fails on every rank
before the epoch. validation_loader(dataset, batch_size) shards rows rank::world
unpadded: every row id is scored exactly once, a rank may have none, and the
validation loop runs no collective.
One update. Per microbatch:
forward + backward through DDP (no_sync until the window's last microbatch)
│ loss numerator only; before backward, one gather agrees on every rank's
│ loss finiteness and, without a task, scorable targets
▼
records gather: each rank's outputs, targets and window so far
▼
window end: W, S = the ranks' loss denominators, ranks with an additive loss
│ (summed from the records gather)
│ a task model with no valid target on any rank → skip the update on every rank
▼
grad = DDP average × world_size / W (an additive loss, S > 0: × world_size)
▼
clip → optimizer.step() — identical parameters on every rank
With this order, each committed update equals one process training on the union of the ranks' batches, unequal valid counts included.
Besides DDP's gradient all-reduce, a step takes two gathers: the agreement
before the backward and the records after it. W and S need no collective
of their own. Every rank sums the gathered denominators in rank order, so W
is identical on every rank. With more than two ranks and fractional
denominators (class-weighted losses), it can differ from an all-reduced sum
in the last bit.
Records and decisions. Each batch's outputs, targets and loss terms are
gathered and scored the same way on every rank. Validation gathers each
rank's scored shard once. Records are therefore global and identical on every
rank. Monitors, EarlyStopping, BEST and the plateau scheduler decide alike.
Every rank returns the same NNRun (id, records and the writer's
provenance).
Each step gathers the batch's outputs and targets, and validation gathers every scored output once. That traffic suits supervised models, not models with huge outputs such as large-vocabulary logits.
One writer. Only the writer rank (DDP(writer_rank=0)) holds the run
lease. It alone writes history, LAST / BEST / phase checkpoints, deferred
callback checkpoints and the provenance attempt. Its attempt start and each
epoch's commit are agreed, so a failed write stops every rank.
Checkpoints hold the canonical module's keys. DDP wraps model.net per fit
and is never assigned to it. Checkpoints also hold the world size, the
partitions and every rank's RNG streams. A resume with the same world size and
partition restores them all. Any other resume fails before anything is
restored. So does a single-process stateful resume of a distributed
checkpoint; resume_mode="weights_only" starts fresh from its weights.
The writer rank alone verifies the resume point (its files' SHA-256). It shares the manifest or the refusal, so the other ranks never hash it. A torn, mixed or corrupted point is refused on every rank with the same reason.
Agreed failures. At each of these points the ranks share their outcome,
so a failure on one rank makes every rank raise within seconds: the failing
rank its own error, the others usually a DistributedFailure naming it.
- the preflight refusals, building the DDP wrapper and reserving the run;
- the writer's provenance attempt start (
provenance.json,attempt.json); - the resume and the component restore;
on_train_begin;- each epoch's step count and
on_epoch_begin, whose agreement also says whether any rank listens for updates; - each default step's loss finiteness and target checks;
- update listeners registered in
on_train_beginoron_epoch_begin, at each batch's stop decision (agreed again at each epoch's start, so a listener added inon_epoch_begincounts); on_epoch_endand each epoch's commit;on_train_endand the final commit.
A writer-only callback failing in any of these hooks therefore stops every
rank; a resume whose on_train_begin fails hands every rank's model and RNG
back. Anything else failing on one rank only ends through the process
group's timeout and torchrun stopping the other ranks.
writer rank other ranks
lease runs/.leases/<id>.lock —
history runs/<id>/idps.csv, run.yaml in memory (same records)
checkpoint LAST / BEST / phase / deferred —
callbacks "all" + "writer" + writer_only() "all"
Callbacks declare their rank behaviour (Callback.distributed).
"all" callbacks (EarlyStopping, LRMonitor) run everywhere and must not
write. "writer" callbacks (ModelCheckpoint, plain function callbacks) run
on the writer only and may not carry checkpointed component state. TensorBoardCallback and
WandbCallback write when constructed, so a borrowed instance is refused;
nnx.distributed.writer_only(lambda: TensorBoardCallback(...)) builds one on
the writer alone.
A callback that declares nothing is refused before training,
on every rank. So is a callback that changes model.net's topology (it
overrides Callback.checkpoint_transforms, as QATLifecycleCallback does),
wrapped in writer_only or not: on one rank only, DDP would average
mismatched gradients.
Exactness holds for deterministic forwards. Batch normalization is refused, because its running statistics would differ per rank. Dropout draws each rank's own stream, matching one process only in distribution.
Out of scope: multi-node or elastic runs, FSDP / DeepSpeed, mixed precision,
compile=, custom train or validation steps and objectives, history journals,
graph neighbour sampling. ExperimentPlan.fit, nnx.search.search,
Trainer.train and NNModel.train without distributed=DDP() train in one
process and refuse a group of more than one rank. See
examples/ddp_supervised.py.