Skip to content

[rl] FSDP generator: sync weights one FSDP module at a time - #5268

Merged
felipemello1 merged 6 commits into
pytorch:mainfrom
felipemello1:fix/rl-fsdp-generator-per-module-weight-sync
Oct 11, 2026
Merged

felipemello1 merged 6 commits into
pytorch:mainfrom
felipemello1:fix/rl-fsdp-generator-per-module-weight-sync

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

TLDR: On main, a weight sync holds two copies of the generator's weights, so the first sync OOMs unless the second copy fits in the ~6 GiB that vLLM leaves free on an H100. This PR syncs one FSDP module at a time: Qwen3.5-35B-A3B at TP1 needs 1.6 GiB extra instead of its 64.6 GiB state dict, and the KV cache keeps its size.

Problem

  1. With FSDP, each weight has a sharded buffer, which load_state_dict writes, and an unsharded buffer, which forward and CUDA graphs read.
  2. Between syncs, only the unsharded buffers stay allocated.
  3. A sync re-allocates all sharded buffers (prepare_for_state_dict_load) before load_state_dict, so both sets are resident.
  4. With generator FSDP degree 1 (TP-only or 1-GPU generators), the sharded set is a whole second copy of the local model.
  5. vLLM fills GPU memory up to gpu_memory_limit (default 0.9) at startup, leaving a sync about 6 GiB on a 95 GiB H100.
  6. Qwen3.5-9B at TP1 needs 16.7 GiB and OOMs at the first sync.

Solution

  1. VLLMModelWrapper.load_state_dict (overriding nn.Module's, keyed like self.model) keeps one load_state_dict call. For each group of modules sharded together (e.g. [norm, lm_head]), it adds a temporary pre-hook on the first module, which calls prepare_for_state_dict_load for that group, and a post-hook on the last, which calls prepare_for_forward.
  2. prepare_for_state_dict_load no longer skips groups that already read as sharded: FSDP's own load pre-hook reshards a module that owns parameters (e.g. tok_embeddings) before ours runs.
  3. The generator's pull calls model.load_state_dict(model_sd).
  4. Both prepare methods take one FSDPModule and act on its FSDP group; __init__ loops over the FSDP modules for the initial unshard.
before:  re-allocate ALL sharded -> load_state_dict -> unshard + free ALL           peak: 2x weights
after:   load_state_dict, per FSDP group: re-allocate -> copy -> unshard + free     peak: weights + ~1 group

With tied embeddings, the [tok_embeddings, norm, lm_head] group stays allocated for the whole load.

Results

H100 (95 GiB), bf16, gpu_memory_limit 0.9: extra GPU memory during one sync
main = the state dict size; this PR = measured peak
Qwen3.5-35B-A3B, TP1     64.6 -> 1.6 GiB     (5.9 GiB free)    sync 1.3 s
Qwen3.5-9B, TP1          16.7 -> 1.9 GiB     (6.1 GiB free)    sync 0.37 s   main OOM observed
Qwen3.5-9B, TP2           8.3 -> 0.95 GiB    (5.7 GiB free)    sync 0.2-0.24 s
Qwen3.5-4B, TP1, tied     9.0 -> 1.4 GiB     (6.1 GiB free)    sync 0.2 s
  • Greedy decode under FULL CUDA graphs is identical across syncs of the same weights. A perturbed norm.weight changes it, and undoing that restores it.
  • RL runs, H100:
    • Qwen3.5-4B-Base, 2 GPUs, generator TP1, 8 steps: trainer-generator logprob diff mean 5.6e-5 at step 8.
    • rl_grpo_qwen3_moe_debug_varlen (generator DP=2, so a real FSDP all-gather inside the load; CUDA graphs off), 5 steps: per-step max logprob diff 0.009-0.059, main 0.007-0.058; pull 0.60 s, main 0.62 s.
    • rl_dapo_qwen3_4b_math_8k, 8 GPUs, 109 steps (then stopped by an unrelated host OOM kill): mean reward 0.17 over steps 1-10 and 0.35 over steps 91-109; 0.2 s per sync.

You may ask:

  • Why per FSDP group, not per module? fully_shard([norm, lm_head]) gives both one FSDP state; unsharding after norm would all-gather lm_head before it loads.
  • Why hooks, not one load_state_dict per FSDP module? That call also loads the nested FSDP modules, whose sharded buffers are still freed.
  • Why not leave room for the second copy, by lowering gpu_memory_limit or reserving it during vLLM's memory profiling? It comes out of the KV cache. Reserving it at profiling, on one H100:
    Qwen3.5-9B TP1          KV cache 67.81 -> 51.44 GiB (1.23M -> 0.93M tokens)
    Qwen3.5-35B-A3B TP1     engine fails to start (OOM during memory profiling)
    

NOTE: results above are from an earlier main (49c4cff1f); the 9B and 35B probes were re-run on this branch (below).

Test plan

  • pytest tests/rl/unit_tests/cpu/test_generator.py tests/rl/unit_tests/cpu/test_engine_loop.py tests/rl/unit_tests/cpu/test_inter_generator_router.py tests/rl/unit_tests/cpu/test_weight_sync.py
  • pytest tests/rl/unit_tests/cpu/test_vllm_wrapper.py::test_load_state_dict_allocates_one_fsdp_group_at_a_time (new): real FSDP2 on CPU, a tied [tok_embeddings, norm, lm_head] group plus 3 blocks. Each group's sharded buffers are allocated before its copy, at most 2 groups at once, all are freed after, and every param equals the new weights. It fails if the is_sharded skip comes back.
  • torchrun --nproc-per-node=2 -m pytest tests/rl/unit_tests/gpu/test_bitwise_parity.py::TestBitwiseParityQwen35DebugVarlen (4 passed): its weight sync fills the generator's pinned CPU copy and calls wrapper.load_state_dict, as production does.
  • 1-GPU engine probe on this branch (vLLM engine with the TorchTitan generator model, FULL CUDA graphs, two syncs):
    Qwen3.5-9B TP1          sync extra peak 1.89 GiB, 0.37 / 0.35 s
    Qwen3.5-35B-A3B TP1     sync extra peak 1.57 GiB, 1.34 / 1.33 s
    both: greedy identical after syncing the same weights, changed by a perturbed norm.weight, restored after undoing it
    

A weight sync re-allocated every module's sharded buffers before one
load_state_dict, while the unsharded buffers that CUDA graphs read stayed
resident, so it held two copies of the generator's weights. vLLM sizes its KV
cache at startup and leaves only the memory above gpu_memory_limit free, so
on an H100 at gpu_memory_limit 0.9 the first sync needs more than is free:
- Qwen3.5-9B, TP1: 16.7 GiB with 6.1 GiB free (OOM observed)
- Qwen3.5-9B, TP2 (rl_grpo_qwen3_5_9b_varlen's generator): 8.3 GiB with 5.7 GiB free
- Qwen3.5-35B-A3B, TP1: 64.6 GiB with 5.9 GiB free

VLLMModelWrapper.load_model_state_dict replaces prepare_for_state_dict_load,
load_state_dict and prepare_for_forward in the generator's pull. It keeps one
load_state_dict call and adds temporary hooks per group of modules sharded
together: a pre-hook on the first re-allocates the group's sharded buffers,
and a post-hook on the last unshards into the kept buffers and frees the
sharded ones. Calling load_state_dict per module instead would also reshard
every module nested in it while its sharded buffers are freed.

A sync now adds about one module's weights: 1.6 GiB for 35B-A3B, 1.9 GiB for
9B (its embedding). Tested on H100 with 35B-A3B TP1, 9B TP1/TP2 and 4B (tied
embeddings): greedy decode is identical across syncs of the same weights, and
a perturbed norm weight changes the output and then restores it.
@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Oct 11, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 11, 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.

nice! Happy to stamp after you addressed comments

Comment thread torchtitan/rl/generator.py Outdated
# Perform the local CPU-to-GPU copy
model.model.load_state_dict(model_sd, strict=True)
model.prepare_for_forward()
model.load_model_state_dict(model_sd)

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.

Suggested change
model.load_model_state_dict(model_sd)
model.load_state_dict(model_sd)

modules_by_fsdp_state = defaultdict(list)
for module in self.model.modules():
if isinstance(module, FSDPModule):
modules_by_fsdp_state[module._get_fsdp_state()].append(module)

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.

oh this looks a bit subtle -- IIUC the existence of the dict at all is because you want this per- FSDP group behavior

For each group of modules sharded together (e.g. [norm, lm_head]), it adds a temporary pre-hook on the first module, which calls prepare_for_state_dict_load for that group, and a post-hook on the last, which calls prepare_for_forward.

but curious why do we want the per-group behavior -- it seems because the code below has
for param_group in module._get_fsdp_state()._fsdp_param_groups which covers one whole group at a time

Please add some documents, as the code is not very readable

cc @weifengpy

handles = []
for modules in modules_by_fsdp_state.values():
handles.append(
modules[0].register_load_state_dict_pre_hook(

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 hooks, not one load_state_dict per FSDP module? That call also loads the nested FSDP modules, whose sharded buffers are still freed.

Please add a comment on why doing this

Comment thread torchtitan/rl/model/vllm_wrapper.py Outdated
handle.remove()

def prepare_for_state_dict_load(
self, modules: Iterable[torch.nn.Module] | None = 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.

from what I read we only need

Suggested change
self, modules: Iterable[torch.nn.Module] | None = None
self, module: torch.nn.Module

and maybe even should be a torchtitan Module

Comment thread torchtitan/rl/model/vllm_wrapper.py Outdated

def prepare_for_forward(self) -> None:
def prepare_for_forward(
self, modules: Iterable[torch.nn.Module] | None = 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.

similar

… prepare call

- Rename load_model_state_dict to a load_state_dict override, so the generator
  calls model.load_state_dict(model_sd). Keys stay those of self.model.
- Document why hooks bracket each FSDP group and why one load_state_dict call.
- prepare_for_state_dict_load / prepare_for_forward take one optional module.
@felipemello1
felipemello1 marked this pull request as draft October 11, 2026 03:25
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 11, 2026
Comment thread torchtitan/rl/model/vllm_wrapper.py Outdated

def prepare_for_state_dict_load(self) -> None:
def load_state_dict(
self, state_dict: Mapping[str, Any], strict: bool = True, assign: 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.

Do we need strict and assign? If not let's remove

Comment thread torchtitan/rl/model/vllm_wrapper.py Outdated
for handle in handles:
handle.remove()

def prepare_for_state_dict_load(

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.

Suggested change
def prepare_for_state_dict_load(
def _prepare_for_state_dict_load(

but I think we should embed this hook function inline

Comment thread torchtitan/rl/model/vllm_wrapper.py Outdated
handle.remove()

def prepare_for_state_dict_load(
self, module: torch.nn.Module | None = 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.

  • would it ever be None? If not let's remove until it's needed later, also remove default value.
  • also I think this can be an inline embedded function in load_state_dict() and it doesn't need self, either

Comment thread torchtitan/rl/model/vllm_wrapper.py Outdated
alloc_storage(sharded_data)

def prepare_for_forward(self) -> None:
def prepare_for_forward(self, module: torch.nn.Module | None = None) -> 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.

similar

Felipe Mello added 3 commits October 10, 2026 20:34
…Module

- load_state_dict's docstring shows the allocate/free order per FSDP group as a
  picture; comments say why the dict groups by FSDP state and why hooks.
- prepare_for_state_dict_load / prepare_for_forward take one FSDPModule (the
  bodies call _get_fsdp_state() and unshard()); __init__ loops over FSDP modules.
- Drop the try/finally around the load (a strict-key error is already fatal).
- The bitwise-parity helper syncs through wrapper.load_state_dict, as production does.
Restore the memory, per-group and hooks reasons as a short list under the
picture, and the note that keys are those of self.model (no model. prefix).
- Hardcode strict=True: with strict=False a missing parameter would get
  uninitialized memory, and nothing passes strict or assign.
- The memory note says the second copy is at FSDP degree 1, with the numbers.
- The picture's last row is 'unshard, free'; the is_sharded comment states the
  invariant; both prepare pictures use before/after.
@felipemello1

felipemello1 commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor Author

reply by claude: All comments are addressed. Summary of the changes:

  • model.load_state_dict(model_sd): VLLMModelWrapper now overrides load_state_dict. Keys are those of self.model (no model. prefix). strict=True is fixed: with strict=False, a missing param would end up with uninitialized memory.
  • Why per FSDP group: modules from one fully_shard call, e.g. [norm, lm_head], share one FSDP state. Unsharding right after norm would all-gather lm_head before it loads. The docstring now draws when each group is allocated and freed.
  • Why hooks: calling load_state_dict per module would also load its nested modules while their buffers are still freed. The hooks run inside one call, right before and after each group. Added a comment.
  • One module: prepare_for_state_dict_load / prepare_for_forward take one module: FSDPModule (they call _get_fsdp_state() and unshard()). __init__ loops over the FSDP modules.
  • Tests: CPU unit tests, a new CPU FSDP2 regression test, 2-GPU bitwise parity, and the 9B / 35B-A3B engine probes all pass.
  • Red CI: "1 GPU Integration (Fake PG)" fails on the SFT loss golden. That's main: the recent in-place WGRAD change updated real_pg/a10g/sft.txt but not fake_pg/a10g/sft.txt. Not from this PR.

@felipemello1
felipemello1 marked this pull request as ready for review October 11, 2026 04:25
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 11, 2026
@felipemello1
felipemello1 merged commit 39513f1 into pytorch:main Oct 11, 2026
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.

2 participants