Add absorbed-mla#3193
Conversation
|
/ok to test 1374fb9 |
|
/ok to test 2670a9b |
|
/ok to test 3f344ac |
|
/ok to test 472808d |
| layernorm_zero_centered_gamma=False, | ||
| expert_model_parallel_size=1, | ||
| tensor_model_parallel_size=tensor_model_parallel_size, | ||
| sequence_parallel=tensor_model_parallel_size > 1, |
There was a problem hiding this comment.
Does absorbed MLA support TP > 1 without SP for now? If yes, please add at least one test case to cover it. If no, please add an assertion in TransformerConfig or AbsorbedMLA.__init__.
There was a problem hiding this comment.
Because this PR only adds the AbsorbedMLA but doesn't change the spec, so there is no config to enable this AbsorbedMLA directly. I added assertion in the AbsorbedMLA class instead.
| if self.recompute_up_proj: | ||
| quantization = self.config.fp8 or self.config.fp4 | ||
| assert not quantization, "FP8/FP4 is not supported for AbsorbedMLA" | ||
| self.qkv_up_checkpoint = tensor_parallel.CheckpointWithoutOutput(fp8=quantization) |
There was a problem hiding this comment.
Missing
from megatron.core import tensor_parallelThere was a problem hiding this comment.
Maybe need a UT to cover recompute. I think it is not emergent, so you can mark as a TODO.
There was a problem hiding this comment.
Added missing import, also added test case to guard it.
|
|
||
| def get_absorbed_mla_submodules( | ||
| down_proj_use_column_parallel: bool, qk_layernorm: bool, rms_norm: bool | ||
| ) -> AbsorbedMLASelfAttentionSubmodules: |
There was a problem hiding this comment.
How about using the layer spec function in core.model.gpt_layer_spec to simplify the code and cover the real spec function in the UT? As it has not been supported yet, we can mark it as a TODO here.
There was a problem hiding this comment.
This PR only adds the AbsorbedMLA but doesn't change the spec, because the current unfused dsa doesn't support absorption yet. Will introduce new dsa in the next PR, in that PR I'll do what you said.
Added TODO comments.
yuzhongw-nvidia
left a comment
There was a problem hiding this comment.
Thanks for your great work! Overall LGTM. I've left a few minor comments.
| kv_layernorm: Union[ModuleSpec, type] = None | ||
|
|
||
|
|
||
| class AbsorbedMLASelfAttention(Attention): |
There was a problem hiding this comment.
there are some duplicated code with MLASelfAttention. Was this done on purpose because it's an experimental variant? Does it make sense to subclass MLASelfAttention?
There was a problem hiding this comment.
It's done on purpose.
We will change/optimize this class a lot in the near future, and want to iterate faster without adding risks to standard MLA which is already used in some production scenario.
We plan to merge it with the standard MLA or make it a subclass of MLA when this feature is stable.
| assert ( | ||
| packed_seq_params.local_cp_size is None | ||
| ), "dynamic context parallel is not supported with MLA yet and is planned for future. \ | ||
| Please disable dynamic context parallel." |
There was a problem hiding this comment.
MLASelfAttention has this as "hybrid context parallel"
Maybe we need to cherrypick the recent changes in multi_latent_attention.py?
There was a problem hiding this comment.
CP is not supported yet, and it's not easy because we need some new CP solution for the attention variant like dsa. We will add this hybrid context parallel feature when we add CP to it.
6b7de3b to
1339a7b
Compare
|
/ok to test 1339a7b |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA/Megatron-LM/actions/runs/21981893832 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA/Megatron-LM/actions/runs/21990716575 |
What does this PR do ?
PR for main #3198
Implement MLA with matrix absorption:
The absorption is mathematically equivalent to standard MLA but enables MQA-style attention which
can be more efficient for certain attention variants.
1. TL;DR
AbsorbedMLASelfAttentionclass that implements MLA with matrix absorption optimization, where K's up-projection is absorbed into Q before core attention, enabling MQA-style computation.2. Big Picture
graph TB subgraph "Before: Standard MLA" A1[hidden_states] --> B1[Q down proj] A1 --> C1[KV down proj] B1 --> D1[Q up proj] C1 --> E1[KV up proj<br/>joint K+V] D1 --> F1[RoPE on Q] E1 --> G1[RoPE on K] E1 --> H1[V extraction] F1 --> I1[Core Attention<br/>MHA: n heads for Q,K,V] G1 --> I1 H1 --> I1 I1 --> J1[linear_proj] end subgraph "After: Absorbed MLA" A2[hidden_states] --> B2[Q down proj] A2 --> C2[KV down proj] B2 --> D2[Q up proj] C2 --> E2[K up weight<br/>NOT applied to KV] D2 --> F2["Q absorbed = Q @ K_up^T"] E2 --> F2 F2 --> G2[RoPE on Q_absorbed] C2 --> H2[Compressed KV<br/>single head] H2 --> I2[RoPE on K_pos] G2 --> J2["Core Attention<br/>MQA: n heads Q, 1 head KV"] I2 --> J2 J2 --> K2["V up proj AFTER attention"] K2 --> L2[linear_proj] end style F2 fill:#90EE90 style K2 fill:#90EE90 style J2 fill:#FFD7003. Design Rationale
3.1 Problem Background
Standard MLA (Multi-Latent Attention) as implemented in
MLASelfAttentionworks as follows:Limitation: The KV up-projection expands to all
nattention heads before core attention, which cannot leverage specialized MQA kernels that are optimized for single-head KV.3.2 Solution Approach
Matrix Absorption exploits the mathematical equivalence:
Key insight: Instead of projecting K and V up to multi-head before attention, we can:
Q' = Q @ K_up_proj^T(still multi-head)3.3 Key Design Points
New Classes and Responsibilities:
AbsorbedMLASelfAttentionSubmodules(dataclass):MLASelfAttentionSubmodulesbut with separatelinear_k_up_projandlinear_v_up_projinstead of fusedlinear_kv_up_projAbsorbedMLASelfAttention(class):AttentionclassMLASelfAttention:get_query_key_value_tensors()forward()Interface Contracts:
4. Execution Path Deep Dive
4.1 Entry Point
The absorbed MLA is triggered when a transformer layer is configured with
AbsorbedMLASelfAttention:4.2 Call Chain Visualization
sequenceDiagram participant TL as TransformerLayer participant ABS as AbsorbedMLASelfAttention participant QKV as get_query_key_value_tensors() participant CA as core_attention participant VP as V up-projection participant LP as linear_proj TL->>ABS: forward(hidden_states, attention_mask) ABS->>QKV: get_query_key_value_tensors(hidden_states) Note over QKV: Q down proj → layernorm → Q up proj Note over QKV: KV down proj → layernorm Note over QKV: K_up_weight absorbed into Q Note over QKV: Apply RoPE QKV-->>ABS: q_absorbed, kv_compressed, q_compressed ABS->>CA: core_attention(q_absorbed, kv_compressed, v=None) Note over CA: MQA-style: Q multi-head, KV single-head CA-->>ABS: attn_out [s, b, n * kv_lora_rank] ABS->>VP: einsum("...nc,ndc->...nd", attn_out, v_up_weight) Note over VP: Project to full value dimension VP-->>ABS: attn_out [s, b, n * v_head_dim] ABS->>LP: linear_proj(attn_out) LP-->>ABS: output [s, b, hidden_size] ABS-->>TL: output, bias4.3 Data Flow
graph TD A["hidden_states<br/>[s, b, hidden_size]"] -->|Q down proj| B["q_compressed<br/>[s, b, q_lora_rank]"] A -->|KV down proj| C["kv_combined<br/>[s, b, kv_lora_rank + qk_pos_emb]"] B -->|layernorm| D["q_compressed_norm<br/>[s, b, q_lora_rank]"] C -->|split| E["kv_compressed<br/>[s, b, kv_lora_rank]"] C -->|split| F["k_pos_emb<br/>[s, b, qk_pos_emb]"] E -->|layernorm| G["kv_compressed_norm<br/>[s, b, kv_lora_rank]"] D -->|Q up proj| H["q<br/>[s, b, n, qk_head_dim + qk_pos_emb]"] H -->|split| I["q_no_pe<br/>[s, b, n, qk_head_dim]"] H -->|split| J["q_pos_emb<br/>[s, b, n, qk_pos_emb]"] I -->|"einsum(q, k_up_weight)"| K["q_absorbed<br/>[s, b, n, kv_lora_rank]"] J -->|apply RoPE| L["q_pos_emb_rope<br/>[s, b, n, qk_pos_emb]"] F -->|apply RoPE| M["k_pos_emb_rope<br/>[s, b, 1, qk_pos_emb]"] K -->|concat| N["q_final<br/>[s, b, n, kv_lora_rank + qk_pos_emb]"] L --> N G -->|concat| O["kv_final<br/>[s, b, 1, kv_lora_rank + qk_pos_emb]"] M --> O N -->|core_attention| P["attn_out<br/>[s, b, n, kv_lora_rank]"] O --> P P -->|"einsum(out, v_up_weight)"| Q["projected<br/>[s, b, n, v_head_dim]"] Q -->|reshape + linear_proj| R["output<br/>[s, b, hidden_size]"] style K fill:#90EE90 style Q fill:#90EE904.4 Core Code Walkthrough
4.4.1 K Absorption into Q
4.4.2 V Up-Projection After Attention
4.4.3 Checkpoint Loading with Weight Conversion
5. Risks & Edge Cases
test_absorbed_mla.pytp_cp = [[1,1], [2,1], [1,2], [2,2]]qkv_format = ['sbhd', 'thd']_load_from_state_dict()weight conversionassert inference_context is Noneassert not quantizationassert not self.cache_mla_latentsraise NotImplementedError("clip_qk")down_proj_use_column_parallelparamContribution process
flowchart LR A[Pre-checks] --> B[PR Tests] subgraph Code Review/Approval C1[Expert Review] --> C2[Final Review] end B --> C1 C2 --> D[Merge]Pre-checks
Core 0.8)Code review
The following process is enforced via the CODEOWNERS file for changes into
megatron/core. For changes outside ofmegatron/core, it is up to the PR author whether or not to tag the Final Reviewer team.For MRs into `main` branch
Feel free to message or comment the @mcore-oncall to help accelerate your merge into main. The less complex your PR is, the faster it will be approved and merged!
(Step 1): Add PR label
Expert Review(Step 2): Collect the expert reviewers reviews
Expert Reviewlabel when your PR is ready for review.Final Review might get declined if these requirements are not fulfilled.
(Step 3): Final Review
Final Reviewlabel(Optional Step 4): Cherry-pick into release branch
If this PR also needs to be merged into
core_r*release branches, after this PR has been merged, selectCherry-pickto open a new PR into the release branch.For MRs into `dev` branch
The proposed review process for `dev` branch is under active discussion.MRs are mergable after one approval by either
eharper@nvidia.comorzijiey@nvidia.com.Merging your PR
Any member of core-adlr and
core-nemowill be able to merge your PR.