Skip to content

[Checkpointer] Remove the dependencies on PyTorch distributed state_dict APIs - #3623

Merged
fegin merged 6 commits into
mainfrom
gh/fegin/137/head
Jun 12, 2026
Merged

fegin merged 6 commits into
mainfrom
gh/fegin/137/head

Conversation

@fegin

@fegin fegin commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary:
Same as #2441 but with new implementation to be compatiblewith the latest OptimizerContainer

Verification:

Check Result
Checkpoint compat, FSDP (old saves -> new loads, resume to step 100) PASS - bit-identical all 100
steps
Checkpoint compat, PP=2 (old saves -> new loads) PASS - bit-identical
loss_compare, FSDP (old vs new, 100 steps, seed checkpoint) PASS - identical loss
CPU unit tests (lr_scheduler, optimizer_param_groups, state_dict_keys, checkpoint) 51 passed
Full unit suite 411 passed (2 unrelated tokenizer-download failures)
Lint (ufmt, flake8, pydoclint) pass

fegin added 2 commits June 10, 2026 12:54
[ghstack-poisoned]
[ghstack-poisoned]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jun 10, 2026
[ghstack-poisoned]
fegin added a commit that referenced this pull request Jun 10, 2026
…ict APIs

Summary:
Same as #2441 but with new implementation to be compatiblewith the latest OptimizerContainer

ghstack-source-id: 2a34d94
Pull-Request: #3623
[ghstack-poisoned]
fegin added a commit that referenced this pull request Jun 10, 2026
…ict APIs

Summary:
Same as #2441 but with new implementation to be compatiblewith the latest OptimizerContainer

ghstack-source-id: c6be0ff
Pull-Request: #3623
[ghstack-poisoned]
fegin added a commit that referenced this pull request Jun 10, 2026
…ict APIs

Summary:
Same as #2441 but with new implementation to be compatiblewith the latest OptimizerContainer

ghstack-source-id: 07dee57
Pull-Request: #3623
@fegin
fegin marked this pull request as ready for review June 10, 2026 21:12

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now that we are not using DCP APIs, could you prompt claude to add the _save_to_state_dict / ``_load_from_state_dict` hooks and see if it just solves #3569

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need to modify _save_to_state_dict and _load_from_state_dict. nn.Module provides the APIs to register hook. #3638. I haven't reviewed the details yet, but the code looks legit.

Comment thread torchtitan/components/lr_scheduler.py Outdated
# Per-optimizer regex patterns (aligned with self.schedulers), used as lr
# metric labels. Sourced from the container so patterns stay off the
# optimizer param groups and out of the saved state dict.
self._param_group_patterns = optimizers._param_group_patterns

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we not add this simply for logging purpose? I think it's available in optimizers.config?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We usually don't keep config. I remove this but the downside is that the log now loses the pattern and is now replaced with index only.

Comment thread torchtitan/components/optimizer.py Outdated
# the list of patterns for that optimizer's param groups. Kept here, off the
# optimizer param groups, so they feed logging and lr metrics without leaking
# into the saved optimizer state dict.
_param_group_patterns: list[list[str]]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems it's also only for logging. Let's remove for now, or we can move the logging into _build_param_groups where we still have access to patterns.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can be removed. But lr_scheduler, which is a different Class now loses the patter access.

@meetv18 meetv18 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From checkpoint POV this change makes sense to me. We should def upstream some of this! for e.g to make things easier with optimizer SD handling.

[ghstack-poisoned]

@fegin fegin left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to decide whether we want to keep pattern for lr_scheduler logging purpose.

Comment thread torchtitan/components/lr_scheduler.py Outdated
# Per-optimizer regex patterns (aligned with self.schedulers), used as lr
# metric labels. Sourced from the container so patterns stay off the
# optimizer param groups and out of the saved state dict.
self._param_group_patterns = optimizers._param_group_patterns

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We usually don't keep config. I remove this but the downside is that the log now loses the pattern and is now replaced with index only.

Comment thread torchtitan/components/optimizer.py Outdated
# the list of patterns for that optimizer's param groups. Kept here, off the
# optimizer param groups, so they feed logging and lr metrics without leaking
# into the saved optimizer state dict.
_param_group_patterns: list[list[str]]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can be removed. But lr_scheduler, which is a different Class now loses the patter access.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need to modify _save_to_state_dict and _load_from_state_dict. nn.Module provides the APIs to register hook. #3638. I haven't reviewed the details yet, but the code looks legit.

@fegin
fegin changed the base branch from gh/fegin/137/base to main June 12, 2026 16:46
@fegin
fegin merged commit 772dd1b into main Jun 12, 2026
14 checks passed
saforem2 pushed a commit to saforem2/torchtitan that referenced this pull request Jun 12, 2026
…ict APIs (pytorch#3623)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* pytorch#3638
* __->__ pytorch#3623

**Summary:**
Same as pytorch#2441 but with new
implementation to be compatiblewith the latest OptimizerContainer

**Verification:**
  | Check | Result |
  |---|---|
| Checkpoint compat, FSDP (old saves -> new loads, resume to step 100) |
PASS - bit-identical all 100
  steps |
| Checkpoint compat, PP=2 (old saves -> new loads) | PASS -
bit-identical |
| loss_compare, FSDP (old vs new, 100 steps, seed checkpoint) | PASS -
identical loss |
| CPU unit tests (lr_scheduler, optimizer_param_groups, state_dict_keys,
checkpoint) | 51 passed |
| Full unit suite | 411 passed (2 unrelated tokenizer-download failures)
|
  | Lint (ufmt, flake8, pydoclint) | pass |
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 28, 2026
… optim-statedict format migration

The clone-pull ckpt-resume break was mis-attributed in-session first to pytorch#3714
(fused-qkv-by-default) and then to the optimizer implementation="fused" flag.
Both ruled out by direct evidence:
- implementation defaulted to "fused" in BOTH 1263e5a (pinned/working) and HEAD
- FusedQKVLinear hooks touch only MODEL state, never tok_embeddings optim state

Verified cause: optimizer state-dict FORMAT migration. 1263e5a uses
get/set_optimizer_state_dict (nested); HEAD uses get_flat_optim_state_dict/
load_flat_optim_state_dict (flat) via pytorch#3623 (772dd1b) + pytorch#3269 (632f67f),
both ancestors of HEAD but not 1263e5a. The .fused-suffixed keys are the new
flat layout applied to all params.

Decision: do NOT build a compat shim (nested->flat migration is hard and can
silently load wrong Adam momentum). Clones stay pinned pre-pytorch#3623 -- they resume
cleanly (2B-256N chain advanced 86200->86674). New known-bug doc + corrected
incident report.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jul 6, 2026
Promote smoke_multi_autoretry.sh to a production 4-chain umbrella. Fuses
the legacy failover umbrella's multi-clone/multi-venv table with native
`ezpz launch --auto-retry` (the smoke-validated replacement for the
failover_lib.sh blind-swap that lost 3/4 chains in 8568429).

- Per-trainer cd to its OWN pinned clone (torchtitan imports from cwd; the
  20b clones are rolled back pre-pytorch#3623 for DCP-resume compat, so cwd is
  load-bearing).
- Per-model venv pre-stage to /tmp/.venv-<model>, deduped by resolved
  tarball (20b-n256 symlinks 20b-v2's -> one broadcast). auto-retry only
  reads the venv, so concurrent disjoint slices never collide.
- Inline training command = faithful copy of submit_agpt_{2b,20b}_autoretry.sh
  flags (config/optimizer/LR/GBS/validator/ckpt policy); advances the same
  4 canonical chain ckpt dirs. Default 1536 train (512+512+256+256)+4*SPARES.
- DRY_RUN plan-print + MULTI_PROFILE=tiny throwaway-ckpt smoke retained.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jul 22, 2026
… off)

Umbrella 8680578 crashed all 3 trainers at arg-parse (rc=143): the pinned
pre-pytorch#3623 production clones train.py has no nan_abort_consecutive field, so
the flag (added in e60beb9) => Unrecognized options: --nan-abort-consecutive.
Now NAN_ABORT_CONSECUTIVE defaults empty and the flag is only emitted when
set (nan_abort_args array), so the umbrella runs on pinned clones by default;
HEAD-based clones can still opt in via the env var.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 18, 2026
Fourth consecutive umbrella lost by the 2B-256 constlr seat, and my head-rename
fix from yesterday only solved half of it. Model keys loaded clean; the seat
then died on
  Missing key in checkpoint state_dict: optimizer.state.layers.0.attention.qkv_linear.wq.weight.step

MECHANISM (confirmed against the code, not inferred). torchtitan expands only
the MODEL to flat FQN strings -- `_flattened_model_states_sd` does
`sd.update(states[MODEL].state_dict())` and leaves every other entry as a
top-level name. So the wrapper is handed the literal string "optimizer" bound
to a live container, and `_down("optimizer")` is a guaranteed no-op. The real
optimizer FQNs appear INSIDE dcp.load, when it calls state_dict() on that
container -- after the wrapper has already run. The regex was never wrong; it
simply never ran on those keys.

Fix: scope-swap the container's state_dict() for the duration of the load so it
emits on-disk spellings, and widen _OPT_PREFIX to also match CONTAINER-level
`state.` / `param_groups.` keys (the container emits those without an
`optimizer.` prefix; only DCP's flattener adds it).

Two things adversarial review caught that I had wrong:

1. ORDERING. My plan installed the swap "before calling original", but
   dcp_load has TWO exits, and the early return fires precisely when every
   top-level key is already current -- i.e. exactly the optimizer-only case
   this fixes. The swap now wraps both. There is a regression test for that
   path specifically.
2. The swap MUST be scoped. The save path also calls state_dict() on every
   Stateful, so a permanent wrapper would write new checkpoints in the OLD
   spelling, turning a read shim into a corruption source. Restored via finally,
   by deleting the instance attribute rather than reassigning.

Also settled a blocker that would have made this moot: review flagged that a
pre-pytorch#3623 checkpoint cannot resume on HEAD at all (nested->flat optim migration,
unfixable by any rename). Read step-9500's metadata: it is already FLAT
(`optimizer.param_groups.<fqn>.<key>`), and its lack of `.fused`/`.foreach` is
because SophiaG's defaults are lr/betas/rho/weight_decay/maximize/capturable --
not because it predates the migration. The fix applies.

load_state_dict is deliberately NOT wrapped: it must receive current-code keys,
since _unflatten_optim_state_dict resolves them against the live optimizer's
param_names.

11 assertions, torch-free. NOT yet copied into the pinned clone -- the seat will
fail a fifth time in 8764675, which is the honest cost of not shipping an
unvalidated fix into a 2098-node job.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 20, 2026
The t4 constlr seat has produced zero training steps across five umbrellas.
Two causes are already peeled off: the lm_head.weight rename (ckpt_key_compat),
and -- found today -- that its clone ran a STALE copy of that shim with no
optimizer-namespace handling at all. With both fixed it now fails one layer
deeper, inside SophiaG:

    state["hessian"].mul_(beta2)...
    AttributeError: 'dict' object has no attribute 'mul_'

The optimizer state loads but arrives nested, not flat: the documented
pre-pytorch#3623 format migration. The converter bridges exactly that and is PROVEN
(4-link dress rehearsal, 2026-07-22).

But this is a TEST, not a fix. What is proven is the converter; what is NOT
established is that this seed is sound. step-9200 -- same early region, same
chain -- is independently corrupt, resuming to ~6.5 both natively and after
conversion. step-9500 has never produced a step, so it has never been shown
good. So: convert, then immediately smoke-resume in the same allocation.

    PASS  loss ~2.7 / gn ~0.7  -> format only; re-seed the seat from DST
    FAIL  loss ~6.5 / gn ~18   -> seed corrupt; re-seed from a later ckpt

Both outcomes are worth 4 nodes, and a FAIL is far cheaper to learn here than
in another 266-node umbrella seat dying at startup. 4N suffices: 2B is pure DP
and DCP reshards on load, so node count does not affect the converter.

Verifies the ARTIFACT (DST shard count + .metadata) rather than the converter's
exit code, since "exited 0, wrote nothing" is this repo's signature failure.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 22, 2026
Our NaN guard runs AFTER self.optimizers.step() and inspects only the loss, so
a NaN gradient is written into the weights before anything notices.

Job 12473142 is the case in point, from our own 80b/README.md:

  grad_norm nan @30, loss nan @31, nan-abort @35

grad_norm went bad a full step before the loss, so the earliest available
signal was one ahead of the one we were watching -- and five more updates
landed on top of it. A separate incident (job 8663177) ran ~370 NaN steps
unbounded.

The existing guard is also weaker than it looks in practice: nan_abort_
consecutive defaults to 0 (off, trainer.py:221) and production omits the flag
ENTIRELY, because the pinned pre-pytorch#3623 clones have no such field and passing
it crashes every rank (killed umbrella 8680578). So today, at production, a
NaN grad is applied and nothing stops the run.

This adds a host-side isfinite check on grad_norm immediately before the step.
Non-finite -> zero_grad, log, skip the step, still advance the lr scheduler.
The model is left unchanged rather than poisoned; the loss guard keeps its
existing job of deciding whether to abort.

grad_norm is already reduced across ranks (and across pp when pp_mesh is
passed) inside clip_grad_norm_, so every rank sees the same value and branches
identically. No new collective. The .item() is on a value already read for
logging a few lines later.

Deliberately NOT torch._assert_async, which upstream's pytorch#4226 uses for the same
purpose: on CUDA a failed device-side assert invalidates the process, which
our failover machinery would read as a crash rather than a clean stop, and its
XPU behavior is undocumented. Upstream's fix also lands in Trainer.train_step,
which FaultTolerantTrainer overrides wholesale -- so merging pytorch#4226 would give
us nothing here. This is the hand-port.

maybe_wait_for_staging() stays outside the branch: it is a checkpoint concern,
and skipping it on a skipped step would leave an async save un-awaited.

nanguard.pbs smokes it. The bar is bit-identity against the parent commit on a
healthy run, seeded and deterministic at 12 ranks / 1 node / seq=2048 -- the
regime where the control actually holds. A guard in the hot path that
perturbs normal training would be worse than no guard.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 25, 2026
The Umbrellas table stopped at 8756957 (08-16). Two production umbrellas ran
after it and neither was recorded.

  8760249  08-17  12h00m / 12h (100%)   2/5 productive
  8764675  08-20  12h00m31s / 12h (100%) 2/5 productive

Both are the t1/t2 pattern: the two 20B chains ran the full window while t0,
t3 and t4 died at init. Those runs are where the +910 and +1,431 steps the
cached dashboard was missing came from -- 20B-512 to 10,699 and 20B-256 to
11,800.

Two things the rows change in the taxonomy. First, three umbrellas in a row
have now used ~all of their allocation (97%, 100%, 100%, 100%), and every one
asked 12h or less -- the 24h dispatches are the ones that kept dying young, so
12h should be the default ask. Second, the t4 seat's failure has moved past the
checkpoint-key rename this log records three times: in 8760249 the shim fired
but optimizer.state...qkv_linear.wq.weight.step was still missing, and in
8764675 the load SUCCEEDED in 62s and then 3,073 ranks died in SophiaG
update_hessian on `'dict' object has no attribute 'mul_'` -- the pre-pytorch#3623
nested->flat optimizer format. Converting step-9500 resolved it (smoke 8772046,
seed loaded 10.42s, 8 clean steps).

Also notes t0 has been stalled since 08-16, which is why the 2B stage-2 chain
has not advanced.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants