Refactor QKV Fusion Utilities to be LoRA-Aware#14047
Conversation
…e to original fusion state, module-level helpers to get Q,K,V in both fused and split cases
…duleMixin Tests are in tests/models/test_attention_mixins.py and cover the four minimal concrete AttentionModuleMixin fixtures (_MinimalSelfAttn, _MinimalCrossAttn, _MinimalAddedKVAttn, _MinimalAddedQKVAttn): TestAttentionModuleMixin (53 tests): - Idempotency of fuse_projections/unfuse_projections - Module attribute invariants for non-inplace and inplace paths - Weight/bias correctness: fused weight equals concatenation of split weights - Inplace round-trip weight preservation and storage-sharing (no copy on unfuse) - Cross-attention to_kv path, added-KV to_added_kv path (Wan-style), and added-QKV to_added_qkv path (Flux-style) - get_qkv and get_added_qkv numerical correctness in split and fused cases - LoRA guard: fuse_projections/unfuse_projections raise ValueError when PEFT-style lora_A/lora_B submodules are detected on split or fused projections TestAttentionMixin (6 tests): - fuse_qkv_projections/unfuse_qkv_projections propagate to all eligible blocks - restore_checkpoint_fusion_state respects _native_fused_projections=None/True/False per block, including mixed-state models Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
|
The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update. |
| delattr(self, "to_k") | ||
| delattr(self, "to_v") |
There was a problem hiding this comment.
Does it free the memory? If not, what is the purpose of deleting these attributes? Also, from what I understand this and some of the other refactors introduced in this PR aren't particularly for LoRA-awareness?
| delattr(self, "to_q") | ||
| delattr(self, "to_k") | ||
| delattr(self, "to_v") |
| @staticmethod | ||
| def _has_active_lora(module: nn.Module) -> bool: | ||
| """Checks for the presence of PEFT-style LoRA modules without needing to import `peft`.""" | ||
| return any("lora_A" in name or "lora_B" in name for name, _ in module.named_modules()) |
There was a problem hiding this comment.
I think a better way to detect it is:
for name, mod in module.named_modules():
if isinstance(mod, BaseTunerLayer): ...This way, we can cater towards any non-LoRA adapters in the future.
| if isinstance(module, AttentionModuleMixin) and module._supports_qkv_fusion: | ||
| module.unfuse_projections() | ||
|
|
||
| def restore_checkpoint_fusion_state(self, inplace: bool = False): |
There was a problem hiding this comment.
Could you provide an example of where / how this is used?
My mental model says:
- Load the pipeline
- Call the
fuse_qkv_projections()method onpipe.transformer. - Then, before loading we call this method.
- And then load the LoRA weights?
| @@ -0,0 +1,624 @@ | |||
| import pytest | |||
There was a problem hiding this comment.
Would it not make sense to make these a common mixin that can be added to models?
| return self.base(x) + self.lora_B(self.lora_A(x)) | ||
|
|
||
|
|
||
| class TestAttentionModuleMixin: |
There was a problem hiding this comment.
The tests are missing:
- If outputs with and without fusion stay the same (they should).
- If expected errors are raised when LoRA is attached.
Additionally, are we checking if the projection attributes like to_k, to_q, etc. are actually getting deleted for in-place fusions and are successfully restored when the user wants them?
| assert not hasattr(model.block2, "to_kv") | ||
|
|
||
| # ------------------------------------------------------------------------- | ||
| # restore_checkpoint_fusion_state |
There was a problem hiding this comment.
Should the corresponding tests also check if we have the fused QKV projections rather than just checking the fused_projections attribute?
| def test_restore_checkpoint_noop_for_none(self, model): | ||
| # Default _native_fused_projections is None — state should be unchanged. | ||
| model.restore_checkpoint_fusion_state() | ||
| assert model.block1.fused_projections is False |
There was a problem hiding this comment.
Prefer
| assert model.block1.fused_projections is False | |
| assert not model.block1.fused_projections |
What does this PR do?
This PR refactors the attention QKV fusion utilities in
AttentionMixinandAttentionModuleMixinto be more LoRA-aware. In particular, this PR adds guards when attempting to fuse/unfuse with a LoRA attached (because LoRAs cannot be easily transferred over when fusing/unfusing) and aninplaceoption to fuse without keeping copies of the split Q,K,V projections.Changelist
inplaceargument; ifinplace=True, the module is modified to have only the fused QKV projection (e.g.to_qkv) with the split Q,K,V projections (e.g.to_q/to_k/to_v) removed. (inplace=False, the default, retains the current behavior).add_k_projandadd_v_projare present withoutadd_q_projalso present (e.g. Wan models).get_qkvandget_added_qkvhelper methods inAttentionModuleMixinwhich handles getting the Q, K, V (and added Q,K,V, for second stream projections in MM-DiT-style models like Flux) in both the fused and split case. This is intended to make it easier for attention processors to support both fused and split QKV.restore_checkpoint_fusion_statemethod toAttentionMixinto put models back in the fusion state of the original model checkpoint. A new_native_fused_projectionsattribute onAttentionModuleMixinis added to allow this state to be described. (The motivation is to make it easier to support PEFT adapters which target the original checkpoint structure.)Partially addresses #14003.
Before submitting
.ai/review-rules.md?documentation guidelines, and
here are tips on formatting docstrings.
Who can review?
Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.
@sayakpaul
@DN6