Repository navigation
FusedQKVLinear checkpoint interop via state_dict hooks - #3656
Conversation
|
Hi @sdmyzlp! Thank you for your pull request and welcome to our community. Action RequiredIn order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you. ProcessIn order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA. Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with If you have received this in error or have any questions, please contact us at [email protected]. Thanks! |
|
|
bd75751 to
4cafd6b
Compare
|
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks! |
|
|
||
| def __init__(self, model: nn.Module | list[nn.Module]) -> None: | ||
| self.model = [model] if isinstance(model, nn.Module) else model | ||
| self.cached_state_dict = self._get_state_dict() |
There was a problem hiding this comment.
I didn't get the necessity to remove cache.
You said
ModelWrapper previously cached model.state_dict() at init time and returned the same dict on subsequent calls. This assumed dict values are live references to actual parameter tensors. However, any module using register_state_dict_post_hook that produces new tensors (via .contiguous(), torch.cat, etc.) creates disconnected copies that go stale during training — causing checkpoints to silently save initial weights.
But
- https://github.com/pytorch/torchtitan/blob/main/torchtitan/trainer.py#L263 apply_overrides is applied before checkpointer build https://github.com/pytorch/torchtitan/blob/main/torchtitan/trainer.py#L480
- where it for the first time apply the check hook? https://github.com/pytorch/pytorch/blob/94c0a41a16f7a65c690b28f5150c886d3a72dac6/torch/nn/modules/module.py#L2274
There was a problem hiding this comment.
The hook registration timing isn't the issue. The problem is that .contiguous() in the hook allocates new storage:
state_dict["wq.weight"] = w_4d[:, :hpk].reshape(-1, in_f).contiguous()The slice is non-contiguous (Q/K/V are interleaved), so .contiguous() creates an independent copy (likewise the FusedSwiGLU case). The cache holds these copies from init time — they're never updated by the optimizer.
After 10 training steps, state_dict() still returns step-0 values. Verified with checkpoint_compat_test.py — without the fix, resuming shows a loss spike proving stale weights were saved. The unit test TestModelWrapper.test_state_dict_reflects_updates_with_hooks also reproduces this in isolation.
To answer your question — the hook first runs here, at init time, and the resulting copies are cached. On subsequent state_dict() calls (at save time), the cache returns these stale copies without re-running the hook.
[rank0]: File "<frozen runpy>", line 198, in _run_module_as_main
[rank0]: File "<frozen runpy>", line 88, in _run_code
[rank0]: File "/home/developer/workspace/torchtitan/torchtitan/train.py", line 79, in <module>
[rank0]: main()
[rank0]: File "/home/developer/workspace/torchtitan/torchtitan/train.py", line 51, in main
[rank0]: trainer = config.build() # pyrefly: ignore [missing-attribute]
[rank0]: File "/home/developer/workspace/torchtitan/torchtitan/config/configurable.py", line 121, in build
[rank0]: return self._owner(config=replace(self))
[rank0]: File "/home/developer/.local/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/errors/__init__.py", line 367, in wrapper
[rank0]: return f(*args, **kwargs)
[rank0]: File "/home/developer/workspace/torchtitan/torchtitan/trainer.py", line 480, in __init__
[rank0]: self.checkpointer = config.checkpoint.build(
[rank0]: File "/home/developer/workspace/torchtitan/torchtitan/config/configurable.py", line 130, in build
[rank0]: return self._owner(config=replace(self), **kwargs)
[rank0]: File "/home/developer/workspace/torchtitan/torchtitan/components/checkpoint.py", line 416, in __init__
[rank0]: MODEL: ModelWrapper(model_parts),
[rank0]: File "/home/developer/workspace/torchtitan/torchtitan/components/checkpoint.py", line 82, in __init__
[rank0]: self.cached_state_dict = self._get_state_dict()
[rank0]: File "/home/developer/workspace/torchtitan/torchtitan/components/checkpoint.py", line 86, in _get_state_dict
[rank0]: return {k: v for model in self.model for k, v in model.state_dict().items()}
[rank0]: File "/home/developer/.local/lib/python3.12/site-packages/torch/nn/modules/module.py", line 2269, in state_dict
[rank0]: module.state_dict(
[rank0]: File "/home/developer/.local/lib/python3.12/site-packages/torch/nn/modules/module.py", line 2269, in state_dict
[rank0]: module.state_dict(
[rank0]: File "/home/developer/.local/lib/python3.12/site-packages/torch/nn/modules/module.py", line 2269, in state_dict
[rank0]: module.state_dict(
[rank0]: [Previous line repeated 2 more times]
[rank0]: File "/home/developer/.local/lib/python3.12/site-packages/torch/nn/modules/module.py", line 2275, in state_dict
[rank0]: hook_result = hook(self, destination, prefix, local_metadata)
[rank0]: File "/home/developer/workspace/torchtitan/torchtitan/models/common/attention.py", line 662, in _split_qkv_on_save
[rank0]: traceback.print_stack()
Does this clarifies your concern? @tianyu-l
|
|
||
| def __init__(self, model: nn.Module | list[nn.Module]) -> None: | ||
| self.model = [model] if isinstance(model, nn.Module) else model | ||
| self.cached_state_dict = self._get_state_dict() |
There was a problem hiding this comment.
I'm also not sure about
The cache provided no functional benefit: state_dict() is called once per save, DCP's async stager deep-copies all tensors and clears its storage cache between saves, and no consumer relies on tensor object identity.
@fegin could you confirm?
2b63c93 to
13354d1
Compare
13354d1 to
cda5683
Compare
@fegin After further research, I see that PyTorch core PR pytorch/pytorch#183424 has indeed removed the I've rebased my PR onto the latest main, numerical tests passed as before. PTAL when you get a chance. |
Add save/load hooks so FusedQKVLinear transparently checkpoints as
wq/wk/wv (stock QKVLinear layout), making fused and non-fused
checkpoints interchangeable.
Remove fuse_qkv branching from HF adapters (llama3, qwen3, gpt_oss)
and split/merge helpers from base StateDictAdapter.
Tested by:
```
$ python scripts/checkpoint_compat_test.py . . \
--module llama3 --config llama3_debugmodel_fused_qkv \
--steps 20 --resume-step 10 --ngpus 2 --assert-equal \
--options "--parallelism.spmd_backend full_dtensor"
[CKPT_COMPAT] PASS: All losses are bit-identical.
```
cda5683 to
77f3082
Compare
| "model.layers.{}.self_attn.v_proj.bias": "layers.{}.attention.qkv_linear.wv.bias", | ||
| } | ||
|
|
||
| self.from_hf_map = { |
There was a problem hiding this comment.
Is HF adapter integration verified? If not let's add a unit test. Check fused linear test for example.
| def _split_qkv_on_save(module, state_dict, prefix, local_metadata) -> None: | ||
| """Split fused ``wqkv`` into stock ``wq.weight``/``wk.weight``/``wv.weight``.""" | ||
| hd, hpk, r = module.head_dim, module.heads_per_kv, module.r_dim | ||
|
|
There was a problem hiding this comment.
nit: the logic can be deduplicated into a two step for-loop, one for weight and another one for bias. This can also be applied to _merge_qkv_on_load
|
@sdmyzlp could you address the remaining comment and rebase |
Summary
This PR makes
FusedQKVLinearcheckpoints interoperable with stockQKVLinearby saving in thewq.weight/wk.weight/wv.weightlayout via module-level state_dict hooks.Adds
register_state_dict_post_hookandregister_load_state_dict_pre_hooktoFusedQKVLinearso that:wqkv.weightis split intowq.weight/wk.weight/wv.weightwq/wk/wvkeys are merged back intowqkv.weightVerification
Bit-identical loss across 20 training steps (straight-through vs save-at-10/resume) using
scripts/checkpoint_compat_test.pywith--debug.deterministic --debug.seed=42:PASS: All losses are bit-identical.