Skip to content

fix async tp and move it into compile - #4045

Merged
acisseJZhong merged 13 commits into
mainfrom
gh/acisseJZhong/26/head
Aug 12, 2026
Merged

acisseJZhong merged 13 commits into
mainfrom
gh/acisseJZhong/26/head

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary

inheriting from #3869
Fix async TP setup across SPMD backends by:

  • enabling symmetric memory on the exact dense TP process group
  • adding ParallelDims.get_dense_tp_mesh() for backend-aware mesh
    selection
  • Move async TP enablement from parallelism config to compile config.
  • Configure async TP inside apply_compile using the dense TP mesh.

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Aug 1, 2026
ghstack-source-id: e47ce56
Pull-Request: #4045
)

with warnings.catch_warnings():
warnings.simplefilter("ignore", FutureWarning)

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 does this do?

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.

replicate

warnings.simplefilter("ignore", FutureWarning)

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.

that doesn't explain it :\

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.

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,

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 not convinced by evidence that this is needed at all, let's wait

Comment on lines +82 to +84
maybe_enable_async_tp(
parallelism, compile_config, parallel_dims.get_dense_tp_mesh()
)

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

@acisseJZhong acisseJZhong Aug 11, 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.

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?

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

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

acisseJZhong added a commit that referenced this pull request Aug 11, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* #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.
acisseJZhong added a commit that referenced this pull request Aug 11, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* #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]
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Aug 11, 2026
ghstack-source-id: 8bf13b0
Pull-Request: #4045
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Aug 11, 2026
ghstack-source-id: 9e5e0d4
Pull-Request: #4045
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Aug 11, 2026
ghstack-source-id: 73ab4de
Pull-Request: #4045
acisseJZhong added a commit that referenced this pull request Aug 11, 2026
ghstack-source-id: f18d8cf
Pull-Request: #4045
@acisseJZhong acisseJZhong added ciflow/h100.8 Trigger H100.8 CI ciflow/graph-trainer Run GraphTrainer CI labels Aug 11, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 11, 2026

Copy link
Copy Markdown

Warning: Unknown label ciflow/graph-trainer.
Currently recognized labels are

  • ciflow/8gpu
  • ciflow/h100.8
  • ciflow/rl

Please add the new label to .github/pytorch-probot.yml

@acisseJZhong acisseJZhong changed the title fix async tp fix async tp and move it into compile Aug 11, 2026
Comment on lines +88 to +90
with warnings.catch_warnings():
warnings.simplefilter("ignore", FutureWarning)
enable_symm_mem_for_group(group_name) # pyrefly: ignore [deprecated]

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.

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.

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 seems a bug on core, let me raise an issue and track here.

@acisseJZhong acisseJZhong Aug 11, 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.

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 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")

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.

with vision encoder this could print twice, not sure if it's a big deal

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 will keep this logging as printing twice should be better than nothing 😆

acisseJZhong added a commit that referenced this pull request Aug 11, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* #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:

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.

@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,

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.

parallel_dims.get_optional_mesh("tp") is enough.

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.

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

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.

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.

Comment on lines +88 to +90
with warnings.catch_warnings():
warnings.simplefilter("ignore", FutureWarning)
enable_symm_mem_for_group(group_name) # pyrefly: ignore [deprecated]

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 enable_symm_mem_for_group the main root cause that you want to fix?

@acisseJZhong

Copy link
Copy Markdown
Contributor Author

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]
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Aug 11, 2026
ghstack-source-id: 3762aba
Pull-Request: #4045
"""
maybe_enable_async_tp(
compile_config,
parallel_dims.get_dense_tp_mesh() if parallel_dims.tp_enabled else 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.

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]
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Aug 12, 2026
ghstack-source-id: 130c43c
Pull-Request: #4045
@acisseJZhong
acisseJZhong changed the base branch from gh/acisseJZhong/26/base to main August 12, 2026 18:03
@acisseJZhong
acisseJZhong changed the base branch from main to gh/acisseJZhong/26/base August 12, 2026 19:29
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Aug 12, 2026
ghstack-source-id: 28ac7b5
Pull-Request: #4045
@acisseJZhong
acisseJZhong changed the base branch from gh/acisseJZhong/26/base to main August 12, 2026 19:30
@acisseJZhong
acisseJZhong merged commit 7375947 into main Aug 12, 2026
16 checks passed
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 16, 2026
…_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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 16, 2026
… 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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 19, 2026
…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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 19, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/graph-trainer Run GraphTrainer CI ciflow/h100.8 Trigger H100.8 CI ciflow/rl ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants