Skip to content

[CP] Decouple input and metadata sharding with configurable CP load balancer - #4617

Merged
acisseJZhong merged 3 commits into
mainfrom
refactor_cp_shard
Sep 27, 2026
Merged

acisseJZhong merged 3 commits into
mainfrom
refactor_cp_shard

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Represent context-parallel load balancing as one explicit per-batch token
    permutation shared by model inputs and attention metadata. Head-tail and
    PTRR generate permutations; None is reserved for Ulysses.
  • Replace ContextParallelPartitioner and private PyTorch CP sharding helpers
    with TorchTitan shard_inputs(), which applies the permutation and shards
    declared tensors with spmd.shard().
  • Let each CP attention backend prepare the metadata required by its own
    communication algorithm. K/V all-gather builds a query-sharded BlockMask,
    while Ulysses keeps metadata global.
  • Resolve the CP group, rank, size, and device from the active SPMD context
    instead of threading DeviceMesh through model and trainer APIs.
  • Share the resulting preprocessing flow across decoder models, Flux, graph
    trainer, and the Transformers backend: build metadata -> generate the
    permutation -> prepare backend metadata -> shard inputs -> annotate SPMD
    types.

Design: review discussion and Context Parallel Permutation Refactor Plan

Testing

  • pytest -q tests/unit_tests/cpu/test_cp_attention.py torchtitan/experiments/transformers_modeling_backend/tests/test_hf_build_forward_inputs.py (33 passed, 2 subtests passed)

Deterministic parent-vs-PR comparisons used seed=42 and 10 training steps. All used a shared seed checkpoint except the Transformers backend row, which used identical deterministic initialization. Values were read at full precision from TensorBoard.

Configuration GPUs Loss diff Grad norm diff
Llama 3 all-gather CP 4 0 at every step 0 at every step
Llama 3 Ulysses CP 2 0 at every step 0 at every step
Flux HSDP 2x2 + CP=2 with validation 8 0 at every step 0 at every step
DeepSeek V3 MoE FSDP2 + TP2 + CP2 + EP8 8 0 at every step 0 at every step
Qwen3 MoE param groups FSDP2 + TP2 + CP2 + EP8 8 0 at every step 0 at every step
Transformers backend MoE FSDP + TP + EP + CP (PTRR) 8 0 at every step 0 at every step

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 12, 2026
@acisseJZhong
acisseJZhong force-pushed the refactor_cp_shard branch 5 times, most recently from e08744e to 3219338 Compare September 13, 2026 00:02
@acisseJZhong acisseJZhong changed the title [do not review][CP]refactor cp shard metadata and shard input [CP]decouple cp shard metadata and shard input Sep 13, 2026
@acisseJZhong
acisseJZhong marked this pull request as ready for review September 13, 2026 00:22
Comment on lines +81 to +98
if isinstance(attention_masks, BlockMask):
block_masks = [attention_masks]
block_mask_keys = None
elif isinstance(attention_masks, Mapping):
block_mask_dict = {
key: mask
for key, mask in attention_masks.items()
if isinstance(mask, BlockMask)
}
if not block_mask_dict:
return input_dict
block_masks = list(block_mask_dict.values())
block_mask_keys = block_mask_dict.keys()
else:
raise ValueError(
"K/V all-gather context parallelism requires BlockMask metadata, "
f"but got {type(attention_masks).__name__}."
)

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 probably should use some efficient tree_map, instead of many if-else

Comment thread torchtitan/models/common/decoder.py Outdated
Comment on lines +333 to +337
batch = self._prepare_context_parallel_batch(
batch,
input_sharding,
parallel_dims.get_mesh("cp"),
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.

Let's avoid using "batch". After all here you are preparing 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.

maybe we should change together with #4649? depending on the landing order, if your PR lands first, I will update mine.

Comment on lines 46 to 47
load_balancer_type: str | None = "headtail",
input_seq_dims: int | tuple[int, ...] = 0,
ptrr_mask_key: str | None = 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.

This is very fragile. I think we should instead

  • have a LoadBalancer / CPLoadBalancer as Configurable and can build from configs; maybe it can be put under trainer.parallelism.
  • decoder's preprocess_inputs will build it based on inputs, and then it owns shard / cp_shard method to shard the inputs, including tensors and attention metadata -- if you use something like PTRR you need to build it every iteration.
  • RL batcher should use it similarly

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 can have a CPLoadBalancer class. But why do you suggest that putting it into trainer.parallelism? Even if a folder is too much for context parallel, we should still put it into context_parallel.py, like cudagraph.py. Are you suggesting this because of unifying DP and CP load balancing?

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 you are mixing two things. Here I'm not talking about file organization; instead, I'm talking about config nesting. I actually don't know what's the best place to put this LoadBalancer.Config. It feels half dataloader, half parallelism.

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

have a LoadBalancer / CPLoadBalancer as Configurable and can build from configs; maybe it can be put under trainer.parallelism.

let's follow up on this as a separate PR? as this PR mainly just reorganize things.

decoder's preprocess_inputs will build it based on inputs, and then it owns shard / cp_shard method to shard the inputs, including tensors and attention metadata -- if you use something like PTRR you need to build it every iteration.

after this PR, each attention backend will own it's cp_shard_metadata(attn_masks), and decoder only shards input tokens.

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.

Introducing LoadBalancer as Configurable is "reorganizing things".

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 actually don't know what's the best place to put this LoadBalancer.Config. It feels half dataloader, half parallelism.

If we eventually want to combine DP and CP load balancing, I feel put it into dataloader seems to be a better choice, but this will have to expose the attention structures to the dataloader, which I don't like very much.

For now, trainer.parallelism seems to be the right place given that we don't have DP load balancer yet.

cc., @jinsooihm

return load_balancer


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

Do you mean cp_shard_tensors. However, I think after we have the load balancer, we don't need this file or this method.

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 do need a cp_shard method to shard the inputs even with a LoadBalancer class. What do you mean we don't need a method?

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.

Nvm, I saw you propose to move cp_shard to LoadBalancer

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.

sorry didn't get this, we still need cp_shard_metadata for each attn backend even if we move cp_shard_inputs to LoadBalancer right?

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.

yes, load balancer's cp_shard will call into whatever functions it needs to

return load_balancer


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

We do need a cp_shard method to shard the inputs even with a LoadBalancer class. What do you mean we don't need a method?

return load_balancer


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

Nvm, I saw you propose to move cp_shard to LoadBalancer

Comment on lines 46 to 47
load_balancer_type: str | None = "headtail",
input_seq_dims: int | tuple[int, ...] = 0,
ptrr_mask_key: str | None = 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.

We can have a CPLoadBalancer class. But why do you suggest that putting it into trainer.parallelism? Even if a folder is too much for context parallel, we should still put it into context_parallel.py, like cudagraph.py. Are you suggesting this because of unifying DP and CP load balancing?

from torchtitan.distributed.spmd_types import _per_axis_types
from torchtitan.models.common.attention import AttentionMasksType

ContextParallelLoadBalancer = _LoadBalancer | 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.

If we are going to have a CPLoadBalancer idea, we should have a default LoadBalancer which perform no load balancing, then we can keep the UX the same.

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.

LoadBalancer is responsible for sharding, so to me it'd be

  • None: don't shard
  • DefaultLoadBalancer / NoLoadBalancer: naive sharding

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

When CP is on, the inputs have to be sharded regardless of the CP inner kernel (e.g., allgather, ulysses). So it is always NoLoadBalancer for Flux. ContextParallelLoadBalancer = _LoadBalancer | None shouldn't be a valid typing but ContextParallelLoadBalancer | None should be used.

But I think we may not need ContextParallelLoadBalancer = _LoadBalancer | None if we make load balancer to be a configure, not sure about this stement.

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.

hmm, I don't think you answered this question #4617 (comment)

When I was saying None, I was referring to the case when CP degree == 1.

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.

yes, None is CP degree ==1 case, which I agree.

I was saying that None should be a part of ContextParallelLoadBalancer but the typing should be more like load_balancer: ContextParallelLoadBalancer | None = None. The second paragraph of my reply is incorrect.

As for the question, I guess you are referring to the where to put this class. I replied in that thread.

@acisseJZhong
acisseJZhong force-pushed the refactor_cp_shard branch 3 times, most recently from 088766f to 4a4147f Compare September 15, 2026 08:42
Comment thread torchtitan/config/configs.py Outdated


@dataclass(kw_only=True, slots=True)
class ContextParallelLoadBalancerConfig(Configurable.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.

why don't we create a LoadBalancer as configurable, so that it becomes extensible? This is still hardcoding. You should have HeadTail load balancer and PTRRLoadBalancer.

@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Sep 15, 2026
@acisseJZhong
acisseJZhong force-pushed the refactor_cp_shard branch 3 times, most recently from e34ea58 to db45abd Compare September 15, 2026 23:13

Model inputs are sharded before the attention backend is selected. Each CP
backend then handles only the metadata required by its attention layout,
using the same per-batch load balancer that sharded the model 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.

This is the right description, but it also lacks the description that each subclass should implement its own algorithm. This description looks like the CPInnerAttention only performs the metadata sharding, which is not correct.

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.

yeah that's true, updated the doc string. Each CPInnerAttention should impl forward and cp_shard_metadata.

class Config(ContextParallelLoadBalancerConfig):
"""Configuration for PTRR context-parallel load balancing."""

mask_key: Annotated[str | None, tyro.conf.Suppress] = 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 do you need to do tyro.conf.Suppress here? If you do tyro.conf.Suppress of the load balancer in the decoder parallelism config, all the sub-config should be suppressed.

Comment thread torchtitan/config/configs.py Resolved
Comment thread torchtitan/config/manager.py Outdated
Comment on lines +238 to +241
@registry.primitive_rule
def context_parallel_load_balancer_rule(
type_info: tyro.constructors.PrimitiveTypeInfo,
):

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 are deprecating CLI, so if this is for the existing CLI usage, you can delete it. Any new changes should consider configuration-only use cases. So if we break CLI usage, that is the intention to gradually force users to avoid using CLI.

Comment thread torchtitan/config/configs.py Outdated
Comment on lines +129 to +136
@dataclass(kw_only=True, slots=True)
class LoadBalancerConfig(Configurable.Config):
"""Base configuration for load-balancing strategies."""


@dataclass(kw_only=True, slots=True)
class ContextParallelLoadBalancerConfig(LoadBalancerConfig):
"""Configuration for the default contiguous context-parallel partition."""

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 are these two classes defined here? Is it because if we put them in context_paralle/api.py, there will be a circular import?

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 exactly. This is because in this configs.py we need to have ContextParallelLoadBalancerConfig. If I put it in context_paralle/api.py, it will have circular import. I couldn't think of better ways.

Comment on lines +85 to +87
input_dict: dict[str, Any],
input_shardings: dict[str, SpmdType] | None,
cp_mesh: DeviceMesh,

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.

Let's not pass these arguments into the constructor. See the reasoning below.

Comment on lines +113 to +120
def _build_load_balancer_impl(
self,
*,
input_dict: dict[str, Any],
seq_len: int,
) -> _LoadBalancer | None:
del input_dict, seq_len
return 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.

shard_inputs has the input_dict so it should be shard_inputs which calls this and this should be an abc.abstractmethod, so you don't need to implement the detail, which is not used. _load_balancer_impl is lazily initialized when shard_input is called.

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.

enforced _build_load_balancer_impl to be an abstractmethod, and created another class _ContiguousLoadBalancer for conguous sharding / None.

Comment on lines +91 to +107
self._shard_dims = (
_cp_shard_dims(input_shardings)
if input_shardings is not None
else {"input": 0, "labels": 0, "positions": 0}
)
self._shard_names = tuple(
name
for name in self._shard_dims
if isinstance(input_dict.get(name), torch.Tensor)
)
self._load_balancer_impl: _LoadBalancer | None = None
if not self._shard_names:
return
first_name = self._shard_names[0]
seq_len = cast(torch.Tensor, input_dict[first_name]).size(
self._shard_dims[first_name]
)

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.

seq_len can be directly get through input_dict["input"] if you call _build_load_balancer_impl in shard_inputs, which assume the existence of input. Or we can let the caller (decoder) pass the seq_len if that makes the contract cleaner.

permutation: torch.Tensor | None,
) -> _GlobalContextMetadataT:
"""Keep context metadata global under Ulysses CP."""
del cp_mesh, permutation

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

raise should not be supported

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 this will be hit as in decoder we are calling owner.prepare_cp_metadata on every CPInnerAttention. So this prepare _cp_metadata should be no op instead of raising runtime error.

Another option is to introduce one more base class except CPInnerAttention and let Ulysses inherit that to indicate no metadata sharding. But I think that's adding to much.

)
# Mapping (not dict) lets covariant value types accept dictionaries containing
# one or more BlockMasks. A None value marks an unused mask.
FlexAttentionMetadata = Mapping[str, BlockMask] | BlockMask

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.

follow up in another PR: define map of attn backend class <-> attention metadata class

no VarlenAttentionMetadata = VarlenMetadata

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.

add TODO

@acisseJZhong
acisseJZhong marked this pull request as draft September 25, 2026 22:21
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Sep 25, 2026
@acisseJZhong
acisseJZhong force-pushed the refactor_cp_shard branch 2 times, most recently from 0e472d3 to 0b420c9 Compare September 25, 2026 23:44
@acisseJZhong
acisseJZhong marked this pull request as ready for review September 25, 2026 23:45
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Sep 25, 2026
Comment thread torchtitan/config/configs.py Outdated
Comment on lines 32 to 33
FSDPSymmMemScope: TypeAlias = Literal["all", "dense", None]
_FSDP_SYMM_MEM_SCOPES = get_args(FSDPSymmMemScope)

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.

belong to the parallelism file?

Comment thread torchtitan/config/parallelism.py Outdated

context_parallel_load_balancer: Annotated[
ContextParallelLoadBalancer.Config | None, tyro.conf.Suppress
] = field(default_factory=HeadTailCPLoadBalancer.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 allow None? I guess it's for Ulysses. Then default should be 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.

why do we want to default to None? I am honoring the old behavior which default to headtail.

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.

making behavior explicit -- e.g. why we default to head-tail when doing Ulysses

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, defaulting to None will change the golden loss.

config: Config,
*,
seq_len: int,
context_metadata: AttentionMasksType | 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.

Suggested change
context_metadata: AttentionMasksType | None,
attention_metadata: AttentionMasksType | None,

return tensor


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

should be

Suggested change
def shard_inputs(
def shard_tensors(

as metadata is also model inputs?

)
# Mapping (not dict) lets covariant value types accept dictionaries containing
# one or more BlockMasks. A None value marks an unused mask.
FlexAttentionMetadata = Mapping[str, BlockMask] | BlockMask

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.

add TODO

Comment thread torchtitan/models/common/decoder.py Outdated
return inputs, labels, batch

def _cp_shard_inputs(
def _prepare_cp_batch(

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.

Suggested change
def _prepare_cp_batch(
def _cp_shard(

Comment thread torchtitan/models/common/decoder.py Outdated
permutation=permutation,
)

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

prefer not having this as a separate function in Decoder

Comment thread torchtitan/models/README.md Outdated
- `BaseModel.parallelize()` applies declarative model parallelism, activation checkpointing, `torch.compile`, and FSDP/HSDP in order.
- Override `parallelize()` only when the model needs a different lifecycle order, and override `_apply_fsdp()` when it has a model-family-specific FSDP structure.
- Language-model CP goes through `Decoder.preprocess_inputs` -> `prepare_context_parallel_input`.
- Language-model CP goes through `Decoder.preprocess_inputs` -> `context_parallel.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.

not enough? also 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.

consider doing the same for every config in this file and remove this file

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, as there are only four configs. I will do this in next PR.

Comment thread torchtitan/components/validate.py Outdated
Comment on lines +219 to +220
with dist_utils.get_spmd_context(parallel_dims=self.parallel_dims):
for input_dict in microbatch_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.

order can be switched? only preprocess_inputs need context

@tianyu-l tianyu-l left a comment

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.

related:
https://github.com/pytorch/torchtitan/blob/main/torchtitan/training_engine.py#L147
the factor of 2 should only apply to head-tail balancer, aka the check should be determined by CP attention backend

contiguous sharding. Ulysses requires None.
"""

def __post_init__(self):

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.

put this after all fields?

Comment thread torchtitan/models/muse_glimmer/model.py Outdated
if parallel_dims.cp_enabled:
batch = self._cp_shard_inputs(
batch, input_sharding, parallel_dims, parallelism
batch = self._cp_shard(

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.

let's replace this term for every model

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.

all the models have changed to _cp_shard?

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.

don't use "batch"

Comment on lines +270 to +277
@staticmethod
def prepare_cp_metadata(
attention_metadata: _GlobalAttentionMetadataT,
*,
permutation: torch.Tensor | None,
) -> _GlobalAttentionMetadataT:
del permutation
return attention_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.

raise dead end error

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

right now in decoder it will still call into Ulysses's prepare_cp_metadata, I will need to add some check in decoder to skip UlyssesCPInnerAttention if we want to raise Runtime error here.

personally I think it's fine to directly return here? as it just indicates Ulysses does nothing to its attn metadata. It's a little bit weird if we add UlyssesCPInnerAttention check outside?

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.

makes sense

@acisseJZhong
acisseJZhong force-pushed the refactor_cp_shard branch 2 times, most recently from fb5d938 to 700a65d Compare September 26, 2026 21:32
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

related:
https://github.com/pytorch/torchtitan/blob/main/torchtitan/training_engine.py#L147
the factor of 2 should only apply to head-tail balancer, aka the check should be determined by CP attention backend

  • Head-tail: divisible by both 2 * CP and CP * SP.
  • PTRR or contiguous: divisible by CP * SP.

I believe the previous 2 * CP * SP is unnecessarily restrictive.

@acisseJZhong
acisseJZhong merged commit f359667 into main Sep 27, 2026
26 checks passed
acisseJZhong added a commit that referenced this pull request Sep 30, 2026
## Summary

Update the A10G Real PG Llama 3 numerics golden after #4617 changed the
default CP input sharding from head-tail to contiguous sharding.

The full-precision loss and grad-norm values were extracted from the
artifacts of the failing scheduled main run:

https://github.com/pytorch/torchtitan/actions/runs/36610567412/job/109550670049

Both `llama3_fsdp+tp+cp` and `llama3_fsdp+tp+cp+region_ac` produced
identical metrics and continue to share this golden file.

## Testing

- Compared all 10 loss and grad-norm steps from the `llama3_fsdp+tp+cp`
TensorBoard artifact with the updated golden using
`scripts/loss_compare.py` helpers
- Repeated the comparison for `llama3_fsdp+tp+cp+region_ac`
- `pre-commit run --files tests/assets/losses/real_pg/a10g/llama3.txt`
meta-codesync Bot pushed a commit to meta-pytorch/flex_shard that referenced this pull request Oct 8, 2026
…anges

Summary:
Recent TorchTitan syncs changed several APIs that `experiments/fb/flex_shard` depends on, so `flex_shard_tests` now fails at import time (`unittest` `loadTestsFromName` ImportError). This diff moves the fb FlexShard code to the new APIs, fixes the EP>1 DistMuon break from #4419, and ports the Qwen3 recipe.

- pytorch/torchtitan#4904 (optimizer config refactor): `build_dist_muon(...)` is replaced by the `DistMuon(...)` class, which takes the same arguments. `comm_free_adapter.build_local_dist_muon` now constructs `DistMuon` directly.
- pytorch/torchtitan#4660 (`components.optimizer` -> `components.optim`, `Trainer.Config.optim`):
  - Imports now come from `torchtitan.components.optim`.
  - DSV3 Muon configs set `config.optim.optimizer`.
  - `FlexShardDistMuonOptimizers` accepts the new `enable_cuda_graph` kwarg. It raises if the flag is set, the same way upstream `OptimizersContainer` rejects optimizers that can't be captured.
  - `_log_optimizer` now takes a pattern string.
- pytorch/torchtitan#4617: `ParallelismConfig` now lives in `torchtitan.config.parallelism`.
- pytorch/torchtitan#4905:
  - `ParallelDims` is now `ParallelismContext`, and the `parallel_dims=` kwarg is now `parallelism_context=`.
  - `get_spmd_context(...)` is replaced by `parallelism_context.activate_spmd()`.
  - The `efsdp` mesh axis is now `edp_shard`. This also covers the `partition_rank_axis_name` passed to the DistMuon bucket planner.
  - Tests build the context with `ParallelismContext.from_config(config, DistributedTopology(world_size=...))`.
- pytorch/torchtitan#4840: `BlockShard(block_size=R)` is now `BlockShard(block_sizes=(R,))`.
- pytorch/torchtitan#4878: the DSV3 `model_registry` now requires `enable_sp`. The FlexShard wrapper passes `enable_sp=False`. FlexShard rejects TP, and `False` keeps the shared-expert `w2` as a plain `Linear`, as it was before #4878.
- pytorch/torchtitan#4419 (EP without DTensor): `Module._parallelize` now leaves EP-sharded routed experts as plain local `nn.Parameter` shards. It records their layouts in each module's `_sharding_config` instead of returning DTensors. With EP>1, DistMuon failed with "Partitioned block parameters must be DTensors", and `dtensor_to_global_layout` no longer found anything to declare.
  - flex_shard `dist_muon/placement.py` and `storage_layout.py` now read the FlexShard `GlobalLayout` contract (`get_global_layout`) instead of DTensor placements. `get_dim0_block_partitions` no longer takes `partition_axis_name`.
  - The new `experiments/fb/flex_shard/spmd_layouts.py` `declare_spmd_global_layouts(model, mesh)` collects `_sharding_config.state_shardings` and declares them through `spmd_types_to_global_layout`. The DSV3 recipes and tests call it where they used to call `dtensor_to_global_layout`.
- EP>1 configs now need `training.disable_cuda_graphs`: upstream config validation rejects CUDA graphs with the all-to-all token dispatcher. `flex_shard_deepseek_v3_debug_muon` sets EP=2 after construction, so it skipped that check and would fail when launched from the CLI. It now disables CUDA graphs, as upstream EP configs do.
- Qwen3 recipe port. It was broken before these syncs, by `protocols.model_spec`, `FusedQKVLinear`, `components.metrics`, `tools.logging`, `default_adamw` and `set_spmd_backend`.
  - It follows the DSV3 pattern: `FlexShardQwen3Model(Qwen3Model)` with `Config.muon_pattern`, and `parallelize()` runs `parallelize_qwen3_muon` under `activate_spmd()`.
  - Configs are rebuilt on the current `Trainer.Config` fields with the same hyperparameters.
  - Q/K/V BlockShard plans use the fused `QKVLinear.wqkv`: one `head_dim`-row matrix per Q/K/V head.
  - `parallelize_qwen3_muon` uses `dp_shard`, always calls `_parallelize` (as DSV3 does), and declares the EP layouts.
- DSV3 `test_debug_muon_train_step` now disables autograd multithreading, as upstream `init_distributed` does. The SPMD mesh is thread-local, and FSDPTest skips `init_distributed`. So selective-AC recompute ran on an autograd device thread with no mesh set, the MoE token dispatch skipped EP there, and backward failed in `torch._grouped_mm` with "matrix batch sizes have to match". The upstream Trainer is not affected: the DSV3 debug model with EP=2 + SAC trains normally.

The `comm_free_adapter` change is the same as the one in D122391176, the auto-generated Test Blame fix. This diff also covers the other breakages in fb/flex_shard.

The DistMuon tests (DSV3 `test_shard0_owned_mixed` and `test_debug_muon_train_step`, and Qwen3 `test_debug_muon_train_step`) now get past every API break. They still fail on the fused `w13` weights, which the next diff (D122443668) fixes.

Reviewed By: weifengpy

Differential Revision: D122692766

Pull Request resolved: #50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl 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.

3 participants