kempnerforge.training.loop¶
The training step loop and the three step bodies it dispatches to.
run_training_loop owns everything that repeats: the step body, NaN
handling, optimizer/scheduler advance, freeze and phase transitions,
metrics, eval, checkpointing, and shutdown. The step body itself is a
plain callable (StepFn) chosen once by select_step_fn(), so a
model family with a different forward contract is a new function rather
than another branch inside the loop.
Functions
|
MoE auxiliary + router z-loss terms (only called when |
|
Metadata saved alongside every checkpoint so a resume is exact. |
|
Clip the step's gradients to |
|
PP step: collect microbatches, hand them to the schedule, broadcast loss. |
|
Run the step loop from |
|
Pick the step body for this job: PP wins, then VLM, then text-only. |
|
Standard step (no PP, text-only), with optional per-dataset mixture metrics. |
|
VLM step (no PP): pixel_values + input_ids forward, with a text-token count. |
Classes
The training dataloader plus its live iterator. |
|
What one training step reports back to the loop. |
|
Everything one training run needs after the build phase. |
- class kempnerforge.training.loop.BatchStream[source]¶
Bases:
objectThe training dataloader plus its live iterator.
Wraps the epoch-boundary restart and the “no dataloader configured” case so the step bodies don’t each re-implement them. The loader is read off the pipeline on every access, so swapping
pipeline.dataloadertakes effect on the next step instead of leaving a stale snapshot.- __init__(pipeline)[source]¶
- Parameters:
pipeline (DataPipeline)
- Return type:
None
- ensure_started()[source]¶
Materialize the iterator, if it isn’t already, for the loader in use.
next_batchdoes this itself; the loop calls it up front so building an iterator (which spawns dataloader workers) stays outside the regionMetricsTrackertimes.- Return type:
None
- reset()[source]¶
Drop the iterator so the next step takes a fresh one from the loader.
A
StatefulDataLoaderre-applies its recorded skip, so this picks up inside the current epoch rather than restarting it. A loader with arestart(), asStatefulDataLoaderandStreamingDataLoaderhave, is told, so a checkpoint saved before the next step records what the iterator that step starts draws.- Return type:
None
- close()[source]¶
Drop the live iterator and shut the loader’s worker processes down.
Calls the loader’s
close()where it has one, asStatefulDataLoaderandStreamingDataLoaderdo, andshutdown_workersfor a plainDataLoader. Both stop the workers through the loader’s own sentinel path, since workers that ignore SIGTERM (seeignore_shutdown_signals_in_worker) cannot be stopped with it.Rank-local and idempotent, with no collective, so it is safe on the exception path in
train_loop’sfinally.- Return type:
None
- class kempnerforge.training.loop.StepResult[source]¶
Bases:
objectWhat one training step reports back to the loop.
The per-dataset fields stay None for step bodies that don’t produce them;
text_tokensstays None, which a VLM run treats as an error rather than logging a zero. With a data mixture, on a step the tracker will log,dataset_tokensholds the positions this rank drew from each source, by source index, anddataset_losseseach source’s summed cross-entropy (row 0) and labeled-token count (row 1).tokensis the number of positions the model ran on this rank over every micro-step, image positions and padding included, andseq_lenthe length of each of those rows; withtokensNone the loop countstrain.batch_size * train.seq_lenper micro-step. A VLM step also reports thedocumentsit trained on, theimage_tokensof their real images, theirdocument_text_tokens(prompt included, padding excluded; None when the batch does not say) and theencoder_imagesthe vision encoder ran, padding frames included.- dataset_tokens: torch.Tensor | None = None¶
- dataset_losses: torch.Tensor | None = None¶
- __init__(loss, grad_norm, text_tokens=None, dataset_tokens=None, dataset_losses=None, tokens=None, seq_len=None, documents=None, image_tokens=None, document_text_tokens=None, encoder_images=None)¶
- Parameters:
- Return type:
None
- class kempnerforge.training.loop.TrainingSession[source]¶
Bases:
objectEverything one training run needs after the build phase.
documents_seencounts the documents a VLM run trained on over the data-parallel ranks, from the checkpoint it resumed; it stays None while the step body reports none.- runtime: RuntimeContext¶
- model: torch.nn.Module¶
- optimizer: torch.optim.Optimizer¶
- scheduler: Any¶
- loss_fn: LossFn¶
- step_fn: StepFn¶
- data: DataPipeline¶
- phases: PhaseState¶
- checkpointer: CheckpointManager¶
- tracker: MetricsTracker¶
- hooks: HookRunner¶
- nan_detector: NaNDetector¶
- shutdown_handler: ShutdownHandler¶
- pipeline: PipelineBundle | None = None¶
- autocast_dtype: torch.dtype | None = None¶
- property batches: BatchStream¶
The live batch iterator. Rebuilt if
datais replaced wholesale.
- property dp_groups: tuple¶
data_parallel_groupsof the runtime’s mesh, taken from it once.The logged losses and token counts are reduced over these groups, so every rank logs and hands its hooks the same values for the whole job.
- __init__(config, runtime, model, optimizer, scheduler, loss_fn, step_fn, data, phases, checkpointer, tracker, hooks, nan_detector, shutdown_handler, pipeline=None, eval_dataloader=None, profiler=None, autocast_dtype=None, control_group=None, documents_seen=None)¶
- Parameters:
config (JobConfig)
runtime (RuntimeContext)
model (torch.nn.Module)
optimizer (torch.optim.Optimizer)
scheduler (Any)
loss_fn (LossFn)
step_fn (StepFn)
data (DataPipeline)
phases (PhaseState)
checkpointer (CheckpointManager)
tracker (MetricsTracker)
hooks (HookRunner)
nan_detector (NaNDetector)
shutdown_handler (ShutdownHandler)
pipeline (PipelineBundle | None)
eval_dataloader (Any | None)
profiler (Any | None)
autocast_dtype (torch.dtype | None)
control_group (Any | None)
documents_seen (int | None)
- Return type:
None
- kempnerforge.training.loop.clip_grads(model, max_norm, pp_group=None)[source]¶
Clip the step’s gradients to
max_norm; return their norm before clipping.Under expert parallelism the gradients of the parameters every EP rank holds a copy of are first averaged over the EP group (
average_non_expert_grads_), so every EP rank clips and steps its copies alike. Every rank must make the call.- Parameters:
model (torch.nn.Module)
max_norm (float)
pp_group (Any)
- Return type:
- kempnerforge.training.loop.add_moe_losses(loss, model, mc)[source]¶
MoE auxiliary + router z-loss terms (only called when
mc.is_moe).The routers’ losses are then detached (see
Transformer.detach_router_losses).- Parameters:
loss (torch.Tensor)
model (torch.nn.Module)
mc (Any)
- Return type:
- kempnerforge.training.loop.pipeline_step(session, step)[source]¶
PP step: collect microbatches, hand them to the schedule, broadcast loss.
stepis unused — MoE (the only step-dependent branch) is rejected with PP inJobConfig.validate.- Parameters:
session (TrainingSession)
step (int)
- Return type:
- kempnerforge.training.loop.vlm_step(session, step)[source]¶
VLM step (no PP): pixel_values + input_ids forward, with a text-token count.
Each row the decoder runs holds the model’s
num_image_tokensimage positions (zero when they do not enter the residual stream) and the text. A packed batch (one withimage_rows) also carriesdoc_ids,position_ids, the image placement (image_starts,image_tokens) and the text positions, all passed through to the wrapper, withattention_group_idswhen a collator emits them. Its rows hold their image positions already, and its row count varies, so the leading dims are marked dynamic fortorch.compile.- Parameters:
session (TrainingSession)
step (int)
- Return type:
- kempnerforge.training.loop.text_step(session, step)[source]¶
Standard step (no PP, text-only), with optional per-dataset mixture metrics.
Each source’s tokens and loss are counted only on a step the tracker will log, which is
step + 1:stepcounts the steps done before this one. The loss is the plain cross-entropy of the source’s labeled tokens, without the z-loss or MoE terms the training loss may add.- Parameters:
session (TrainingSession)
step (int)
- Return type:
- kempnerforge.training.loop.select_step_fn(config)[source]¶
Pick the step body for this job: PP wins, then VLM, then text-only.
- Parameters:
config (JobConfig)
- Return type:
- kempnerforge.training.loop.checkpoint_extra(config, step, phases, documents_seen=None, consecutive_nans=0)[source]¶
Metadata saved alongside every checkpoint so a resume is exact.
vlm_freezereflects the post-transition state when a FreezeStage has fired (seefreeze_meta_at_step).pluginsis the run’s plugins list, which a resume compares with its own (seerestore_checkpoint).documents_seen, when given, is saved for the resumed run to count on from.consecutive_nans, the NaN detector’s count of NaN steps in a row, is saved when it is not zero, for the resumed run to count on from, so it stops at the step the uninterrupted run stops at; a checkpoint without it resumes at zero.
- kempnerforge.training.loop.run_training_loop(session, *, step=0, tokens_seen=0)[source]¶
Run the step loop from
steptotrain.max_steps.Returns the final
(step, tokens_seen). Drains an async checkpoint at the first step boundary at which no rank is still writing it, and any still pending before returning, so the caller can tear down the process group safely.session.datais read once and must stay fixed for the duration; only itsdataloadermay be swapped mid-run. An optimizer whose statesession.checkpointerdid not restore starts at the rate its scheduler last set, times the active phase’slr_scale; a restored one keeps its rate.Every rank must call it: the shutdown and NCCL-health stops are agreed over
session.control_group. When that isNonethe loop makes the group, and destroys it when it returns or raises. It never callsshutdown_handler.finish(); the handler’s owner does, once teardown is done. After an NCCL-health stop it saves nothing, drains any pending async save and raisesRuntimeErroron every rank, so the job fails rather than ending as if it completed. The NaN stop, oncenan_detector.rollback_recommended, saves nothing either and returns: nothing rolls back, and the rollback to an earlier checkpoint is manual.