"""Library entry point for a KempnerForge training job.
``scripts/train.py`` is a thin CLI wrapper over :func:`run_training`: it
parses argv, loads the config, and calls in. Each phase below is a
separate function so an experiment can reuse the scaffold โ or swap one
phase โ without editing the shared script.
"""
from __future__ import annotations
import contextlib
import json
import os
from collections.abc import Callable
from functools import partial
from pathlib import Path
from typing import cast
import torch
import torch.distributed as dist
from kempnerforge.checkpoint.manager import CheckpointManager
from kempnerforge.config.checkpoint import is_weights_only
from kempnerforge.config.job import JobConfig
from kempnerforge.config.vlm import MoTConfig, VLMConfig
from kempnerforge.distributed.parallel import (
apply_ac,
apply_float8,
apply_fsdp2,
autocast_dtype,
build_parallel_model,
default_mp_policy,
)
from kempnerforge.distributed.setup import destroy_distributed
from kempnerforge.distributed.tensor_parallel import apply_tensor_parallel
from kempnerforge.distributed.utils import get_dp_info
from kempnerforge.metrics.logger import get_logger
from kempnerforge.metrics.tracker import MetricsTracker
from kempnerforge.model.masking import use_dynamic_flex_shapes
from kempnerforge.model.mot import mot_warm_start_from_text_stack
from kempnerforge.model.transformer import Transformer
from kempnerforge.model.vlm import inner_transformer, packed_tokens_per_image
from kempnerforge.profiling.profiler import build_profiler
from kempnerforge.resilience.elastic import resolve_resume_path
from kempnerforge.resilience.health import NaNDetector
from kempnerforge.resilience.signal_handler import ShutdownHandler, resolve_shutdown_timeouts
from kempnerforge.training.data_pipeline import (
DataFn,
build_data_pipeline,
build_eval_dataloader,
build_phase_state,
)
from kempnerforge.training.freeze import (
apply_freeze_specs,
effective_freeze,
freeze_meta_at_step,
trainable_for_the_run,
)
from kempnerforge.training.hooks import HookRunner
from kempnerforge.training.loop import (
LossFn,
StepFn,
TrainingSession,
run_training_loop,
select_step_fn,
)
from kempnerforge.training.loss import build_loss_fn
from kempnerforge.training.optimizer import build_optimizer
from kempnerforge.training.runtime import PipelineBundle, RuntimeContext, setup_distributed
from kempnerforge.training.scheduler import build_scheduler
logger = get_logger(__name__)
[docs]
def build_model(
config: JobConfig, runtime: RuntimeContext, loss_fn: LossFn
) -> tuple[torch.nn.Module, PipelineBundle | None]:
"""Build the model with the full parallelism stack applied.
With ``distributed.pp > 1`` this builds this rank's pipeline stage plus
its schedule (which is why ``loss_fn`` is needed here); otherwise it
delegates to ``build_parallel_model`` and returns no pipeline. A stage
is wrapped with FSDP2's ``reshard_after_forward=False``: the schedule
sends every microbatch of a step through it, and its parameters stay
gathered after each forward, so the next forward or backward through it
does not all-gather them again.
"""
tc = config.train
device = runtime.device
device_mesh = runtime.device_mesh
mp_policy = default_mp_policy(tc.param_dtype, tc.reduce_dtype)
if config.distributed.pp <= 1:
vision = config.vision_encoder
encoder_mp_policy = (
default_mp_policy(vision.compute_dtype or tc.param_dtype, vision.reduce_dtype)
if config.is_vlm and vision is not None
else None
)
model = build_parallel_model(
config.model,
device,
device_mesh,
vision_config=config.vision_encoder,
adapter_config=config.adapter,
vlm_config=config.vlm,
frames_per_clip=config.views_per_sample,
ac_mode=tc.activation_checkpointing,
mp_policy=mp_policy,
encoder_mp_policy=encoder_mp_policy,
param_dtype=tc.master_dtype,
compile_model=tc.compile_model,
fp8=tc.is_fp8,
)
return model, None
from kempnerforge.distributed.pipeline_parallel import (
build_pipeline_schedule,
build_pipeline_stage,
build_stage_module,
get_pp_rank,
get_pp_size,
)
if device_mesh is None:
raise RuntimeError("pipeline parallelism requires a device mesh")
pp_rank = get_pp_rank(device_mesh)
pp_size = get_pp_size(device_mesh)
tp_enabled_pp = "tp" in device_mesh.mesh_dim_names # type: ignore[reportOperatorIssue]
if tp_enabled_pp:
with torch.device("meta"):
stage_mod = cast("Transformer", build_stage_module(config.model, pp_rank, pp_size))
apply_tensor_parallel(stage_mod, device_mesh)
if tc.is_fp8:
apply_float8(stage_mod)
apply_ac(stage_mod, tc.activation_checkpointing)
apply_fsdp2(stage_mod, device_mesh, mp_policy=mp_policy, reshard_after_forward=False)
stage_mod.to_empty(device=device)
stage_mod.init_weights_and_freqs()
stage_mod.to(dtype=tc.master_dtype)
else:
stage_mod = cast(
"Transformer",
build_stage_module(config.model, pp_rank, pp_size).to(
device=device, dtype=tc.master_dtype
),
)
if tc.is_fp8:
apply_float8(stage_mod)
apply_ac(stage_mod, tc.activation_checkpointing)
apply_fsdp2(stage_mod, device_mesh, mp_policy=mp_policy, reshard_after_forward=False)
model: torch.nn.Module = stage_mod
if tc.compile_model:
logger.info("Compiling model with torch.compile...")
model = torch.compile(model) # type: ignore[assignment]
n_params = sum(p.numel() for p in model.parameters())
logger.info(f"Model (PP stage {pp_rank}/{pp_size}): {n_params:,} parameters")
amp_dtype = autocast_dtype(stage_mod, tc.master_dtype, tc.param_dtype)
shape_inference_ctx = (
torch.autocast(device_type=device.type, dtype=amp_dtype)
if amp_dtype is not None
else contextlib.nullcontext()
)
with shape_inference_ctx:
pp_stage = build_pipeline_stage(
model, # type: ignore[arg-type]
device_mesh,
device,
batch_size=tc.batch_size,
seq_len=tc.seq_len,
param_dtype=tc.param_dtype if amp_dtype is None else tc.master_dtype,
reduce_every_microbatch=tc.reduces_every_micro_step,
)
pp_schedule = build_pipeline_schedule(
stage=pp_stage,
n_microbatches=tc.grad_accum_steps,
loss_fn=loss_fn,
schedule=config.distributed.pp_schedule.value,
)
return model, PipelineBundle(rank=pp_rank, size=pp_size, schedule=pp_schedule)
[docs]
def build_checkpoint_manager(
config: JobConfig,
runtime: RuntimeContext,
model: torch.nn.Module,
optimizer: torch.optim.Optimizer,
pipeline: PipelineBundle | None,
) -> CheckpointManager:
"""Create the checkpoint manager, scoping DCP to the PP stage when needed.
With PP, each stage has different parameters โ DCP needs a group scoped
to ranks within the same PP stage (all non-PP mesh dimensions), and each
stage saves DCP shards to its own subdirectory to avoid file collisions.
The manager records the pipeline degree with every save and compares it on
load. It records each rank's data-parallel coordinates, the partition
``build_data_pipeline`` reads, with the per-rank loader/RNG state.
"""
ckpt_pg = None
ckpt_pp_rank = None
ckpt_pp_size = None
device_mesh = runtime.device_mesh
if pipeline is not None and device_mesh is not None:
from kempnerforge.distributed.pipeline_parallel import build_stage_group
ckpt_pp_rank = pipeline.rank
ckpt_pp_size = pipeline.size
ckpt_pg = build_stage_group(device_mesh, config.distributed.nccl_timeout_sec)
return CheckpointManager(
config.checkpoint,
model,
optimizer,
process_group=ckpt_pg,
pp_rank=ckpt_pp_rank,
pp_size=ckpt_pp_size,
dp_info=get_dp_info(device_mesh),
weight_decay_scope=config.optimizer.weight_decay_scope,
lr_multipliers=config.optimizer.lr_multipliers,
module_patterns=config.vlm.module_patterns if config.vlm is not None else None,
group_timeout_sec=config.distributed.nccl_timeout_sec,
)
def _trainable_for_the_run(
model: torch.nn.Module, config: JobConfig
) -> contextlib.AbstractContextManager[list[str]]:
"""``trainable_for_the_run`` for a VLM with a freeze schedule; otherwise a context that
changes nothing and yields no names."""
if config.vlm is None or not config.vlm.freeze_schedule:
return contextlib.nullcontext([])
return trainable_for_the_run(model, config.vlm)
def _mot_text_warm_start(
vlm_cfg: VLMConfig | None,
model: torch.nn.Module,
agree: Callable[[BaseException | None, str], None],
) -> None:
"""Copy the dense block weights of ``mot_warm_start_path`` into a MoT model.
``agree`` is the checkpoint manager's rank agreement: every rank reports
whether it read the source before any rank enters the copy's DTensor
collectives, so a rank that cannot read the file fails the run on every rank
instead of leaving the others waiting until the process-group timeout.
"""
if not isinstance(vlm_cfg, MoTConfig) or not vlm_cfg.mot_warm_start_from_text:
return
source = {}
error = None
try:
source = torch.load(vlm_cfg.mot_warm_start_path, map_location="cpu", weights_only=True)
if isinstance(source, dict) and "model" in source:
source = source["model"]
except Exception as exc:
error = exc
agree(error, f"MoT warm-start: reading {vlm_cfg.mot_warm_start_path}")
mot_warm_start_from_text_stack(inner_transformer(model), source)
logger.info(f"MoT warm-start: copied dense block weights from {vlm_cfg.mot_warm_start_path}")
def _resume_path_on_rank_zero(checkpoint_dir: str, num_stages: int | None) -> Path | None:
"""``resolve_resume_path`` on rank 0, broadcast to every rank with any error it raised.
Only rank 0 looks at the checkpoint tree, so every rank resumes the same checkpoint, and a
rank 0 that cannot read the tree leaves no rank waiting in the broadcast.
Raises:
Exception: On rank 0, what resolving the checkpoint raised.
RuntimeError: On every other rank, naming rank 0's error.
"""
outcome: list[dict[str, str | None]] = [{"path": None, "error": None}]
error: Exception | None = None
if dist.get_rank() == 0:
try:
found = resolve_resume_path(checkpoint_dir, num_stages)
outcome = [{"path": str(found) if found else None, "error": None}]
except Exception as e:
error = e
outcome = [{"path": None, "error": f"{type(e).__name__}: {e}"}]
dist.broadcast_object_list(outcome, src=0)
if error is not None:
raise error
if outcome[0]["error"] is not None:
raise RuntimeError(f"Rank 0 could not find the checkpoint to resume: {outcome[0]['error']}")
return Path(outcome[0]["path"]) if outcome[0]["path"] else None
def _unused_load_path_message(config: JobConfig, resume_path: Path) -> str:
"""The warning that a resume from ``checkpoint.dir`` wins over ``checkpoint.load_path``."""
ckpt = config.checkpoint
message = (
f"checkpoint.load_path={ckpt.load_path} is not used: checkpoint.dir={ckpt.dir} already "
f"has a checkpoint, and resuming {resume_path} takes precedence so that a requeued run "
f"continues where it stopped."
)
if ckpt.exclude_from_loading:
message += (
f" checkpoint.exclude_from_loading={ckpt.exclude_from_loading} is not applied "
f"either: a resume restores full state."
)
return message + (
" To start from load_path instead, for example to roll back to an earlier step, "
"set checkpoint.dir to a new, empty directory."
)
def _load_path_is_the_resume(config: JobConfig, resume_path: Path) -> bool:
"""Whether ``checkpoint.load_path`` names the resumed checkpoint and excludes nothing.
The resume then loads what ``load_path`` asks for, so nothing in it goes unused. Both paths
go through ``os.path.realpath``, so a relative path or one through ``latest`` compares by
its target, and through ``str`` first: the config loader keeps a bare-number ``load_path``
such as ``--checkpoint.load_path=5000`` as an int. Unlike ``Path.resolve``,
``os.path.realpath`` does not raise on a symlink loop: only rank 0 runs this, and a raise
here would leave the other ranks waiting in the load's broadcast.
"""
ckpt = config.checkpoint
if not ckpt.load_path or ckpt.exclude_from_loading:
return False
return os.path.realpath(str(ckpt.load_path)) == os.path.realpath(str(resume_path))
WARM_START_CHECKPOINT_TAG = "kempnerforge.warm_start.checkpoint"
WARM_START_SOURCE_RUN_TAG = "kempnerforge.warm_start.source_run_id"
def _source_mlflow_run_id(source: Path, extra: dict) -> str | None:
"""The MLflow run that saved ``source``: its ``metadata.json`` record, else the train state's.
The sidecar comes first because a load that skips ``train_state.pt`` still has it. A sidecar
that is missing, unreadable or of another shape falls back to the ``mlflow_run_id`` in
``extra``. Nothing here raises: only rank 0 runs it, and a raise would leave the other ranks
waiting in the next collective.
"""
with contextlib.suppress(OSError, ValueError, AttributeError, TypeError, RecursionError):
meta = json.loads((source / "metadata.json").read_text())
for record in meta.get("tracking") or []:
run_id = record.get("run_id") if record.get("backend") == "mlflow" else None
if isinstance(run_id, str) and run_id.strip():
return run_id
run_id = extra.get("mlflow_run_id")
return run_id if isinstance(run_id, str) and run_id.strip() else None
def _tag_warm_start_run(config: JobConfig, extra: dict) -> None:
"""Point a ``load_path`` warm start's new MLflow run at the checkpoint it starts from.
A warm start is a new run, so the run ids its checkpoint carries are not restored and each
enabled tracking backend opens a run of its own, unless the config names one. Rank 0 says
which saved runs it does not continue and, with MLflow on, adds the tags
``kempnerforge.warm_start.checkpoint`` (the checkpoint's real path) and, when the run that
saved it is known, ``kempnerforge.warm_start.source_run_id`` to ``metrics.mlflow_tags``; a
tag of the same name already there wins.
"""
metrics = config.metrics
source = Path(os.path.realpath(str(config.checkpoint.load_path)))
mlflow_source = _source_mlflow_run_id(source, extra) if metrics.enable_mlflow else None
unused = [
f"{key}={run_id}"
for key, run_id, enabled, named in (
("mlflow_run_id", mlflow_source, metrics.enable_mlflow, metrics.mlflow_run_id),
("wandb_run_id", extra.get("wandb_run_id"), metrics.enable_wandb, metrics.wandb_run_id),
)
if enabled and not named and run_id
]
if unused:
logger.info(
f"Warm start from {source}: not continuing the tracking runs that saved it "
f"({', '.join(unused)}); set metrics.mlflow_run_id or metrics.wandb_run_id to "
f"continue one"
)
if not metrics.enable_mlflow:
return
tags = {WARM_START_CHECKPOINT_TAG: str(source)}
if mlflow_source is not None:
tags[WARM_START_SOURCE_RUN_TAG] = mlflow_source
metrics.mlflow_tags = {**tags, **metrics.mlflow_tags}
def _apply_effective_freeze(model: torch.nn.Module, vlm_cfg: VLMConfig | None, step: int) -> None:
"""Under a freeze schedule, apply ``vlm.freeze`` and every ``FreezeStage`` up to ``step``."""
if vlm_cfg is None or not vlm_cfg.freeze_schedule:
return
valid_modules = set(vlm_cfg.module_patterns.keys())
specs = effective_freeze(step, vlm_cfg.freeze, vlm_cfg.freeze_schedule, valid_modules)
apply_freeze_specs(model, specs, vlm_cfg.module_patterns)
logger.info(f"Starting at step={step}; applied effective freeze ({len(specs)} specs)")
[docs]
def restore_checkpoint(
config: JobConfig,
model: torch.nn.Module,
scheduler: object,
ckpt_mgr: CheckpointManager,
) -> tuple[int, int]:
"""Auto-resume from ``latest`` (or ``checkpoint.load_path``).
Returns ``(step, tokens_seen)`` โ ``(0, 0)`` when there is nothing to
resume from. Also restores the metrics run ids, runs the MoT text warm
start when no checkpoint supplied the model weights and the run starts at
step 0, and applies the effective freeze at the step it returns, a fresh
run's step 0 and the ``FreezeStage`` there included. A module
that a freeze stage unfreezes gets its saved optimizer state back, or
empty state when the saved optimizer had none for it.
A checkpoint in ``checkpoint.dir`` takes precedence over ``checkpoint.load_path``, so a
requeued warm start resumes rather than starting over; rank 0 then warns that
``load_path`` is not used, naming both paths, unless ``load_path`` names the resumed
checkpoint and excludes nothing.
Only that auto-resume restores the metrics run ids. A ``load_path`` warm start is a new run:
each enabled tracking backend opens a run of its own unless ``metrics.mlflow_run_id`` or
``metrics.wandb_run_id`` names one, and with MLflow on, rank 0 tags the new run with the
checkpoint and the MLflow run that saved it (``_tag_warm_start_run``).
A checkpoint saved with another ``plugins`` list is refused before any state is read
(see ``CheckpointManager.load``'s ``plugins_expected``). A VLM run, unless it warm starts
from the weights alone, compares the freeze the checkpoint records with its own at the step
the checkpoint records, for the checkpoint ``load`` settles on (see its
``vlm_freeze_expected``).
"""
num_stages = config.distributed.pp if config.distributed.pp > 1 else None
if dist.is_initialized():
resume_path = _resume_path_on_rank_zero(config.checkpoint.dir, num_stages)
else:
resume_path = resolve_resume_path(config.checkpoint.dir, num_stages)
vlm_cfg = config.vlm
if not resume_path and not config.checkpoint.load_path:
_mot_text_warm_start(vlm_cfg, model, ckpt_mgr.agree)
_apply_effective_freeze(model, vlm_cfg, 0)
return 0, 0
rank_zero = not dist.is_initialized() or dist.get_rank() == 0
if (
resume_path
and config.checkpoint.load_path
and rank_zero
and not _load_path_is_the_resume(config, resume_path)
):
logger.warning(_unused_load_path_message(config, resume_path))
warm_start_exclude = (
(config.checkpoint.exclude_from_loading or None) if resume_path is None else None
)
weights_only = is_weights_only(warm_start_exclude)
vlm_freeze_expected = None
if config.is_vlm and not weights_only:
assert vlm_cfg is not None
vlm_freeze_expected = partial(freeze_meta_at_step, config=vlm_cfg)
with _trainable_for_the_run(model, config) as unfrozen_later:
step, tokens_seen, ckpt_extra_loaded = ckpt_mgr.load(
path=str(resume_path) if resume_path else None,
scheduler=scheduler,
warm_start=resume_path is None,
exclude_keys=warm_start_exclude,
vlm_freeze_expected=vlm_freeze_expected,
fresh_if_unheld=unfrozen_later,
exact_resume=resume_path is not None,
plugins_expected=list(config.plugins),
)
if resume_path is not None:
if ckpt_extra_loaded.get("wandb_run_id"):
config.metrics.wandb_run_id = ckpt_extra_loaded["wandb_run_id"]
if ckpt_extra_loaded.get("mlflow_run_id"):
config.metrics.mlflow_run_id = ckpt_extra_loaded["mlflow_run_id"]
elif rank_zero:
_tag_warm_start_run(config, ckpt_extra_loaded)
if warm_start_exclude is not None and "model" in warm_start_exclude:
_mot_text_warm_start(vlm_cfg, model, ckpt_mgr.agree)
_apply_effective_freeze(model, vlm_cfg, step)
return step, tokens_seen
[docs]
def run_training(
config: JobConfig,
*,
step_fn: StepFn | None = None,
hooks: HookRunner | None = None,
data_fn: DataFn | None = None,
) -> None:
"""Run a full training job: build every phase, run the loop, tear down.
``step_fn`` and ``hooks`` let an experiment own the step body or register
hooks, and ``data_fn`` its data pipeline, without copying the build phases.
All default to what ``scripts/train.py`` uses; ``data_fn`` is called as
``build_data_pipeline`` is, after the model is built, so it receives the
model's ``tokens_per_image`` on a packed or multi-image VLM run, and must
follow the ``DataFn`` contract. A custom
``step_fn`` must run its forward and loss under ``session.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 a ``SIGTERM``'s to the
launch script's signal lead unless ``train.shutdown_timeout_sec`` is set;
they are resolved before the process group starts, so a malformed lead
fails first.
"""
timeout_sec, sigterm_timeout_sec = resolve_shutdown_timeouts(config.train.shutdown_timeout_sec)
runtime = setup_distributed(config)
tracker: MetricsTracker | None = None
ckpt_mgr: CheckpointManager | None = None
shutdown_handler = ShutdownHandler(
timeout_sec=timeout_sec, sigterm_timeout_sec=sigterm_timeout_sec
)
finished = False
try:
shutdown_handler.register()
nan_detector = NaNDetector(
action=config.train.nan_action, max_consecutive=config.train.nan_max_consecutive
)
loss_fn = build_loss_fn(config.train)
use_dynamic_flex_shapes(config.is_vlm and config.data.pack_sequences)
model, pipeline = build_model(config, runtime, loss_fn)
amp_dtype = autocast_dtype(model, config.train.master_dtype, config.train.param_dtype)
if amp_dtype is not None:
logger.info(
f"No FSDP2 wrap casts the {config.train.master_dtype} master weights: "
f"forward passes run under torch.autocast({amp_dtype})"
)
with _trainable_for_the_run(model, config):
optimizer = build_optimizer(
model,
config.optimizer,
module_patterns=config.vlm.module_patterns if config.vlm is not None else None,
)
scheduler = build_scheduler(optimizer, config.scheduler, max_steps=config.train.max_steps)
ckpt_mgr = build_checkpoint_manager(config, runtime, model, optimizer, pipeline)
ckpt_mgr.claim_dir()
step, tokens_seen = restore_checkpoint(config, model, scheduler, ckpt_mgr)
tracker = MetricsTracker(config, num_gpus=runtime.world_size)
tracker.init_backends(config)
ckpt_mgr.set_tracking_source(tracker.tracking_entries)
ckpt_mgr.set_checkpoint_registrar(tracker)
prof = build_profiler(config.profiling, rank=runtime.rank)
laid_out = config.data.pack_sequences or config.data.hf_max_images != 1
tokens_per_image = packed_tokens_per_image(model) if config.is_vlm and laid_out else None
data = (data_fn or build_data_pipeline)(config, runtime, tokens_per_image=tokens_per_image)
expected = get_dp_info(runtime.device_mesh)
if (data.dp_rank, data.dp_size) != expected:
raise ValueError(
f"data_fn returned dp_rank={data.dp_rank}, dp_size={data.dp_size}, but this "
f"rank's data-parallel partition is dp_rank={expected[0]}, "
f"dp_size={expected[1]} (get_dp_info(runtime.device_mesh))"
)
if data.dataloader is not None:
ckpt_mgr.apply_dataloader_state(data.dataloader)
eval_dataloader = build_eval_dataloader(config, runtime)
phases = build_phase_state(config, data, step)
nan_detector.state.consecutive_nans = ckpt_mgr.restored_extra.get("consecutive_nans", 0)
session = TrainingSession(
config=config,
runtime=runtime,
model=model,
optimizer=optimizer,
scheduler=scheduler,
loss_fn=loss_fn,
step_fn=step_fn or select_step_fn(config),
data=data,
phases=phases,
checkpointer=ckpt_mgr,
tracker=tracker,
hooks=hooks or HookRunner(),
nan_detector=nan_detector,
shutdown_handler=shutdown_handler,
pipeline=pipeline,
eval_dataloader=eval_dataloader,
profiler=prof,
autocast_dtype=amp_dtype,
documents_seen=ckpt_mgr.restored_extra.get("documents_seen"),
)
run_training_loop(session, step=step, tokens_seen=tokens_seen)
finished = True
finally:
use_dynamic_flex_shapes(False)
if tracker is not None:
tracker.close()
if finished:
try:
if ckpt_mgr is not None:
ckpt_mgr.release_dir()
finally:
destroy_distributed()
shutdown_handler.finish()