Repository navigation
fix async tp and move it into compile - #4045
Conversation
[ghstack-poisoned]
| ) | ||
|
|
||
| with warnings.catch_warnings(): | ||
| warnings.simplefilter("ignore", FutureWarning) |
There was a problem hiding this comment.
replicate
There was a problem hiding this comment.
that doesn't explain it :\
There was a problem hiding this comment.
to suppress this warning https://github.com/pytorch/pytorch/blob/98ebd10b379f7bf87d1cae21a133ebb0fd8a5684/torch/distributed/_symmetric_memory/__init__.py#L26, if enable_symm_mem_for_group is not called, during async tp is_symm_mem_enabled_for_group will return false and fail to fuse.
| context_parallel_degree=1, | ||
| pipeline_parallel_degree=1, | ||
| enable_sequence_parallel=False, | ||
| enable_sequence_parallel=self.enable_sequence_parallel, |
There was a problem hiding this comment.
we are not convinced by evidence that this is needed at all, let's wait
| maybe_enable_async_tp( | ||
| parallelism, compile_config, parallel_dims.get_dense_tp_mesh() | ||
| ) |
There was a problem hiding this comment.
I feel we can put this under compile enablement -- if model compile is enabled and inductor backend is used, we should always enable async TP (any reason not to?). And we should delete the enable_async_tp flag. WDYT?
My eventual goal is to delete the special parallelize_deepseekv3, having a unified one for decoder, and make it simple.
There was a problem hiding this comment.
if model compile is enabled and inductor backend is used, we should always enable async TP (any reason not to?)
Here's are some counter arguments listed by codex:
- Async TP requires suitable all-gather/matmul and matmul/reduce-scatter patterns, normally from
sequence parallelism. - Symmetric-memory kernels are topology-sensitive; the integration tests explicitly require NVLink.
- Small TP shards are not profitable/supported—the upstream pass skips some shards below 1024
- It can change performance and numerics, so silently enabling it for every compiled TP workload
would alter a battle-tested default. - The flag remains useful as an opt-out and for performance ablations.
I feel moving enable_async_tensor_parallel to compile makes sense? and maybe_enable_async_tp could move inside apply_compile, wdyt?
There was a problem hiding this comment.
I feel moving enable_async_tensor_parallel to compile makes sense? and maybe_enable_async_tp could move inside apply_compile, wdyt?
yeah great point, let's do that
| spmd_backend: Literal["default", "spmd_types"] = "default" | ||
| """SPMD backend used by TorchTitan model parallelization in the generator.""" | ||
|
|
||
| enable_async_tensor_parallel: bool = False |
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0) (oldest at bottom): * #4045 * #4067 * #4100 * #4080 * __->__ #3996 ## Summary This updates the MoE EP/SP sharding contract so token dispatchers return the local sequence shard directly instead of constructing a full global-length sparse contribution. The main change is that routed expert outputs are represented as the MoE local output layout: - EP on: sequence-sharded layout - EP off, experts using pure TP: Partial layout Shared experts are updated to produce the same layout as routed experts before the routed + shared add. The outer MoE boundary remains responsible for redistributing the final MoE output to `sp_layout`. ## Changes - Update standard AllToAll combine to scatter into a local-shard output buffer instead of a full `sp_size`-expanded buffer. - Remove the SP global-index remapping path from EP token dispatchers. - Remove `local_seq_len_after_padding` from the dispatcher combine interface since local-shard combine no longer needs per-rank-to-global SP index mapping. - Keep `num_local_tokens_after_padding` for logical sequence padding, so AllToAll can size the local padded output without materializing pad rows. - Make DeepEP combine stay async for all SP sizes; `MoE.forward()` syncs before the routed output is read. - Update MoE sharding annotations so routed and shared expert outputs match before addition: - under EP: sequence-sharded - without EP: Partial - Move shared expert TP redistributions onto the linear layers so `w1/w3` expose input all-gather and `w2` exposes Partial-to-output-layout reduction. - Update the MoE sharding diagram. ## Test plan loss parity on FSDP4, TP=2, SP on, EP=2, ETP=1: AssertionError: 7.949278831481934 != 7.9492878913879395 : Loss mismatch at step 1: baseline=7.949278831481934, test=7.9492878913879395 ``` NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='deepseek_v3' --baseline-config='deepseek_v3_debugmodel' --baseline-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2" --baseline-ngpus=8 --test-module='deepseek_v3' --test-config='deepseek_v3_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2" --test-ngpus=8 --assert-equal --no-seed-checkpoint ``` loss parity on FSDP4, TP=2, SP off, EP=2, ETP=1: [LOSS_COMPARE] Average difference: 0.000000 ``` NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='deepseek_v3' --baseline-config='deepseek_v3_debugmodel' --baseline-options="--parallelism.spmd_backend spmd_types --parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2 --parallelism.no-enable-sequence-parallel" --baseline-ngpus=8 --test-module='deepseek_v3' --test-config='deepseek_v3_debugmodel' --test-options="--parallelism.spmd_backend spmd_types --parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2 --parallelism.no-enable-sequence-parallel" --test-ngpus=8 --assert-equal --no-seed-checkpoint ``` loss parity on FSDP4, TP=2, SP on, EP=1, ETP=2: AssertionError: 6.0643310546875 != 6.064278602600098 : Loss mismatch at step 2: baseline=6.0643310546875, test=6.064278602600098 ``` NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='deepseek_v3' --baseline-config='deepseek_v3_debugmodel' --baseline-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 1" --baseline-ngpus=8 --test-module='deepseek_v3' --test-config='deepseek_v3_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 1" --test-ngpus=8 --assert-equal --no-seed-checkpoint ``` loss parity on FSDP4, TP=2, SP off, EP=1, ETP=2: [LOSS_COMPARE] Average difference: 0.000000 ``` NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='deepseek_v3' --baseline-config='deepseek_v3_debugmodel' --baseline-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 1 --parallelism.no-enable-sequence-parallel" --baseline-ngpus=8 --test-module='deepseek_v3' --test-config='deepseek_v3_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 1 --parallelism.no-enable-sequence-parallel" --test-ngpus=8 --assert-equal --no-seed-checkpoint ``` passed spmd type checking: ``` NCCL_NVLS_ENABLE=0 NGPU=8 MODULE=deepseek_v3 CONFIG=deepseek_v3_debugmodel ./run_train.sh \ --parallelism.pipeline_parallel_degree 1 \ --parallelism.data_parallel_shard_degree 4 \ --parallelism.tensor_parallel_degree 2 \ --parallelism.expert_parallel_degree 2 \ --parallelism.spmd_backend spmd_types \ --debug.spmd_typechecking \ --training.steps 10 \ activation-checkpoint:none ``` Also used a temporary script based on `TestBitwiseParityMoEEP` to run main and the current commit with identical checkpoint weights and uneven prompts, then compared all prefill/decode logprobs and generated token IDs bit-for-bit.
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0) (oldest at bottom): * #4045 * #4067 * #4100 * __->__ #4080 ## Summary this would resolve #3622 Pad MoE inputs to the expert sequence-parallel degree before routing, then trim the output to its original length. This ensures equal TP shards for uneven decode batches and removes virtual-padding bookkeeping from token dispatchers. Adds a TP=EP=4 vLLM test covering a three-request decode batch and verifying bitwise decode/prefill parity. ## Test Plan ``` CUDA_VISIBLE_DEVICES=0,1,2,3 torchrun --standalone --nproc-per-node=4 -m pytest -q torchtitan/experiments/rl/tests/test_generator.py::test_vllm_uneven_decode_tp_padding ```
[ghstack-poisoned]
|
Warning: Unknown label
Please add the new label to .github/pytorch-probot.yml |
| with warnings.catch_warnings(): | ||
| warnings.simplefilter("ignore", FutureWarning) | ||
| enable_symm_mem_for_group(group_name) # pyrefly: ignore [deprecated] |
There was a problem hiding this comment.
to suppress this warning https://github.com/pytorch/pytorch/blob/98ebd10b379f7bf87d1cae21a133ebb0fd8a5684/torch/distributed/_symmetric_memory/__init__.py#L26, if enable_symm_mem_for_group is not called, during async tp is_symm_mem_enabled_for_group will return false and fail to fuse.
This sounds a bug on pytorch core? Please add a note / todo here if so.
There was a problem hiding this comment.
yeah seems a bug on core, let me raise an issue and track here.
There was a problem hiding this comment.
Is enable_symm_mem_for_group the main root cause that you want to fix?
| enable_symm_mem_for_group(group_name) # pyrefly: ignore [deprecated] | ||
|
|
||
| torch._inductor.config._micro_pipeline_tp = True | ||
| logger.info("Async TP is enabled") |
There was a problem hiding this comment.
with vision encoder this could print twice, not sure if it's a big deal
There was a problem hiding this comment.
I will keep this logging as printing twice should be better than nothing 😆
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0) (oldest at bottom): * #4045 * __->__ #4100 ## Summary Move uneven sequence padding out of the common MoE model and into the vLLM inference path, where uneven decode batches originate. The custom vLLM V1 runner pads dense/expert-SP token counts to the TP degree and filters invalid expert-SP CUDA graph capture sizes. This keeps inference-specific padding out of shared model and training code. ## Test Plan CUDA_VISIBLE_DEVICES=0,1,2,3 torchrun --standalone --nproc-per-node=4 -m pytest -q torchtitan/ experiments/rl/tests/test_generator.py::test_vllm_uneven_decode_tp_padding
| self.build_mesh() | ||
| return self._global_meshes.get("spmd_sparse_for_fwdbwd") | ||
|
|
||
| def get_dense_tp_mesh(self) -> DeviceMesh: |
There was a problem hiding this comment.
@fegin do you know if this is a principled way or is there other suggested approach?
| """ | ||
| maybe_enable_async_tp( | ||
| compile_config, | ||
| parallel_dims.get_dense_tp_mesh() if parallel_dims.tp_enabled else None, |
There was a problem hiding this comment.
parallel_dims.get_optional_mesh("tp") is enough.
There was a problem hiding this comment.
- get_optional_mesh("tp") returns the TP mesh derived from dataloading_mesh.
- spmd_types collectives use spmd_dense_mesh()["tp"].
- full_dtensor collectives use spmd_meshes()[0]["tp"].
if we use TP mesh derived from dataloading_mesh, spmd types will not work with async TP.
There was a problem hiding this comment.
uh, this is painful. Let's land this version first. I'll kill full_dtensor and convert partial_dtensor to use the same one as spmd_types.
| with warnings.catch_warnings(): | ||
| warnings.simplefilter("ignore", FutureWarning) | ||
| enable_symm_mem_for_group(group_name) # pyrefly: ignore [deprecated] |
There was a problem hiding this comment.
Is enable_symm_mem_for_group the main root cause that you want to fix?
yes the original fix was just this one line, but later we decide to move async tp into compile. |
[ghstack-poisoned]
| """ | ||
| maybe_enable_async_tp( | ||
| compile_config, | ||
| parallel_dims.get_dense_tp_mesh() if parallel_dims.tp_enabled else None, |
There was a problem hiding this comment.
uh, this is painful. Let's land this version first. I'll kill full_dtensor and convert partial_dtensor to use the same one as spmd_types.
[ghstack-poisoned]
…_enable_async_tp Upstream pytorch#4045 ("fix async tp and move it into compile") DELETED maybe_enable_async_tp from distributed/tensor_parallel.py and made apply_compile keyword-only with a new parallel_dims argument. Both ezpz/agpt/parallelize.py and ezpz/moe/parallelize.py imported the deleted symbol, so post-merge they would have died at IMPORT -- before step 1, on every rank. The merge itself was conflict-free and touched no ezpz file, which is exactly why this needed catching by hand: a clean merge is not a working one when the break is a deleted symbol in a file the merge never opened. agpt: thread parallel_dims through _apply_compile_with_mode into apply_compile (which now enables async TP itself), and drop the standalone call. moe: drop the import and the call. This file compiles per-block directly rather than via apply_compile, so there is nothing to thread parallel_dims into -- async TP is simply unavailable on the MoE path now. Not a regression: that call only ran under tp_enabled, and MoE+async-TP has never been validated on XPU. Verified: no ezpz reference to the removed symbol remains, and all ezpz files parse. Numerical + smoke verification on hardware is next.
… clean numerics Conflict-free merge that touched NO ezpz file and still broke the branch twice, both times via symbols in files the merge never opened: pytorch#4045 deleted maybe_enable_async_tp -> ImportError in agpt + moe pytorch#3559/pytorch#4146 added Trainer.fwd_bwd_fn -> AttributeError, 3/3 arms dead Both replayed and verified on the RC: compile TP=4 and MoE EP=1 both pass 10 steps. Also records that the loss A/B FIRST reported "the merge CHANGED numerics" and that this was MY error, not upstream's -- I ran it without a control. Re-running the same pre-merge commit twice reproduces the divergence exactly (0.00106 / 0.00260 / 0.01201 at steps 8/9/10, matching pre-vs-post to three decimals), so the merge is numerically clean. The control exposed a standing problem worth more attention than the sync: --debug.deterministic does NOT produce bit-identical runs on this stack, contrary to the contract in CLAUDE.md. Every "identical loss" check we run is currently blind to regressions below ~0.012 at step 10. Untriaged, with the 1-rank-vs-multi-rank / TP split noted as the way to separate a nondeterministic kernel from a nondeterministic collective.
…ch#3996 stopped passing it Every ezpz MoE config dies at init: TypeError: AllToAllTokenDispatcher.wire_meshes() missing 1 required keyword-only argument: 'tp_mesh' Upstream PR pytorch#3996 ('Experimenting MoE new sharding') changed models/common/moe.py:187 to call wire_meshes(ep_mesh=...) only, dropping tp_mesh. Core's own dispatchers were updated to match; our four ezpz overrides still declared tp_mesh as required keyword-only, so the inherited MoE.parallelize() call raises before step 1. Same class of silent break as pytorch#4045 removing maybe_enable_async_tp. Defaults tp_mesh=None on all four (base, AllToAll, DeepEP, HybridEP). The new caller omits it; anything still passing it keeps working. The default is CORRECT for TP=1 -- sp_size/sp_rank are initialised to 1/0 in __init__, which is exactly the no-SP case. It is NOT correct under TP>1, where combine() would expand to the wrong sequence length. Rather than fail silently, the three dispatchers that consume tp_mesh now warn when it is absent but the mesh topology has a 'tp' axis. The TP check reads the mesh already in hand (ep_mesh's root mesh_dim_names). A first attempt used ParallelDims._current, which does not exist -- with its bare except that helper would have always returned False, i.e. dead code wearing the costume of a guard. Verified by AST: all four now require only ep_mesh. Helper unit-tested on None / no-tp / tp / nested-root / garbage inputs.
…imizer Upstream pytorch#4172 deleted torchtitan/components/lr_scheduler.py. It had become a re-export shim when pytorch#4140 grouped the optimizer components into a package, so LRSchedulersContainer now lives in torchtitan.components.optimizer. Four ezpz registries imported the deleted path: agpt, moe, and the two RL config registries. Without this every one of them fails at import, which is the same failure shape as pytorch#4045 (maybe_enable_async_tp) and pytorch#3996 (wire_meshes tp_mesh) -- upstream removes a path, ezpz overrides still name it. components.optimizer itself survives as a package, so the five other ezpz files importing default_adamw / OptimizersContainer / ParamGroupConfig need no change. Verified: 0 unresolvable torchtitan imports and 0 syntax errors across all ezpz .py files on the merged tree.
Stack from ghstack (oldest at bottom):
Summary
inheriting from #3869
Fix async TP setup across SPMD backends by:
ParallelDims.get_dense_tp_mesh()for backend-aware meshselection
apply_compileusing the dense TP mesh.