Skip to content

[rl] Enable FSDP on the generator - #4838

Merged
tianyu-l merged 1 commit into
pytorch:mainfrom
andrewor14:generator-fsdp-pr
Oct 8, 2026
Merged

tianyu-l merged 1 commit into
pytorch:mainfrom
andrewor14:generator-fsdp-pr

Conversation

@andrewor14

@andrewor14 andrewor14 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary: Enable FSDP on the generator for quantization,
which reuses the FSDP tensor lifecycle mechanism introduced in
#4203 but for inference.
We use fsdp=1 to avoid an actual all-gather for now.

New lifecycle:

bf16 sharded params (_LinearShardedTensorWithMXFP8Compute)
        |                                            ^
        |  fetch from TorchStore (new weight sync)   |
        v                                            |
updated bf16 sharded params                          |
        |                                            |
        |  unshard                                   |
        v                                            |
all-gathered mxfp8 params (_UnshardedFSDPTensor)     |
        |                                            |
        |                                            |
        |  forward (many decode steps)               |
        |                                            |
        ----------------------------------------------
                            reshard

Code cleanups enabled by this change:

  • Removed skip_dp flag, since we never skip_dp anymore
  • Removed spmd <-> DTensor glue code during weight sync,
    since model state dict always contains DTensors now

Design considerations:

  1. Cudagraph compatibility: FSDP frees the unsharded storage
    today on reshard. However, cudagraph requires the unsharded
    address be stable across weight syncs. This is enabled through
    model.set_keep_unsharded_storage(True), added in
    [fsdp2] Optionally keep unsharded storage across reshard pytorch#198417.

  2. Avoid extra memory during decode: FSDP never frees the
    sharded storage today because it's supposed to be the source of
    truth. However, during decode, we don't actually need the bf16
    copy anymore, since forward only needs the mxfp8 operands.
    At fsdp=1, this incurs an extra bf16 copy of the weights per
    layer during decode. We work around this by calling private
    FSDP APIs to free this storage after unshard.

Memory lifecycle:

1. prepare_for_state_dict_load: re-allocate previously freed sharded buffers
            |   
            |  1 bf16 copy + 1 mxfp8 copy
            v
2. model.state_dict() hook: reshards model (but keep unsharded buffers)
            |
            |  1 bf16 copy + 1 mxfp8 copy
            v
3. ts.get_state_dict: fetch new weights into sharded buffers
            |
            |  1 bf16 copy + 1 mxfp8 copy
            v
4. prepare_for_forward: free sharded buffers
            |
            |  1 mxfp8 copy
            v
(prefill/decode, then repeat step 1)

Testing: For DAPO math Qwen3-4B, the reward was consistent with before this PR and matches the README reference, with MXFP8 decode 27% faster than before this PR.

image

@pytorch-bot

pytorch-bot Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 22, 2026
@andrewor14
andrewor14 marked this pull request as draft September 22, 2026 20:18
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Sep 22, 2026

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

very cool!!

Comment thread torchtitan/rl/generator.py Resolved
Comment thread torchtitan/rl/generator.py Resolved
Comment thread torchtitan/rl/model/vllm_wrapper.py Resolved
Comment thread torchtitan/quantization/mxfp8/linear.py Resolved
Comment thread torchtitan/rl/model/vllm_wrapper.py Resolved
Comment thread torchtitan/rl/model/vllm_wrapper.py Resolved
Comment thread torchtitan/rl/model/vllm_wrapper.py Resolved
Comment thread torchtitan/rl/model/vllm_wrapper.py Resolved
Comment thread torchtitan/rl/model/vllm_wrapper.py Resolved
@tianyu-l
tianyu-l requested a review from weifengpy September 23, 2026 00:30

@anijain2305 anijain2305 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 work!

Comment thread torchtitan/quantization/_fsdp_tensor.py Resolved
Comment thread torchtitan/rl/model/vllm_wrapper.py Resolved
andrewor14 added a commit to pytorch/pytorch that referenced this pull request Sep 23, 2026
**Summary:** This commit adds two flags to `FSDPModule.reshard`:

- `free_unsharded`: Whether to free the unsharded storage,
  useful for cudagraphs which requires unsharded addresses to
  remain the same. Defaults to True.

- `force`: Whether to always trigger a reshard, regardless
  of RAF setting (previously no-op if RAF=false). This is
  useful for inference where RAF=false. Defaults to False.

Enables pytorch/torchtitan#4838.

**Test Plan:**

```
python test/distributed/_composable/fsdp/test_fully_shard_training.py \
    TestFullyShardRegisteredParams.test_force_reshard_with_raf_disabled_in_forward
```
andrewor14 added a commit to pytorch/pytorch that referenced this pull request Sep 23, 2026
**Summary:** This commit adds two flags to `FSDPModule.reshard`:

```
free_unsharded (default True):
    Whether to free the unsharded storage, useful for cudagraphs
    which requires unsharded addresses to remain the same.

force (default False):
    Whether to always trigger a reshard, regardless of RAF setting.
    Previously, reshard is a no-op if RAF=false, which is always
    the case for inference.
```

Enables pytorch/torchtitan#4838.

**Test Plan:**

```
python test/distributed/_composable/fsdp/test_fully_shard_training.py \
    TestFullyShardRegisteredParams.test_force_reshard_with_raf_disabled_in_forward
```
andrewor14 added a commit to pytorch/pytorch that referenced this pull request Sep 23, 2026
**Summary:** This commit adds two flags to `FSDPModule.reshard`:

```
free_unsharded (default True):
    Whether to free the unsharded storage, useful for cudagraphs
    which requires unsharded addresses to remain the same.

force (default False):
    Whether to always trigger a reshard, regardless of RAF setting.
    Previously, reshard is a no-op if RAF=false, which is always
    the case for inference.
```

Enables pytorch/torchtitan#4838
and preserves existing behavior.

**Test Plan:**

```
python test/distributed/_composable/fsdp/test_fully_shard_training.py \
    TestFullyShardRegisteredParams.test_force_reshard_with_raf_disabled_in_forward
```
andrewor14 added a commit to pytorch/pytorch that referenced this pull request Sep 23, 2026
**Summary:** This commit adds two flags to `FSDPModule.reshard`:

```
free_unsharded (default True):
    Whether to free the unsharded storage, useful for cudagraphs
    which requires unsharded addresses to remain the same.

force (default False):
    Whether to always trigger a reshard, regardless of RAF setting.
    Previously, reshard is a no-op if RAF=false, which is always
    the case for inference.
```

Enables pytorch/torchtitan#4838
and preserves existing behavior.

**Test Plan:**

```
python test/distributed/_composable/fsdp/test_fully_shard_training.py \
    TestFullyShardRegisteredParams.test_force_reshard_with_raf_disabled_in_forward
```
Comment thread torchtitan/rl/model/vllm_wrapper.py Resolved
Comment thread torchtitan/quantization/mxfp8/linear.py Resolved
@andrewor14
andrewor14 force-pushed the generator-fsdp-pr branch 3 times, most recently from 556755b to d2bd774 Compare October 2, 2026 20:01
Comment thread torchtitan/rl/model/vllm_wrapper.py Resolved
pytorchmergebot pushed a commit to pytorch/pytorch that referenced this pull request Oct 2, 2026
**Summary:** Add a recursive setter that controls whether resharding
frees the unsharded parameter storage. This preserves storage addresses
without changing the existing reshard API.

```python
model = fully_shard(model)
model.set_keep_unsharded_storage(True)
model.unshard()
model.reshard()  # Unsharded storage stays resident in memory.
```

Enables pytorch/torchtitan#4838 and preserves
existing behavior.

**Test Plan:**
```
python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py \
  -k keep_unsharded_storage

python test/distributed/_composable/fsdp/test_fully_shard_training.py \
  -k keep_unsharded_storage_with_post_forward_reshard
```
Pull Request resolved: #198417
Approved by: https://github.com/weifengpy
@andrewor14
andrewor14 force-pushed the generator-fsdp-pr branch 2 times, most recently from 5489c8b to e8487e7 Compare October 2, 2026 20:50
Comment thread torchtitan/rl/model/vllm_wrapper.py Resolved
@tianyu-l

tianyu-l commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

@claude could you review the change in vllm_wrapper.py, where get_state_dict_layouts is deleted? I would like to make sure that this PR won't cause regression, given that I forgot why exactly those code was added in the first place, for spmd_types compatibility.

@claude

claude Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 18s —— View job


Review: removing get_state_dict_layouts / spmd_types <-> DTensor glue

  • Figure out why get_state_dict_layouts / PlainToDTensorStateDictAdapter were added
  • Trace how generator FSDP represents TP/EP-sharded spmd_types params
  • Check the initial HF load path (from_hf fused-QKV resharding)
  • Check the TorchStore weight-sync path (buffers, params with no sharding config)
  • Post findings

Bottom line: I don't see a correctness regression from deleting get_state_dict_layouts. The glue existed only because skip_dp=True left generator params as plain local tensors. With FSDP now applied, the generator state dict goes through the same FSDP -> DTensor path the trainer already uses, so all three jobs the layouts did are handled elsewhere. Two things are worth following up: test coverage, and a behavior change at data_parallel_degree=2. Both are below.

Why the code existed

Before this PR, the generator ran with skip_dp=True. TP/EP-sharded params under spmd_types were plain local tensors with no DTensor metadata. get_state_dict_layouts() rebuilt a {fqn: SpmdType} map from each module's _sharding_config.state_shardings so that plain_tensor_to_dtensor_state_dict could wrap the tensors as DTensors. It had three consumers:

  1. TorchStore weight sync (_get_spmd_state_dict, plus the CPU prefetch buffers in VLLMGenerator.__init__). TorchStore only knows how to reshard DTensor entries, so plain TP shards had to be wrapped to get the right slice of the trainer's tensor.
  2. Initial HF load (PlainToDTensorStateDictAdapter). to_hf needs DTensors to fuse q/k/v. On the way back, from_hf split fused tensors, so torch.cat of Shard(0) pieces followed by split came out with a different placement than the model's (usually Replicate). The adapter called redistribute(...) back to the model layout before to_local(), because to_local() on the wrong placement gives the wrong local shard. The deleted test_hf_adapter_restores_local_shards covered exactly this, for Qwen3.5 in_proj_q/k/v, conv_q/k/v and vision wq/wk/wv.
  3. Buffers and params with no sharding config. The vllm_attn _k_scale/_q_scale/... entries and the else: SpmdType({}) branch were only there so plain_tensor_to_dtensor_state_dict wouldn't raise KeyError. An empty SpmdType({}) resolves to get_activated_mesh(()) -> None -> continue, so those entries were never wrapped anyway.

Why it's safe to remove now

  • (1) TorchStore. _apply_fsdp -> resolve_fsdp_mesh (torchtitan/distributed/fsdp.py:81-108) passes DataParallelMeshDims whenever the dense storage mesh [dp_replicate, dp_shard, cp, tp] has size > 1. That is always true when TP > 1. fully_shard then turns the spmd_types annotations into DTensor params on the joint (dp_shard, tp) mesh, which is what @pianpwk described. The EP experts get the same treatment through edp_mesh_dims. So model.state_dict() now has DTensors with both the TP and FSDP placements, the same representation the trainer pushes. The pinned CPU buffers built from it in vllm_wrapper.py (_create_cpu_state_dict(self.model.state_dict(), ...)) also keep those layouts. When TP=1 and DP=1, the mesh has size 1, so there's nothing to resolve.
  • (2) HF load. dcp.py:400-401 (sd_adapter.from_hf(...) then load_state_dict) now loads DTensors into FSDP DTensor params, and nothing is converted to local tensors. If a fused-QKV split produces a Replicate DTensor, it reaches param.copy_(src), and DTensor redistributes src to the param's placements. This is the trainer's FSDP+TP HF-load path, which is already exercised. The manual redistribute was only needed because the old path dropped the DTensor metadata.
  • (3) Buffers and unannotated params. FSDP doesn't touch buffers, so the vllm_attn scales stay plain tensors, the same as before. Params with no _sharding_config used to be plain, full tensors. Now they are FSDP DTensors (full at fsdp=1), which TorchStore handles the same way as on the trainer side.

Things I'd still flag

  1. Test coverage was dropped along with the glue. tests/rl/unit_tests/cpu/test_vllm_wrapper.py was deleted as a whole file, but:

    • test_vllm_replacements_preserve_resolved_sharding has nothing to do with layouts. It tests _replace_vllm_layer_configs, which still exists (vllm_wrapper.py:45). That test should be kept.
    • The fused-QKV round trip (test_hf_adapter_restores_local_shards) is the one case where the old code did more than wrap tensors. It would be worth porting to the new path: build a TP=2 model under fully_shard (gloo / fake PG), run to_hf -> from_hf -> load_state_dict, and check the local shards. Alternatively, point to an existing GPU/integration test that loads a Qwen3.5 HF checkpoint into a TP>1 generator and checks logits. That would give direct evidence for point (2) above instead of relying on the trainer path.
      Fix this ->
  2. data_parallel_degree=2 now means real FSDP sharding. This isn't about the deleted function, but it is a behavior change. The PR description says "fsdp=1", but InferenceParallelismConfig.to_training() maps data_parallel_degree straight to data_parallel_shard_degree. The EP recipes (rl_grpo_qwen3_moe_debug_varlen*, alphabet_sort.py:739,893,969, generator DP=2/TP=2/EP=4) therefore now shard dense params over 2 vLLM DP ranks. That means a real all-gather in prepare_for_forward, while before each rank held a full replica. The experts are unaffected (edp_shard = 8/... = 1). It should be correct, since _pull_model_state_dict runs on all ranks, but it's not the fsdp=1 setup the description talks about. It's also the configuration where (2) and the EP shard_placement_fn path matter most. Please confirm that test_generator_uneven_decode and the MoE bitwise-parity test pass on this PR, or update the description and the docstring at parallelism.py:19.

Overall, removing get_state_dict_layouts, PlainToDTensorStateDictAdapter and the plain_tensor_to_dtensor_state_dict/dtensor_to_plain_tensor_state_dict helpers looks justified to me.

Note: the CI checkout is shallow and I couldn't fetch full history, so I worked out the original purpose from the deleted code and tests rather than from the commit that added them. I reviewed the code only and didn't run any tests.

Comment thread torchtitan/rl/model/vllm_wrapper.py Resolved
@andrewor14

Copy link
Copy Markdown
Contributor Author

@claude review the latest changes, is the vllm scale buffer spmd_types annotation issue resolved? See this comment: #4838 (comment)

Comment thread torchtitan/rl/model/attention.py Resolved
Comment thread torchtitan/rl/model/vllm_wrapper.py Resolved
Comment thread torchtitan/rl/model/vllm_wrapper.py Resolved
Comment thread torchtitan/rl/model/attention.py Resolved
@andrewor14
andrewor14 force-pushed the generator-fsdp-pr branch 2 times, most recently from f5ab7ee to 61d3c41 Compare October 6, 2026 21:37
Comment thread torchtitan/rl/model/vllm_wrapper.py Outdated
local_sinks = sinks._local_tensor if isinstance(sinks, DTensor) else sinks
module.inner_attention.vllm_attn.impl.out_transform = partial(
apply_attention_sink_rescale, sinks=local_sinks
_apply_attention_sink_rescale, module

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.

@tianyu-l latest fix for integration test, tldr is sinks here could be the sharded params which may be freed at this point, so we populate sinks dynamically instead

Comment thread torchtitan/rl/model/vllm_wrapper.py Resolved
@andrewor14
andrewor14 force-pushed the generator-fsdp-pr branch 3 times, most recently from dfa1246 to 3c76ab8 Compare October 7, 2026 22:06
**Summary:** Enable FSDP on the generator for quantization,
which reuses the FSDP tensor lifecycle mechanism introduced in
pytorch#4203 but for inference.
We use fsdp=1 to avoid an actual all-gather for now.

New lifecycle:

```
bf16 sharded params (_LinearShardedTensorWithMXFP8Compute)
        |                                            ^
        |  fetch from TorchStore (new weight sync)   |
        v                                            |
updated bf16 sharded params                          |
        |                                            |
        |  unshard                                   |
        v                                            |
all-gathered mxfp8 params (_UnshardedFSDPTensor)     |
        |                                            |
        |                                            |
        |  forward (many decode steps)               |
        |                                            |
        ----------------------------------------------
                            reshard
```

Code cleanups enabled by this change:
- Removed `skip_dp` flag, since we never skip_dp anymore
- Removed spmd <-> DTensor glue code during weight sync,
  since model state dict always contains DTensors now

**Design considerations:**

1. **Cudagraph compatibility:** FSDP frees the unsharded storage
  today on reshard. However, cudagraph requires the unsharded
  address be stable across weight syncs. This is enabled through
  `model.set_keep_unsharded_storage(True)`, added in
  pytorch/pytorch#198417.

2. **Avoid extra memory during decode:** FSDP never frees the
  sharded storage today because it's supposed to be the source of
  truth. However, during decode, we don't actually need the bf16
  copy anymore, since forward only needs the mxfp8 operands.
  At fsdp=1, this incurs an extra bf16 copy of the weights per
  layer during decode. We work around this by calling private
  FSDP APIs to free this storage after unshard.

Memory lifecycle:

```
1. prepare_for_state_dict_load: re-allocate previously freed sharded buffers
            |
            |  1 bf16 copy + 1 mxfp8 copy
            v
2. model.state_dict() hook: reshards model (but keep unsharded buffers)
            |
            |  1 bf16 copy + 1 mxfp8 copy
            v
3. ts.get_state_dict: fetch new weights into sharded buffers
            |
            |  1 bf16 copy + 1 mxfp8 copy
            v
4. prepare_for_forward: free sharded buffers
            |
            |  1 mxfp8 copy
            v
(prefill/decode, then repeat step 1)
```

Note: In step (2), there is currently a memory spike since FSDP
allocates separate buffers for unsharded and sharded buffers, and
we need to keep both resident in memory during weight sync. E.g.
for bf16 generator and fsdp=1, this currently uses 2x the model
memory. This may be fine since it's not the peak memory, but we
should revisit in the future.
@tianyu-l
tianyu-l merged commit 980f83a into pytorch:main Oct 8, 2026
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
)

**Summary:** Add a recursive setter that controls whether resharding
frees the unsharded parameter storage. This preserves storage addresses
without changing the existing reshard API.

```python
model = fully_shard(model)
model.set_keep_unsharded_storage(True)
model.unshard()
model.reshard()  # Unsharded storage stays resident in memory.
```

Enables pytorch/torchtitan#4838 and preserves
existing behavior.

**Test Plan:**
```
python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py \
  -k keep_unsharded_storage

python test/distributed/_composable/fsdp/test_fully_shard_training.py \
  -k keep_unsharded_storage_with_post_forward_reshard
```
Pull Request resolved: pytorch#198417
Approved by: https://github.com/weifengpy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants