Repository navigation
[rl] FSDP generator: sync weights one FSDP module at a time - #5268
felipemello1 merged 6 commits into
Conversation
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.
tianyu-l
left a comment
There was a problem hiding this comment.
nice! Happy to stamp after you addressed comments
| # 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) |
There was a problem hiding this comment.
| 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) |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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
| handle.remove() | ||
|
|
||
| def prepare_for_state_dict_load( | ||
| self, modules: Iterable[torch.nn.Module] | None = None |
There was a problem hiding this comment.
from what I read we only need
| self, modules: Iterable[torch.nn.Module] | None = None | |
| self, module: torch.nn.Module |
and maybe even should be a torchtitan Module
|
|
||
| def prepare_for_forward(self) -> None: | ||
| def prepare_for_forward( | ||
| self, modules: Iterable[torch.nn.Module] | None = None |
…or-per-module-weight-sync
… 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.
|
|
||
| def prepare_for_state_dict_load(self) -> None: | ||
| def load_state_dict( | ||
| self, state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False |
There was a problem hiding this comment.
Do we need strict and assign? If not let's remove
| for handle in handles: | ||
| handle.remove() | ||
|
|
||
| def prepare_for_state_dict_load( |
There was a problem hiding this comment.
| def prepare_for_state_dict_load( | |
| def _prepare_for_state_dict_load( |
but I think we should embed this hook function inline
| handle.remove() | ||
|
|
||
| def prepare_for_state_dict_load( | ||
| self, module: torch.nn.Module | None = None |
There was a problem hiding this comment.
- 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 needself, either
| alloc_storage(sharded_data) | ||
|
|
||
| def prepare_for_forward(self) -> None: | ||
| def prepare_for_forward(self, module: torch.nn.Module | None = None) -> None: |
…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.
|
reply by claude: All comments are addressed. Summary of the changes:
|
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
load_state_dictwrites, and an unsharded buffer, which forward and CUDA graphs read.prepare_for_state_dict_load) beforeload_state_dict, so both sets are resident.gpu_memory_limit(default 0.9) at startup, leaving a sync about 6 GiB on a 95 GiB H100.Solution
VLLMModelWrapper.load_state_dict(overridingnn.Module's, keyed likeself.model) keeps oneload_state_dictcall. For each group of modules sharded together (e.g.[norm, lm_head]), it adds a temporary pre-hook on the first module, which callsprepare_for_state_dict_loadfor that group, and a post-hook on the last, which callsprepare_for_forward.prepare_for_state_dict_loadno 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.model.load_state_dict(model_sd).FSDPModuleand act on its FSDP group;__init__loops over the FSDP modules for the initial unshard.With tied embeddings, the
[tok_embeddings, norm, lm_head]group stays allocated for the whole load.Results
norm.weightchanges it, and undoing that restores it.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:
fully_shard([norm, lm_head])gives both one FSDP state; unsharding afternormwould all-gatherlm_headbefore it loads.load_state_dictper FSDP module? That call also loads the nested FSDP modules, whose sharded buffers are still freed.gpu_memory_limitor reserving it during vLLM's memory profiling? It comes out of the KV cache. Reserving it at profiling, on one H100: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.pypytest 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 theis_shardedskip 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 callswrapper.load_state_dict, as production does.