Repository navigation
[Attn] Unify attention metadata - #5335
Conversation
20676f8 to
eb56df7
Compare
eb56df7 to
7ec31ae
Compare
7ec31ae to
cc77436
Compare
c821492 to
5b9e243
Compare
| inner_attention: InnerAttention.Config | ||
|
|
||
| @property | ||
| def is_linear_attention(self) -> bool: |
There was a problem hiding this comment.
is_full_attention on InnerAttention, this no outer attention -- inconsistency
even if you really need them at current location, we can do
- is_linear_attention
- is_full_inner_attention
| @@ -756,14 +768,14 @@ def create_varlen_metadata_for_document( | |||
| class BaseAttention(Module): | |||
There was a problem hiding this comment.
we should either name InnerAttention -> BaseInnerAttention, or call this one Attention
| layer, so callers needing its metadata look up the first such layer | ||
| rather than assuming ``layers[0]``. | ||
| """ | ||
| def first_non_linear_attention(self) -> BaseAttention.Config | None: |
There was a problem hiding this comment.
are you not looking for full attention to be fed to CP here? what is it used for
There was a problem hiding this comment.
CP still prefers full attention: _cp_shard first searches for is_full_attention, then falls back to first_non_linear_attention if none exists. The property also serves these callers:
| Use | Purpose | Code |
|---|---|---|
| TP validation | Check attention head counts against the TP degree. | validation.py, decoder.py |
| CP load balancing | Fallback when no full-attention layer exists, e.g. an SWA-only model. | decoder.py |
| Multimodal preprocessing | Check the inner attention type before building metadata. | Muse Glimmer, Kimi K2.7 |
| vLLM integration | Read head counts/dimensions and validate supported attention types. | vllm_registry.py, generate.py, generator.py |
| Kimi Muon recipes | Read MLA projection dimensions to configure optimizer blocks. | Kimi K3, Kimi K2.7 |
first_non_linear_attention returns the first attention config excluding GDN/KDA; it includes MLA and SWA, so it does not guarantee full attention. It returns None for an all-linear model. Links point to the updated PR commit.
| if attention_metadata is None | ||
| else attention_metadata.get( | ||
| cast(TransformerBlock, layer).attention.attention_metadata_key | ||
| type(cast(TransformerBlock, layer).attention.inner_attention) |
| feed_forward: FeedForward.Config | None = field() | ||
| moe: MoE.Config | None = field() |
There was a problem hiding this comment.
refactor this in the next PR in the stack
| @dataclass(kw_only=True, slots=True) | ||
| class Config(Module.Config): | ||
| class Config(TransformerBlock.Config): | ||
| layer_id: int |
There was a problem hiding this comment.
address in next PR
| if attention_metadata is None | ||
| else attention_metadata.get( | ||
| cast(TransformerBlock, layer).attention.attention_metadata_key | ||
| type(cast(TransformerBlock, layer).attention.inner_attention) |
There was a problem hiding this comment.
not only flex / varlen should get metadata? this was legacy code due to sdpa
| type( | ||
| cast( |
| if not cfg.layers: | ||
| raise ValueError(f"Model config {type(cfg).__qualname__} has no layers") | ||
| attn = cfg.first_base_attention | ||
| attn = cfg.first_non_linear_attention |
There was a problem hiding this comment.
here should be looking for full instead of non-linear -- although I don't see why
There was a problem hiding this comment.
actually here it shouldn't be looking for first full, it should be looking for first non linear. This is because it this config is used to extract
num_attention_heads
num_key_value_heads
head_dim
as hf config.
There was a problem hiding this comment.
I think here if you look for full it'd also work. In inference we don't have PP yet, so full attention must exist.
I guess claude's mixtral example is legit, whatever
50dd37b to
c6637c4
Compare
| moe: MoE.Config | None = None | ||
| attention_norm: RMSNorm.Config | ||
| ffn_norm: RMSNorm.Config | ||
| attention_norm: Module.Config |
There was a problem hiding this comment.
this is because now both kimik3 and qwen35 inherits from TransformerBlock and they use RMSNorm and OffsetRMSNorm, so common type is Module.Config here.
There was a problem hiding this comment.
Given how common it is, we probably should have a base norm class. But won't block this PR.
b84d332 to
59171ca
Compare
|
|
||
| @dataclass(kw_only=True, slots=True) | ||
| class Config(InnerAttention.Config): | ||
| head_dim: int |
There was a problem hiding this comment.
This seems the only difference between InnerKDA config and InnerGDN config, but it also can be sent in from outer KDA (and the post init check can be done there too). Maybe we should have an InnerLinearAttention.Config that's shared?
There was a problem hiding this comment.
the only thing they could share implementation is build_attention_metadata. Given how many attention classes we have already, I think it's not worth to introduce one more? It will become InnerGDN/KDA -> InnerLinearAttention -> InnerAttention.
| moe: MoE.Config | None = None | ||
| attention_norm: RMSNorm.Config | ||
| ffn_norm: RMSNorm.Config | ||
| attention_norm: Module.Config |
There was a problem hiding this comment.
Given how common it is, we probably should have a base norm class. But won't block this PR.
| layer, so callers needing its metadata look up the first such layer | ||
| rather than assuming ``layers[0]``. | ||
| """ | ||
| def first_non_linear_attention(self) -> Attention.Config | None: |
There was a problem hiding this comment.
@claude I don't like this name. Help find a better name.
- the problem is that SWA is also linear ...
- and I think here it tries to find a common ancestor of GQA (full or SWA) and MLA, which has K and V and is not KDA/GDN. So maybe
first_key_value_attention?
There was a problem hiding this comment.
I'm OK with first_softmax_attention ... not perfect
| selected_attention_metadata = attention_metadata.get( | ||
| full_cp_inner_attention | ||
| # All layers share one token permutation. Prefer full-attention metadata, | ||
| # falling back to the first non-linear attention's metadata. |
There was a problem hiding this comment.
how is that going to help though? I think without full attention, it may not be worth load balancing anyways.
There was a problem hiding this comment.
also what happens if there's none? e.g. only linear attention everywhere (in some PP stage)
There was a problem hiding this comment.
@acisseJZhong I don't think we should take SWA into account when doing CP load balancing
There was a problem hiding this comment.
without full attention, it may not be worth load balancing anyways
sure I have is_full_attention property, so I can do that.
also what happens if there's none? e.g. only linear attention everywhere (in some PP stage)
if it cannot find attention metadata, it will fall back to no load balancing / contiguous loading balancing. Also here we are searching from self.config.layers not the pp stage self.layers.
| if not cfg.layers: | ||
| raise ValueError(f"Model config {type(cfg).__qualname__} has no layers") | ||
| attn = cfg.first_base_attention | ||
| attn = cfg.first_non_linear_attention |
There was a problem hiding this comment.
I think here if you look for full it'd also work. In inference we don't have PP yet, so full attention must exist.
I guess claude's mixtral example is legit, whatever
|
@claude review my review, especially on the naming question |
|
Claude finished @tianyu-l's task in 2m 13s —— View job Review of @tianyu-l's review
1. Naming of
|
| GQA full | GQA SWA | MLA (DSv3/Kimi) | DSv4 | GDN / KDA | |
|---|---|---|---|---|---|
| softmax over keys | yes | yes | yes | yes | no |
| KV cache grows with context | yes | yes (bounded by W) | yes (latent) | yes | no (fixed recurrent state) |
| has K/V projections | yes | yes | yes | yes | yes |
The last row is identical across the whole table, so a name based on K/V can't tell the groups apart. The first row can.
Recommendation: first_softmax_attention.
- It describes what the set is rather than what it isn't. "Softmax attention vs. linear attention" is the standard split in the linear-attention literature and in hybrid-model papers.
- SWA, full GQA, MLA and DSv4 are all clearly softmax attention, so the SWA ambiguity goes away.
- It fits every consumer: TP head checks (
validation.py:69,decoder.py:165), vLLM head dims (vllm_registry.py:71), the flex/varlen backend check (rl/generate.py:126,rl/generator.py:940), Muon MLA dims (recipes), and the CP fallback (decoder.py:340).
Second choice: first_kv_cache_attention. It reads well for the vLLM callers but less well for TP and CP. I'd go with softmax.
If you rename it, also update:
- the docstring at
decoder.py:94(say "softmax attention, i.e. not GDN/KDA"), - the error strings "no non-linear attention layer" in
rl/model/vllm_registry.py:74,rl/generate.py:128andrl/generator.py:943, - the comment at
decoder.py:332, - the
SimpleNamespace(first_non_linear_attention=...)mocks intests/rl/unit_tests/cpu/test_generator.py:536andtests/unit_tests/cpu/models/common/test_cp_attention.py:143.
2. Inconsistency between is_full_attention (inner) and linear-ness (outer), plus InnerLinearAttention.Config (kda.py:145)
Your two comments point to the same fix. InnerKDA.Config and InnerGDN.Config already share conv_kernel_size and a byte-identical build_attention_metadata (kda.py:155-172 vs. gdn.py:281-298). Only kernel differs in type, plus KDA's head_dim. I agree with adding InnerLinearAttention(InnerAttention) in linear_attention.py, which already imports from .attention, so there's no import cycle. Move conv_kernel_size and the metadata builder there.
That would also make the softmax/linear predicate an inner property, next to is_full_attention. first_softmax_attention, _cp_shard and validation.py:202 could then all test inner_attention the same way, and the "full on inner, linear on outer" mismatch you flagged would disappear. KDA's head_dim == 128 check can stay on InnerKDA or move to the outer KDA as you suggested. Either is fine. This could land in the follow-up PR.
3. CP fallback when there is no full attention (decoder.py:332)
- "What if a PP stage is all-linear?" This case is already safe.
pipeline_parallel.pydeep-copies the whole model and deletes layer modules, butself.config.layerskeeps the full list. Every PP rank callsmodel_parts[0].preprocess_inputs(training_engine.py:602), and both_cp_shardand_get_attention_metadata(decoder.py:389) iterate overself.config.layers. So every stage picks the same layer and generates the same permutation. Stage-local selection would actually break things, because stages would disagree on the permutation. - What if the whole model is all-linear?
selected_attention_metadataisNone.HeadTailCPLoadBalancerignores it, so that works.PTRRFlexAttentionCPLoadBalancerraises "PTRR load balancing requires attention metadata, but got None" on the first step (context_parallel.py:116). Validation (validation.py:202)continues over linear layers, so the config passes validation and only fails at runtime. Rejecting PTRR when the model has no softmax attention invalidation.pywould be a small improvement. - "How does the SWA fallback help?" For load balance, you're mostly right. With SWA, per-query cost is
min(pos_in_doc, W), so imbalance only exists in the firstWtokens of each document. The practical effect is that PTRR gets aBlockMaskand works instead of raising. It also keeps the previous behavior: the oldcanonicalize_cp_inner_attentionpath had the same full-then-SWA fallback. I'd keep it, since removing it would be a behavior change for SWA-only plus PTRR. If you'd rather drop it, add the validation error above at the same time.
4. vLLM: first full vs. first non-linear (vllm_registry.py:71)
I'd push back on your comment here and keep the softmax version. It is a superset of "full", so it works for every case "full" handles. It also works for all-SWA models (e.g. Mistral-7B-v0.1-style, every layer windowed), where looking for full attention would raise even without PP. The head counts and dims are the same for SWA and full layers in every current hybrid (gpt-oss, Qwen3.5), and the comment at line 69 already says so.
5. Other comments
- Base norm class (
decoder.py:62): agreed it can wait.Module.Configloses type safety onattention_norm/ffn_norm; a TODO pointing at the follow-up would help. InnerAttention→BaseInnerAttentionvs.BaseAttention→Attention: the PR went withAttention, which is consistent now (Attention/InnerAttention/LinearAttention).type(cast(...).attention.inner_attention)in kimi_k2_7, muse_glimmer, qwen3_5, mtp: theDecoder.forwardversion (decoder.py:251) is already clean. Checking that the other models drop the cast the same way is worth one more pass.simple_fsdp.py:225: the reason given holds up. Metadata is now keyed bytype(inner_attention), and SimpleFSDP's parametrization swaps a module's class even when it has no parameters, which would break the lookup. It deserves a one-line code comment, since it's otherwise non-obvious.- Out of scope (not this PR): the TP divisibility check at
validation.py:69anddecoder.py:165only looks at the first softmax layer. GDN/KDA head counts, which are also TP-sharded, aren't checked. The same check also appears in both places.
59171ca to
1911f53
Compare
1911f53 to
266fffe
Compare
266fffe to
9187987
Compare
|
CI triage for
All three fail identically on main, including the exact loss values. These four tests hit
The same five tests fail with the same errors on main.
Core CPU/GPU, regular H100/B200, full Real-PG integration, and RL checks passed. |
…ypass Update the new tests for API changes merged from main: cp_attention moved under models/common/attention, flex_attention is patched in attention.attention, and forward takes attention_metadata (pytorch#5335). Warn when a compile_backend/compile_options override is built under deterministic mode, since set_determinism only replaces the shared default callable.
Build and route metadata by the configured inner-attention type, removing cached metadata keys and redundant config lists. Use
first_full_attentionfor shared config consumers. CP load balancing requires full attention; models without it use contiguous sharding and emit a warning.Unify hybrid Qwen/Kimi blocks under one
attentionconfig and module, and update checkpoint adapters and Muon parameter matching. Rename DeepSeek MLA toDeepSeekMLAAttentionand type inner-attention configs explicitly.HF checkpoints remain compatible. Native Kimi K3 KDA (
delta_attention) and Qwen3.5/3.6/3.8 (attn) decoder paths becomeattention; older native checkpoints require key migration.Testing
Rebased onto
3f021a1eb9. Focused checks using local import compatibility shims: 106 tests passed; three dependency/API failures reproduce on main. Scoped Pyrefly diagnostics are unchanged from before the rebase.Earlier validation: