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

add_moe_losses(loss, model, mc)

MoE auxiliary + router z-loss terms (only called when mc.is_moe).

checkpoint_extra(config, step, phases[, ...])

Metadata saved alongside every checkpoint so a resume is exact.

clip_grads(model, max_norm[, pp_group])

Clip the step's gradients to max_norm; return their norm before clipping.

pipeline_step(session, step)

PP step: collect microbatches, hand them to the schedule, broadcast loss.

run_training_loop(session, *[, step, ...])

Run the step loop from step to train.max_steps.

select_step_fn(config)

Pick the step body for this job: PP wins, then VLM, then text-only.

text_step(session, step)

Standard step (no PP, text-only), with optional per-dataset mixture metrics.

vlm_step(session, step)

VLM step (no PP): pixel_values + input_ids forward, with a text-token count.

Classes

BatchStream

The training dataloader plus its live iterator.

StepResult

What one training step reports back to the loop.

TrainingSession

Everything one training run needs after the build phase.

class kempnerforge.training.loop.BatchStream[source]

Bases: object

The 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.dataloader takes effect on the next step instead of leaving a stale snapshot.

__init__(pipeline)[source]
Parameters:

pipeline (DataPipeline)

Return type:

None

property dataloader: Any
property has_data: bool
ensure_started()[source]

Materialize the iterator, if it isn’t already, for the loader in use.

next_batch does this itself; the loop calls it up front so building an iterator (which spawns dataloader workers) stays outside the region MetricsTracker times.

Return type:

None

reset()[source]

Drop the iterator so the next step takes a fresh one from the loader.

A StatefulDataLoader re-applies its recorded skip, so this picks up inside the current epoch rather than restarting it. A loader with a restart(), as StatefulDataLoader and StreamingDataLoader have, 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, as StatefulDataLoader and StreamingDataLoader do, and shutdown_workers for a plain DataLoader. Both stop the workers through the loader’s own sentinel path, since workers that ignore SIGTERM (see ignore_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’s finally.

Return type:

None

next_batch()[source]
Return type:

dict[str, torch.Tensor]

class kempnerforge.training.loop.StepResult[source]

Bases: object

What one training step reports back to the loop.

The per-dataset fields stay None for step bodies that don’t produce them; text_tokens stays 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_tokens holds the positions this rank drew from each source, by source index, and dataset_losses each source’s summed cross-entropy (row 0) and labeled-token count (row 1). tokens is the number of positions the model ran on this rank over every micro-step, image positions and padding included, and seq_len the length of each of those rows; with tokens None the loop counts train.batch_size * train.seq_len per micro-step. A VLM step also reports the documents it trained on, the image_tokens of their real images, their document_text_tokens (prompt included, padding excluded; None when the batch does not say) and the encoder_images the vision encoder ran, padding frames included.

loss: float
grad_norm: float
text_tokens: int | None = None
dataset_tokens: torch.Tensor | None = None
dataset_losses: torch.Tensor | None = None
tokens: int | None = None
seq_len: int | None = None
documents: int | None = None
image_tokens: int | None = None
document_text_tokens: int | None = None
encoder_images: int | 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:
  • loss (float)

  • grad_norm (float)

  • text_tokens (int | None)

  • dataset_tokens (torch.Tensor | None)

  • dataset_losses (torch.Tensor | None)

  • tokens (int | None)

  • seq_len (int | None)

  • documents (int | None)

  • image_tokens (int | None)

  • document_text_tokens (int | None)

  • encoder_images (int | None)

Return type:

None

class kempnerforge.training.loop.TrainingSession[source]

Bases: object

Everything one training run needs after the build phase.

documents_seen counts 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.

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 = None
eval_dataloader: Any | None = None
profiler: Any | None = None
autocast_dtype: torch.dtype | None = None
control_group: Any | None = None
documents_seen: int | None = None
property batches: BatchStream

The live batch iterator. Rebuilt if data is replaced wholesale.

property dp_groups: tuple

data_parallel_groups of 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.

autocast()[source]

torch.autocast to autocast_dtype, or a no-op when it is None.

Return type:

AbstractContextManager

__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:
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:
Return type:

float

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:
Return type:

torch.Tensor

kempnerforge.training.loop.pipeline_step(session, step)[source]

PP step: collect microbatches, hand them to the schedule, broadcast loss.

step is unused — MoE (the only step-dependent branch) is rejected with PP in JobConfig.validate.

Parameters:
Return type:

StepResult

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_tokens image positions (zero when they do not enter the residual stream) and the text. A packed batch (one with image_rows) also carries doc_ids, position_ids, the image placement (image_starts, image_tokens) and the text positions, all passed through to the wrapper, with attention_group_ids when a collator emits them. Its rows hold their image positions already, and its row count varies, so the leading dims are marked dynamic for torch.compile.

Parameters:
Return type:

StepResult

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: step counts 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:
Return type:

StepResult

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:

Callable[[TrainingSession, int], StepResult]

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_freeze reflects the post-transition state when a FreezeStage has fired (see freeze_meta_at_step). plugins is the run’s plugins list, which a resume compares with its own (see restore_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.

Parameters:
Return type:

dict

kempnerforge.training.loop.run_training_loop(session, *, step=0, tokens_seen=0)[source]

Run the step loop from step to train.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.data is read once and must stay fixed for the duration; only its dataloader may be swapped mid-run. An optimizer whose state session.checkpointer did not restore starts at the rate its scheduler last set, times the active phase’s lr_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 is None the loop makes the group, and destroys it when it returns or raises. It never calls shutdown_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 raises RuntimeError on every rank, so the job fails rather than ending as if it completed. The NaN stop, once nan_detector.rollback_recommended, saves nothing either and returns: nothing rolls back, and the rollback to an earlier checkpoint is manual.

Parameters:
Return type:

tuple[int, int]