Skip to content

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

Closed
fegin wants to merge 3 commits into
gh/fegin/84/basefrom
gh/fegin/84/head
Closed

fegin wants to merge 3 commits into
gh/fegin/84/basefrom
gh/fegin/84/head

Conversation

@fegin

@fegin fegin commented Feb 25, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Why this PR
TorchTitan checkpointer relies on PyTorch distributed state_dict APIs to ensure optimizer and model state_dicts are as expected (e.g., FQNs are correct, flattened optimizer state_dict). However distributed state_dict APIs provide way too many features and support many legacy APIs (FSDP1, DDP).

This PR aims to clean up the dependency of PyTorch distributed state_dict APIs and extract the necessary logic to TorchTitan. We can upstream some utilities back to PyTorch in the future.

Summary

  • Removes the dependency on torch.distributed.checkpoint.state_dict APIs (get_model_state_dict, set_model_state_dict, get_optimizer_state_dict, set_optimizer_state_dict, StateDictOptions), which carry excessive complexity from legacy FSDP1/DDP support.
  • Introduces torchtitan/tools/checkpoint_utils.py with focused utilities: _orig_mod prefix stripping for model state dicts, FQN-keyed optimizer state dict conversion using PyTorch's param_names feature, and flatten/unflatten logic for DCP-compatible optimizer checkpointing.
  • Constructs optimizers with (name, param) tuples so that FQN mappings are natively available without relying on distributed state_dict introspection.
  • Adds an unit test (test_state_dict_keys.py) that validates the exact model and optimizer state dict key contract against hard-coded expected values for the llama3 debugmodel, catching regressions from refactoring or upstream PyTorch changes.
  • Adds a tool like loss_compare.py but is used to verify if a checkpoint generated by "old PR" can be correctly loaded by a "new PR".

[ghstack-poisoned]
fegin added a commit that referenced this pull request Feb 25, 2026
…ict APIs

**Why this PR**
TorchTitan checkpointer relies PyTorch distributed state_dict APIs to ensure optimizer and model state_dict are as expected (e.g., FQNs are correct, flattened optimizer state_dict). However distributed state_dict APIs provide way too many features and support many legacy APIs (FSDP1, DDP).

This PR aims to clean up the dependency of PyTorch distributed state_dict APIs and extract the necessary logic to TorchTitan. We can upstream some utilities back to PyTorch in the future.

**Summary**
- Removes the dependency on torch.distributed.checkpoint.state_dict APIs (get_model_state_dict, set_model_state_dict, get_optimizer_state_dict, set_optimizer_state_dict, StateDictOptions), which carry excessive complexity from legacy FSDP1/DDP support.
- Introduces `torchtitan/tools/checkpoint_utils.py` with focused utilities: _orig_mod prefix stripping for model state dicts, FQN-keyed optimizer state dict conversion using PyTorch's param_names feature, and flatten/unflatten logic for DCP-compatible optimizer checkpointing.
- Constructs optimizers with (name, param) tuples so that FQN mappings are natively available without relying on distributed state_dict introspection.
- *Adds an integration test (test_state_dict_keys.py) that validates the exact model and optimizer state dict key contract against hard-coded expected values for the llama3 debugmodel, catching regressions from refactoring or upstream PyTorch changes.*


ghstack-source-id: 148772b
Pull-Request: #2441
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Feb 25, 2026
@fegin
fegin requested a review from wz337 February 25, 2026 23:42

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.

for proximity, can we put this in components/checkpointer/utils.py?

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 is a quite tricky as there may be checkpointer->optimizer->checkpointer/utils circular dependency if the order doesn't set correct in checkpointer. Let me see what I can do.

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.

put it as component/checkpoint_utils.py

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.

Other than canonical_fqn which can be put somewhere neutral (maybe torchtitan/tools/utils.py), the other functions are either for model, or for optimizer

  • for the ones for model, we can just put them in checkpoint.py because that's where we define ModelWrapper
  • for the ones for optimizer, we can put them in optimizer.py

The argument is that each component should be responsible for its own state dict logic.

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.

I think these APIs should be put together. These APIs are not used to process ModelWrapper nor OptimizerWrapper, they are used to process nn.Module and optim.Optimizer state_dict logic. So logically speaking, they belong to the same place -- one place where it is for processing model and optimizer state_dict for distributed checkpointing. Without distributed checkpointing, these APIs are not needed.

Comment thread torchtitan/components/optimizer.py Resolved
Comment thread torchtitan/components/checkpoint.py Resolved
Comment thread torchtitan/components/checkpoint.py Resolved
Comment thread torchtitan/components/optimizer.py Resolved
[ghstack-poisoned]
fegin added a commit that referenced this pull request Mar 25, 2026
…ict APIs

**Why this PR**
TorchTitan checkpointer relies PyTorch distributed state_dict APIs to ensure optimizer and model state_dict are as expected (e.g., FQNs are correct, flattened optimizer state_dict). However distributed state_dict APIs provide way too many features and support many legacy APIs (FSDP1, DDP).

This PR aims to clean up the dependency of PyTorch distributed state_dict APIs and extract the necessary logic to TorchTitan. We can upstream some utilities back to PyTorch in the future.

**Summary**
- Removes the dependency on torch.distributed.checkpoint.state_dict APIs (get_model_state_dict, set_model_state_dict, get_optimizer_state_dict, set_optimizer_state_dict, StateDictOptions), which carry excessive complexity from legacy FSDP1/DDP support.
- Introduces `torchtitan/tools/checkpoint_utils.py` with focused utilities: _orig_mod prefix stripping for model state dicts, FQN-keyed optimizer state dict conversion using PyTorch's param_names feature, and flatten/unflatten logic for DCP-compatible optimizer checkpointing.
- Constructs optimizers with (name, param) tuples so that FQN mappings are natively available without relying on distributed state_dict introspection.
- *Adds an integration test (test_state_dict_keys.py) that validates the exact model and optimizer state dict key contract against hard-coded expected values for the llama3 debugmodel, catching regressions from refactoring or upstream PyTorch changes.*

ghstack-source-id: ba6e040
Pull-Request: #2441
@fegin
fegin requested review from tianyu-l and wwwjn March 25, 2026 21:51
[ghstack-poisoned]
fegin added a commit that referenced this pull request Mar 25, 2026
…ict APIs

**Why this PR**
TorchTitan checkpointer relies PyTorch distributed state_dict APIs to ensure optimizer and model state_dict are as expected (e.g., FQNs are correct, flattened optimizer state_dict). However distributed state_dict APIs provide way too many features and support many legacy APIs (FSDP1, DDP).

This PR aims to clean up the dependency of PyTorch distributed state_dict APIs and extract the necessary logic to TorchTitan. We can upstream some utilities back to PyTorch in the future.

**Summary**
- Removes the dependency on torch.distributed.checkpoint.state_dict APIs (get_model_state_dict, set_model_state_dict, get_optimizer_state_dict, set_optimizer_state_dict, StateDictOptions), which carry excessive complexity from legacy FSDP1/DDP support.
- Introduces `torchtitan/tools/checkpoint_utils.py` with focused utilities: _orig_mod prefix stripping for model state dicts, FQN-keyed optimizer state dict conversion using PyTorch's param_names feature, and flatten/unflatten logic for DCP-compatible optimizer checkpointing.
- Constructs optimizers with (name, param) tuples so that FQN mappings are natively available without relying on distributed state_dict introspection.
- *Adds an integration test (test_state_dict_keys.py) that validates the exact model and optimizer state dict key contract against hard-coded expected values for the llama3 debugmodel, catching regressions from refactoring or upstream PyTorch changes.*

ghstack-source-id: adddfec
Pull-Request: #2441

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.

do you plan to remove this script before merge?

@fegin fegin Mar 26, 2026 •

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.

No. I actually repeated this verification multiple times when changing state_dict and checkpointer. This script will be used again in the future.

optim.zero_grad(set_to_none=True)


def optim_state_dict_to_fqn_keys(optim_sd: dict[str, Any]) -> dict[str, Any]:

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.

do we need this function to stand alone? May be fine to put the content directly in get_flat_optim_state_dict

@fegin fegin Mar 26, 2026 •

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.

That was the original design after the distributed state_dict received one major feedback from users, there are too many features in two APIs and many of these are not always needed and are proved to by composable. The goal of this PR is not just removing the dependencies but also create utilities that we can eventually upstream back to PyTorch.
The example here, init_optim and optim_state_dict_to_fqn_keys are the two common ones. Checkpointing team is already asking these utilities.

return result


def unflatten_and_load_optim_state_dict(

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.

similar nit, maybe don't need another level of function calling

@fegin fegin Mar 26, 2026 •

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.

I can make this a private function. But I don't see the reason why we need to inline this function, though I do want to move optim.load_state_dict out from this function to make this function purely unflattening purpose.

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.

But I don't see the reason why we need to inline this function

The reason I'm asking these is that this file looks like a collection of many function, some of them are related to each other, some of them are not. Putting small util functions inline help the reader to understand this is a private function only used by another user-facing function, thus establishing some structure (o/w user can only search callsites).

I don't have strong opinions tho. Upstreaming to pytorch sounds good.

return ret


def _reconstruct_nested(flat_sd: dict[str, Any], prefix: str) -> dict[str, Any]:

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.

maybe make this inline function

@fegin fegin Mar 26, 2026 •

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.

I intentionally do this because the original distributed state_dict code is hard to understand because every function is complicated. I don't see the reason to inline this one.

return {"state": new_state, "param_groups": new_param_groups}


def _flatten_state_nested(d: dict[str, Any], prefix: str, out: dict[str, Any]) -> None:

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.

similar nit: maybe make inline

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 is a recursive function, that's why it is a standalone one.

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.

I'm OK with not putting it in the function where it's used. But being recursive doesn't mean it cannot be an inline, embedded function?

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.

Other than canonical_fqn which can be put somewhere neutral (maybe torchtitan/tools/utils.py), the other functions are either for model, or for optimizer

  • for the ones for model, we can just put them in checkpoint.py because that's where we define ModelWrapper
  • for the ones for optimizer, we can put them in optimizer.py

The argument is that each component should be responsible for its own state dict logic.

@fegin

fegin commented Mar 26, 2026

Copy link
Copy Markdown
Contributor Author

I'll do another round to make some functions private, but I don't want to inline many of them. Also, IMO, these APIs are logically together -- they are just a simpler version of distributed state_dict APIs. The best place to put them "separately' are where nn.Module and Optimizer are defined, not where our ModuleWrapper and OptimizerWrapper are defined.

return {"state": new_state, "param_groups": new_param_groups}


def _flatten_state_nested(d: dict[str, Any], prefix: str, out: dict[str, Any]) -> None:

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.

I'm OK with not putting it in the function where it's used. But being recursive doesn't mean it cannot be an inline, embedded function?

return result


def unflatten_and_load_optim_state_dict(

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.

But I don't see the reason why we need to inline this function

The reason I'm asking these is that this file looks like a collection of many function, some of them are related to each other, some of them are not. Putting small util functions inline help the reader to understand this is a private function only used by another user-facing function, thus establishing some structure (o/w user can only search callsites).

I don't have strong opinions tho. Upstreaming to pytorch sounds good.

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
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
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 closed this Jun 10, 2026
fegin added a commit that referenced this pull request Jun 12, 2026
…ict APIs (#3623)

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

**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 |
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 |
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.

4 participants