kempnerforge.training¶
Training loop and optimization for KempnerForge.
- Public API:
run_training: Build and run a full training job from a JobConfig
build_loss_fn / build_optimizer / build_scheduler: Component factories
run_eval: Evaluation loop (loss + perplexity)
maybe_no_sync: Gradient accumulation helper
- kempnerforge.training.build_loss_fn(config)[source]¶
Build a composed loss function from training config.
Follows the build_optimizer pattern: config in, callable out. Binds chunk_size for chunked CE and
fp32whentrain.fp32_cross_entropyis set, and composes z-loss with the same chunk size (every token at once for unchunked CE), so the caller gets a clean(logits, labels) -> Tensorinterface.- Return type:
- kempnerforge.training.build_optimizer(model, config, module_patterns=None)[source]¶
Construct an optimizer with per-parameter-group weight decay settings.
With
config.lr_multipliersset, each listed module’s parameters get their own groups atconfig.lrtimes the module’s multiplier, named by"module"; the scheduler then scales every group’s own rate by the same factor. A module nested in another listed one keeps its own parameters.- Parameters:
model (torch.nn.Module) – Model whose parameters to optimize.
config (OptimizerConfig) – Optimizer configuration.
module_patterns (Mapping[str, Sequence[str]] | None) – Module name to the fnmatch patterns of its parameter names, such as
VLMConfig.module_patterns. Required whenconfig.lr_multipliersis set.
- Returns:
Configured optimizer instance.
- Raises:
ValueError –
config.lr_multipliersnames a modulemodule_patternslacks or one that matches no parameter, or two of its modules match the same parameters or parameters that partly overlap.- Return type:
- kempnerforge.training.build_scheduler(optimizer, config, max_steps)[source]¶
Build a LR scheduler from config.
- Parameters:
optimizer (torch.optim.Optimizer) – Optimizer to schedule.
config (SchedulerConfig) – Scheduler configuration.
max_steps (int) – Total training steps (used to compute decay length).
- Returns:
PyTorch LambdaLR scheduler.
- Return type:
- kempnerforge.training.maybe_no_sync(model, micro_step, grad_accum_steps)[source]¶
Skip gradient sync on intermediate accumulation steps.
On the last micro-step, gradients are synchronized normally. On earlier micro-steps, every FSDP2 unit of
modelthat reduces in fp32 skips its reduce-scatter (and, under HSDP, its all-reduce) and keeps its unsharded gradient until the last micro-step reduces the sum. A unit that reduces in bf16 syncs on every micro-step, so its running sum is kept in the sharded gradient’s dtype, never in bf16. A model whose root is an FSDP2 module and whose units all skip is switched through its root; otherwise each skipping FSDP2 module it holds is switched, also behind atorch.compilewrapper. Sync is turned back on when the block exits. For a model without FSDP2 modules, this is a no-op.- Parameters:
model (torch.nn.Module)
micro_step (int)
grad_accum_steps (int)
- Return type:
Generator[None, None, None]
- kempnerforge.training.run_eval(model, eval_dataloader, loss_fn, device, eval_steps, *, pp_schedule=None, pp_rank=None, pp_size=None, pp_group=None, pp_n_microbatches=None, dp_groups=())¶
Run evaluation and return metrics.
- Parameters:
model (torch.nn.Module) – The model (FSDP-wrapped, TP-sharded, or plain).
eval_dataloader (torch.utils.data.DataLoader) – DataLoader yielding {“input_ids”, “labels”} batches.
loss_fn (callable) – Loss function (logits, labels) -> scalar tensor.
device (torch.device) – Device to move batches to.
eval_steps (int) – Number of eval batches to process.
pp_schedule – Pipeline parallel schedule (None for non-PP). It is the training schedule, run forward-only through its
eval(). Gradients left on the stage are set aside for the calls and put back after them, so they keep their values.pp_rank (int | None) – This rank’s PP stage index.
pp_size (int | None) – Total number of PP stages.
pp_group – Process group for PP loss broadcast.
pp_n_microbatches (int | None) – Microbatches per call of
pp_schedule. The batches go through it this many at a time, so each microbatch has the shape the stages were built for;eval_stepsmust be a multiple of it. None sends alleval_stepsbatches in one call.dp_groups (tuple) –
data_parallel_groupsof the job’s mesh. Each data-parallel rank evaluateseval_stepsbatches of its own share of the eval set, and the loss is the mean over those ranks. Empty reports this rank’s batches alone.
- Returns:
Dict with “eval/loss” and “eval/perplexity”, the exponential of that loss.
- Raises:
ValueError – Under PP,
eval_stepsis not a multiple ofpp_n_microbatches, oreval_dataloaderyields no batch.- Return type:
- kempnerforge.training.run_training(config, *, step_fn=None, hooks=None, data_fn=None)[source]¶
Run a full training job: build every phase, run the loop, tear down.
step_fnandhookslet an experiment own the step body or register hooks, anddata_fnits data pipeline, without copying the build phases. All default to whatscripts/train.pyuses;data_fnis called asbuild_data_pipelineis, after the model is built, so it receives the model’stokens_per_imageon a packed or multi-image VLM run, and must follow theDataFncontract. A customstep_fnmust run its forward and loss undersession.autocast(), which casts fp32 master weights to the compute dtype when no FSDP2 wrap does (one GPU, a pp-only mesh).The shutdown handler stays registered, and its forced-exit timer armed, until the process group is destroyed, so a second signal cannot cut the emergency checkpoint’s flush or the teardown short. On the exception path nothing retires it, so the timer still bounds the exit. The timer’s timeouts come from
resolve_shutdown_timeouts, which fits aSIGTERM’s to the launch script’s signal lead unlesstrain.shutdown_timeout_secis set; they are resolved before the process group starts, so a malformed lead fails first.- Parameters:
config (JobConfig)
step_fn (Callable[[TrainingSession, int], StepResult] | None)
hooks (HookRunner | None)
data_fn (DataFn | None)
- Return type:
None
Modules
Training/eval data pipeline construction and phase (annealing) scheduling. |
|
Library entry point for a KempnerForge training job. |
|
Evaluation utilities for KempnerForge. |
|
Parameter freezing helpers. |
|
Gradient utilities for distributed training. |
|
Training loop hooks for extensibility without forking train.py. |
|
The training step loop and the three step bodies it dispatches to. |
|
Loss function registry for KempnerForge. |
|
Optimizer construction for KempnerForge. |
|
Exact Newton-Schulz orthogonalization of sharded matrices for Muon. |
|
Process-level context for a training job: ranks, device, mesh, pipeline. |
|
Learning rate schedulers for KempnerForge. |