Skip to content

[Config][CP] Implement ModelTransform internface and use CP as the first example - #4322

Merged
fegin merged 10 commits into
mainfrom
gh/fegin/164/head
Sep 11, 2026
Merged

fegin merged 10 commits into
mainfrom
gh/fegin/164/head

Conversation

@fegin

@fegin fegin commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

  1. Implement ModelTransform interface .
  2. Rewrite the current CP:
    Move the K/V all-gather from local-map redistribution in Module.forward() into AllGatherCPFlexAttention. Add kernel selection and validation, then update CP recipes and tests.

All CP implementation will follow this approach.

fegin added 2 commits August 25, 2026 14:01
[ghstack-poisoned]
[ghstack-poisoned]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 25, 2026
@fegin fegin changed the title [CP] Move collectives into attention kernels [WIP][CP] Move collectives into attention kernels Aug 25, 2026
@fegin
fegin marked this pull request as ready for review August 25, 2026 22:42
@fegin
fegin requested review from jinsooihm and pianpwk August 25, 2026 22:42
_SEQ_DIM = 0


def use_cp_kernel(config: "Trainer.Config", kernel: type[Module]) -> 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.

Why would you take Trainer.Config, instead of just BaseModel.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.

trying to wrap my head around that this is kinda doing parallelize work, but not under parallelize, and has to be called separately

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.

There are two ways of creating a config

  • Like here, first create a base version and then apply transformation. But this is just a ModelConfigConverter, so if we follow this way, we should create a ModelConfigConverter
  • Instead of transformation, in the first place create the target. If we ban CLI parallelism change, we could have done this together with model_registry(attn_backend="flex", cp_backend="all-gather")

I like the latter slightly more, because with multiple converters we have to worry about the ordering of applications.

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.

First of all, for your example, separating attn_backend and cp_backend is an orthogonal discussion. I want make it clear so that we are not confused during the discussion; model converter can also achieve the same thing.

The major problem of ModelConfigConverter is not ordering but fusion. We can solve A->B->C by declaring the ordering somewhere. And model_registry doesn't escape this problem -- we write down the order in model_registry. The problem exists in both approaches with different solutions, but it is solvable.

The major issue of ModelConfigConverter is fusion,A(B()) or B(A()). What is the best way to do fusion is not clear to me. I haven't thought this clearly yet. And ordering must be designed in a force-able way such that people won't forget adding it.

The major issue of model_registry is the UX. The arguments of model_register is going to be complicated. For example, in the future, we need to support different attentions with different CP backends. These arguments need to be in model_registry's arguments and the complexity of arguments will inflate. model_registry become the central complexity.

So for me, ModelConfigConverter gives a better UX, but ordering (should be solvable but need more design than model_registry) and fusion are the two weak points of ModelConfigConverter.

model_registry makes solving ordering easier -- developers look at a central point to develop different optimization, we solve the ordering problem when developing a new transformation. But I don't like its UX.

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.

The major issue of ModelConfigConverter is fusion,A(B()) or B(A()). What is the best way to do fusion is not clear to me.

I didn't understand what is "fusion" here. Could you give an example?

These arguments need to be in model_registry's arguments and the complexity of arguments will inflate. model_registry become the central complexity.

Yes, I'm sure it will. See e.g. #4328

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Hi, weighing in since my opinion was asked (bias disclosure: I build my configs directly, so I've never needed these).

I'm not a big fan of the transformations because they need knowledge of the whole config to behave as expected. What if there's no attention module? What if it isn't where you'd expect? What if you want CP on only some layers (odd, I know)? The transformation has to rely on knowledge that may not even be available. And anything that changes on the config side now has to be ported to the transformations too.

In practice I use model_registry when a default config suffices, and build directly when I need something custom:

Trainer.Config(
    model=Decoder.Config(
        layers=[...],
        ...
    ),
    ...
)

When I need customization I write a function for it, one that takes parameters and returns a config, rather than one that edits a config that already exists.

This also answers the inflation worry: CP never needs to enter model_registry's signature. It's enough that the CP settings have their own config object, so it's discoverable how CP is configured.

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.

@francesco-bertolotti

I don't agree that today's model_registry is that useful. It is useful only because we added everything, e.g., tp_gemm_backend, moe_comm_backend to model_registry which we shouldn't - those options actually depend on Parallelism. So if you take those options out from model_registry, model_registry becomes a pure model definition function. And if users want to use it without any changes, it can be used with FSDP only case. For other cases, it is not enough -- with TP, you will want async TP, with CP, you will want different CP backends, with EP, you will want different MoE backends.

I do agree that directly building Trainer.Config can solve the problem. The question is it may be too verbose and hard for users to build. But with agent, I think this is one approach. Any of the proposal won't eliminate this approach.

And every solution need the certain contexts/knowledges, even the plain Trainer.Config solution.

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.

Our config is flexible enough that users can use it however they want, e.g.

  • [bottom-up] they can build all the way from bottom up, including the model itself inside Trainer.Config
  • [transform] build a default than transform it

For things in config_registry.py, I don't think they are part of the core repo anyway, and we probably should put in torchtitan_recipes/.

For model_registry, it's an intermediate layer of the lego. The biggest value is that it fixed OSS available arch, e.g. what qwen3.5 27B looks like -- this is regardless of TP / CP / MoE backend. As an OSS framework which can load HF weights, we need a way to do so. But because we are doing [bottom-up] in model_registry, we are sending CP backend / TP backend / MoE backend / Attn backend to choose building blocks.

Regarding when [transform] could be useful

  • when you need to make multiple changes for one feature, e.g. apply CP with load balancing would require dataloader change
  • without transform, you'd have to When I need customization I write a function for it, one that takes parameters and returns a config, which flavor-wise sounds like model_registry with inflated fields.

@fegin fegin Aug 28, 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.

https://gist.github.com/fegin/f1d667ead4fe13b95360821706b76564

@tianyu-l this is the current proposal. It includes a table that answer what belong to model_registry. The ordering part may be over-designed if there are no more transformation in the future.

cc., @jinsooihm @pianpwk

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.

left comments there

[ghstack-poisoned]
[ghstack-poisoned]
@fegin fegin changed the title [WIP][CP] Move collectives into attention kernels [CP] Move collectives into attention kernels Sep 3, 2026
@fegin
fegin requested review from jinsooihm and pianpwk September 3, 2026 21:18
Comment thread torchtitan/config/transform/apply.py Resolved
for _, traversed, _, _ in model.traverse(BaseAttention.Config):
# traverse returns the base config type.
attention = cast(BaseAttention.Config, traversed)
attention.inner_attention = retype_node(attention.inner_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.

I remember you mentioning that for Muse Glimmer, we could do Ulysess for global causal layer and selected gather for sliding window layer. Would one need to write a new ModelTransform class for that, or would this class be extended to handle such cases?

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.

Check line 26 of this file. That's the TODO.

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 am wondering if transform should take a function of type Module.Config -> Bool that a model provides that can conditionally apply retype_node, for ex, by looking at the sliding_window_size field. Then one can apply two transforms sequentially. But I guess that can make run_after and conflicts_with logic more complicated if transform can be parametrized.

[ghstack-poisoned]
@fegin fegin changed the title [CP] Move collectives into attention kernels [Config][CP] Implement Transform Protocol and Use CP as the First Example Sep 4, 2026
@fegin fegin changed the title [Config][CP] Implement Transform Protocol and Use CP as the First Example [Config][CP] Implement ModelTransform internface and use CP as the first example Sep 4, 2026
Comment thread torchtitan/transforms/README.md Outdated
Comment on lines +44 to +45
Needing training settings for validation does not make an option a transform.
For example, the attention backend still belongs in `model_registry`.

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.

didn't understand this sentence, why attention backend couldn't be a model transform here?

@fegin fegin Sep 8, 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.

Attention kernel selection is more related to algorithm and metadata selection. For example, you can only use Flex but not varlen for a certain attention. I agree that you can use transform for attention backend. But this is more design choice -- the base model definition is defined by the model_registry.

However, you can also argue that LoRA also changes the model. So I have to admit the line here is not clearly drew.

Comment thread torchtitan/trainer.py Outdated

# Validate features that span config sections once model_spec is set.
if self.model_spec is not None:
validate_context_parallel(self.model_spec.model, self.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.

maybe validate_context_parallel should live here? similar to other _validate functions 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.

I personally would like to make trainer.py succinct by moving validation logic to other files, so this particular function matches my goal, compared with making more self._validate_xyz() functions

On the other hand, I also feel it's scattered too much if

  • every component owns a validate.py file
  • cross component validation ownership is not clear

So how about creating a dedicated validate.py file under some folder, say torchtitan/config/, which holds all the validation functions?

@acisseJZhong acisseJZhong Sep 6, 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.

creating a dedicated validate.py file under some folder, say torchtitan/config/, which holds all the validation functions?

I feel this is no difference from putting all validation logic here. We could hypothetically just have a huge validate funciton that contains all the validations in this file.

every component owns a validate.py file

I think this is a good idea, like what already did for CP validation.py. For cross component validation, maybe we can duplicate in both files?

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.

every component owns a validate.py file

I still prefer keeping distributed/context_parallel/validation.py. So I prefer each component owns a validation.py file. The rules are CP-specific while Trainer.Config is the first object that owns the required information. So it is owned by CP but called here. This clarifies the ownership and caller.

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.

so, "what if" CP and quantization has composability issues, even if temporary, who owns the validation?

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.

Depending on which component introduces the composability issue, that component should valid the case. This is not unique to validation -- the transform/convert/pass has the problem as well. If one transform cannot work with another one, we can directly add conflict_with,. If one transform must be after another one (ensure the dtype or something), then the order must be enforced. And the validation should follow, the component that introduces the issue validate the result.

@tianyu-l tianyu-l Sep 8, 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.

It sounds like this introducing a DAG among validate.py in the codebase (expecting import issues, lol), with arrow directions defined by "the component that introduces the issue validate the result" which won't always be 100% clear, although I don't have examples at hand. What could be worse is that they stay decentralized so even agents need to look at the entire codebase to construct the DAG.

edit: not DAG, could have cycles

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 think I confused myself. So we agreed that validation should be done in each component's __post_init__, but cross validation should be in the lowest ancestor component which can access all the required configs. So in this case validate_context_parallel should live in Trainer.Config.__post_init__. But since we don't want to put everything in trainer.py and want to have validation.py, it should be put in config/validation.py.

I'll do the change. But the local validation still live in its own __post_init__ If we feel that is too scattered, we can later centralize them.

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.

sounds great

Comment thread torchtitan/trainer.py Outdated
Comment on lines +129 to +130
# Validate features that span config sections once model_spec is set.
if self.model_spec is not 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.

should always be not None

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.

No, it is not. model_spec is always valid when Trainer is already constructed but not Trainer.Config. We may construct Trainer.Config first without model_spec. It may be from a test code only but it is not the case. We can add a TODO to remove this and change the typing, but not in this PR.

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'll refactor this.

Comment thread torchtitan/trainer.py Outdated

# Validate features that span config sections once model_spec is set.
if self.model_spec is not None:
validate_context_parallel(self.model_spec.model, self.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.

I personally would like to make trainer.py succinct by moving validation logic to other files, so this particular function matches my goal, compared with making more self._validate_xyz() functions

On the other hand, I also feel it's scattered too much if

  • every component owns a validate.py file
  • cross component validation ownership is not clear

So how about creating a dedicated validate.py file under some folder, say torchtitan/config/, which holds all the validation functions?

Comment thread torchtitan/transforms/base.py Outdated
__all__ = ["ModelTransform", "retype_node"]


class ModelTransform(ABC):

@tianyu-l tianyu-l Sep 5, 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.

question 1: Instead of transform model, it's transforming model config -- should we call it ModelConfigTransform? Also, I feel this is similar to graph "passes", they are just "config passes" -- should we align the term with graph concepts?

question 2: what if later we need trainer level transform, do we rename this and generalize this, or do we have another transform abstraction?

question 3: Shall we deprecate ModelConfigConverter https://github.com/pytorch/torchtitan/blob/main/torchtitan/protocols/model.py#L19 which almost does the same thing? Can we rename and reuse it instead of creating something separate but similar? The main difference seems that ModelConfigConverter is a configurable which requires build before usage, but ModelTransform itself is a dataclass and can apply transform directly which makes sense.

@acisseJZhong acisseJZhong Sep 6, 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.

what is the main motivation for us to move from ModelConfigConverter to ModelConfigTransform?

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.

  1. ModelConfigTransform is clear. The current design only performs the config rewrite, so transform is a close term. To me, pass is a self-contained term that includes both analysis, rewrite, and validation. Since our validation is done in another place, Transform semantics is more close from my perspective. Just my opinion.
  2. I prefer to a base ConfigTransform + TranerConfigTransform
  3. Yes. That's the plan. As for why don't we just improve ModelConfigConvert? Mostly just for BC, I don't want to disrupt the users. We can of course just improve the the existing ModelConfigConvert but this may make the transition harder.

Comment thread torchtitan/models/common/attention.py Resolved
"""Mixin for attention kernels that own their CP collectives."""

@property
def cp_group(self) -> dist.ProcessGroup:

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 feel this should be a spmd_types utils rather than CP kernel util.

Also in linear attention, InnerXYZAttention is reserved for "conv" + "kernel", as the replacement boundary for vllm inference. So CPKernel is conflicting with that in naming. Maybe we can call this CPInnerAttention since that's the replacement target?

Given these two reasons, I feel this abstraction is less necessary.

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.

Sure, if you prefer, we can move cp_group to spmd_types utils.

return cp_group


class AllGatherCPFlexAttention(ContextParallelKernel, FlexAttention):

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.

should mention "all-gather KV"? E.g. technically I could all-gather Q

them.
"""

kernel: type[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.

similar -- kernel is ambiguous

Comment thread torchtitan/config/transform/base.py Resolved
Comment thread torchtitan/transforms/apply.py Outdated
__all__ = ["apply_transforms", "transform_model"]


def _ordered(transforms: list[ModelTransform]) -> list[ModelTransform]:

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.

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.

Yes, same as the ModelConverter argument, which we will just have one eventually.

Comment thread torchtitan/config/transform/__init__.py Resolved
@QIU023 QIU023 mentioned this pull request Sep 8, 2026
14 of 18 tasks
[ghstack-poisoned]
[ghstack-poisoned]
Comment thread torchtitan/config/transform/apply.py Outdated
)


def transform_model_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.

should we do

Suggested change
def transform_model_config(
def transform_model_config_(

Comment thread torchtitan/distributed/spmd_types.py Outdated
return mesh.size(names.index(axis_name))


def require_spmd_mesh_axis_group(

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.

why not

Suggested change
def require_spmd_mesh_axis_group(
def get_spmd_mesh_axis_group(

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.

prepare_context_parallel_input,
)

batch: dict[str, Any] = dict(input_dict)

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.

separate topic: maybe should rename this to dp_local_microbatch

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.

Not sure about this, microbatch means either gradient accumulation or PP are used. But with a smaller scale, users may use neither.

) -> dict[str, Any]:
from torchtitan.models.common.cp_attention import CPInnerAttention

inner_attention = self.config.first_full_attention_backend

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 it true that today, regardless of

  • if FlexAttention is used for both full and sliding window
  • there could be linear attn layers

We are all using the same load balancing algo? I wonder if we should introduce cost function for each Inner(Linear)Attn instance so that our (DP / CP) load balancer can make decision on top of that.

cc @acisseJZhong @jinsooihm @wwwjn

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.

does the load balancer also need to know number of full attn/linear attn layers to calculate the load?

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.

For Muse Glimmer that has full and sliding window, you can choose which mask to balance make the balance decision #3972. It turns out adding the cost of sliding window does not change the PTRR load balancing decision because it only considers the relative order of the costs. So we can just use the mask for the full layer to load balance.

But for more complicated load balancing algorithms, it could be helpful to know the cost for each layer and the ratio between full and linear attention.

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.

@jinsooihm has a nice proof (iirc, lol) that shows at least for full and sliding window, PTRR will get the best result by just looking into the full attention.

But I do agree this needs some design and how the interface should be. I haven't had time to actually think about this. It is also related to #4500 (comment)
cc., @drisspg

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.

Another use case for the cost function could come from actual profiling rather than the estimates we may derive from the attention masks, linear/quadratic attention, etc.

Comment thread torchtitan/config/transform/base.py Outdated
"""


def retype_node(existing: Module.Config, replacement: type[Module]) -> 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.

retype doesn't sound a word and there is no official "node" concept, would you please try another name. How about cast_type or cast_config_type?

parallel_dims.get_mesh("cp"),
parallelism.context_parallel_load_balancer,
parallelism.context_parallel_ptrr_mask_key,
batch = self._cp_shard_inputs(

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.

can we use sth like self.inner_attention.cp_shard_inputs, where each inner attention should have it's own shard function?

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 this needs more careful design. Currently the input is sharded once and used consistently across all layers. Who'd be responsible for generating such a plan? I personally think we should have a LoadBalancer (which works for DP as well) concept which takes the whole model config, and can be used to make CP shard decision, RL batching decision, and potentially pretraining DP sharding decision.

@anijain2305
anijain2305 self-requested a review September 10, 2026 00:12
acisseJZhong pushed a commit to acisseJZhong/torchtitan that referenced this pull request Sep 11, 2026
Add config transforms and use one to install CP attention. Validate CP against the transformed model config.

ghstack-source-id: 9881a43
Pull-Request: pytorch#4322
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@fegin
fegin changed the base branch from gh/fegin/164/base to main September 11, 2026 17:06
@fegin
fegin merged commit 31fbb62 into main Sep 11, 2026
9 checks passed
fegin added a commit that referenced this pull request Sep 11, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* #4459
* #4450
* #4533
* __->__ #4449
* #4322

Switch to use `spmd_types.redistribute` instead of using
`flex_cp_allgather`.

The backward of the gather is a reduce-scatter, and the API requires an
explicit dtype for it under reduced precision.
`AllGatherCPFlexAttention.Config.reduce_dtype` exposes that choice. It
defaults to None, which keeps the reduction in the input dtype and so
matches `flex_cp_allgather`. Set it to float32 to trade two casts for
accuracy, which matters as the CP degree grows and the reduce-scatter
sums more contributions.

**Numerics Verification**

Loss and grad_norm are bitwise identical before and after, with the
default `reduce_dtype`. `scripts/loss_compare.py` over
`llama3_debugmodel_fsdp2_cp2` (FSDP 2 + CP 2, 4 H100s, spmd_types, bf16
params), shared seed checkpoint, `--debug.seed=42
--debug.deterministic`, 10 steps, values read from the TensorBoard
scalars:

    metric     max |before - after|
    loss       0.0
    grad_norm  0.0

Step 1 loss is 8.048094749450684 on both sides and step 10 is
4.038208961486816. `--assert-equal` passed for both metrics.
wwwjn added a commit that referenced this pull request Sep 15, 2026
## Summary

- restore CIFlow tag routing so stacked PRs are tested independently of
their base branch
- automatically apply `ciflow/fake-pg` only to ready, non-draft PRs with
relevant code or test changes
- use each `ciflow/fake-pg/*` tag to run both broad 1-GPU Fake PG
coverage and the 8-GPU `real_pg_required` subset
- add `ciflow/real-pg` as the opt-in trigger for the full 8-GPU Real PG
suite
- document the integration-test cadence and reusable `execution_mode`
input

## Why

**The historical `ciflow/8gpu` label and moving tag allowed integration
CI to run on stacked PRs whose base was not `main`**. After that label
was repurposed as an opt-in full-suite trigger, stacked PRs could miss
required integration coverage. PR #4322 exposed this gap: its PR checks
passed, but five model configurations failed immediately after landing
on `main`.

This change separates the two responsibilities:

- `ciflow/fake-pg` is automatically managed and triggers both Fake PG
coverage and the `real_pg_required` Real PG subset for normal and
stacked PRs.
- `ciflow/real-pg` is manually applied when the full 8-GPU suite is
desired before landing.

The full Real PG suite continues to run after pushes to `main`, on
schedule, and through manual or Real PG reusable workflow invocations.

Failing post-merge run:
https://github.com/pytorch/torchtitan/actions/runs/34625822895/job/103350597237

## Testing

- changed-file pre-commit hooks pass
- all modified workflow and Probot configuration files parse as valid
YAML
- verified the event routing conditions for Fake PG tags (Fake PG plus
the Real PG required subset), Real PG tags, main pushes, schedules,
manual dispatches, and reusable workflow calls
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

6 participants