Skip to content

[CP] Pluggable CP attention via cp_method + attention_sharding - #3978

Closed
fegin wants to merge 2 commits into
gh/fegin/153/basefrom
gh/fegin/153/head
Closed

fegin wants to merge 2 commits into
gh/fegin/153/basefrom
gh/fegin/153/head

Conversation

@fegin

@fegin fegin commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary
There are various CP implementations: allgather, ring attention, selective gather, ulysses, and more. The first three are sequence-sharded with different implementation optimizations, while ulysses is a sequence-sharded to head-sharded CP.

To properly support different implementations, we implement the replacement logic within TorchTitan's Config system -- based on the cp_method argument, the logic replaces the inner attention sharding config or even replaces the entire inner attention config. Examples of the former are the allgather-based CP (which we already have for FlexAttention) and the Ulysses CP introduced in this PR. Examples of the latter are selective gather and ring attention, which will come later.

This PR implements this logic and introduces Ulysses CP as an example to show how the replacement works.

GPT-OSS + Ulysses CP
Ulysses CP changes the Q, K, V sharding from S(1)@ CP to S(2)@ CP. However, GPT-OSS's attention sink is R@ CP, so this will result in a mismatch (apply_sink is in the local region so no resharding will happen). One quick (but wrong) solution is to change the attention sink to S(2)@ CP as well. This is wrong because FSDP expects all parameters to be R@DP and R@ CP. The spmd_types type check will error out.

We currently raise an NotImplementedError if Ulysses CP is used with GPT-OSS. Fixing this issue will be in a follow-up PR.

[ghstack-poisoned]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jul 24, 2026
@fegin
fegin requested a review from jinsooihm July 24, 2026 05:21
[ghstack-poisoned]
fegin added a commit that referenced this pull request Jul 24, 2026
**Summary**
There are various CP implementations: allgather, ring attention, selective gather, ulysses, and more. The first three are sequence-sharded with different implementation optimizations, while ulysses is a sequence-sharded to head-sharded CP.

To properly support different implementations, we implement the replacement logic within TorchTitan's Config system -- based on the cp_method argument, the logic replaces the inner attention sharding config or even replaces the entire inner attention config. Examples of the former are the allgather-based CP (which we already have for FlexAttention) and the Ulysses CP introduced in this PR. Examples of the latter are selective gather and ring attention, which will come later.

This PR implements this logic and introduces Ulysses CP as an example to show how the replacement works.

**GPT-OSS + Ulysses CP**
Ulysses CP changes the Q, K, V sharding from S(1)CP to S(2)CP. However, GPT-OSS's attention sink is R@CP, so this will result in a mismatch. One quick (but wrong) solution is to change the attention sink to S(2)CP as well. This is wrong because FSDP expects all parameters to be R@DP and R@CP. The spmd_types type check will error out.

We currently raise an NotImplementedError if Ulysses CP is used with GPT-OSS

ghstack-source-id: a1abe18
Pull-Request: #3978
NOTE: The passed-in model preferably should be on meta device. Otherwise,
the model must fit on GPU or CPU memory.
"""
validate_context_parallel(model, parallel_dims, parallelism)

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 can be done in Trainer.Config post_init at config time

@jinsooihm jinsooihm Jul 24, 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.

Wouldn't it be better to do it in the model's update_from_config? There is already a similar check here:

tp = parallelism.tensor_parallel_degree
attention = self.first_attention
if tp > 1 and attention is not None:
n_heads = attention.n_heads
n_kv_heads = getattr(attention, "n_kv_heads", None) or n_heads
if n_heads % tp != 0:
raise ValueError(
f"tensor_parallel_degree ({tp}) must divide "
f"n_heads ({n_heads})."
)
if n_kv_heads % tp != 0:
raise ValueError(
f"tensor_parallel_degree ({tp}) must divide "
f"n_kv_heads ({n_kv_heads})."
)

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.

Maybe a noob question, but why are there many models (llama3, deepseek v3, gpt_oss, qwen3) that call validate_config function in parallelize.py? It seems like that can also be moved to update_from_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.

we should, also I'm looking for a way to consolidate update_from_config and Trainer.Config.__post_init__

Comment on lines +211 to +216
context_parallel_method: Literal["allgather", "ulysses"] = "allgather"
"""
Context-parallel attention method:
- "allgather": sequence-shard Q, all-gather K/V (default behavior).
- "ulysses": head-shard via all-to-all around a standard attention kernel.
"""

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.

Right now it seems pure sharding config options, just like enable_sp or not on TP axis.

I'm a bit worried when we introduce other variants which config couldn't handle, thus requiring inner_attention replacement. In those cases, how should we do config? We talked about avoiding introducing strings in config, as it creates coupling -- every time we introduce a new feature, we need to update the options, and it won't be possible for people who extend torchtitan out-of-repo.

Alternatively, I think we can do a ModelConfigConverter which is essentially a "config pass", and swaps existing inner attention with CP-version of inner attention.

If that's the case, maybe we should have a default (e.g. all-gather) and let different CP be different ConfigConverters. Ulysses and any out-of-repo CP style can be achieved in consistent ways.

One could argue SP can also be achieved that way. I don't know, maybe SP vs. TP is canonical enough, but clearly people have more than two ways of doing CP.

@fegin fegin Jul 24, 2026 •

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.

I'm a bit worried when we introduce other variants which config couldn't handle, thus requiring inner_attention replacement.

As discussed in the summary, this is designed to achieve this goal. We will simply replace the inner_attention config. Right now the two methods just replace the inner_attention sharding config. But in the case you mention, we will 1) implement an inner attention module, e.g., SelectiveGatherInnerAttention 2) replace the inner attention with it.

and it won't be possible for people who extend torchtitan out-of-repo.

CP is a bit different from SP/TP because it is also coupled with dataloader (or trainer). So it is not easy to achieve out-of-repo modification for CP. So model config pass may not be enough for CP.

And isn't this the reason why you introduce override? Override can achieve the same thing.

Alternatively, I think we can do a ModelConfigConverter which is essentially a "config pass", and swaps existing inner attention with CP-version of inner attention.

What's the difference between ModelConfigConverter and override? Also, the core logic of this PR is just doing the config replacement. It's just that Ulysses only need replacing the sharding config, not the entire inner attention config.

I'm worried that there are too many ways for users and TorchTitan developers to replace config. We already used some config programming to replace the MoE dispatcher, but the replacement logic is purely config programming. This PR also does config programming but exposes the nob to CLI. override is one step more to consume external modules and perform pattern match replacement.

I actually think the best way (from my perspective) for users to do out-of-repo modification is to create their own model registries. They can do the truly config programming to replace any module configs they want.

@tianyu-l tianyu-l Jul 25, 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.

And isn't this the reason why you introduce override? Override can achieve the same thing.

What's the difference between ModelConfigConverter and override?

Latest thoughts on override:
One should only use override for two things

  1. you are not torchtitan team, but you want to pip install titan, and patch your modules and maybe publish a compatible library so that people can jointly pip install. E.g. you are a hardware vendor, with every titan release, you release a compatible package, making it fast on your hardware.
  2. you are torchtitan team, you are too tired of "people complaining about titan perf who're unwilling to do any kernel work", but as titan team member you have high bar on code quality / organization -- you are willing to patch some thing in to showcase perf but you don't want to maintain the code. Current torchtitan/overrides/ belong to this category.

We already used some config programming to replace the MoE dispatcher, but the replacement logic is purely config programming.

The current ModelConfigConverter is just a config space helper. I'm not opinionated about how people construct the eventual config (in model_registry or config_registry), but as a maintainer I have to have some way to constructing config and the current ways are convenient for me.

I actually think the best way (from my perspective) for users to do out-of-repo modification is to create their own model registries. They can do the truly config programming to replace any module configs they want.

Yes I agree. If you don't need to maintain torchtitan to support multiple models + multiple quantization + lora + CP, you can do it however you want.

So model config pass may not be enough for CP.

Like I said, it's just convenient for current use case. For CP with dataloader modifcation, we can have a TrainerConfigConverter -- it's just config programming util.

I'm worried that there are too many ways for users and TorchTitan developers to replace config.

As mentioned above, maybe all via *ConfigConverter as long as we agree on something. This is also the reason why I hesitate to agree with what this PR is doing, a.k.a.

Also, the core logic of this PR is just doing the config replacement. It's just that Ulysses only need replacing the sharding config, not the entire inner attention config.

I think for Ulysses it seems fine (given how similar it is to TP/SP). Could you share what's the plan for others, e.g. "ring"? My guess is that it'll be similar to quantization, for which we are doing ModelConfigConverter today but we could also have args in model_registry(..., linear_quantization_type, moe_quantization_type, ...).

Also I'm not yet convinced that it's helpful to expose context_parallel_methods \in ["allgather", "ulysses", "selective_gather", "ring"] to anyone who knows ParallelismConfig. This sounds information leakage.

This PR also does config programming but exposes the nob to CLI.

I think this is not that important

  • our quantization doesn't support CLI as well
  • if one really want CLI capability, they should build on top of torchtitan configs and expose higher level CLI options

head = SpmdLayout(
{DP: spmd.V, CP: spmd.V, TP: spmd.V},
partition_spec=(DP, None, (TP, CP), 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.

it's cool this is expressible

f"so n_heads ({n_heads}) and n_kv_heads ({n_kv_heads}) must both be "
f"divisible by tensor_parallel_degree * context_parallel_degree "
f"({tp} * {cp} = {div})."
)

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.

sorry, maybe dumb q, could you remind me why this doesn't work

fegin added a commit that referenced this pull request Aug 11, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* #3978
* __->__ #3977

**Summary**
Create a context_parallel package to contain different implementations
of CP.

Some planned CP implementations:
1. Ulysses style
2. Allgather-based VarlenCP (already have PRs). Allgather-based FlexCP
is already supported by the PyTorch API.
3. SelectiveGather

Pure refactor, no behavior change.
fegin added a commit that referenced this pull request Aug 17, 2026
…#4114)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* __->__ #4114

**TL;DR**

We plan to remove most CLI options, especially the options related to
models, optimization, and parallelism, in the future. All users should
use configuration programming to create their own `Trainer.Config`,
which can be done easily with a coding agent. If CLI is a must, users
can create their own CLI on top of the configuration system.

**Motivation**

There are several problems with the current configuration + CLI system.
The two major ones developers hit today:

1. `update_from_config`: some configurations can only be decided after
the CLI is parsed, so every model has to provide an `update_from_config`
to update the model configurations (e.g., sharding, optimization,
backends) from the "new" configurations coming out of the CLI. This path
is indirect and painful to maintain.

2. CLI option exposure: when developers add a new feature they have to
think about whether and how to expose the option, because the CLI is the
entry to expose a knob. This is further amplified by the first issue --
developers also need to understand how (or if) `update_from_config`
interacts with the new knob.

**Implementation**

`torchtitan_configs` is a package that lives outside the core torchtitan
folder and is installed by `pip install`. It is not going to contain all
use cases, because there are exponentially many combinations. It will
only contains the test configs and some golden configs we verify on
certain hardware. Users can put their own configs in this folder to
launch a job.

**Tentative Plan**

1. Introduce the torchtitan_configs package and freeze the CLI (this
PR): Users should launch with `MODULE=torchtitan_configs.tests
CONFIG=llama3_debugmodel_fsdp2_cp2 ./run_train.sh` and no further CLI
options. Replace "tests" and "llama3_debugmodel_fsdp2_cp2" to fit your
setting. To change options, change the configuration instead of
appending a CLI flag. The existing flags still work, but only for
backward compatibility; they are no longer the recommended way to
configure a run.

2. Move all the integration tests to use the new way to launch jobs. 

3. Demonstrate and document how to replace a module: With the future
removal of the CLI, using a different implementation/optimization is
done through config replacement. This step will document and demonstrate
how to achieve that. #3978 is
the tentative PR (still WIP).

4. Optimization composability: Now that optimizations are composed by
replacing configs, we need to make sure these optimizations still
compose. This needs more discussion and thought on the composability,
and on whether there is a composability issue at all. We also need to
understand if `input_dst_sharding` is still required.

5. Split `update_from_config`: It does three different things:
validation, derivation of the sharding configs, and the RoPE cache
resize. Move the validation to one place so that every model does not
need to implement its own, and leave the RoPE resize where it is. This
step does not change any CLI behavior.

6. Move the derivation into the configuration functions, which removes
the rest of `update_from_config`: The derivation reads
`--parallelism.enable_sequence_parallel` and
`--parallelism.expert_parallel_degree`, and the CLI can still change
them after the configuration function has run, so these two options have
to go first. This is why steps 5 and 6 come late: users need time to
move off these flags, and step 2 already removes the integration tests'
dependency on them. This is also a BC breaking step, both for the two
flags and for any out-of-repo model that implements its own
`update_from_config`.

7. Restructure configurations and trim CLI options and leave only the
necessary ones: This is a huge BC breaking step. Tentative proposal,
very early version, read this only if you are interested,
https://gist.github.com/fegin/276f0b6d3d7a80ae2573516b25917166
@fegin

fegin commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Close this in favor of #4322.

@fegin fegin closed this Sep 4, 2026
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.

4 participants