Skip to content

FusedQKVLinear checkpoint interop via state_dict hooks - #3656

Merged
tianyu-l merged 1 commit into
pytorch:mainfrom
sdmyzlp:br_fused_qkv_hooks
Jun 18, 2026
Merged

tianyu-l merged 1 commit into
pytorch:mainfrom
sdmyzlp:br_fused_qkv_hooks

Conversation

@sdmyzlp

@sdmyzlp sdmyzlp commented Jun 13, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

This PR makes FusedQKVLinear checkpoints interoperable with stock QKVLinear by saving in the wq.weight/wk.weight/wv.weight layout via module-level state_dict hooks.

Adds register_state_dict_post_hook and register_load_state_dict_pre_hook to FusedQKVLinear so that:

  • On save: fused wqkv.weight is split into wq.weight/wk.weight/wv.weight
  • On load: stock wq/wk/wv keys are merged back into wqkv.weight

Verification

Bit-identical loss across 20 training steps (straight-through vs save-at-10/resume) using scripts/checkpoint_compat_test.py with --debug.deterministic --debug.seed=42:

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"
Step Reference Resume Match
1-10 (identical) (identical) OK
11 3.59175968170166 3.59175968170166 OK
12 3.5357553958892822 3.5357553958892822 OK
13 3.4192099571228027 3.4192099571228027 OK
14 3.3772449493408203 3.3772449493408203 OK
15 3.3474314212799072 3.3474314212799072 OK
16 3.3615636825561523 3.3615636825561523 OK
17 3.215083599090576 3.215083599090576 OK
18 3.1624622344970703 3.1624622344970703 OK
19 3.313873529434204 3.313873529434204 OK
20 3.1608173847198486 3.1608173847198486 OK

PASS: All losses are bit-identical.


@meta-cla

meta-cla Bot commented Jun 13, 2026

Copy link
Copy Markdown

Hi @sdmyzlp!

Thank you for your pull request and welcome to our community.

Action Required

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

Process

In 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 CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at [email protected]. Thanks!

@pytorch-bot

pytorch-bot Bot commented Jun 13, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@meta-cla

meta-cla Bot commented Jun 13, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jun 13, 2026

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()

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

@sdmyzlp sdmyzlp Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I didn't get the necessity to remove cache.

Already rebased PR with the approach from #3675 (thanks @fegin) and removed the previous caching-related commit. PTAL when you have time.


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()

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 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?

@sdmyzlp
sdmyzlp force-pushed the br_fused_qkv_hooks branch 2 times, most recently from 2b63c93 to 13354d1 Compare June 15, 2026 09:49
@fegin

fegin commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

@sdmyzlp Thanks for reflecting a real bug. However, removing cache is not a good idea. The pinned memory based checkpointing does require the same storage. I created a PR to fix this problem: #3675. You can pivot this PR as fused qkv hook state_dict.

@sdmyzlp
sdmyzlp force-pushed the br_fused_qkv_hooks branch from 13354d1 to cda5683 Compare June 16, 2026 06:04
@sdmyzlp

sdmyzlp commented Jun 16, 2026

Copy link
Copy Markdown
Collaborator Author

The pinned memory based checkpointing does require the same storage.

@fegin After further research, I see that PyTorch core PR pytorch/pytorch#183424 has indeed removed the _cached_storage_mapping cleanup that used to happen after every _stage() call. I think now I understand why keeping the storage invariant is essential. Thanks for your guidance.

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.
```
@sdmyzlp
sdmyzlp force-pushed the br_fused_qkv_hooks branch from cda5683 to 77f3082 Compare June 16, 2026 07:01
@sdmyzlp
sdmyzlp requested a review from tianyu-l June 16, 2026 11:22
"model.layers.{}.self_attn.v_proj.bias": "layers.{}.attention.qkv_linear.wv.bias",
}

self.from_hf_map = {

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.

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

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.

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

@tianyu-l

Copy link
Copy Markdown
Contributor

@sdmyzlp could you address the remaining comment and rebase

@tianyu-l
tianyu-l merged commit 70dd945 into pytorch:main Jun 18, 2026
17 of 21 checks passed
@sdmyzlp

sdmyzlp commented Jun 21, 2026

Copy link
Copy Markdown
Collaborator Author

@sdmyzlp could you address the remaining comment and rebase

Very sorry for missing the message, I created a separated PR #3728 to address the previous comments. Please take a look. Much thanks. @tianyu-l @fegin

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