Skip to content

[full DTensor] Use all DTensor for Qwen3 and llama4 at TP region - #2149

Merged
wwwjn merged 19 commits into
mainfrom
qwen3-dtensor
Apr 22, 2026
Merged

wwwjn merged 19 commits into
mainfrom
qwen3-dtensor

Conversation

@wwwjn

@wwwjn wwwjn commented Dec 12, 2025 •

Copy link
Copy Markdown
Contributor

Command to run

NGPU=8 MODULE=llama3 CONFIG=llama3_debugmodel ./run_train.sh

NGPU=8 MODULE=qwen3 CONFIG=qwen3_14b ./run_train.sh

NGPU=8 MODULE=qwen3 CONFIG=qwen3_moe_debug ./run_train.sh

If need to disable SP, add --parallelism.no-enable-sequence-parallel

Test

  1. FSDP + TP , no SP: Run successfully
  2. FSDP + TP + SP: Run successfully
  3. FSDP + TP (no SP) + PP: blocked by RFC: DTensor Support for Pipeline Parallelism Stages pytorch#172419
  4. FSDP + TP + SP + PP: blocked by RFC: DTensor Support for Pipeline Parallelism Stages pytorch#172419
  5. FSDP + TP + SP + EP: Run successfully
  6. FSDP + TP + SP + CP: run successfully

Numerics check:
Screenshot 2026-04-22 at 1 48 17 PM

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Dec 12, 2025
@wwwjn

wwwjn commented Dec 12, 2025

Copy link
Copy Markdown
Contributor Author

If this change looks good, I will go ahead and change TP plan of deepseek_v3, llama3, llama4

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

nice, it seems it failed with MoE. Could you try to adjust MoE so that only the boundaries (input and output) are DTensor? We can discuss if you hit issues.

@wwwjn wwwjn changed the title Use all DTensor for Qwen3 model TP Use all DTensor for Qwen3 and llama4 through TP region Dec 12, 2025
@wwwjn

wwwjn commented Dec 12, 2025

Copy link
Copy Markdown
Contributor Author

nice, it seems it failed with MoE. Could you try to adjust MoE so that only the boundaries (input and output) are DTensor? We can discuss if you hit issues.

Updated! As qwen3 and llama4 share the apply_moe_ep_tp function, I updated llama4 TP plan together in this PR

@tianyu-l

Copy link
Copy Markdown
Contributor

test didn't pass

@wwwjn

wwwjn commented Dec 13, 2025

Copy link
Copy Markdown
Contributor Author

test didn't pass

Updated dsv3 as well - Because dsv3 reused llama4 apply_moe_ep_tp.

Run loss comparison on dsv3 and qwen3 as well, they both passed.

@tianyu-l

Copy link
Copy Markdown
Contributor

Could you also modify the test_generate script in torchtitan to use sp instead of no-sp?

Btw, I think FlexAttention doesn't work with DTensor yet. Is your PR only enforce DTensor in SP regions (norm) but not TP regions (embedding, attention, mlp)? Specifically, have you tried your change with FlexAttn?

@wwwjn

wwwjn commented Dec 13, 2025

Copy link
Copy Markdown
Contributor Author

Is your PR only enforce DTensor in SP regions (norm) but not TP regions (embedding, attention, mlp)? Specifically, have you tried your change with FlexAttn?

No, it's acutally enforce DTensor in all TP regions. I tested dsv3 with FlexAttention and it works because of the special attention_kernel_plan:

attention_kernel_plan = prepare_module_input(
, which turns DTensor to plain tensor before attention kernel

But I don't think qwen3 / llama4 will work with FlexAttn out-of-box, let me fix, Thanks for catching!

@fegin

fegin commented Dec 13, 2025

Copy link
Copy Markdown
Contributor

Nice, but DSV3 integration test fails. I believe it is because tok_embeddings doesn't exist for some stages when PP is enabled. You will need to check if tok_embeddings before applying the plan.

input_layouts=(Shard(1), None, None, None),
desired_input_layouts=(Replicate(), None, None, None),
input_layouts=(Shard(1), Replicate(), None, None),
desired_input_layouts=(Replicate(), Replicate(), None, None),

@fegin fegin Dec 13, 2025 •

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.

Nice, now we consistently make freqs_cis as a DTensor. The only one model that still uses plain tensor for freqs_cis is llama3.

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.

Thank you so much! I plan to add change for llama3 as well

@wwwjn

wwwjn commented Dec 14, 2025

Copy link
Copy Markdown
Contributor Author

Nice, but DSV3 integration test fails. I believe it is because tok_embeddings doesn't exist for some stages when PP is enabled. You will need to check if tok_embeddings before applying the plan.

From the error stack, it's raising error from attention() part , which might not related to tok_embeddings? is it related to freqs_cis? cc @H-Huang

    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1830, in inner
      result = forward_call(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/pytorch/torchtitan/torchtitan/models/deepseek_v3/model/model.py", line 497, in forward
      h = layer(h, self.freqs_cis, attention_masks, positions)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1776, in _wrapped_call_impl
      return self._call_impl(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1882, in _call_impl
      return inner()
             ^^^^^^^
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1830, in inner
      result = forward_call(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/pytorch/torchtitan/torchtitan/models/deepseek_v3/model/model.py", line 384, in forward
      x = x + self.attention(
              ^^^^^^^^^^^^^^^
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1776, in _wrapped_call_impl
      return self._call_impl(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1882, in _call_impl
      return inner()
             ^^^^^^^
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1819, in inner
      args_result = hook(self, args)
                    ^^^^^^^^^^^^^^^^
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/distributed/tensor/parallel/style.py", line 580, in <lambda>
      lambda _, inputs: self._prepare_input_fn(inputs, device_mesh)
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/distributed/tensor/parallel/style.py", line 552, in _prepare_input_fn
      self._prepare_input_arg(inp, device_mesh, input_layout, desired_layout)
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/distributed/tensor/parallel/style.py", line 529, in _prepare_input_arg
      dt_inp = dt_inp.redistribute(placements=(desired_layout,))
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/distributed/tensor/_api.py", line 566, in redistribute
      return Redistribute.apply(
             ^^^^^^^^^^^^^^^^^^^
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/autograd/function.py", line 583, in apply
      return super().apply(*args, **kwargs)  # type: ignore[misc]
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/distributed/tensor/_redistribute.py", line 949, in forward
      output = redistribute_local_tensor(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/distributed/tensor/_redistribute.py", line 840, in redistribute_local_tensor
      new_local_tensor = current_placement._to_replicate_tensor(
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/distributed/tensor/placement_types.py", line 303, in _to_replicate_tensor
      result = funcol.all_gather_tensor(
               ^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/distributed/_functional_collectives.py", line 200, in all_gather_tensor
      group_size = c10d._get_group_size_by_name(group_name)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/distributed/distributed_c10d.py", line 1118, in _get_group_size_by_name
      group = _resolve_process_group(group_name)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  RuntimeError: Could not resolve the process group registered under the name 18
  

@fegin

fegin commented Dec 15, 2025

Copy link
Copy Markdown
Contributor

You are right, tok_embeddings is just a warning, not the actual error.

@wwwjn wwwjn changed the title Use all DTensor for Qwen3 and llama4 through TP region Use all DTensor for Qwen3 and llama4 at TP region Dec 15, 2025
@wwwjn

wwwjn commented Dec 16, 2025 •

Copy link
Copy Markdown
Contributor Author

The error is when TP + PP is applied, both dense model and MoE model has this issue.

When PP rank0 send activation to PP rank1, the activation will be DTensor with this PR. The dtensor's placement was created on PP rank 0, where the TP mesh on PP rank0 has device 0,1. However, when the dtensor was send to PP rank 1, the TP mesh on PP rank 1 has device 2,3. So the underlaying PG will be different.

cc @H-Huang @wconstab @sanketpurandare , we could propose a plan to make PP work with DTensor?

@wwwjn wwwjn changed the title Use all DTensor for Qwen3 and llama4 at TP region [WIP] Use all DTensor for Qwen3 and llama4 at TP region Dec 16, 2025
@wwwjn

wwwjn commented Feb 12, 2026

Copy link
Copy Markdown
Contributor Author

Blocked by pytorch/pytorch#172419 , @sanketpurandare is testing the implementation

@wwwjn wwwjn changed the title [WIP] Use all DTensor for Qwen3 and llama4 at TP region [WIP][full DTensor] Use all DTensor for Qwen3 and llama4 at TP region Feb 12, 2026
@wwwjn wwwjn added this to the New Feature, Model, Misc milestone Feb 12, 2026
"tok_embeddings": RowwiseParallel(
input_layouts=Replicate(),
output_layouts=Replicate(),
use_local_output=True, # needed for _scatter

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'm puzzled by the comments above. I probably missed it during earlier review.

@shuhuayu could you review and follow up? Let's remove blockers for full DTensor.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

There is output tensor x from token embedding, and we have some vision embeddings from vision encoder. we want to replace the placeholders in x by the actual vision token embeddings. using scatter operation. But this op is not supported by dtensor, so we used plain tensors here.

I will add dtensor support for this op. We can use plain tensors for now.

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 here I followed the previous Qwen3-vl behavior. So technically Qwen3-vl is not full DTensor in TP region

Comment thread torchtitan/models/llama4/parallelize.py Outdated
comm_backend: str = "standard",
enable_sp: bool = True,
pad_multiple: int | None = None,
use_local_output: 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.

why do we need to introduce this? Can we just set it to False below

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.

@wwwjn wwwjn Apr 22, 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.

@shuhuayu I updated Qwen3-VL's parallel plan:
The idea is there are 2 places we have to use plain tensor instead of full DTensor

  1. _scatter_vision_embeds: This is handled by set tok_embedding layer's output, and wrap each transformer layers
  2. DeepStack: Use PrepareModelnputOutput to turn each transformer layers' output to be a plain tensor, and it was changed back to DTensor at the beginning of next transformer layer's PrepareModelnputOutput
    • This introduce an extra clone, because we implicitly called to_local() on the output of Transformer layer.

Can you help review this change makes sense for you?

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.

Sorry for the late reply. I do not get why we need PrepareModelnputOutput here. The NoParallel at the entry of the transformer block can handle a plain tensor as an input.

ep_etp_mesh=parallel_dims.get_optional_mesh(["ep", "etp"]),
enable_sp=False,
pad_multiple=find_pad_multiple(model_converters.converters),
use_local_output=True, # Plain tensors for DeepStack boolean indexing

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.

Because plain tensor is needed for boolean indexing, so I add a parameter to the shared function apply_moe_ep_tp(). However, I updated design to be: Always let MoE module return a DTensor activation, unwrap DTensor and rewrap DTensor around DeepStack boolean indexing (this might be replace to a local map)

Comment thread torchtitan/models/llama4/parallelize.py Outdated
comm_backend: str = "standard",
enable_sp: bool = True,
pad_multiple: int | None = None,
use_local_output: bool = False,

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.

Comment thread torchtitan/models/qwen3/parallelize.py Outdated
),
"feed_forward.w1": colwise_parallel(),
"feed_forward.w1": colwise_parallel(use_local_output=False),
"feed_forward.w2": rowwise_output_plan,

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 reusing fine? Not sure if this stateful thing can be reused, please double check. Alternatively may choose to not share and always inline build a new object.

Either way, it will be refactored by fegin soon.

Comment thread torchtitan/models/qwen3_vl/model.py Resolved
@wwwjn
wwwjn merged commit 703b72e into main Apr 22, 2026
18 of 22 checks passed
@github-project-automation github-project-automation Bot moved this from Todo to Done in TorchTitan Development Apr 22, 2026
@tianyu-l
tianyu-l deleted the qwen3-dtensor branch April 22, 2026 23:41
SherlockNoMad pushed a commit that referenced this pull request Apr 23, 2026
…itioner regression

The full DTensor change (#2149) triggers "Node tangents_2 was invalid,
but is output" in PyTorch's default_partition. This affects all JIT and
AOT mode tests but not aot_fx_trace. Disable until the upstream
partitioner issue is resolved.
SherlockNoMad pushed a commit that referenced this pull request Apr 23, 2026
…itioner regression

The full DTensor change (#2149) triggers "Node tangents_2 was invalid,
but is output" in PyTorch's default_partition. This affects all JIT and
AOT mode tests but not aot_fx_trace. Disable until the upstream
partitioner issue is resolved.
SherlockNoMad added a commit that referenced this pull request Apr 23, 2026
…ession (#3061)

## Summary
- Disable all JIT and AOT mode integration tests via `_JIT_AOT_DISABLED`
flag
- The full DTensor change (#2149) triggers `AssertionError: Node
tangents_2 was invalid, but is output` in PyTorch's `default_partition`
- All 6 `aot_fx_trace` mode tests remain enabled and passing

## Test plan
- [x] `PYTHONPATH=. python
torchtitan/experiments/graph_trainer/tests/integration_tests.py
~/tmp/integration_test_output --test_suite graph_trainer_default --ngpu
8` — all remaining tests pass

Co-authored-by: bahuang <[email protected]>
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Apr 23, 2026
Upstream PR pytorch#2149 switched TP to keep tensors as DTensors
(use_local_output=False) instead of converting to plain tensors.
Applied same change to ezpz agpt parallelize: embed_plan, norm_plan,
and rowwise_output_plan now use use_local_output=False.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Apr 25, 2026
Revert fc3880c's use_local_output=False change. The full DTensor TP
causes:
- torch 2.10: TP=2 forward pass hang (even with IPEX)
- torch 2.13: AC + compile crash (DeviceMesh saved in AOT autograd
  graph triggers tensors_saved_with_vc_check assertion)

Restore use_local_output=enable_sp (the pre-DTensor-TP default) which
works on both torch versions. The upstream PR pytorch#2149 requires a newer
torch that properly handles DeviceMesh in the AC autograd context.
zwluestc pushed a commit to zwluestc/verl that referenced this pull request May 12, 2026
…t#5356)

### What does this PR do?

Add RL support for TorchtitanEngine. Tested FSDP, TP/SP on Qwen3 0.6b
and verified parity with FSDP engine.

Note: 
- TP requires Torchtitan to have full DTensor:
pytorch/torchtitan#2149 (will land soon)
- Will add PP and EP support, and set up integration/CI test for
torchtitan engine as follow up PRs.
- Torchtitan critic model is not supported, will follow up. GRPO doesn't
use critic.

### Test
```
GRPC_ENABLE_FORK_SUPPORT=0 NCCL_NVLS_ENABLE=0 MODEL_ID=Qwen/Qwen3-0.6B bash tests/special_e2e/run_ppo_trainer_torchtitan.sh

NUM_GPUS=4 FSDP_SIZE=2 TP_SIZE=2 GRPC_ENABLE_FORK_SUPPORT=0 NCCL_NVLS_ENABLE=0  bash tests/special_e2e/run_ppo_trainer_torchtitan.sh
```
[Package versions I am
using](https://gist.github.com/acisseJZhong/e6f3920df5c5d88fef86750ce8518141),
[version
2](https://gist.github.com/acisseJZhong/6cf2c14eab40a5c2a129443027894317)
[Torchtitan engine
config](https://gist.github.com/acisseJZhong/6e68366c50b8efa396bcb50da7701a84)
[FSDP engine
config](https://gist.github.com/acisseJZhong/9decbe8a22c3f5b0499f42f21229e10d)

test on qwen3 0.6b single process
- **critic scores, actor pg loss, actor loss are matching, and Titan
step time is significantly less than FSDP engine**

<img width="1380" height="668" alt="image"
src="https://github.com/user-attachments/assets/b2270ae0-71bd-4769-b7ff-73d06489a529"
/>
<img width="1378" height="678" alt="image"
src="https://github.com/user-attachments/assets/6c6a8739-4a1d-44f5-abbd-3dc4f830ed45"
/>
<img width="1378" height="665" alt="image"
src="https://github.com/user-attachments/assets/c5ee9191-5995-4138-b9af-f77f64d77af8"
/>

test on qwen3 0.6b fsdp_size=2, tp_size=2
<img width="1343" height="637" alt="image"
src="https://github.com/user-attachments/assets/f3abf367-b106-49c3-9bad-e5d4597b7c85"
/>
<img width="1337" height="617" alt="image"
src="https://github.com/user-attachments/assets/948aea2a-3e95-4fe1-80cb-7244c23483f1"
/>
<img width="1345" height="605" alt="image"
src="https://github.com/user-attachments/assets/22c3fbbb-c352-4160-b0eb-1cbc398fea4a"
/>


### Checklist Before Submitting

> [!IMPORTANT]
> Please check all the following items before requesting a review,
otherwise the reviewer might deprioritize this PR for review.

- [ ] Read the [Contribute
Guide](https://github.com/volcengine/verl/blob/main/CONTRIBUTING.md).
- [ ] Apply [pre-commit
checks](https://github.com/volcengine/verl/blob/main/CONTRIBUTING.md#code-linting-and-formatting):
`pre-commit install && pre-commit run --all-files --show-diff-on-failure
--color=always`
- [ ] Add / Update [the
documentation](https://github.com/volcengine/verl/tree/main/docs).
- [ ] Add unit or end-to-end test(s) to [the CI
workflow](https://github.com/volcengine/verl/tree/main/.github/workflows)
to cover all the code. If not feasible, explain why: ...
- [ ] Once your PR is ready for CI, send a message in [the `ci-request`
channel](https://verl-project.slack.com/archives/C091TCESWB1) in [the
`verl` Slack
workspace](https://join.slack.com/t/verl-project/shared_invite/zt-3855yhg8g-CTkqXu~hKojPCmo7k_yXTQ).
(If not accessible, please try [the Feishu group
(飞书群)](https://applink.larkoffice.com/client/chat/chatter/add_by_link?link_token=772jd4f1-cd91-441e-a820-498c6614126a).)
- [ ] If your PR is related to the `recipe` submodule, please also
update the reference to the submodule commit via `git submodule update
--remote` or `cd recipe && git pull origin main`.
xvlincaigou pushed a commit to xvlincaigou/verl that referenced this pull request May 19, 2026
…t#5356)

### What does this PR do?

Add RL support for TorchtitanEngine. Tested FSDP, TP/SP on Qwen3 0.6b
and verified parity with FSDP engine.

Note: 
- TP requires Torchtitan to have full DTensor:
pytorch/torchtitan#2149 (will land soon)
- Will add PP and EP support, and set up integration/CI test for
torchtitan engine as follow up PRs.
- Torchtitan critic model is not supported, will follow up. GRPO doesn't
use critic.

### Test
```
GRPC_ENABLE_FORK_SUPPORT=0 NCCL_NVLS_ENABLE=0 MODEL_ID=Qwen/Qwen3-0.6B bash tests/special_e2e/run_ppo_trainer_torchtitan.sh

NUM_GPUS=4 FSDP_SIZE=2 TP_SIZE=2 GRPC_ENABLE_FORK_SUPPORT=0 NCCL_NVLS_ENABLE=0  bash tests/special_e2e/run_ppo_trainer_torchtitan.sh
```
[Package versions I am
using](https://gist.github.com/acisseJZhong/e6f3920df5c5d88fef86750ce8518141),
[version
2](https://gist.github.com/acisseJZhong/6cf2c14eab40a5c2a129443027894317)
[Torchtitan engine
config](https://gist.github.com/acisseJZhong/6e68366c50b8efa396bcb50da7701a84)
[FSDP engine
config](https://gist.github.com/acisseJZhong/9decbe8a22c3f5b0499f42f21229e10d)

test on qwen3 0.6b single process
- **critic scores, actor pg loss, actor loss are matching, and Titan
step time is significantly less than FSDP engine**

<img width="1380" height="668" alt="image"
src="https://github.com/user-attachments/assets/b2270ae0-71bd-4769-b7ff-73d06489a529"
/>
<img width="1378" height="678" alt="image"
src="https://github.com/user-attachments/assets/6c6a8739-4a1d-44f5-abbd-3dc4f830ed45"
/>
<img width="1378" height="665" alt="image"
src="https://github.com/user-attachments/assets/c5ee9191-5995-4138-b9af-f77f64d77af8"
/>

test on qwen3 0.6b fsdp_size=2, tp_size=2
<img width="1343" height="637" alt="image"
src="https://github.com/user-attachments/assets/f3abf367-b106-49c3-9bad-e5d4597b7c85"
/>
<img width="1337" height="617" alt="image"
src="https://github.com/user-attachments/assets/948aea2a-3e95-4fe1-80cb-7244c23483f1"
/>
<img width="1345" height="605" alt="image"
src="https://github.com/user-attachments/assets/22c3fbbb-c352-4160-b0eb-1cbc398fea4a"
/>


### Checklist Before Submitting

> [!IMPORTANT]
> Please check all the following items before requesting a review,
otherwise the reviewer might deprioritize this PR for review.

- [ ] Read the [Contribute
Guide](https://github.com/volcengine/verl/blob/main/CONTRIBUTING.md).
- [ ] Apply [pre-commit
checks](https://github.com/volcengine/verl/blob/main/CONTRIBUTING.md#code-linting-and-formatting):
`pre-commit install && pre-commit run --all-files --show-diff-on-failure
--color=always`
- [ ] Add / Update [the
documentation](https://github.com/volcengine/verl/tree/main/docs).
- [ ] Add unit or end-to-end test(s) to [the CI
workflow](https://github.com/volcengine/verl/tree/main/.github/workflows)
to cover all the code. If not feasible, explain why: ...
- [ ] Once your PR is ready for CI, send a message in [the `ci-request`
channel](https://verl-project.slack.com/archives/C091TCESWB1) in [the
`verl` Slack
workspace](https://join.slack.com/t/verl-project/shared_invite/zt-3855yhg8g-CTkqXu~hKojPCmo7k_yXTQ).
(If not accessible, please try [the Feishu group
(飞书群)](https://applink.larkoffice.com/client/chat/chatter/add_by_link?link_token=772jd4f1-cd91-441e-a820-498c6614126a).)
- [ ] If your PR is related to the `recipe` submodule, please also
update the reference to the submodule commit via `git submodule update
--remote` or `cd recipe && git pull origin main`.
SherlockNoMad added a commit that referenced this pull request Jun 2, 2026
…isabled tests (#3480)

## Summary

Root-causes and fixes the bug behind a large batch of `graph_trainer`
tests disabled in #3432, then re-enables the ones it actually explains
(**14 tests across 4 files**).

Most failures in #3432 were filed as assorted "upstream nightly
regressions" (cuDNN, FlexAttention, histc-int64, mixed-dtype mm,
CUDA-graph device-asserts). They turned out to be a **single bug**:
make_fx traced DTensor **shard propagation**.
`ShardingPropagator._propagate_tensor_meta_non_cached` runs each op on
fake **global-shape** tensors to derive output metadata; when an
enclosing make_fx tracer captures that inference, it leaves a dead
"shadow" node for every DTensor op — backed by uninitialized
`empty_strided` placeholders — that no real local-shard output consumes.
Harmless for most ops, but bounds-checked ops like `aten.embedding` read
the uninitialized `empty_strided` index and trigger an out-of-bounds
gather on the TP-sharded weight → `device-side assert`. It's
**nondeterministic** (garbage indices occasionally land in-bounds), and
under cudagraph/cuDNN/FlexAttention/precompile it surfaced as
different-looking errors — which is why it was misfiled as many separate
regressions. Any `tensor_parallel_degree > 1` trace is affected.

## Fix

- `make_fx_tracer.py`: **`_remove_dead_empty_strided_chains`** — a
targeted DCE that strips the dead `empty_strided` shadow chains from the
traced graph. This lets the tests be re-enabled **now**, without waiting
for the upstream PyTorch fix to reach the CI nightly. It becomes a no-op
once the upstream fix is present, and should be removed then (noted in
its docstring).
- The proper upstream fix wraps shard propagation's fake-tensor
inference in `disable_proxy_modes_tracing` so it never enters the graph
(separate pytorch/pytorch change).

## Tests re-enabled (14)

Verified on 8×H100 against **unfixed** PyTorch, with controls confirming
each fails with the same `vectorized_gather_kernel index out of bounds`
without the fix and passes with it.

**`integration_tests.py` (7)** — `llama3_fsdp_tp_flexattn`,
`llama3_fsdp_tp_sac_and_offload`, `qwen3_moe_fsdp_tp_ep`,
`deepseek_v3_fsdp_tp_ep_flexattn`,
`deepseek_v3_fsdp_tp_ep_full_inductor`, and the two CP tests
`llama3_fsdp_tp_cp` / `qwen3_fsdp_tp_cp` (these run with cudagraph
disabled — see caveat).

**`test_trace_module.py` (6 classes)** — `TestTraceDTensor`,
`TestMetadataPropagation`, `TestTraceModels`, etc. (were
`@unittest.skip("upstream DTensor+Embedding device-side assert
regression")`). Full file: 46 passed, 2 skipped (2 remaining = unrelated
`test_gpt_oss` scatter-dtype).

**`test_numerics.py` (4)** —
`test_{dense_llama3,moe_dsv3,dense_qwen3,moe_qwen3}_aot_fx_trace_vs_eager`
(were "DTensor mixed-dtype mm sharding-prop regression"). These are
`--assert-equal` loss compares, so they confirm **bitwise** numerics
match eager.

**`run_precompile_tests.py` (1)** —
`aot_fx_trace_llama3_precompile_fsdp_tp` (was "CUDA graph device-side
assert regression").

## Left disabled (genuinely separate; comments corrected)

- `deepseek_v3_fsdp_tp_cp_ep` — `aten.add got mixed torch.Tensor and
DTensor` (CP+EP bug)
- `deepseek_v3_precompile_fsdp_tp_ep` — precompile unbacked-symint
failure (`Could not extract specialized integer from u13`, sharding prop
on `aten.view`)
- `deepseek_v3_hybridep` — requires the `deep_ep` package
- DSv3 `test_bitwise_deterministic` (2) — stale golden hashes (need
re-blessing; not a code bug)
- AutoParallel tests — require the `autoparallel` package
- JIT-mode / partitioner #2149 tests — separate partitioner regression

## Caveat: cudagraph + context parallelism

The two CP tests are enabled with `--compile.disable_passes
cudagraph_pass`. CUDA-graph **replay** of the coalesced FSDP collectives
still fails under context parallelism with `CUDA error: invalid
argument` — a separate, pre-existing issue. Each carries a TODO to drop
the flag once that's fixed.

## Test plan

```
# llama3 suite (passes end-to-end on 8xH100)
python torchtitan/experiments/graph_trainer/tests/integration_tests.py <out> \
  --test_suite graph_trainer_default --ngpu 8
# qwen3 / deepseek_v3 configs run individually on 8xH100
pytest torchtitan/experiments/graph_trainer/tests/test_trace_module.py   # 46 passed, 2 skipped
pytest torchtitan/experiments/graph_trainer/tests/test_numerics.py -k aot_fx_trace  # 4 passed
```

🤖 Generated with [Claude Code](https://claude.com/claude-code)
SherlockNoMad added a commit that referenced this pull request Jun 3, 2026
…y_strided shadow-node bug)

The skip on `test_llama3_aot_fx_trace_autoparallel_vs_eager` (and the
integration test `autoparallel_llama3_fsdp_tp`) blamed an "upstream
AutoParallel nll_loss assertion regression" / "incorrect loss partitioning".
That was a misattribution: it is the same empty_strided dead-shadow-node bug
that #3480 root-caused and fixed with `_remove_dead_empty_strided_chains`.

AutoParallel produces a model-only graph (vocab-sharded DTensor logits); the
loss op is applied afterwards inside graph_trainer's `make_fwd_bwd_step`, which
is traced by `minimal_fx_tracer` -- exactly the graph the DCE cleans. Under the
unfixed nightly, DTensor shard propagation leaves a dead `nll_loss` shadow node
reading an uninitialized `empty_strided` target, which trips the bounds check
`t >= 0 && t < n_classes` at runtime (same failure class as the embedding OOB).
`_remove_dead_empty_strided_chains` strips that dead chain. The upstream fix is
pytorch/pytorch #185865.

Verified on 8xH100 (autoparallel installed): the loss matches eager (max diff
1.3e-4), `1 passed`. CI runs this unit test on the unfixed nightly
(integration_test_8gpu_graph_trainer.yaml), so it exercises the DCE path
directly -- keep `_remove_dead_empty_strided_chains` until #185865 lands.

The DSv3 AutoParallel and JIT (#2149) tests remain disabled: separate,
still-open bugs (confirmed #2149 still reproduces "Node tangents_2 was invalid,
but is output").

Test plan:
  pytest torchtitan/experiments/graph_trainer/tests/test_numerics.py::TestGraphTrainerAutoParallelNumerics::test_llama3_aot_fx_trace_autoparallel_vs_eager

🤖 Generated with [Claude Code](https://claude.com/claude-code)
SherlockNoMad added a commit that referenced this pull request Jun 4, 2026
…y_strided shadow-node bug)

The skip on `test_llama3_aot_fx_trace_autoparallel_vs_eager` (and the
integration test `autoparallel_llama3_fsdp_tp`) blamed an "upstream
AutoParallel nll_loss assertion regression" / "incorrect loss partitioning".
That was a misattribution: it is the same empty_strided dead-shadow-node bug
that #3480 root-caused and fixed with `_remove_dead_empty_strided_chains`.

AutoParallel produces a model-only graph (vocab-sharded DTensor logits); the
loss op is applied afterwards inside graph_trainer's `make_fwd_bwd_step`, which
is traced by `minimal_fx_tracer` -- exactly the graph the DCE cleans. Under the
unfixed nightly, DTensor shard propagation leaves a dead `nll_loss` shadow node
reading an uninitialized `empty_strided` target, which trips the bounds check
`t >= 0 && t < n_classes` at runtime (same failure class as the embedding OOB).
`_remove_dead_empty_strided_chains` strips that dead chain. The upstream fix is
pytorch/pytorch #185865.

Verified on 8xH100 (autoparallel installed): the loss matches eager (max diff
1.3e-4), `1 passed`. CI runs this unit test on the unfixed nightly
(integration_test_8gpu_graph_trainer.yaml), so it exercises the DCE path
directly -- keep `_remove_dead_empty_strided_chains` until #185865 lands.

The DSv3 AutoParallel and JIT (#2149) tests remain disabled: separate,
still-open bugs (confirmed #2149 still reproduces "Node tangents_2 was invalid,
but is output").

Test plan:
  pytest torchtitan/experiments/graph_trainer/tests/test_numerics.py::TestGraphTrainerAutoParallelNumerics::test_llama3_aot_fx_trace_autoparallel_vs_eager

🤖 Generated with [Claude Code](https://claude.com/claude-code)
SherlockNoMad added a commit that referenced this pull request Jun 4, 2026
…y_strided shadow-node bug) (#3495)

## Summary

The skip on `test_llama3_aot_fx_trace_autoparallel_vs_eager` and the
integration test `autoparallel_llama3_fsdp_tp` blamed an *"upstream
AutoParallel nll_loss assertion regression"* / *"incorrect loss
partitioning"*. That was a **misattribution** — it is the same
`empty_strided` dead-shadow-node bug that #3480 root-caused and fixed
with `_remove_dead_empty_strided_chains`.

## Root cause

AutoParallel produces a **model-only** graph (vocab-sharded DTensor
logits); the loss op is applied afterwards inside graph_trainer's
`make_fwd_bwd_step`, which is traced by `minimal_fx_tracer` — **exactly
the graph the DCE cleans**. Under the unfixed nightly, DTensor shard
propagation leaves a dead `nll_loss` shadow node reading an
uninitialized `empty_strided` target, which trips the bounds check `t >=
0 && t < n_classes` at runtime — the same failure class as the embedding
OOB in #3480. `_remove_dead_empty_strided_chains` strips that dead
chain. The upstream fix is pytorch/pytorch #185865.

Minimal isolation (simulating the unfixed nightly by restoring the
pre-fix `_propagate_tensor_meta_non_cached`) confirms the DCE removes
the dead bounds-checked shadow op:
```
before: empty_strided=2, embedding=2   # dead aten.embedding(empty_strided_w, empty_strided_idx) [num_users=0]
after _remove_dead_empty_strided_chains: empty_strided=0, embedding=1
```

## Verification

Ran on 8×H100 with `autoparallel` installed — loss matches eager:
```
Max loss difference: step=11 baseline=3.6115226 test=3.6113948 diff=0.000128
1 passed in 226.67s
```

CI runs this unit test on the **unfixed** nightly
(`integration_test_8gpu_graph_trainer.yaml`), so it exercises the DCE
path directly. Keep `_remove_dead_empty_strided_chains` until #185865
lands.

## Left disabled (verified separate, still-open bugs)

- **DSv3 AutoParallel** — different failure, not the shadow-node bug.
- **JIT (#2149)** — confirmed still reproduces `AssertionError: Node
tangents_2 was invalid, but is output` in
`torch/_functorch/partitioners.py`.

## Test plan

```bash
pytest torchtitan/experiments/graph_trainer/tests/test_numerics.py::TestGraphTrainerAutoParallelNumerics::test_llama3_aot_fx_trace_autoparallel_vs_eager
```

🤖 Generated with [Claude Code](https://claude.com/claude-code)
sunjie279 pushed a commit to lds-ustc/EasyOPD that referenced this pull request Jun 17, 2026
### What does this PR do?

Add RL support for TorchtitanEngine. Tested FSDP, TP/SP on Qwen3 0.6b
and verified parity with FSDP engine.

Note: 
- TP requires Torchtitan to have full DTensor:
pytorch/torchtitan#2149 (will land soon)
- Will add PP and EP support, and set up integration/CI test for
torchtitan engine as follow up PRs.
- Torchtitan critic model is not supported, will follow up. GRPO doesn't
use critic.

### Test
```
GRPC_ENABLE_FORK_SUPPORT=0 NCCL_NVLS_ENABLE=0 MODEL_ID=Qwen/Qwen3-0.6B bash tests/special_e2e/run_ppo_trainer_torchtitan.sh

NUM_GPUS=4 FSDP_SIZE=2 TP_SIZE=2 GRPC_ENABLE_FORK_SUPPORT=0 NCCL_NVLS_ENABLE=0  bash tests/special_e2e/run_ppo_trainer_torchtitan.sh
```
[Package versions I am
using](https://gist.github.com/acisseJZhong/e6f3920df5c5d88fef86750ce8518141),
[version
2](https://gist.github.com/acisseJZhong/6cf2c14eab40a5c2a129443027894317)
[Torchtitan engine
config](https://gist.github.com/acisseJZhong/6e68366c50b8efa396bcb50da7701a84)
[FSDP engine
config](https://gist.github.com/acisseJZhong/9decbe8a22c3f5b0499f42f21229e10d)

test on qwen3 0.6b single process
- **critic scores, actor pg loss, actor loss are matching, and Titan
step time is significantly less than FSDP engine**

<img width="1380" height="668" alt="image"
src="https://github.com/user-attachments/assets/b2270ae0-71bd-4769-b7ff-73d06489a529"
/>
<img width="1378" height="678" alt="image"
src="https://github.com/user-attachments/assets/6c6a8739-4a1d-44f5-abbd-3dc4f830ed45"
/>
<img width="1378" height="665" alt="image"
src="https://github.com/user-attachments/assets/c5ee9191-5995-4138-b9af-f77f64d77af8"
/>

test on qwen3 0.6b fsdp_size=2, tp_size=2
<img width="1343" height="637" alt="image"
src="https://github.com/user-attachments/assets/f3abf367-b106-49c3-9bad-e5d4597b7c85"
/>
<img width="1337" height="617" alt="image"
src="https://github.com/user-attachments/assets/948aea2a-3e95-4fe1-80cb-7244c23483f1"
/>
<img width="1345" height="605" alt="image"
src="https://github.com/user-attachments/assets/22c3fbbb-c352-4160-b0eb-1cbc398fea4a"
/>


### Checklist Before Submitting

> [!IMPORTANT]
> Please check all the following items before requesting a review,
otherwise the reviewer might deprioritize this PR for review.

- [ ] Read the [Contribute
Guide](https://github.com/volcengine/verl/blob/main/CONTRIBUTING.md).
- [ ] Apply [pre-commit
checks](https://github.com/volcengine/verl/blob/main/CONTRIBUTING.md#code-linting-and-formatting):
`pre-commit install && pre-commit run --all-files --show-diff-on-failure
--color=always`
- [ ] Add / Update [the
documentation](https://github.com/volcengine/verl/tree/main/docs).
- [ ] Add unit or end-to-end test(s) to [the CI
workflow](https://github.com/volcengine/verl/tree/main/.github/workflows)
to cover all the code. If not feasible, explain why: ...
- [ ] Once your PR is ready for CI, send a message in [the `ci-request`
channel](https://verl-project.slack.com/archives/C091TCESWB1) in [the
`verl` Slack
workspace](https://join.slack.com/t/verl-project/shared_invite/zt-3855yhg8g-CTkqXu~hKojPCmo7k_yXTQ).
(If not accessible, please try [the Feishu group
(飞书群)](https://applink.larkoffice.com/client/chat/chatter/add_by_link?link_token=772jd4f1-cd91-441e-a820-498c6614126a).)
- [ ] If your PR is related to the `recipe` submodule, please also
update the reference to the submodule commit via `git submodule update
--remote` or `cd recipe && git pull origin main`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot. high priority

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

8 participants