Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 22 additions & 13 deletions codebase-map.json
Original file line number Diff line number Diff line change
Expand Up @@ -1013,6 +1013,7 @@
"build_data_pipeline(config, runtime, *, tokens_per_image=None) -> DataPipeline",
"build_eval_dataloader(config, runtime) -> DataLoader | None",
"build_phase_state(config, data, step) -> PhaseState",
"check_phase_weights(config, data) (every data phase's weights against the pipeline's mixture sampler; the refusal names the phase)",
"advance_phases(state, data, step) -> bool"
],
"tested_by": [
Expand Down Expand Up @@ -1083,7 +1084,8 @@
"build_checkpoint_manager(config, runtime, model, optimizer, pipeline) -> CheckpointManager",
"restore_checkpoint(config, model, scheduler, ckpt_mgr) -> tuple[int, int]",
"_trainable_for_the_run(model, config) (trainable_for_the_run for a VLM with a freeze schedule, else a context that changes nothing)",
"_apply_effective_freeze(model, vlm_cfg, step) (vlm.freeze and every FreezeStage up to step, at a fresh start and on a resume)"
"_apply_effective_freeze(model, vlm_cfg, step) (vlm.freeze and every FreezeStage up to step, at a fresh start and on a resume)",
"_agreed_data_pipeline(config, runtime, data_fn, tokens_per_image, agree) -> DataPipeline (every rank reports its data build, partition check and check_phase_weights to the checkpoint manager's agreement before any rank goes on)"
],
"tested_by": [
"tests/unit/test_train_entry.py::TestRunTraining",
Expand All @@ -1098,7 +1100,8 @@
"tests/e2e/test_training_e2e.py",
"tests/smoke/test_smoke.py",
"tests/unit/test_slurm_scripts.py",
"tests/unit/test_shutdown_timeout.py::TestResolveShutdownTimeouts"
"tests/unit/test_shutdown_timeout.py::TestResolveShutdownTimeouts",
"tests/unit/test_train_entry.py::TestADataPipelineErrorFailsEveryRank"
]
},
"kempnerforge/data/dataset.py": {
Expand Down Expand Up @@ -1465,10 +1468,13 @@
"clip_grad_norm_(model, max_norm, foreach, pp_group) -> Tensor",
"new_control_group(timeout_sec) -> ProcessGroup | None",
"any_rank(flag, group) -> bool",
"any_rank_each(flags, group) -> list[bool] (each flag reduced over the group, all in one MAX all-reduce)"
"any_rank_each(flags, group) -> list[bool] (each flag reduced over the group, all in one MAX all-reduce)",
"run_keeping_own_error(collective, error, what) (runs a collective every rank enters with the outcome of its part of what; if the collective itself fails, an interrupt included, a rank with an error still raises its own, with that failure in a note, and a rank without one raises the failure with a note naming what; agree_across_ranks and the checkpoint manager's own agreements run their collectives through it)",
"agree_across_ranks(error, what, *, group=None) (one all-reduce on group: a rank with an error re-raises it, the others raise naming the failed ranks; if the all-reduce itself fails, an interrupt included, a rank with an error still raises its own, with that failure in a note)"
],
"tested_by": [
"tests/unit/test_distributed.py::TestClipGradNorm",
"tests/unit/test_distributed.py::TestAgreeAcrossRanks",
"tests/unit/test_dp_info.py::TestDataParallelReduction",
"tests/unit/test_shutdown_agreement.py::TestAnyRank",
"tests/unit/test_ep_gradients.py::TestClipUnderExpertParallelism",
Expand Down Expand Up @@ -1520,6 +1526,7 @@
"_resume_past_mismatch(view, envelope, error) -> (view, carried) (with ignore_rank_state_mismatch: a changed topology keeps the saved data position if the envelope is sound where it was saved, rank 0's or for a stream on the saved data-parallel size its own data-parallel rank's, else drops it; never restores RNG)",
"_resume_without_rank_state(train_state) -> (view, carried) (with ignore_rank_state_mismatch, a checkpoint with no per-rank state resumes as if the topology changed: rank 0's data position kept, its RNG dropped)",
"_read_saved_keys(dcp_dir) -> (keys, restored_on_any_rank) (this rank's DCP keys; with a scope or multipliers an all-reduce on the gloo group tells every rank whether any rank's index holds optimizer state)",
"_optimizer_saved_on_any_rank(error, holds) -> bool (that all-reduce: a rank whose read failed re-raises its error, the others raise naming it; if the all-reduce itself fails, a rank whose read failed still raises its error, with that failure in a note)",
"_agreed_dcp_keys(dcp_dir) -> dict (this rank's DCP keys, read under one all-reduce on the gloo group, so a rank whose read fails raises on every rank; the derived-buffer read of a load without optimizer state)",
"_broadcast_metadata(ckpt_dir, read) -> (meta, error) (rank 0 shares the read _agreed_load_dir made, or reads metadata.json, and broadcasts the object or why it could not; the layout, scope, multipliers and group-layout checks all decide from one read per load)",
"_check_plugins(metadata, ckpt_dir, expected) (every rank refuses another plugins list before any state is read, unless checkpoint.ignore_plugins_mismatch)",
Expand All @@ -1529,8 +1536,9 @@
"_check_lr_multipliers(metadata, ckpt_dir) -> saved group modules | None (every rank refuses other multipliers or patterns; a run without multipliers loads past an unreadable record with a warning; runs once per load, before loading optimizer state on any rank or before restoring a scheduler from train_state.pt)",
"_present_experts(dcp_state, load_from, saved_keys) (before a load: EP experts placed among all of them; refuses a checkpoint of fewer experts than the model; the ranks agree before DCP)",
"_prepare_save(ckpt_dir, dcp_dir) -> (dcp_state, layout) (this rank's part of a save before the write, with no collective: creates the step and stage directories, builds the model, optimizer and never-stepped state, and places EP experts among all of them)",
"_agree_to_write(error, flush_error) (one all-reduce on the gloo group before any rank dispatches a save's DCP write: a failure on any rank, of _prepare_save or of the wait for its previous async write, raises on every rank, naming the failed ranks; the pending async checkpoint is first committed when every rank's write of it ended well, else dropped)",
"_check_model_fits(dcp_state, every_rank, dcp_dir, restaged, saved_keys, planner) (before any tensor is read: every rank sends rank 0 its index and its model entries' global shapes, keyed as DCP's load planner reads the state the load's _NeverSteppedStatePlanner leaves it from that index, with every EP rank's expert names; rank 0 reads each index once and refuses, for every rank alike, model tensors no rank loads, of another size, or that a rank loads and the index lacks; a rank that cannot list its entries sends why, as rank 0 does when comparing fails, and every rank raises; checkpoint.ignore_extra_model_tensors leaves the extra ones unread with a warning, and a refusal names it only when the indexes hold every tensor the ranks load at its size)",
"_agree_to_write(error, flush_error) (one all-reduce on the gloo group before any rank dispatches a save's DCP write: a failure on any rank, of _prepare_save or of the wait for its previous async write, raises on every rank, naming the failed ranks; the pending async checkpoint is first committed when every rank's write of it ended well, else dropped; if the all-reduce itself fails, the pending checkpoint stays pending and a rank with an error still raises its own, with that failure in a note)",
"_gather_rank_states(dataloader, error) -> (envelope | None, error | None) (every rank's loader/RNG payload, gathered on the gloo group into the per-rank envelope; a rank whose capture fails enters the gather with no payload; if the gather itself fails, a rank with error, what its part of the save raised so far, or else with its capture's error still raises it, with that failure in a note)",
"_check_model_fits(dcp_state, every_rank, dcp_dir, restaged, saved_keys, planner) (before any tensor is read: every rank sends rank 0 its index and its model entries' global shapes, keyed as DCP's load planner reads the state the load's _NeverSteppedStatePlanner leaves it from that index, with every EP rank's expert names; rank 0 reads each index once and refuses, for every rank alike, model tensors no rank loads, of another size, or that a rank loads and the index lacks; a rank that cannot list its entries sends why, as rank 0 does when comparing fails, and every rank raises; if the gather or the broadcast itself fails, a rank with an error, rank 0's refusal included, still raises it, with that failure in a note; checkpoint.ignore_extra_model_tensors leaves the extra ones unread with a warning, and a refusal names it only when the indexes hold every tensor the ranks load at its size)",
"_model_misfit_error(gathered, known, lone_stage) -> Exception | None (rank 0's verdict for _check_model_fits)",
"apply_dataloader_state(dataloader) (every rank checks the position and the ranks share their verdicts before any rank applies it; a position some rank cannot place raises DataPositionError on every rank on a resume and starts the data fresh on every rank, with a warning, on a warm start or a carried position; a carried position goes only to a StatefulDataLoader or StreamingDataLoader)",
"_position_refusals(dataloader, state) -> (refusals, world) (each rank's check_state verdict, gathered on every rank on the gloo group; a check that fails another way raises on every rank)",
Expand Down Expand Up @@ -2038,6 +2046,7 @@
"tests/unit/test_distributed.py": {
"classes": [
"TestClipGradNorm(4)",
"TestAgreeAcrossRanks(5)",
"TestBuildBlockTPPlan(8)",
"TestApplyTensorParallelSequenceParallel(3)",
"TestBuildCrossAttentionTPPlan(3)",
Expand All @@ -2050,7 +2059,7 @@
"TestFsdpWrapTransformerBlocksHelper(1)",
"TestApplyFsdp2GuardedAttributes(3)"
],
"count": 45
"count": 50
},
"tests/unit/test_resilience.py": {
"classes": [
Expand Down Expand Up @@ -2099,7 +2108,7 @@
"TestWeightsOnlyWarmStart(8)",
"TestLoadVLMFreezeCompare(9)",
"TestAsyncLatestSymlinkSafety(32)",
"TestAFailedSaveCommitsNothing(20)",
"TestAFailedSaveCommitsNothing(23)",
"TestDurableTrainState(6)",
"TestSyncBarrierGroup(6)",
"TestCheckpointManagerLoad(3)",
Expand All @@ -2112,14 +2121,14 @@
"TestOptimizerChecksAcrossStages(5)",
"TestCheckpointEveryOptimizer(8)",
"TestComponentSwapOnResume(1)",
"TestWeightDecayScopeOnResume(46)",
"TestWeightDecayScopeOnResume(48)",
"TestRestoredExtra(2)",
"TestResumedStep(7)",
"TestUnreadableTrainStateAcrossRanks(1)",
"TestTornStageAcrossRanks(1)",
"TestOptimizerTypeChangeOnResume(6)"
],
"count": 385
"count": 390
},
"tests/unit/test_checkpoint_publish.py": {
"classes": [
Expand All @@ -2146,15 +2155,15 @@
"TestPerRankEnvelopeSchema(17)",
"TestEnvelopeValidatedBeforeSelection(6)",
"TestGatherMustCoverTheWorld(2)",
"TestAFailedCaptureFailsEveryRank(4)",
"TestAFailedCaptureFailsEveryRank(6)",
"TestFourRankSaveLoad(6)",
"TestLegacyAndTopology(10)",
"TestDataParallelLayout(12)",
"TestLoadsThatAreNotAResume(2)",
"TestWeightsOnlyWarmStart(3)",
"TestMidSaveInterruption(1)"
],
"count": 63
"count": 65
},
"tests/unit/test_observability.py": {
"classes": [
Expand Down Expand Up @@ -2338,10 +2347,10 @@
"TestPipelineCheckpointSaveAndResume(6)",
"TestResumeScanNeedsEveryStage(1)",
"TestLatestWaitsForEveryStage(2)",
"TestAFailedSaveFailsEveryRank(18)",
"TestAFailedSaveFailsEveryRank(19)",
"TestAFailedReadFailsEveryRank(9)"
],
"count": 36
"count": 37
},
"tests/unit/test_ep_checkpoint.py": {
"classes": [
Expand Down
8 changes: 7 additions & 1 deletion docs/architecture/data-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,13 @@ initializes the collaborators:
streaming dataset, wrapped by `StreamingDataLoader` with no sampler.
Both loaders are in
[`kempnerforge.data`](https://github.com/KempnerInstitute/KempnerForge/tree/main/kempnerforge/data).
`ckpt_mgr.apply_dataloader_state` then hands the loader the position the
- **Data-build agreement**: every rank reports, over the checkpoint
manager's gloo group (`ckpt_mgr.agree`), whether its pipeline built
with the data-parallel partition `get_dp_info` gives it and a sampler
that takes every data phase's weights (`check_phase_weights`), before
any rank goes on, so a build that fails on one rank stops every rank,
the others with an error naming it. Right after that agreement,
`ckpt_mgr.apply_dataloader_state` hands the loader the position the
load kept; without that call `run_training_loop` stops before its first
step.
- **Eval dataloader and `torch.profiler`** (optional).
Expand Down
2 changes: 1 addition & 1 deletion docs/checkpointing/train-state.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ Entry points, both in

```python
# manager.py, inside save() (abridged)
per_rank, gather_error = self._gather_rank_states(dataloader) # every rank
per_rank, gather_error = self._gather_rank_states(dataloader, error) # every rank
if error is None:
error = gather_error

Expand Down
8 changes: 5 additions & 3 deletions docs/data/sampler.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,11 +139,13 @@ its share of the epoch goes to the others, so every rank yields `len()`
samples, also when a temperature gives a zero weight a small probability.

The training pipeline builds the sampler with the weights a data phase at
step 0 sets, so such a phase can give a small source weight 0.
`build_phase_state` checks every phase's weights with `check_weights`
step 0 sets, so such a phase can give a small source weight 0; weights the
sampler refuses there stop the build with an error that names the phase.
`check_phase_weights` checks every phase's weights with `check_weights`
before training starts, also against a mixture a `data_fn` built, so a
phase that would weight a small source stops the run then, not when it
begins.
begins. `run_training` runs it with the data build on every rank, and
`build_phase_state` runs it too.

Each `__iter__()` then does:

Expand Down
12 changes: 8 additions & 4 deletions docs/training/training-loop.md
Original file line number Diff line number Diff line change
Expand Up @@ -322,10 +322,14 @@ in order, then hands a `TrainingSession` to `run_training_loop`:
`run_training(config, data_fn=...)` builds the training pipeline with
`data_fn` in place of `build_data_pipeline`, following the `DataFn`
contract in `kempnerforge/training/data_pipeline.py`; the eval loader
still comes from `build_eval_dataloader`. Right after the training
pipeline, `ckpt_mgr.apply_dataloader_state` hands its loader the data
position the restore kept; `run_training_loop` raises before its first
step while that position is unapplied and the run has a loader.
still comes from `build_eval_dataloader`. Every rank reports, over the
checkpoint manager's gloo group, whether its training pipeline built with
a sampler that takes every data phase's weights (`check_phase_weights`)
before any rank goes on, so a build that fails on one rank stops every
rank, the others with an error naming it. Right after that agreement,
`ckpt_mgr.apply_dataloader_state` hands its loader the data position the
restore kept; `run_training_loop` raises before its first step while that
position is unapplied and the run has a loader.

The full list with links lives in
[Data flow § Startup, once](../architecture/data-flow.md#startup-once).
Expand Down
23 changes: 19 additions & 4 deletions examples/assembled_run/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,24 +113,35 @@ code; the names after it are the core pieces it orders.
`CheckpointManager.set_tracking_source` and `set_checkpoint_registrar`). The
backends continue the runs the restore named, and every checkpoint records
them.
10. **`apply_dataloader_state` after the restore and the loader, and before the
10. **The ranks' agreement on the data build before `apply_dataloader_state`**
(`build_data`; `build_data_pipeline`, `check_phase_weights`,
`CheckpointManager.agree`). Every rank reports whether it built its data,
with a sampler that takes every data phase's weights, before any rank goes
on, so a build that fails on one rank fails the run on every rank, the
others with an error naming it. Leave the agreement out and the other ranks
go on into collectives that rank never joins, such as the training loop's
first, which holds them until the process-group timeout
(`distributed.nccl_timeout_sec`, 1800 s by default) or the launcher's kill.
On a resume, the check of the data position can fail on them first, with a
lost-connection error that does not say what failed.
11. **`apply_dataloader_state` after the restore and the loader, and before the
loader's first batch** (`build_data`;
`CheckpointManager.apply_dataloader_state`). The case above: the data is
built after the restore, as `run_training` builds it, so the load keeps the
position and this call applies it; left out, `run_training_loop` raises
before its first step. Called before the restore it finds nothing to apply,
and the loop then raises as if it were left out. Every rank calls it, since
the ranks check the position together before any of them applies it.
11. **The phases after the restore and the data** (`build_data`;
12. **The phases after the restore and the data** (`build_data`;
`build_phase_state`). It applies each data phase that starts at or before
the restored step, so the run starts in the phase it stopped in, at that
phase's `lr_scale` and, on a mixture, with its weights on the sampler.
12. **The NaN count and the documents seen after the restore** (`train`;
13. **The NaN count and the documents seen after the restore** (`train`;
`NaNDetector`, `TrainingSession`). The detector continues the count of NaN
steps in a row that the checkpoint saved, so a resumed run stops at the step
an uninterrupted one stops at, and the session continues the count of
documents seen, for a step body that reports documents.
13. **The teardown on the success path only** (`train`;
14. **The teardown on the success path only** (`train`;
`CheckpointManager.release_dir`, `destroy_distributed`,
`ShutdownHandler.finish`). The tracker closes on every path, since its
backends are rank-local. Releasing `checkpoint.dir`, destroying the process
Expand Down Expand Up @@ -177,6 +188,10 @@ it in the same `checkpoint.dir`:
- The signal leaves the emergency checkpoint as `latest`, the claim on
`checkpoint.dir` released and the `SIGTERM` and `SIGUSR1` handlers as they
were. A run whose hook raises keeps its claim and its shutdown handler.
- A data build that fails, on a token directory with no shards or on a data
phase whose weights the sampler refuses, goes through the ranks' agreement on
the build. When the agreement reports that another rank's build failed, a
resume stops there, before `apply_dataloader_state`.
- A VLM config is refused before anything is built, and the entry point passes
the config and its overrides through.

Expand Down
Loading
Loading