Data Flow

The path a batch of tokens takes from the dataloader to a committed gradient update. Follow this page with kempnerforge/training/loop.py open in another tab — the structure below maps one-to-one onto the training loop body.

One-slide view

   ┌─ MemoryMappedDataset or MixtureDataset
   │
   ├─ DistributedSampler / MixtureSampler (rank-partitioned indices)
   │
   ├─ StatefulDataLoader ──► batch = {input_ids, labels, doc_ids?}
   │
   ▼
for micro_step in range(grad_accum_steps):       ── maybe_no_sync sets
    ├─ model.set_moe_step(step, max_steps)          DDP/FSDP grad-sync off
    ├─ logits = model(input_ids, doc_ids=doc_ids)   on all but last micro
    ├─ loss   = loss_fn(logits, labels)
    ├─ [+ moe_aux_loss_weight * model.get_moe_aux_loss()]
    └─ (loss / grad_accum_steps).backward()       ── gradient accumulation

[EP] average_non_expert_grads_(model)
grad_norm = clip_grad_norm_(model, grad_clip_norm)
if NaN: drop the routers' counts, zero_grad, maybe stop, skip the update;
        still run freeze stages / phases, scheduler.step() and the shutdown check
optimizer.step() ; [MoE] model.balance_routers() ; optimizer.zero_grad()
step += 1 ; freeze stages / phases due at step ; scheduler.step()

tracker.end_step(step, loss, grad_norm, lr, tokens_in_step)
hook_runner.on_step_end(StepContext(...))
[every N steps] eval, NCCL health, profiler.step, ckpt_mgr.save
if should_shutdown() on any rank: save (unless saved above) + break

Startup, once

Before the loop starts, run_training initializes the collaborators:

  • init_distributed(config.distributed, seed=...) from kempnerforge.distributed.setup — reads RANK / LOCAL_RANK / WORLD_SIZE (torchrun) or SLURM_PROCID / SLURM_NTASKS (multi-node srun), calls dist.init_process_group, builds the DeviceMesh, seeds torch.

  • ShutdownHandler from kempnerforge.resilience.signal_handler — installs SIGTERM / SIGUSR1 handlers for cooperative SLURM preemption.

  • NaNDetector from kempnerforge.resilience.health — tracks consecutive NaN steps, with the action train.nan_action ("warn" by default). After train.nan_max_consecutive (default 10) in a row it sets rollback_recommended and the loop stops; rolling back is manual.

  • Loss function from the registry ("cross_entropy" or "chunked_cross_entropy").

  • Model via build_parallel_model — applies the full parallelism stack (see Parallelism order).

  • Optimizer and scheduler from their registries.

  • CheckpointManager from kempnerforge.checkpoint.manager — owns DCP async save/load, latest-symlink, step_N directories.

  • ckpt_mgr.claim_dir(): rank 0 records the run in <checkpoint.dir>/.owner, and every rank stops when another run that is alive, or not known to have ended, owns the directory (see Auto-resume § One run per checkpoint directory).

  • resolve_resume_path(config.checkpoint.dir) from kempnerforge.resilience.elastic — follows the latest symlink or picks the newest step_N whose save completed. If non-None, ckpt_mgr.load(resume_path) restores model, optimizer, scheduler, dataloader position, and RNG state before the loop starts.

  • MetricsTracker from kempnerforge.metrics.tracker — per-step metrics + EMA smoothing + WandB / TensorBoard backends.

  • Data pipeline: MemoryMappedDataset, MixtureDataset or an eager HF dataset (config dispatches), wrapped by DistributedSampler or MixtureSampler and then by StatefulDataLoader; or an HF streaming dataset, wrapped by StreamingDataLoader with no sampler. Both loaders are in kempnerforge.data.

  • Eval dataloader and torch.profiler (optional).

  • Phase schedule (optional): for curriculum training, rebalances a [[data.datasets]] mixture and scales the LR, on any run, from phase.start_step. The phases active at the step the run starts at, step 0 included, apply here, as does the freeze of that step. An optimizer whose state no checkpoint restored then starts at its scheduler’s last LR times the active phase’s lr_scale.

Inside the loop: one step

The step body is where the interesting routing happens.

1 · Microbatch fetch

for micro_step in range(grad_accum_steps):
    batch = next(data_iter)
    input_ids = batch["input_ids"].to(device)
    labels    = batch["labels"].to(device)
    doc_ids   = batch.get("doc_ids").to(device) if "doc_ids" in batch else None

When dataloader is None, the loop generates random integer tokens — useful for smoke-testing the parallelism stack without any corpus.

doc_ids is optional: non-None only when the dataset packs multiple documents into one sequence. It triggers the block-diagonal attention mask path (see Model § Attention paths).

2 · maybe_no_sync

with maybe_no_sync(model, micro_step, grad_accum_steps):
    ...

Utility from kempnerforge.training.grad, re-exported from kempnerforge.training. On all microbatches except the last, it disables gradient synchronization so the backward pass accumulates locally and does not fire reduce-scatter N times per optimizer step.

3 · MoE step propagation

if mc.is_moe:
    model.set_moe_step(step, tc.max_steps)

Forwards (step, max_steps) to every SigmoidTopKRouter. Used by the adaptive bias schedule (see docs/moe/). Dense models skip this.

4 · Forward

logits = model(input_ids, doc_ids=doc_ids)
loss   = loss_fn(logits, labels)

The forward pass follows the model page: token embedding → N transformer blocks (RoPE + GQA + SwiGLU or MoE) → final RMSNorm → output head → (batch, seq_len, vocab_size) logits.

Per-dataset metrics, if the dataloader is a mixture, are collected here before backward so the logits are still alive.

5 · MoE auxiliary loss

if mc.is_moe:
    aux_loss = model.get_moe_aux_loss()
    loss = loss + mc.moe_aux_loss_weight * aux_loss

get_moe_aux_loss() sums the MoEMLP.aux_loss attributes of every router: one per MoE layer, or one per modality on a MoT layer. For dense runs it returns 0.0 and the line is a no-op.

6 · Backward with gradient accumulation

scaled_loss = loss / tc.grad_accum_steps
scaled_loss.backward()
total_loss += loss.item()

Scaling by grad_accum_steps keeps the effective learning rate invariant to the accumulation factor.

7 · Clip, NaN check, optimizer step

After the microbatch loop:

average_non_expert_grads_(model)
grad_norm = clip_grad_norm_(model, tc.grad_clip_norm)

if not nan_detector.check_loss(avg_loss, step, grad_norm=grad_norm):
    _route_balance(session, step_ran=False)  # drops the sigmoid routers' counts
    optimizer.zero_grad()
    if nan_detector.rollback_recommended:
        break
    step += 1
    _apply_step_transitions(session, step)   # freeze stages, then phases (section 9)
    _advance_lr_schedule(session)            # scheduler.step() + phase LR scaling
    if _shutdown_if_requested(               # saves only finite weights (section 11)
        session, step, tokens_seen, saved_this_step=False, nan_skipped=True
    ):
        break
    continue                                 # no update, token count, metrics or hooks

optimizer.step()
_route_balance(session, step_ran=True)       # sigmoid routers balance (MoE)
optimizer.zero_grad()
step += 1                                    # section 8
_apply_step_transitions(session, step)       # freeze stages, then phases (section 9)
scheduler.step()
if phase_lr_scale != 1.0:
    for pg in optimizer.param_groups: pg["lr"] *= phase_lr_scale

The step bodies make both calls through clip_grads. Under expert parallelism average_non_expert_grads_ gives every EP rank the EP group’s mean gradient of each parameter it holds a copy of, so the copies take the same step and stay equal; without EP it does nothing. clip_grad_norm_ wraps PyTorch’s utility so it works with FSDP2 sharded parameters. Under pipeline parallelism pipeline_step also passes the PP group, so the norm covers every stage rather than this rank’s own; under expert parallelism it reads the EP group from the model and covers every rank’s experts. The NaN detector returns False on a NaN/Inf loss or gradient norm, and the loop zeroes the grads. After max_consecutive NaN steps in a row the detector sets rollback_recommended and the loop stops; rolling back to an earlier checkpoint is manual (see NaN detection).

A skipped step still counts as a step (section 8): it applies the freeze stages and the phases (section 9) due at the new step, advances the LR schedule, and runs the shutdown check (section 11), so all three stay on the step counter. It skips the update, the token count (section 8), metrics and hooks (section 10), and the rest of the periodic work in section 11.

Phase LR scaling applies after the scheduler: it multiplies the base LR that scheduler.step() just computed, with the lr_scale of the phase active at the new step, so the step that starts at a phase’s start_step runs at its scale.

8 · Step accounting

tokens_in_step, documents_in_step, images_in_step = _step_counts(session, result)
# each data-parallel rank adds result.tokens (the configured batch when a
# step body counts none) in one reduction, with its documents and images
step += 1
tokens_seen += tokens_in_step

result.tokens counts every micro-step’s positions, padding included; a VLM step also counts the image positions in the residual stream.

tokens_in_step sums over the ranks of the data-parallel dimensions, not the full world_size: TP, PP and EP peers hold the same batch and count it once.

9 · Phase transitions

If a mixture phase is due, sampler.update_weights(...) rebalances the MixtureSampler and data_iter = None forces a refresh next microbatch so the new weights take effect immediately. Without a mixture, a due phase sets only phase_lr_scale, and the iterator stays.

10 · Metrics and hooks

applied_lr = optimizer.param_groups[0]["lr"]   # read before optimizer.step()
...
loss = dp_mean(result.loss, session.dp_groups, runtime.device)
step_metrics = tracker.end_step(step=step, loss=loss,
                                grad_norm=result.grad_norm, lr=applied_lr,
                                tokens_in_step=tokens_in_step,
                                seq_len=result.seq_len)
hook_runner.on_step_end(StepContext(...))

loss is the step’s loss averaged over the data-parallel ranks, the same on every rank, and lr is the rate the step’s update used (for schedule_free_adamw, the rate before the warmup the optimizer applies inside step()).

tracker.end_step dispatches to WandB / TensorBoard at metrics.log_interval. HookRunner (from kempnerforge.training.hooks) runs user-defined TrainingHook callbacks each step.

MoE runs additionally log moe/aux_loss and moe/expert_balance (min/max of per-expert loads, each router’s counts over its own total) at the same cadence, plus moe/expert_balance/<modality> on MoT.

11 · Periodic work

In order:

  • NCCL health (every tc.nccl_health_check_interval steps) — fires a small all-reduce; if it fails on any rank, every rank leaves the loop without saving, and the loop raises once the last async save is drained.

  • Eval (every eval_config.interval steps) — runs run_eval on the eval dataloader, logs metrics, fires on_eval_end hooks.

  • Profiler — prof.step() advances the torch.profiler schedule.

  • Checkpoint (checkpoint.should_save(step): dyn_ckpt_window milestones inside the window, every checkpoint.interval steps outside it) — ckpt_mgr.save writes a DCP checkpoint. A synchronous save moves the latest symlink to it at once; an async one, written in the background, moves it at the first step at which no rank is still writing it (the shutdown vote below carries that flag).

  • Graceful shutdown — if SIGTERM/SIGUSR1 fired, whichever rank it reached (the ranks vote over a gloo group of their own, and a rank the vote stops arms its own forced-exit timer), every rank writes ckpt_mgr.save(step) as the emergency checkpoint, then exits; a step the checkpoint above already saved is not saved again, and the loop waits for that save. With no shutdown pending, the same vote tells whether any rank is still writing a pending async save; once none is, every rank drains it with ckpt_mgr.wait(), which moves latest to it. A NaN-skipped step (section 7) runs this check too; the checkpoint above never saves such a step, so it writes its own emergency checkpoint, but only if an all-reduced check finds every rank’s parameters finite. After a bad update (an optimizer step that passed the NaN check) they are not, and the shutdown logs an ERROR and saves nothing (see NaN detection § A shutdown after a bad update).

Shutdown

After the loop exits:

  • prof.stop() flushes traces.

  • ckpt_mgr.wait() drains the last async save.

  • hook_runner.on_train_end(step, tokens_seen).

  • tracker.close() flushes WandB / TB.

  • ckpt_mgr.release_dir() marks the run’s .owner record released, on a clean finish.

  • destroy_distributed() tears down the process group.

  • shutdown_handler.finish(), last, restores the signal handlers and cancels the forced-exit timer, so both cover the flush and the teardown.