Repository navigation
[CP] Decouple input and metadata sharding with configurable CP load balancer - #4617
Conversation
e08744e to
3219338
Compare
3219338 to
84080c5
Compare
| 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__}." | ||
| ) |
There was a problem hiding this comment.
we probably should use some efficient tree_map, instead of many if-else
| batch = self._prepare_context_parallel_batch( | ||
| batch, | ||
| input_sharding, | ||
| parallel_dims.get_mesh("cp"), | ||
| parallelism, |
There was a problem hiding this comment.
Let's avoid using "batch". After all here you are preparing microbatch.
There was a problem hiding this comment.
maybe we should change together with #4649? depending on the landing order, if your PR lands first, I will update mine.
| load_balancer_type: str | None = "headtail", | ||
| input_seq_dims: int | tuple[int, ...] = 0, | ||
| ptrr_mask_key: str | None = None, |
There was a problem hiding this comment.
This is very fragile. I think we should instead
- have a LoadBalancer / CPLoadBalancer as
Configurableand can build from configs; maybe it can be put undertrainer.parallelism. - decoder's
preprocess_inputswill build it based on inputs, and then it ownsshard/cp_shardmethod 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
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Introducing LoadBalancer as Configurable is "reorganizing things".
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
Do you mean cp_shard_tensors. However, I think after we have the load balancer, we don't need this file or this method.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Nvm, I saw you propose to move cp_shard to LoadBalancer
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
yes, load balancer's cp_shard will call into whatever functions it needs to
| return load_balancer | ||
|
|
||
|
|
||
| def cp_shard_inputs( |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
Nvm, I saw you propose to move cp_shard to LoadBalancer
| load_balancer_type: str | None = "headtail", | ||
| input_seq_dims: int | tuple[int, ...] = 0, | ||
| ptrr_mask_key: str | None = None, |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
LoadBalancer is responsible for sharding, so to me it'd be
- None: don't shard
- DefaultLoadBalancer / NoLoadBalancer: naive sharding
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
088766f to
4a4147f
Compare
|
|
||
|
|
||
| @dataclass(kw_only=True, slots=True) | ||
| class ContextParallelLoadBalancerConfig(Configurable.Config): |
There was a problem hiding this comment.
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.
e34ea58 to
db45abd
Compare
|
|
||
| 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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
| @registry.primitive_rule | ||
| def context_parallel_load_balancer_rule( | ||
| type_info: tyro.constructors.PrimitiveTypeInfo, | ||
| ): |
There was a problem hiding this comment.
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.
| @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.""" |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
| input_dict: dict[str, Any], | ||
| input_shardings: dict[str, SpmdType] | None, | ||
| cp_mesh: DeviceMesh, |
There was a problem hiding this comment.
Let's not pass these arguments into the constructor. See the reasoning below.
| def _build_load_balancer_impl( | ||
| self, | ||
| *, | ||
| input_dict: dict[str, Any], | ||
| seq_len: int, | ||
| ) -> _LoadBalancer | None: | ||
| del input_dict, seq_len | ||
| return None |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
enforced _build_load_balancer_impl to be an abstractmethod, and created another class _ContiguousLoadBalancer for conguous sharding / None.
| 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] | ||
| ) |
There was a problem hiding this comment.
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.
db45abd to
08f5478
Compare
| permutation: torch.Tensor | None, | ||
| ) -> _GlobalContextMetadataT: | ||
| """Keep context metadata global under Ulysses CP.""" | ||
| del cp_mesh, permutation |
There was a problem hiding this comment.
raise should not be supported
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
follow up in another PR: define map of attn backend class <-> attention metadata class
no VarlenAttentionMetadata = VarlenMetadata
16513de to
d502bd3
Compare
0e472d3 to
0b420c9
Compare
| FSDPSymmMemScope: TypeAlias = Literal["all", "dense", None] | ||
| _FSDP_SYMM_MEM_SCOPES = get_args(FSDPSymmMemScope) |
There was a problem hiding this comment.
belong to the parallelism file?
|
|
||
| context_parallel_load_balancer: Annotated[ | ||
| ContextParallelLoadBalancer.Config | None, tyro.conf.Suppress | ||
| ] = field(default_factory=HeadTailCPLoadBalancer.Config) |
There was a problem hiding this comment.
should we allow None? I guess it's for Ulysses. Then default should be None.
There was a problem hiding this comment.
why do we want to default to None? I am honoring the old behavior which default to headtail.
There was a problem hiding this comment.
making behavior explicit -- e.g. why we default to head-tail when doing Ulysses
There was a problem hiding this comment.
sure, defaulting to None will change the golden loss.
| config: Config, | ||
| *, | ||
| seq_len: int, | ||
| context_metadata: AttentionMasksType | None, |
There was a problem hiding this comment.
| context_metadata: AttentionMasksType | None, | |
| attention_metadata: AttentionMasksType | None, |
| return tensor | ||
|
|
||
|
|
||
| def shard_inputs( |
There was a problem hiding this comment.
should be
| 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 |
| return inputs, labels, batch | ||
|
|
||
| def _cp_shard_inputs( | ||
| def _prepare_cp_batch( |
There was a problem hiding this comment.
| def _prepare_cp_batch( | |
| def _cp_shard( |
| permutation=permutation, | ||
| ) | ||
|
|
||
| def _prepare_cp_metadata( |
There was a problem hiding this comment.
prefer not having this as a separate function in Decoder
| - `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`. |
There was a problem hiding this comment.
not enough? also metadata
There was a problem hiding this comment.
consider doing the same for every config in this file and remove this file
There was a problem hiding this comment.
sure, as there are only four configs. I will do this in next PR.
| with dist_utils.get_spmd_context(parallel_dims=self.parallel_dims): | ||
| for input_dict in microbatch_group: |
There was a problem hiding this comment.
order can be switched? only preprocess_inputs need context
0b420c9 to
b3508e2
Compare
tianyu-l
left a comment
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
put this after all fields?
| if parallel_dims.cp_enabled: | ||
| batch = self._cp_shard_inputs( | ||
| batch, input_sharding, parallel_dims, parallelism | ||
| batch = self._cp_shard( |
There was a problem hiding this comment.
let's replace this term for every model
There was a problem hiding this comment.
all the models have changed to _cp_shard?
| @staticmethod | ||
| def prepare_cp_metadata( | ||
| attention_metadata: _GlobalAttentionMetadataT, | ||
| *, | ||
| permutation: torch.Tensor | None, | ||
| ) -> _GlobalAttentionMetadataT: | ||
| del permutation | ||
| return attention_metadata |
There was a problem hiding this comment.
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?
fb5d938 to
700a65d
Compare
700a65d to
7156c59
Compare
7156c59 to
e709598
Compare
I believe the previous 2 * CP * SP is unnecessarily restrictive. |
## 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`
…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
Summary
permutation shared by model inputs and attention metadata. Head-tail and
PTRR generate permutations;
Noneis reserved for Ulysses.ContextParallelPartitionerand private PyTorch CP sharding helperswith TorchTitan
shard_inputs(), which applies the permutation and shardsdeclared tensors with
spmd.shard().communication algorithm. K/V all-gather builds a query-sharded
BlockMask,while Ulysses keeps metadata global.
instead of threading
DeviceMeshthrough model and trainer APIs.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=42and 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.