Skip to content

[Attn] Unify attention metadata - #5335

Merged
acisseJZhong merged 10 commits into
mainfrom
unify_attn
Oct 15, 2026
Merged

acisseJZhong merged 10 commits into
mainfrom
unify_attn

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Build and route metadata by the configured inner-attention type, removing cached metadata keys and redundant config lists. Use first_full_attention for 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 attention config and module, and update checkpoint adapters and Muon parameter matching. Rename DeepSeek MLA to DeepSeekMLAAttention and 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 become attention; 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:

  • Kimi K3 and Qwen3.5/3.6/3.8 BF16 debug decoders: 10 steps, seed 42, deterministic mode; bitwise-identical outputs, loss, grad_norm, gradients and updated weights after normalizing parameter names.
  • Targeted CP, hybrid, Muon and HF checkpoint round-trip checks passed.
  • Full pre-commit: other hooks passed; 50 existing local Pyrefly errors remain. Three MRoPE tests reproduce the same compiled-library import failure before the changes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 12, 2026
@acisseJZhong
acisseJZhong added this pull request to stack #5336 October 12, 2026 19:49
@acisseJZhong
acisseJZhong force-pushed the unify_attn branch 5 times, most recently from 20676f8 to eb56df7 Compare October 12, 2026 21:32
@acisseJZhong acisseJZhong changed the title [Attn] Unify attention metadata dispatch [Attn] Unify attention metadata Oct 13, 2026
@acisseJZhong
acisseJZhong marked this pull request as ready for review October 13, 2026 00:22
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 13, 2026
@acisseJZhong
acisseJZhong removed this pull request from stack #5336 October 13, 2026 00:38
@acisseJZhong
acisseJZhong added this pull request to stack #5346 October 13, 2026 00:38
inner_attention: InnerAttention.Config

@property
def is_linear_attention(self) -> bool:

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_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):

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.

we should either name InnerAttention -> BaseInnerAttention, or call this one Attention

Comment thread torchtitan/models/common/decoder.py Outdated
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:

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.

are you not looking for full attention to be fed to CP here? what is it used for

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment thread torchtitan/models/kimi_k2_7/model.py Outdated
if attention_metadata is None
else attention_metadata.get(
cast(TransformerBlock, layer).attention.attention_metadata_key
type(cast(TransformerBlock, layer).attention.inner_attention)

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.

still type cast

Comment on lines +237 to +238
feed_forward: FeedForward.Config | None = field()
moe: MoE.Config | None = field()

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.

do we need this two?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

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.

and this one

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

address in next PR

Comment thread torchtitan/models/muse_glimmer/model.py Outdated
if attention_metadata is None
else attention_metadata.get(
cast(TransformerBlock, layer).attention.attention_metadata_key
type(cast(TransformerBlock, layer).attention.inner_attention)

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.

+1

Comment thread torchtitan/models/muse_glimmer/model.py Outdated
Comment on lines 446 to 454

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.

not only flex / varlen should get metadata? this was legacy code due to sdpa

Comment thread torchtitan/models/qwen3_5/model.py Outdated
Comment on lines +732 to +733
type(
cast(

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.

+1

Comment thread torchtitan/rl/model/vllm_registry.py Outdated
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

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.

here should be looking for full instead of non-linear -- although I don't see why

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

@tianyu-l tianyu-l Oct 14, 2026 •

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

moe: MoE.Config | None = None
attention_norm: RMSNorm.Config
ffn_norm: RMSNorm.Config
attention_norm: Module.Config

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

this is because now both kimik3 and qwen35 inherits from TransformerBlock and they use RMSNorm and OffsetRMSNorm, so common type is Module.Config here.

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.

Given how common it is, we probably should have a base norm class. But won't block this PR.

Base automatically changed from default_varlen to main October 13, 2026 06:10
@acisseJZhong
acisseJZhong force-pushed the unify_attn branch 2 times, most recently from b84d332 to 59171ca Compare October 13, 2026 22:36

@dataclass(kw_only=True, slots=True)
class Config(InnerAttention.Config):
head_dim: int

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.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

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.

Given how common it is, we probably should have a base norm class. But won't block this PR.

Comment thread torchtitan/models/common/decoder.py Outdated
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:

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.

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

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 OK with first_softmax_attention ... not perfect

Comment thread torchtitan/models/common/decoder.py Outdated
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.

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.

how is that going to help though? I think without full attention, it may not be worth load balancing anyways.

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.

also what happens if there's none? e.g. only linear attention everywhere (in some PP stage)

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.

@acisseJZhong I don't think we should take SWA into account when doing CP load balancing

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment thread torchtitan/rl/model/vllm_registry.py Outdated
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

@tianyu-l tianyu-l Oct 14, 2026 •

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

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review my review, especially on the naming question

@claude

claude Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 13s —— View job


Review of @tianyu-l's review

  • Read the decoder/attention changes
  • Evaluate the naming question for first_non_linear_attention
  • Evaluate the other review comments (CP fallback, vLLM, InnerLinearAttention, norm base)
  • Post findings

1. Naming of first_non_linear_attention (decoder.py:93)

You're right that non_linear is a bad name, for both reasons you gave. SWA costs O(L*W), so in complexity terms it is linear. And "non-linear" defines the set by what it excludes, so readers have to know that LinearAttention is a term of art (GDN/KDA) and not a complexity class.

first_key_value_attention doesn't separate the two groups, though. GDN and KDA also have K and V: KDA has q_proj/k_proj/v_proj, and the delta rule writes k^T v into its state. The real difference is how K/V is consumed:

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:128 and rl/generator.py:943,
  • the comment at decoder.py:332,
  • the SimpleNamespace(first_non_linear_attention=...) mocks in tests/rl/unit_tests/cpu/test_generator.py:536 and tests/unit_tests/cpu/models/common/test_cp_attention.py:143.

Fix this →

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.py deep-copies the whole model and deletes layer modules, but self.config.layers keeps the full list. Every PP rank calls model_parts[0].preprocess_inputs (training_engine.py:602), and both _cp_shard and _get_attention_metadata (decoder.py:389) iterate over self.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_metadata is None. HeadTailCPLoadBalancer ignores it, so that works. PTRRFlexAttentionCPLoadBalancer raises "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 in validation.py would 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 first W tokens of each document. The practical effect is that PTRR gets a BlockMask and works instead of raising. It also keeps the previous behavior: the old canonicalize_cp_inner_attention path 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.Config loses type safety on attention_norm/ffn_norm; a TODO pointing at the follow-up would help.
  • InnerAttention → BaseInnerAttention vs. BaseAttention → Attention: the PR went with Attention, which is consistent now (Attention / InnerAttention / LinearAttention).
  • type(cast(...).attention.inner_attention) in kimi_k2_7, muse_glimmer, qwen3_5, mtp: the Decoder.forward version (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 by type(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:69 and decoder.py:165 only 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.

@acisseJZhong

Copy link
Copy Markdown
Contributor Author

CI triage for 91879873a: all three failing jobs are GraphTrainer checks. The evidence points to existing failures or a dependency update, rather than this PR's attention changes.

GraphTrainer A10G

  • TestLlama3BitwiseDeterministic::test_precompile_vs_trace and TestQwen3MoEBitwiseDeterministic::test_precompile_vs_trace: the test's SimpleNamespace config lacks training, which the precompile path now reads (config.training.disable_cuda_graphs).
  • TestQwen3MoEFlexAttnBitwiseDeterministic::test_aot_fx_trace_vs_eager: eager/trace determinism failure, with losses 7.010030746459961 vs 7.010027885437012. The exact divergent operation has not been isolated.

All three fail identically on main, including the exact loss values.

GraphTrainer H100

These four tests hit KeyError: mesh_ep while SimpleFSDP converts SPMD parameter metadata: the local type mapping lacks the requested EP axis.

  • aot_fx_trace_deepseek_v3_hsdp_edp_shard_ep
  • aot_fx_trace_deepseek_v3_graph_pp_dual_pipe_v_full_inductor
  • aot_fx_trace_deepseek_v3_graph_pp_zbv_zero_bubble_full_inductor
  • aot_fx_trace_deepseek_v3_graph_pp_interleaved_1f1b_full_inductor

aot_fx_trace_deepseek_v3_fused_mla_swiglu_fsdp_tp_ep fails PyTorch's grouped-MM shape validation during tracing: matrix batch sizes have to match.

The same five tests fail with the same errors on main.

GraphTrainer B200

  • graph_trainer_dist_moe_mxfp8_fsdp_ep_pp: ValueError: weight must be contiguous CUDA storage during model initialization. CI installs unpinned dist_moe@main; it advanced from 6f0c3d4 to fa32967, which added a CUDA-storage check. GraphTrainer calls weight preparation while parameters are still on the meta device.
  • This PR's previous run passed with the older dependency; the only subsequent source change was in a CPU loss test. PR #5345 also hits the same error with the newer dependency. This strongly indicates a dependency compatibility regression; a pinned-dependency GPU rerun remains to confirm it.

Core CPU/GPU, regular H100/B200, full Real-PG integration, and RL checks passed.

@acisseJZhong
acisseJZhong merged commit 0a3480f into main Oct 15, 2026
aws-dixuan pushed a commit to aws-dixuan/torchtitan that referenced this pull request Oct 16, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/graph-trainer Run GraphTrainer CI ciflow/h100.8 Trigger H100.8 CI ciflow/real-pg Run the full 8-GPU Real PG integration suite ciflow/rl 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.

2 participants