Repository navigation
[rl] Generator weight loads: finish the lm_head group's forward before resharding it - #5982
Conversation
…e resharding it The engine computes logits with lm_head alone, and norm runs inside CUDA graph replays without FSDP hooks, so the [norm, lm_head] FSDP group (or the tied [tok_embeddings, norm, lm_head] one) stays in the FORWARD state between steps. A weight load reshards each group, refills its sharded buffers and unshards it. In FORWARD, `unshard()` all-gathers on FSDP's prefetch streams, which wait for the current stream only in the root's pre-forward: the all-gather does not wait for device work the load queued on the current stream to fill the shards. Today's fetches finish writing before they return (blocking pinned copy, or a stream sync before the TorchStore read), so nothing races; a load that writes shards with stream-ordered device work does. LoRA adapter-only loads (#5844) do: they copy the frozen parameters back into their reallocated shards on the device. On Muse Spark 816B (generator DP 4 x TP 4 x EP 16, Dist-MoE, FULL CUDA graphs) lm_head and norm were then gathered from uninitialized shards at the third weight sync, and every later rollout was garbage. `_reshard` now finishes the group's pending forward (`complete_fsdp_grouped_forward`, as the trainer's accelerator-graph validation cleanup does) and calls `module.reshard()`, replacing the private `_to_sharded()` loop. The load then all-gathers in IDLE on the current stream. Test: `test_fetches_shards_into_the_unsharded_params` records the training state of every all-gather of a load; it sees FORWARD without the fix.
|
@claude review |
|
Claude finished @tianyu-l's task in 2m 53s —— View job Approve: the diagnosis is correct, and |
There was a problem hiding this comment.
Verdict: Approve -- the diagnosis is right, the fix is the smallest one that removes the root cause, and it replaces a private _to_sharded() loop with public reshard().
On the human note. Your understanding is correct, and complete_fsdp_grouped_forward is the right helper to call. Two reasons:
- It moves the group to the state a completed forward leaves it in, IDLE. A grouped
fully_shardonly fires its post-forward after every module in the group has run, and callinglm_headalone never gets there. torchtitan/distributed/fsdp.py:57(post_validate_fsdp_for_accelerator_graph) already uses the samecomplete_fsdp_grouped_forward(module, None); module.reshard()pair for the same "lm_head ran alone, norm pending" state, so this reuses an existing pattern.
Once the group is IDLE, get_all_gather_streams returns the current stream for a synchronous unshard, so the copy-in and all-gather are ordered after the load's writes to the shards.
What this PR does. Before each group's reload, the load finishes any pending grouped forward and then calls module.reshard(). The FORWARD state no longer leaks into the load's unshard(), which in that state ran on FSDP's prefetch streams. Those streams last waited on the current stream at the root pre-forward.
Example. Tied group [tok_embeddings, norm, lm_head] with FULL CUDA graphs:
step: graph replay (norm, no hooks) -> lm_head(h) eager
-> pre-hook: group FORWARD, modules_to_run = {tok_emb, norm}
load (before): _to_sharded(); still FORWARD
fetch queues D2D copies into shards on current stream
unshard(): copy-in/all-gather on prefetch streams, no wait -> reads garbage
load (after): _post_forward -> IDLE; reshard()
unshard(): copy-in/all-gather on current stream, after the copies
Should consider
torchtitan/rl/generator/model.pyload()docstring,fetcharg (outside the diff): this PR makes stream-ordered writes on the current stream safe, and that is what #5844 relies on. Consider saying so: "writes queued on the current stream are ordered before the group's all-gather; writes on other streams must finish beforefetchreturns". Then the contract matches what the next PR depends on.
Details
- The problem is latent on
main: today's fetches finish before they return. It shows up with the device-side copies in #5844 (open). Landing it as a separate prerequisite fix with its own regression test is reasonable. - Side effects of
_post_forwardon the group:post_forward->reshard()is a no-op here (reshard_after_forward=False), then the state becomes IDLE, and_register_pre_backward_hook(None)does nothing. The followingmodule.reshard()->_to_sharded()matches what the old loop did, so the buffers CUDA graphs read are handled exactly as before. On the next step,lm_headre-enters FORWARD through the pre-hook, andunshard()there is a no-op because the group is already unsharded. - Alternative considered: completing the grouped forward after every generator step, in the engine. It fixes the same state, but it adds per-step work and touches the engine, and only the load cares about this state. Fixing it at load time is smaller.
- Test: extending the existing gloo test with a recorded training state for each all-gather is a sensible CPU stand-in for the stream race, which needs a GPU to reproduce. Per the description, the test fails without the change.
Not verified: I couldn't read the installed FSDP2 source in this environment, so the stream-selection and _post_forward behavior above comes from my knowledge of upstream _fsdp_param_group.py / _fsdp_state.py, not from this checkout. The GPU results come from the PR description.
; Conflicts: ; torchtitan/rl/generator/model.py
…park 816B (#6025) Replaces #5998, which GitHub closed as merged when a stack reorder pushed its base branch (#5845's) on top of it. Nothing reached main, and a merged PR cannot be reopened. Review comments so far are on #5998. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> **Stack** (image RL; review bottom up, each PR is one commit on the one below): 0. #5873 [multimodal] VisionProcessor: one per-model image and video processor (merged) 1. #5823 [multimodal] Image-reference Qwen3.5 renderer and shared M-RoPE positions (merged) 2. #5824 [rl] Image prompts through rollouts and the vLLM generator (merged) 3. #5825 [rl] Train on image prompts, with a Geometry3K recipe (merged) 4. #5844 [rl] LoRA RL: generators load the base checkpoint, weight syncs carry only the adapters (merged) 5. **→** #6025 [rl] Muse Spark image prompts and a SLAKE LoRA GRPO recipe for Muse Spark 816B 6. #5845 [rl] CUDA graphs for the generator's vision encoder This PR has three commits: Muse Spark image RL and the SLAKE recipe; a generator fix for preempted image requests; the recipe's `target_offpolicy_steps` default. ## Why 1. Image RL runs only Qwen3.5. The Muse Spark renderer rejects image parts. 2. The generator assumes M-RoPE: the vLLM HF config always gets an `mrope_section`. Muse Spark uses 1D positions for image tokens. 3. The generator's multimodal wrapper keeps its own copy of the decoder layer loop, which skips Muse Spark's residual and final-norm dtypes. 4. A preempted image request can crash the generator. vLLM drops the data of images that a new request's prefix-cache hit covers before sending the request to the worker (`strip_covered_mm_data`). With the V1 model runner, a preempted request resumes from the worker's copy of its features. If its prefix blocks were evicted in the meantime: - the scheduler schedules the image's encoder run; - the worker skips the run for lack of data; - `_gather_mm_embeddings` raises "Encoder cache miss" and the engine loop dies. GRPO samples share their group's prompt, so all but the first hit the prefix cache over their images. The first Muse Spark 816B SLAKE validation run crashed this way at step 4, twice, each time on a resumed request (128 prefix-cached tokens, encoder run scheduled). That run lacked #5982, so the preemption came from max-length garbage rollouts. Any preemption with eviction hits this bug, though. **Example.** A SLAKE prompt with one image, rendered for Muse Spark: ``` prompt: [{"type": "image", "path": "<image file>"}, {"type": "text", "text": "Which organ is shown?"}] before: Muse Spark renderer -> one <|patch|> per image (the SFT dataset expands it) generator HF config -> always mrope_section after: tokens <|image_start|> <|patch|> x N <|image_end|> Which organ is shown? ... positions 1D, like text: no mrope_section; the recipe leaves build_mrope_positions False, so no mrope_positions N the patch grid of the image size in the file header ``` ## What changed - **Muse Spark renderer**: built with a vision processor, an image part `{"type": "image", "path": ...}` renders as `<|image_start|>` + N x `<|patch|>` + `<|image_end|>`, as in Muse Spark's multimodal SFT data. N comes from the patch grid of the size in the file header. `multi_modal_data` carries each image's file hash, grid and `<|patch|>` run, as `Qwen35ImageRefRenderer` does, and `bridge_to_next_turn` places a later turn's images after the previous prompt's. Without a vision processor, an image part still renders as one `<|patch|>`, which the multimodal SFT data expands (#5885). - **Models**: `Decoder.forward_embeddings` runs the decoder after the token embedding, and `forward` calls it (mechanical split); `Qwen35Model.forward` ends with it too, so each model has one layer loop that the trainer and the generator share (bitwise-identical loss, see Numerics). Muse Spark overrides it with its residual and final-norm dtypes, adds `get_vision_embeds`, and takes the RL microbatch's bank rows (`image_vision_bank_indices_T`, the Qwen3.5 name). - **Generator**: image tokens of a model without M-RoPE get 1D positions. The HF config gets `mrope_section` only for `MRoPE.Config` (`get_mrope_config`, which #5825's controller check of `build_mrope_positions` uses too), and positions are transposed only when they are 3D. The multimodal wrapper calls `forward_embeddings` instead of copying the layer loop. - **Batcher**: unchanged. The SLAKE recipe leaves `Batcher.Config.build_mrope_positions` (#5825) False, as Muse Spark's SFT recipe leaves the collator's; `Controller.Config` checks it against the trainer model. - **SLAKE example** (`torchtitan/rl/examples/slake`): the English release, closed and open questions, with knowledge-graph questions dropped; the short-answer instruction from Muse Spark's SLAKE SFT recipe; reward by exact match after normalization. - **Recipe** `rl_muse_spark_816b_a42b_slake_lora_gb300`: - LoRA r8/a16 on `wqkv`, `wo` and `output_gate`, with the generators loading the HF base (adapter-only syncs, #5844); - Dist-MoE on both roles, without in-place WGRAD accumulation into the frozen experts; - the measured 32-GPU configuration, fixed in the recipe: an 8-GPU trainer and three 8-GPU generators, 32 prompts x 16 samples, 8K tokens per microbatch, low reasoning effort, 4K response tokens, zero-std groups dropped. Only the paths and `target_offpolicy_steps` (7, third commit) are arguments. The frozen bf16 base needs #5894 (frozen parameters stored in `param_dtype`, now on main) to fit the 8-GPU trainer. Adapter-only syncs need #5982 (generator weight loads finish the lm_head group's forward before resharding it). Without #5982 the generator's lm_head is corrupted from the third sync on. - **Generator, second commit**: `keep_prefix_cached_image_data` makes the scheduler send every new request's image data when the engine serves images. The engine core and its worker run in the generator's process, so the worker's features are the scheduler's own objects and keeping the data costs no memory. - **Recipe, third commit**: `target_offpolicy_steps` defaults to 7. With zero-std groups dropped, the run needs ~118 generated groups per step for 32 kept ones, so rollout supply is capped by the controller's active groups, `(target_offpolicy_steps + 1) x P`, not by the number of generators. - Unchanged: Qwen3.5's M-RoPE path (3D positions, `mrope_section`), and text-only rendering for Muse Spark. ## Alternatives considered - More generators instead of a higher `target_offpolicy_steps`: at 3, two more generators (48 GPUs) only reach 29.4 s per step, vs 24.0 s at 7 on 32 GPUs. ## Numerics / performance Muse Spark Open 816B-A42B on SLAKE, 32 GB300 GPUs (8-GPU trainer, three 8-GPU generators), the recipe's defaults before the third commit (32 x 16, `target_offpolicy_steps` 3, 10 steps), with #5894 and #5982. The comparison run uses the same configuration on the development branch this PR was ported from. Medians are over steps 5-10. | | this PR | development branch | |---|---|---| | step time | 36.0 s | 36.7 s | | trainer forward/backward | 20.8 s | 20.3 s | | trainer waiting for a batch (zero-std groups dropped) | 14.6 s | 16.3 s | | trainer/generator logprob diff, steps 1-10 | -0.004 to -0.006 | -0.004 to -0.005 | | prompt / response tokens | 726 / 224 | 731 / 223 | | reward | 0.511 | 0.504 | | trainer peak reserved memory | 258.8 GiB | 257.8 GiB | All 2,602 rollouts completed, none truncated. Prompt lengths match, so the Muse Spark image renderer emits the same tokens as the development branch's. Time per request outside the generator (router hop and payload): 13 ms. `target_offpolicy_steps` on the same 32 GPUs and tree (medians of steps 5-10): | `target_offpolicy_steps` | step | trainer waits | mean / max policy age | reward | logprob diff | |---|---|---|---|---|---| | 3 | 36.0 s | 14.6 s | 1.4 / 3 | 0.511 | -0.005 | | 5 | 24.0 s (mean 26.9 s) | 10-15 s at 2 of 6 steps | 3.0 / 5 | 0.518 | -0.005 | | **7 (default)** | 24.0 s (mean 23.6 s) | 0.002 s at every step | 4.0 / 7 | 0.526 | -0.005 | At 7 the trainer never waits: 1.5x the samples per second of 3. All rollouts completed, none truncated. `Qwen35Model.forward` ending with `forward_embeddings` (no computation change): `scripts/loss_compare.py` before vs after on the Qwen3.5 debug model (`qwen35_debugmodel`, cc12m-test with M-RoPE positions, FSDP=2, 20 steps, seed 42, deterministic, accelerator graphs off since the multimodal batches change shape each step): loss and grad norm bitwise identical at every step (TensorBoard values, max difference 0.0). ## Testing - New CPU tests: - renderer: an image renders as a `<|patch|>` run with the file hash; a bridge places new images after the previous ones; - vLLM wrapper: the HF config keeps 1D positions for Muse Spark images; - SLAKE dataset, env and rubric; - the recipe puts LoRA on wqkv, wo and output_gate of all 62 layers; - `test_scheduler_sends_prefix_cached_image_data_to_the_worker`: a request whose prefix-cache hit covers its image still sends the image data to the worker. Fails without the second commit (the data is None). - `pytest tests/rl/unit_tests/cpu tests/unit_tests/cpu/models/muse_spark tests/unit_tests/cpu/models/common`: 1009 passed. - After the third commit, on the rebased base: `pytest tests/rl/unit_tests/cpu/test_slake.py`: 18 passed. The 5 failures (`test_dapo_math` Math-Verify worker start, `test_lora_forward` inductor ABI) fail the same way on the base branch in this environment. ## Known issues / follow-ups - Staler samples at `target_offpolicy_steps` 7 (mean policy age 4 instead of 1.4). The effect on learning past 10 steps is not measured; the recipe takes `target_offpolicy_steps` as an argument, so a long run that suffers from staleness can lower it. - `keep_prefix_cached_image_data` is a workaround (TODO in code): remove it once vLLM resends a resumed request's dropped data. - The recipe needs #5982 (see What changed); #5894 is on main.
Human Note
Summary
Generator weight loads finish the lm_head FSDP group's pending forward before resharding it, so the load's all-gather runs on the current stream after the shards are filled. Replaces the private
_to_sharded()loop.Problem
lm_headalone, andnormruns inside CUDA graph replays without FSDP hooks, so the [norm, lm_head] group (or the tied [tok_embeddings, norm, lm_head] one) stays in the FORWARD state between steps.unshard()all-gathers on FSDP's prefetch streams, which wait for the current stream only in the root's pre-forward (FSDPCommContext.get_all_gather_streams): the all-gather does not wait for device work the load queued on the current stream to fill the shards.lm_headandnormwere gathered from uninitialized shards at the third weight sync and every later rollout was garbage (reward 0, trainer/generator logprob diff -0.96).Solution
_reshardcallscomplete_fsdp_grouped_forward(module, None), the helper the trainer's accelerator-graph validation cleanup already uses, thenmodule.reshard(). The group is IDLE, so the load's unshard copies in and all-gathers on the current stream.Results (Qwen3.5-35B-A3B Geometry3K LoRA, generator DP 2 x EP 2 with Dist-MoE and FULL CUDA graphs, adapter-only loads)
lm_head/normafter loadsThe Muse Spark 816B LoRA run with this change kept a logprob diff of -0.004 to -0.005 over 200 steps.
Test
test_fetches_shards_into_the_unsharded_params(gloo, 2 ranks) records the training state of every all-gather of a load, with the tied group left mid-forward by a standalonelm_headcall, and requires IDLE. It fails without this change (FORWARD seen). The generator model, generator and vLLM wrapper CPU tests pass (74).