Skip to content

[rl] LoRA RL: generators load the base checkpoint, weight syncs carry only the adapters - #5844

Merged
fegin merged 1 commit into
mainfrom
wwwjn/image-rl/4-rl-lora-adapter-sync
Nov 12, 2026
Merged

fegin merged 1 commit into
mainfrom
wwwjn/image-rl/4-rl-lora-adapter-sync

Conversation

@wwwjn

@wwwjn wwwjn commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

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. [multimodal] Image-reference Qwen3.5 renderer and shared M-RoPE positions #5823 [multimodal] Image-reference Qwen3.5 renderer and shared M-RoPE positions (merged)
  2. [rl] Image prompts through rollouts and the vLLM generator #5824 [rl] Image prompts through rollouts and the vLLM generator (merged)
  3. [rl] Train on image prompts, with a Geometry3K recipe #5825 [rl] Train on image prompts, with a Geometry3K recipe (merged)
  4. → [rl] LoRA RL: generators load the base checkpoint, weight syncs carry only the adapters #5844 [rl] LoRA RL: generators load the base checkpoint, weight syncs carry only the adapters
  5. [rl] Muse Spark image prompts and a SLAKE LoRA GRPO recipe for Muse Spark 816B #6025 [rl] Muse Spark image prompts and a SLAKE LoRA GRPO recipe for Muse Spark 816B
  6. [rl] CUDA graphs for the generator's vision encoder #5845 [rl] CUDA graphs for the generator's vision encoder

Why

A LoRA run trains a few adapters on a frozen base, but every weight sync sent the whole model (Qwen3.5-27B in bf16: ~54 GB per sync, for ~0.3% trainable parameters at rank 32). Generators can already load the HF checkpoint (Generator.Config.checkpointer, ModelStateDictLoader's initial load), but the RL loop forbade it, so every sync, the initial one included, carried the whole model.

Example. Geometry3K, Qwen3.5-0.8B, rank-32 LoRA (measured below):

before: every weight sync  = the whole model       2.2 GB  (Qwen3.5-27B in bf16: ~54 GB)
after:  generators load the base from the HF checkpoint once,
        every weight sync  = lora_a + lora_b + buffers   38 MB

What changed

  • Every weight sync (the initial one, which also covers resume, included) carries the trainable parameters and the buffers: Trainer.push_model_state_dict leaves out the parameters with requires_grad=False. For LoRA that leaves lora_a and lora_b. Since [rl] Train the MoE router gate; RL turns off only load balancing #5730 RL recipes freeze nothing else (the router gate trains), so every other recipe still sends the whole model. No flag, no new config field.
  • Generators load the frozen parameters from generator.checkpointer, which the controller no longer rejects. Loads leave them out, and they keep their weight: the load reallocates each FSDP group's sharded storage, and _restore_sharded_params refills the frozen parameters' shards from the unsharded storage (which CUDA graphs read) before the group's unshard. Groups of only frozen parameters (e.g. tok_embeddings, the vision tower) are skipped. This lives in the engine-agnostic ModelStateDictLoader (rl/generator/model.py, [rl] generator: move the engine-agnostic model build, state dict load and paged attention out of vllm/ #5811).
  • The generator freezes every parameter, so build_inference_model reads requires_grad right after the build, before freezing, and passes the frozen keys to ModelStateDictLoader. They are passed because the model cannot tell afterwards: a module does not record whether its config froze it. Inferring them from the module structure (every parameter but the LoRA adapters) breaks with LoRATransform.trainable_modules ([lora] Keep selected modules fully trainable in LoRATransform #6003), which keeps any module trainable.
  • With frozen parameters but no generator checkpointer, the loader raises at setup, since no sync would fill them; so does a quantized frozen parameter (its unsharded weight cannot refill its shard). A load that misses any other parameter still raises. The cpu_prefetch path's pinned receive buffers cover only what the trainer pushes. The generator's HF load defaults to the model's HF assets, like the trainer's, for vLLM and SGLang (SGLang passes its model_path).
  • rl_grpo_qwen3_5_0_8b_geometry3k_lora: rank-32 LoRA on the language model's attention, GatedDeltaNet and MLP projections (vision tower frozen), lr 10x the full fine-tuning one, generators loading the HF checkpoint.

At step 0 the generator's adapters are its own random lora_a with lora_b = 0, so its policy equals the trainer's; the first sync after an optimizer step sends both.

Numerics / performance

Geometry3K, Qwen3.5-0.8B on 4 GB300 (trainer FSDP=2 + 2 generators at TP=1), 30 steps: rl_grpo_qwen3_5_0_8b_geometry3k_lora vs the full fine-tuning recipe (TensorBoard logger; FA4 with num_splits=1 for head_dim 256, a separate fix). Sync numbers are TorchStore's own timings, rank 0; later syncs are the median over syncs 2-31.

full fine-tuning LoRA, generators load the base
initial weight sync 2.21 GB 38 MB
later weight syncs: bytes 2,215 MB 38 MB
later weight syncs: generator pull / trainer put 1.02 s / 0.089 s 0.30 s / 0.026 s
generator blocked on the pull, mean per step 0.85 s 0.16 s
step time, steps 2-30, mean 10.4 s 8.6 s
validation reward (601 test problems), start -> end 0.263 -> 0.384 0.291 -> 0.371
trainer-generator logprob difference, mean per token -0.0009 -0.0006

The generators' own HF load gives the trainer's frozen weights: the logprob agreement matches a run whose base came through the weight sync (-0.0007). At 38 MB a pull is bound by per-tensor overhead (~0.13 GB/s); with larger models the bytes dominate (a full Qwen3.5-27B sync in bf16 is ~54 GB). Step-0 validation differs by 0.02 between runs with the same weights, so the reward rows are within run-to-run noise.

Testing

Unit tests: a push carries the trainable parameters and the buffers (a LoRA base or a freeze_gate gate is left out); a load leaves out only frozen parameters, which keep their weight (one rank, and two ranks with uneven shards), and a missing trainable parameter raises; frozen parameters without a generator checkpointer raise at setup.

Known issues / follow-ups

  • TODO in ModelStateDictLoader: every generator replica reads the checkpoint from storage at once (80 reads with 10 nodes x 8 GPUs at DP=1). A follow-up sends the frozen parameters once through the initial weight sync instead (drafted on top of this PR).
  • Not in this PR: adapters-only checkpoints and HF export. (The trainer already stores the frozen base in precision.param_dtype, [distributed] Store frozen parameters in param_dtype #5894.)

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 5, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 5, 2026
@wwwjn
wwwjn added this pull request to stack #5826 November 5, 2026 05:10
@wwwjn
wwwjn force-pushed the wwwjn/image-rl/4-rl-lora-adapter-sync branch from 2836727 to 54fd9e9 Compare November 6, 2026 07:22
@wwwjn
wwwjn removed this pull request from stack #5826 November 6, 2026 07:24
@wwwjn
wwwjn added this pull request to stack #5900 November 6, 2026 07:24
@wwwjn
wwwjn force-pushed the wwwjn/image-rl/4-rl-lora-adapter-sync branch from 54fd9e9 to 244aa11 Compare November 8, 2026 06:07
@wwwjn
wwwjn force-pushed the wwwjn/image-rl/4-rl-lora-adapter-sync branch from 244aa11 to b848d67 Compare November 8, 2026 06:13
wwwjn added a commit that referenced this pull request Nov 8, 2026
…#5873)

**Stack** (image RL for Qwen3.5; review bottom up, each PR is one commit
on the one below):
0. **→** #5873 [multimodal] VisionProcessor: one per-model image and
video processor
1. #5823 [multimodal] Image-reference Qwen3.5 renderer and shared M-RoPE
positions
2. #5824 [rl] Image prompts through rollouts and the vLLM generator
3. #5825 [rl] Train on image prompts, with a Geometry3K recipe
4. #5844 [rl] LoRA RL: generators load the base checkpoint, weight syncs
carry only the adapters
5. #5845 [rl] CUDA graphs for the generator's vision encoder

---

## Summary

TorchTitan has no image processor object. A model's image preprocessing
is spread over two configs and a set of free functions in
`multimodal/utils/`, glued together with keyword arguments:

```
today:
  VisionProcessor.Config (mm_datasets.py)    one per dataset entry, 11 image fields;
                                             it is the Grain row processor, not an image processor
     | each model recipe replace()s them with its values (Muse, Kimi, Glimmer);
     | Qwen relies on the defaults
     v 11 kwargs into every sample_processor hook
  utils/image.py, utils/video.py             free functions: process_image / process_video
                                             (decode, resize, normalize), smart_resize,
                                             calculate_vision_tokens, vision_to_patches
  MultiModalCollator.Config                  second copy of patch_size / temporal / merge / patch_order
     v
  collate_images: vision_to_patches          per item, in the collator
```

Image preprocessing is fixed by the model, like the tokenizer: the patch
and merge sizes are the shapes of the vision encoder's patch embedding
and merger, and the resize rule and normalization are how the encoder
was trained. Hugging Face ships it per checkpoint
(`preprocessor_config.json`, `video_preprocessor_config.json`), next to
`tokenizer.json`.

This PR makes it one object per model, placed and passed like the
tokenizer:

```
Trainer.Config
  tokenizer        = MultiModalTokenizer.Config(**QWEN3_5_SPECIAL_TOKENS)
  vision_processor = VisionProcessor.Config(**QWEN3_5_VISION_PROCESSOR_KWARGS)
Trainer builds it once -> DatasetBuildContext(tokenizer=..., vision_processor=...)
   |-- Grain VisionSampleProcessor -> hook(sample, tokenizer, vision_processor)
   |      resize_and_normalize(image) / resize_and_normalize_video(frames): decode, resize, normalize, per item
   |      -> float32 (T, H, W, C) pixels; num_placeholder_tokens(grid_thw) placeholders
   |-- MultiModalCollator.collate_images: patchify(pixels) per item (as main's collator does)
          -> concatenated float32 patches + stacked grid_thw
```

### `VisionProcessor` (`components/data/multimodal/vision_processor.py`)

- One config for a model's images and video frames: patch,
temporal-patch and merge sizes, mean/std, the resize rules, the patch
order and the interpolation mode.
- The two steps main already splits between the sample processor and the
collator:
- `resize_and_normalize(image)`: decode, resize, normalize one image on
the CPU -> float32 `(1, H, W, C)` pixels and the `(3,)` patch grid they
will have; `resize_and_normalize_video(frames)` does the same for
decoded frames;
- `patchify(pixels)`: cut them into float32 `(num_patches, patch_dim)`
patches -> `(pixel_values, grid_thw)`.
  - `num_placeholder_tokens(grid_thw)` gives the placeholder count.
- Resize rules are `Function` configs (`config/function.py`), each with
only its own budget fields:

  ```python
  VisionProcessor.Config(
..., # patch sizes, mean/std, patch order: describe the encoder, shared
by images and frames
resize=PixelBudgetResize.Config(min_pixels=65_536,
max_pixels=16_777_216), # images
video_resize=PixelBudgetResize.Config(min_pixels=65_536,
max_pixels=16_777_216), # every video frame
  )
  ```

`PixelBudgetResize(min_pixels, max_pixels)` (Qwen-VL),
`NaViTPatchGridResize(max_patches, max_patches_per_side)` (Kimi) and
Muse Spark's `MuseGlimmerPatchGridResize(max_image_tokens)`.
`video_resize=None` means the model takes no video (Kimi, Muse Glimmer):
`resize_and_normalize_video` raises.
- Decoding and resizing are private methods (`_decode_image`,
`_resize`). A model whose preprocessing does not fit a resize rule
(tiling, cropping) overrides `resize_and_normalize`, the way a Hugging
Face processor overrides `_preprocess`.
- torchvision stays optional: `vision_processor.py` imports it only
inside the methods that decode and resize. So model flavors configure
the resize rules, and `trainer.py`, `loader.py`, `types.py` and
`validator.py` import and type the processor directly, without
torchvision; text-only configs load with torchvision and av blocked.
- The Grain row processor `mm_datasets.VisionProcessor` becomes
`VisionSampleProcessor` (like `FluxSampleProcessor`), which frees the
name.

### Why one processor for images and video

A video is a stack of frames the encoder patches like images, so the
patch sizes, mean/std and patch order must be the same for both; only
the resize budget can differ. Two configs would be two copies that have
to stay equal: both in-tree video configs were
`dict(..._IMAGE_PROCESSOR_KWARGS)`. vLLM (`Qwen2VLMultiModalProcessor`),
SGLang (`QwenVLImageProcessor`), qwen-vl-utils, LLaMA-Factory and verl
also keep one processor per model with a separate video budget. Hugging
Face splits the classes because its video processor also decodes the
video and samples frames; here the dataset does that, and timestamps and
prompt expansion stay in the sample hook.

Qwen3.5's Hugging Face `video_preprocessor_config.json` budgets the
whole clip (4,096 to 25,165,824 pixels), while the dataloader has used
the per-frame image budget for video. This PR keeps the current values
(TODO at `video_resize` in `QWEN3_5_VISION_PROCESSOR_KWARGS`); a
clip-wide rule is another `video_resize` rule.

### Per-model settings, next to the special tokens

Each model keeps a dict of `VisionProcessor.Config` keyword arguments
where it keeps its special tokens, and recipes build the config the way
they build the tokenizer's:

| settings | where (next to) | users |
|---|---|---|
| `QWEN3_5_VISION_PROCESSOR_KWARGS`; `QWEN3_6_VISION_PROCESSOR_KWARGS` /
`QWEN3_8_VISION_PROCESSOR_KWARGS` =
`dict(QWEN3_5_VISION_PROCESSOR_KWARGS)` | `models/qwen3_*/flavors.py`
(`QWEN3_*_SPECIAL_TOKENS`) | 9 Qwen recipes, HF numerical test |
| `KIMI_K2_5_VISION_PROCESSOR_KWARGS`, `KIMI_K3_VISION_PROCESSOR_KWARGS`
(images only) | `models/kimi_*/flavors.py` | Kimi recipes, HF numerical
tests |
| `MUSE_SPARK_VISION_PROCESSOR_KWARGS`,
`MUSE_GLIMMER_VISION_PROCESSOR_KWARGS` (images only) | the Muse recipe
files (`MUSE_*_SPECIAL_TOKENS`) | Muse recipes |

The Qwen values match the Hugging Face `preprocessor_config.json`, which
is identical across all 11 Qwen3.5 / 3.6 / 3.8 vision checkpoints (0.8B
to 397B-A17B), as are their special tokens. Recipes that tune the budget
`replace` the resize rule on the built config (the Kimi K3 debug recipe
keeps its small `max_patches=256`). The patch sizes are written in the
dict and in the encoder config, as in Hugging Face's
`preprocessor_config.json` and `config.json`; a test checks every
multimodal recipe's processor against its vision encoder.

The dicts are typed `dict[str, Any]`: Pyrefly cannot type-check a
heterogeneous dict unpacked into keyword arguments.

### Why an object and not `process_image()`

RL on images (#5823-#5825) needs the same preprocessing in three
processes: the rollout worker's renderer (placeholder count only), the
generator and the trainer (pixels). A function does not fit:

1. **Settings.** `process_image` takes 11 keyword arguments. Every
process would need them from somewhere: one config passed to each is a
config plus a function, i.e. an object; loose kwargs are N copies.
2. **Errors.** `process_image` turns every exception into `None`, the
pretraining dataset's skip-the-sample policy. In RL a bad image should
fail that rollout with the real error (the rollouter records it as an
errored rollout), not disappear. `resize_and_normalize` raises; the
dataset hook keeps the skip policy around it.

With the object, every process builds its own instance from the one
config and calls `resize_and_normalize` + `patchify` (generator,
trainer) or only counts placeholder tokens (renderer).

### Other changes

- The data flow is main's: the sample processor emits resized,
normalized float32 pixels (`pixel_values` / `pixel_values_videos`, so
packing buffers hold the same bytes as on main) and `collate_images`
patchifies each item, now with `processor.patchify` instead of the
collator's own patch fields.
- Removed: `multimodal/utils/image.py`, `utils/resize.py` (both now in
`vision_processor.py`) and `utils/video.py` (`load_npy_video_frames`
moved to the synthetic test dataset that reads `.npy` frames;
`load_video` had no callers); `process_image`, `process_video`,
`smart_resize`, `calculate_vision_tokens`; the 11 image fields of the
Grain `VisionProcessor.Config`, the 4 patch fields of
`MultiModalCollator.Config`, the recipes' `replace(processor, ...)`
blocks and `_multimodal_collator_config` helpers.
- The M-RoPE collator rejects a non-block patch order when it is built
instead of on every microbatch, and `VisionProcessor.Config` rejects an
unknown one.
- The validator, the torchft trainer and the checkpoint-conversion
numerical tests use the processor.

## Evidence

Not a numerics change: on 6842fdd3f (this PR before its rebase onto
879aad3), the first microbatches of every multimodal recipe's
dataloader are bitwise equal to main (c2579f7), all tensors (`input`,
`labels`, `positions`, `padding_mask`, `pixel_values`, `grid_thw`,
`pixel_values_videos`, `grid_thw_videos`, `mrope_positions`,
`waveforms`):

| recipe | microbatches | media |
|---|---|---|
| `qwen35_debugmodel` | 4 | images, M-RoPE |
| `qwen35_debugmodel_video` | 4 | videos, M-RoPE |
| `qwen36_debugmodel`, `qwen38_debugmodel` | 2 each | images, M-RoPE |
| `kimi_k2_5_debugmodel`, `kimi_k3_debugmodel` | 4 each | images, NaViT
resize, raster order |
| `muse_glimmer_debugmodel_mm` | 4 | images, raster order |
| `muse_spark_debugmodel_mm` | 8 | 5 with images, 3 with videos, 3 with
audio |

Loss and `grad_norm` are bitwise equal to main for 20 steps on an
earlier revision (85a08a8) whose dataloader output this revision
matches bitwise (`scripts/loss_compare.py c2579f7 85a08a8
--assert-equal --metrics=loss,grad_norm`; 8 GPUs, FSDP, seed 42,
deterministic, seed checkpoint), with accelerator graphs off as the
multimodal integration tests run (media shapes change every step):

| config | step 1 | step 10 | step 20 |
|---|---|---|---|
| `qwen35_debugmodel` on `cc12m-test` | 12.88083 / 1.4373 | 2.33800 /
1.6869 | 1.80099 / 1.0610 |
| `qwen35_debugmodel_video` on `synthetic-video-text` | 12.87572 /
2.5192 | 0.15311 / 0.4581 | 0.12245 / 0.1759 |
| `kimi_k2_5_debugmodel` on `cc12m-test` (DistMuon, no seed checkpoint:
DistMuon needs DTensor parameters, so both runs start from the seed-42
init) | 7.97354 / 8.1438 | 4.72706 / 4.5614 | 3.94997 / 2.8333 |

(loss / grad_norm.) NOTE: on main, the first launch on a cold compile
cache differs from later launches from step 2 (main run 2 vs main run 1
mismatch at step 2, the same way); the runs above use a warm cache for
both sides.

Against Hugging Face,
`scripts/checkpoint_conversion/numerical_tests_qwen3_5.py`
(Qwen3.5-0.8B, 10 image samples) preprocesses with the Qwen3.5 processor
config; on the previous revision (a37b3f7, same preprocessing), 0 of
1,966,080 pixels differ from Hugging Face's image processor (max diff
1.2e-7), and the logits match (top-1 100%, mean KL 2.5e-5). The output
is identical to main's.

## Test

GPU integration tests (8x A100, `--test_suite models` and `h100`
multimodal entries) pass on an earlier revision (c85334b) whose
dataloader output this revision matches bitwise: `qwen3_5_moe`
FSDP+TP+EP(+PP), `qwen3_5` FSDP+TP+varlen+per-op SAC, `kimi_k2_5_muon`
FSDP+EP and PP+FSDP+EP, `muse_glimmer_mm` FSDP+TP+SP and TP+CP+PP+SP,
`muse_spark_mm` FSDP+TP+CP+EP+SP, `qwen3_5_mm` all-gather-KV CP and
Ulysses CP, with losses decreasing over their steps. The two
`kimi_k3_mm` CP entries need sm90 (`gate_transform`) and were not run.

CPU unit tests on 6842fdd3f (full `tests/unit_tests/cpu`, no GPU
visible): 1,948 passed; the 5 failures (2 LoRA tests, 3 Qwen3.5 M-RoPE
routing tests) fail the same way on main (Inductor C++ build in the
local env), and `tests/unit_tests/cpu/quantization` needs torchao.

Updated tests:

- `test_mm_dataset_preprocessing.py`:
`patchify(resize_and_normalize(...))` equals step-by-step decode ->
resize -> normalize -> patchify bitwise (block and raster order), and
`resize_and_normalize`'s grid equals `patchify`'s; the NaViT resize
rule's geometry and padding, interpolation mode, video frames resized by
`video_resize` (not `resize`) with padding, video rejected without
`video_resize`, placeholder counts, patch order permutation, an unknown
patch order rejected; an unreadable image drops its sample; a missing
processor raises.
- `test_qwen_multimodal_data.py`: the Grain `VisionSampleProcessor`
passes the trainer's processor and requires one; every multimodal
recipe's processor matches its vision encoder (Qwen3.5/3.6/3.8 including
the 27B and 35B-A3B recipes, Kimi K2.5, Kimi-VL, Kimi K3, Muse Glimmer,
Muse Spark); the M-RoPE collator rejects a raster patch order when
built.
- Collator, checkpoint-resume and synthetic video tests use the
processor; the `.npy` frame loader's test moved with it to
`test_synthetic_multimodal_data.py`.
@wwwjn
wwwjn force-pushed the wwwjn/image-rl/4-rl-lora-adapter-sync branch from b848d67 to 1b5dee3 Compare November 8, 2026 08:22
wwwjn added a commit that referenced this pull request Nov 8, 2026
…ions (#5823)

**Stack** (image RL for Qwen3.5; review bottom up, each PR is one commit
on the one below):
0. #5873 [multimodal] VisionProcessor: one per-model image and video
processor
1. **→** #5823 [multimodal] Image-reference Qwen3.5 renderer and shared
M-RoPE positions
2. #5824 [rl] Image prompts through rollouts and the vLLM generator
3. #5825 [rl] Train on image prompts, with a Geometry3K recipe
4. #5844 [rl] LoRA RL: generators load the base checkpoint, weight syncs
carry only the adapters
5. #5845 [rl] CUDA graphs for the generator's vision encoder

---

## Summary

RL on image prompts needs each image's placeholder count at render time,
and the same pixels the model was trained on in the generator and the
trainer. Today the only path is the renderers library's Qwen3.5
renderer, which runs the Hugging Face image processor inside `render()`
and returns float32 `pixel_values`. In RL that costs ~9 ms per prompt
for every sample of every group, ships megabytes of pixels per prompt
between processes, and is a second preprocessing implementation next to
the trainer's.

On top of #5873's per-model `VisionProcessor`
(`VisionProcessor.Config(**QWEN3_5_VISION_PROCESSOR_KWARGS)`), this PR
adds:

- **`VisionProcessor.grid_thw(height, width)`**: the patch grid
`resize_and_normalize` gives a `height x width` image, without decoding
it. A renderer that reads the size from the file header gets the grid
and `num_placeholder_tokens(grid)` from it.
- **`Qwen35ImageRefRenderer`** (`models/qwen3_5/renderer.py`): the
library's `Qwen35Renderer` with only `_process_image` replaced, so
rendering emits the same placeholder runs and a hash per image, but no
`pixel_values`:

  ```
image file --read once--> bytes --hash_image_file--> hash (mm_hashes
entry, same from any path)
\--PIL header size--> grid_thw(h, w) --> grid (1, H/16, W/16)
--> num_placeholder_tokens(grid)
  ```

- **`RendererConfig.build(tokenizer=..., vision_processor=...)`**: the
vision processor is a build argument, like the tokenizer, so TitanRL
(#5824) passes the one it builds from
`Controller.Config.vision_processor` to the renderer, the generator and
the trainer. `RenderersConfigAdapter.build` sets it on an in-tree
renderer's config (`CustomRendererConfig`), and raises for a library
renderer or when the renderer config already sets one;
`MuseSparkRendererConfig.build` takes it too and raises (it reads no
image files).
- **`get_mrope_positions(num_tokens, vision_items)`**
(`multimodal/mrope.py`): 3D M-RoPE positions from placeholder offsets
and token grids, now the one implementation.
`MultiModalCollator._build_mrope_positions` finds each packed document's
placeholder runs and calls it, merging each grid with its modality's
processor (`spatial_merge_size`). RL takes the offsets from the
renderer, because a placeholder id the policy samples in a completion is
text, not an image.

## Evidence

- Dataloader microbatches, `mrope_positions` included, are bitwise equal
to main for 8 multimodal recipes (Qwen3.5 image and video, Qwen3.6,
Qwen3.8, Kimi K2.5, Kimi K3, Muse Glimmer, Muse Spark).
- On Geometry3K's 2,101 train prompts, `Qwen35ImageRefRenderer` gives
the library renderer's token ids and placeholders (0 mismatches), at 1.2
ms vs 9.4 ms per prompt (devvm CPU). Measured with the previous
revision's `resized_size`; `grid_thw` computes the same grid from the
same resize rule.

## Test

-
`tests/unit_tests/cpu/components/data/test_mm_dataset_preprocessing.py`:
`grid_thw` equals the grid `resize_and_normalize` gives (Qwen-style, and
Kimi-style NaViT with padding).
- `test_mrope_positions.py`: direct, and through the collator across
packed documents; the collator raises when a microbatch has more
placeholder runs than grids (a bare `StopIteration` there would end
Grain's batch iterator, i.e. the data, silently).
- `tests/unit_tests/cpu/models/qwen3_5/test_qwen3_5_renderer.py`: token
ids, placeholders and grids equal the library renderer's with the HF
processor Qwen3.5 ships, and `patchify(resize_and_normalize(...))`
equals its pixel values; hashes independent of the path; needs a vision
processor; built through
`from_renderers(...).build(vision_processor=...)`. Downloads the
`Qwen/Qwen3.5-0.8B` tokenizer, so it runs in CPU CI; `QWEN3_5_TOKENIZER`
points it at a local copy.
- `tests/unit_tests/cpu/components/test_renderer.py`: `build` rejects a
vision processor for a library renderer, and one set twice.
@wwwjn
wwwjn force-pushed the wwwjn/image-rl/4-rl-lora-adapter-sync branch from 1b5dee3 to 5414392 Compare November 8, 2026 09:42
@wwwjn
wwwjn force-pushed the wwwjn/image-rl/4-rl-lora-adapter-sync branch from 5414392 to 48b3cc2 Compare November 9, 2026 04:30
@wwwjn
wwwjn force-pushed the wwwjn/image-rl/4-rl-lora-adapter-sync branch from 48b3cc2 to 0b0f93d Compare November 9, 2026 21:47
Comment thread torchtitan/rl/controller/controller.py Resolved
- Per group: modules from one `fully_shard` call share one FSDP state, so unsharding
after `norm` would all-gather `lm_head` before it loads.

A generator that did not load the checkpoint must fill every parameter on every

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.

Hard to read

Comment thread torchtitan/rl/generator/generator.py Resolved
@wwwjn
wwwjn added this pull request to stack #6026 November 11, 2026 05:45
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 5m 45s —— View job


Request changes: see the review (@wwwjn's comment about what triggers trainable-only syncs is still open, and SGLang generators fail the hf_assets_path assertion when they load the checkpoint themselves).

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

Verdict: Request changes -- @wwwjn's comment on how trainable-only syncs are triggered is still open at HEAD: the decision is still made from generator.checkpointer, separately in two processes. Separately, SGLang generators crash with the new checkpointer path.

What this PR does. In the RL loop a generator may now load the trainer's initial HF checkpoint itself. When it does, the trainer leaves frozen parameters out of every push. The generator's loader leaves them out of every load, and _restore_sharded_params refills their FSDP shards from the unsharded storage before the group's all-gather. The controller also checks that the trainer's and generator's LoRA projections (fqn, rank, alpha) match, and a rank-32 LoRA Geometry3K recipe is added.

Example. Qwen3.5-0.8B, rank-32 LoRA, generator.checkpointer=CheckpointManager.Config(initial_load_in_hf=True):

before: controller raises "Generator checkpoint must be disabled"; each sync sends 2.2 GB
after:  generators load the base from HF once
        trainer.push(trainable_only=True) -> {lora_a, lora_b, buffers}   38 MB
        generator load: fetch(lora_*) ; frozen shards <- chunk(unsharded) ; all-gather

Must fix

  1. Description: "Not in this PR: the frozen base is stored in the trainer's precision.dtype (float32 in RL recipes)" no longer holds. #5894 (this PR's parent, merged) already stores frozen parameters in param_dtype (training_engine.py:400). Please update that paragraph, and say whether the step-time numbers were measured with or without #5894.
  2. torchtitan/rl/controller/controller.py:589 -- @wwwjn's comment is still open: trainable-only syncs are still keyed on generator.checkpointer, and model.py:467 re-derives the same decision on its own. The inline comment lays out the two ways to resolve it.
  3. torchtitan/rl/generator/model.py:455 -- hf_assets_path defaults to None and the SGLang wrapper doesn't pass it, so an SGLang generator configured like this recipe hits the hf_assets_path assertion at checkpointer/base.py:314. Make the parameter required and pass SGLang's model_path.

Should consider

  • torchtitan/rl/generator/model.py:722 -- skip FSDP groups that contain only frozen parameters, instead of refilling and all-gathering them on every sync.
  • torchtitan/rl/generator/generator.py:505 -- _prefetched_keys does nothing for LoRA at HEAD, and its test describes a design this PR no longer uses.
  • torchtitan/rl/trainer/trainer.py:471 -- canonicalize the key before comparing, as the generator side does.
  • torchtitan/rl/generator/model.py:625 -- extend the TODO to cover the new private FSDP internals the refill uses, with an upstream link.
  • tests/rl/unit_tests/cpu/test_geometry3k.py:163 -- the test re-reads a config whose invariants Controller.Config.__post_init__ already enforces. Delete it.
Details
  • Status of @wwwjn's earlier comments at HEAD: the "hard to read" docstring, the _model_state_dict_loads_fill name, and "why the manual copy" are resolved. The code moved into ModelStateDictLoader, and _restore_sharded_params's docstring now explains the copy (without it the all-gather writes uninitialized memory over the frozen weights). "Only update what is published" is implemented, though see the generator.py:505 comment. The comment on decoupling the trigger is still open.
  • How the frozen sets stay equal: the trainer leaves out its own frozen set, and the generator leaves out the set its model config freezes. Today both come only from configs (the LoRA transform and FreezeMoERoutingTransform, which build_rl_model_configs applies to both roles), and the new LoRA check makes the LoRA part equal. If a parameter were frozen only on the generator, it would silently keep its HF weight. Nothing triggers that today; if per-role freezing ever appears, compare the two frozen FQN sets in the controller.
  • The refill math matches FSDP2's uneven chunking: torch.chunk, and ranks past the last chunk hold no rows. The 2-rank uneven test covers it. TP is handled because the unsharded DTensor is taken to_local() before chunking.
  • Resume: the trainer's frozen weights come from its DCP checkpoint and equal the HF base, so trainable-only syncs after a resume stay correct.

Not verified: torchstore's get_state_dict(strict=False) return value; the perf impact of refilling groups that are entirely frozen. A maintainer still needs to review (this touches the RL trainer/controller core).

Comment thread torchtitan/rl/controller/controller.py Outdated
# TODO: every generator replica then reads the checkpoint from storage at once (80
# reads with 10 nodes x 8 GPUs at DP=1). Send the frozen parameters once in the
# initial weight sync instead, and only the trainable ones after it.
self._sync_trainable_only = config.generator.checkpointer is not 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.

Still open from @wwwjn's earlier comment ("these 2 should not be connected; check if it's LoRA RL, then push trainable parameters only"). HEAD only renamed the attribute. "Trainable-only" is still decided from generator.checkpointer is not None, and it is decided twice, separately: here and in ModelStateDictLoader.__init__ (rl/generator/model.py:467). Each process gets the same answer only because both read the same field.

You can't simply switch on "is LoRA": with LoRA and no generator checkpointer, the base still has to arrive through a sync. That leaves two ways to resolve this:

  • The TODO below, done in this PR: when the model has frozen parameters, the initial sync sends everything and later syncs send only the trainable ones. That deletes the generator-checkpointer exception and its equality check (~25 lines), the hf_assets_path plumbing, and the 80-reads TODO. What it costs: the loader would need first-load-vs-later state, and the cpu_prefetch receive buffers (or a one-off gpu_fetch) would have to cover the frozen keys on the first load.
  • Keep the checkpointer as the switch: then reply to the comment explaining why it has to be the switch (it is what guarantees the generator holds the frozen weights). Also compute the decision in one place and pass it to the generator explicitly, so the loader doesn't re-derive it.

Comment thread torchtitan/rl/generator/model.py Outdated
Comment on lines +455 to +456
frozen_param_keys: frozenset[str] = frozenset(),
hf_assets_path: str | 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.

Because hf_assets_path defaults to None, the SGLang wrapper never passes it (sglang/model_wrapper.py:359). This PR now lets a generator checkpointer through in the RL loop, so an SGLang generator configured like this recipe (CheckpointManager.Config(initial_load_in_hf=True), with no initial_load_path; the controller accepts it because both paths are None) builds the adapter with hf_assets_path=None and then fails assert self.sd_adapter and self.sd_adapter.hf_assets_path at components/checkpointer/base.py:314. Only vLLM gets the new "default to the model's HF assets" behavior.

Fix: make hf_assets_path and frozen_param_keys required here, since every real caller has them. Then pass SGLang's model_path, which SGLangEngine already has (sglang/engine.py:273), through to the wrapper.

Comment thread torchtitan/rl/generator/model.py Outdated
groups = [
(module, keyed, left_out_by_module[module])
for module, keyed in keys_by_module.items()
if keyed or left_out_by_module[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.

This keeps groups whose parameters are all left out, such as the frozen vision tower blocks and the tok_embeddings / [norm, lm_head] groups under LoRA. On every sync each of those groups is resharded, its whole shard is refilled from the unsharded weight, and it is all-gathered back into the same weights. Nothing about them changes, and their unsharded storage (what CUDA graphs read) is already correct. The frozen set is the same on every rank, so skipping these groups can't desync the collectives.

Suggest if keyed. Then and keyed_params at line 548 can go, and so can the quantized check for groups that are entirely frozen. Perf impact not measured.

Comment thread torchtitan/rl/generator/generator.py Outdated

Called on the engine loop thread during a load.
"""
keys = state_dict.keys() & self._prefetched_keys

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.

At HEAD this filter does nothing for LoRA. The receive buffers already leave out the frozen keys (model.py synced_state_dict), and load() never hands the frozen keys to fetch, so state_dict never contains a key the trainable-only push left out. The only keys it can still drop are buffers the trainer never publishes, which is a separate behavior change. Its test (test_generator.py:221) puts a "base" key in the receive buffers, which HEAD never allocates, and describes "after the trainer's first push", a design this PR no longer uses.

Either delete _prefetched_keys and that test, or keep them and say in the comment that the filter is for unpublished buffers. Unverified: whether ts.get_state_dict(strict=False) returns only the published keys. The engine-loop test mock returns the whole user_state_dict.

Comment thread torchtitan/rl/trainer/trainer.py Outdated
model_state_dict = {
key: tensor
for key, tensor in model_state_dict.items()
if key not in frozen

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.

frozen holds canonical_fqn names, but key is the raw state_dict() key. The generator side canonicalizes both sides (canonical_fqn(key) not in left_out_keys). If a wrapper segment ever survives in the trainer's state dict keys, the frozen weights would be pushed again with no error, and the only symptom would be slow syncs. Canonicalize here too to match:

Suggested change
if key not in frozen
if canonical_fqn(key) not in frozen

Comment thread torchtitan/rl/generator/model.py Outdated
Comment on lines +625 to +635
for fsdp_param in refill_from_unsharded:
unsharded = fsdp_param._unsharded_param
if isinstance(unsharded, DTensor):
unsharded = unsharded.to_local()
mesh_info = fsdp_param.mesh_info
chunks = torch.chunk(
unsharded, mesh_info.shard_mesh_size, dim=fsdp_param.fsdp_placement.dim
)
# FSDP pads uneven shards; ranks past the last chunk hold no rows.
if mesh_info.shard_mesh_rank < len(chunks):
sharded = fsdp_param._sharded_local_tensor

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.

The refill uses more private FSDP2 internals (_unsharded_param, _sharded_local_tensor, mesh_info, fsdp_placement) and copies FSDP's chunking rule by hand (torch.chunk with empty trailing ranks). The existing TODO only covers alloc_storage. Please extend it to name the missing upstream API (an FSDP reshard that keeps the data, i.e. refills the shard from the unsharded parameter) and link an upstream issue, per core principle 3.

Comment on lines +163 to +175
def test_lora_recipe_applies_one_lora_to_the_language_model_of_both_roles() -> None:
from torchtitan.models.common.lora import lora_projections
from torchtitan_recipes.rl.geometry3k import rl_grpo_qwen3_5_0_8b_geometry3k_lora

config = rl_grpo_qwen3_5_0_8b_geometry3k_lora()

projections = lora_projections(config.trainer.model)
# 6 full-attention layers x 4, 18 GatedDeltaNet layers x 2, 24 MLPs x 2.
assert len(projections) == 108
assert not any(fqn.startswith("vision_encoder") for fqn, _, _ in projections)
assert lora_projections(config.generator.model) == projections
# The generators load the frozen base themselves; syncs carry only the adapters.
assert config.generator.checkpointer.initial_load_in_hf

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.

This test re-reads the config it builds. rl_grpo_qwen3_5_0_8b_geometry3k_lora() already runs Controller.Config.__post_init__, which enforces "same LoRA on both roles" and the checkpointer check, so the == and initial_load_in_hf assertions duplicate that. The hard-coded 108 breaks whenever the flavor's layer mix changes and guards nothing silent. Suggest deleting it: the two rejects_* tests below already cover the controller checks (tests.md: don't re-read a config you just set).

Comment thread torchtitan/rl/actors/monarch/trainer.py Outdated
@concurrent_endpoint
async def push_model_state_dict(self) -> None:
await super().push_model_state_dict()
async def push_model_state_dict(self, *, trainable_only: bool) -> 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.

Why do we need this flag -- we might want to enable pushing everything later, but for now can we only work on trainable params?

Comment thread torchtitan/rl/controller/controller.py Outdated
Comment on lines +413 to +423
# Weight syncs copy the trainer's parameters into the generator by name.
mismatched_lora = sorted(
set(lora_projections(self.trainer.model))
^ set(lora_projections(self.generator.model))
)
if mismatched_lora:
raise ValueError(
"The trainer and generator must apply the same LoRATransform; their "
f"LoRA projections differ at {len(mismatched_lora)} (fqn, rank, "
f"alpha) entries, e.g. {mismatched_lora[:3]}."
)

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.

controller shouldn't know about lora details

Comment thread torchtitan/rl/controller/controller.py Outdated
Comment on lines +433 to +439
if generator_checkpointer is not None and not (
trainer_checkpointer is not None
and generator_checkpointer.initial_load_in_hf
and trainer_checkpointer.initial_load_in_hf
and generator_checkpointer.initial_load_path
== trainer_checkpointer.initial_load_path
):

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 don't really see why we need such enforcements. E.g. if generator is loading different policy version of trainer's weights, it'd be fine?

Also, they might sit on different hosts with different file paths, would this be too strict? I don't think we could assume they can always access the same path.

I feel that for the initial enablement, we can let weight sync error out in runtime, instead of guarding hard on configs -- we haven't found the best UX for guarding.

Comment thread torchtitan/rl/controller/controller.py Outdated
# TODO: every generator replica then reads the checkpoint from storage at once (80
# reads with 10 nodes x 8 GPUs at DP=1). Send the frozen parameters once in the
# initial weight sync instead, and only the trainable ones after it.
self._sync_trainable_only = config.generator.checkpointer is not 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.

can we by default sync trainable params only and avoid this flag. We might or might not need to sync buffer always, e.g. expert bias. But right now it seems frozen, so no need.

Comment thread torchtitan/rl/generator/model.py Outdated
Comment on lines +463 to +466
# A generator that loads the checkpoint holds the frozen parameters from the
# start, so every model state dict load carries only the trainable ones
# (trainable-only syncs; `Controller` derives the same from
# `generator.checkpointer`).

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.

frozen or not can be determined by the LoRA transform, and doesn't need to be passed around?

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 we can infer from LoRA Tranform and DisableMoELoadBalancingTransform() in #5730

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.

Update: Tried it, but after #6003 the generator can't infer it reliably: LoRATransform.trainable_modules keeps any module trainable, and a built module doesn't record whether its config froze it. So inferring "everything but lora_a/lora_b" would treat e.g. a trainable norm as frozen, and the generator would silently stop updating it.

Instead build_inference_model reads requires_grad right after the build, before it freezes every parameter, and passes the frozen keys to ModelStateDictLoader. That is the same rule the trainer uses to decide what it sends, so the two can't drift. The trainable_only flag and the controller checks stay removed.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review my review

@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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


Request changes: see the review. Comment 2 is correct, comments 1, 3 and 4 are partly correct, and comment 5 is mistaken. If every sync is trainable-only, every MoE RL recipe breaks at the initial sync; if the first push carries everything and later pushes carry only trainable params, the flag goes away.

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

Verdict: Request changes -- I checked @tianyu-l's five comments against the code. The direction behind #1, #3 and #4 holds up: drop the flag and the checkpointer exception. But "push only trainable params on every sync" would break existing recipes. A version that works: the first push carries everything, and every later push carries only the trainable ones.

What this PR does. With a generator checkpointer, every push leaves out frozen params, and the generator refills their FSDP shards from its unsharded storage.

Example. This is what happens if trainable-only becomes the default, as #1/#4 suggest, with nothing else changed:

dapo_math (MoE, no generator checkpointer): router gates are frozen by build_rl_model_configs
  trainer push  -> {trainable params, buffers}        (no router gate)
  generator load expects every param (left_out_keys empty, model.py:704)
  -> RuntimeError "did not fill N weights" on the initial sync

On each comment

  1. monarch/trainer.py:69 -- drop the flag, push only trainable params. Partly correct. As the example shows, every MoE RL recipe freezes router.gate (model_configs.py:31,60, moe.py:211) and none of them sets a generator checkpointer, so they would all break. Here is a flag-free version that works. The trainer's first push after it starts carries everything, and every later push carries only the trainable params. The trainer tracks this itself, so the endpoint argument and _sync_trainable_only go away. The generator loader expects every key on its first load and leaves out the frozen ones after that. This also deletes the generator-checkpointer exception (keep checkpointer=None as on main), the hf_assets_path plumbing along with the SGLang assertion crash it causes, the "80 reads" TODO, and the checkpoint-rejection test. Cost: the first load needs receive buffers for the frozen keys. Pinned cpu_prefetch buffers cost ~100 GB/GPU at 816B, so the first load should use gpu_fetch, and gpu_fetch rejects quantized params (model.py:713).
  2. controller.py:423 -- the controller shouldn't know LoRA. Correct (core principle 5). The root cause is in the recipe: it applies LoRATransform to each role separately (geometry3k.py:1037,1039), and build_rl_model_configs exists precisely so both roles get the same transforms. Fix: let build_rl_model_configs take extra transforms and apply LoRA there. Then delete lora_projections, the controller check and test_recipe_rejects_a_generator_lora.... If a runtime guard is still wanted, compare the trainer's and the generator's frozen key sets (both are already computed). That check is model-agnostic.
  3. controller.py:439 -- the path check is too strict. Partly correct. Comparing path strings is the wrong check. Equal strings aren't required (hosts can mount the same checkpoint at different paths), and they aren't enough either. Both are None in this recipe, so the check passes while the trainer reads Controller.Config.hf_assets_path and vLLM reads vllm_config.model_config.model. But "a different version is fine / errors at runtime" is mistaken. With trainable-only syncs the generator keeps whatever it loaded for frozen params forever, so a different base never raises. The only symptom is logprob drift, which is exactly the kind of silent failure principle 8 rules out. The design in #1 makes the trainer the only source of the base, so this question goes away.
  4. controller.py:589 -- default to trainable-only; buffers may not need syncing. For params, see #1. For buffers, mistaken. expert_bias is frozen in RL, but without a generator checkpoint the only way the generator gets it is a sync. Unfilled buffers keep their init value with no error (ModelStateDictLoader.load), so routing would silently diverge. Buffers must come with at least the first sync. There is no per-buffer frozen marker, and the buffers fit inside the 38 MB per sync, so keep sending them.
  5. model.py:466 -- derive "frozen" from the LoRA transform. Mistaken. At least two things freeze params here: LoRA (config/transform/lora.py:93) and the router gate (moe.py:211). requires_grad after build is the model-agnostic source, and the trainer uses it too (Trainer._frozen_param_keys), so the two sides agree by construction. The set has to be recorded inside build_inference_model, because that function then freezes every param (model.py:126).

Still open from the earlier automated review

  • The description says the frozen base is stored in precision.dtype, which is outdated since #5894.
  • With an SGLang generator checkpointer, hf_assets_path=None fails the assertion at checkpointer/base.py:314. This goes away with #1.
  • test_lora_recipe_applies_one_lora... re-reads a config it just built.

Not verified: whether the RL loop ever replaces a generator mid-run. A replacement would need the frozen params resent. A maintainer still needs to review (RL controller/trainer core).

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude router gate is unfrozen in #5730

Assume it lands, maybe my idea is solid again?

I agree that we can always send buffers, no matter what, as they are not large.

@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 56s —— View job


Yes, once #5730 lands, though it needs one guard first. After #5730, LoRA is the only thing in an RL recipe that freezes parameters. So "every push carries the trainable params plus all buffers" becomes a full sync for every non-LoRA recipe, and the trainable_only flag can go. The guard: raise when a model has frozen params but the generator has no checkpointer.

Details

Why it holds now. The only places that set requires_grad=False are LoRA (config/transform/lora.py:93, models/common/lora.py:54,365) and moe.py:211. moe.py:211 only fires on router.freeze_gate, and #5730 turns that off by default. With no frozen params, a trainable-only push and a full push are the same, so the MoE failure I described earlier goes away.

The case that fails silently without the guard. Take LoRA with generator.checkpointer=None. If the loader always leaves out the frozen keys, nothing ever fills the base, and the generator samples from its init weights with no error. Fix: in ModelStateDictLoader.__init__, add if frozen_param_keys and checkpointer_config is None: raise ValueError(...). It doesn't depend on the model and runs at setup, as you wanted.

The change to the PR:

  • Delete trainable_only from Trainer.push_model_state_dict and the Monarch endpoint (monarch/trainer.py:69). The trainer always drops _frozen_param_keys(), comparing canonical_fqn(key).
  • Delete _sync_trainable_only and its two call-site kwargs (controller.py:589).
  • In the loader, set left_out_keys = frozen_param_keys unconditionally, plus the raise above.
  • Fix two error messages that tell users to unset generator.checkpointer to get full syncs: the quantized-param error in _fsdp_load_groups and the controller's checkpointer error. With this design, unsetting it raises for LoRA.
  • Merge order: this PR has to land after [rl] Train the MoE router gate; RL turns off only load balancing #5730 (still open). Before that, every MoE RL recipe fails the initial sync because the frozen router gate is never sent.

What stays, compared with my "first push carries everything" alternative. A LoRA generator still gets its base only from its own checkpointer. So the hf_assets_path plumbing stays, and so does the 80-reads TODO. The SGLang crash with hf_assets_path=None also stays, and it still has to be fixed. The trade is a trainer and loader that keep no per-sync state, against N storage reads at startup. I'd take yours: the code is simpler, and the startup reads are the follow-up the author has already drafted.

Two cases that still fail silently:

  1. The generator freezes a param the trainer trains (if freezing ever becomes per-role). The trainer pushes it, the generator never fetches it, and the generator keeps the HF weight. The opposite case already raises ("did not fill"). This can replace the controller's lora_projections check, which you flagged at controller.py:423: at setup, compare the trainer's frozen keys (union over ranks) with the generator's frozen_param_keys and raise if they differ. Both sets are already computed, and the check doesn't need to know about LoRA.
  2. The generator loads a different base than the trainer. Frozen params are never synced, so a mismatch never errors at runtime. It only shows up as drift in the trainer-generator logprob difference. The path check guards this, crudely. Dropping it means accepting that risk.

Buffers. Agreed. The trainer already sends every buffer (only parameters are filtered), so nothing changes there.

@wwwjn
wwwjn force-pushed the wwwjn/image-rl/4-rl-lora-adapter-sync branch 3 times, most recently from 268e16f to 69034cc Compare November 12, 2026 05:40
@wwwjn

wwwjn commented Nov 12, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wwwjn's task in 3m 44s —— View job


Approve, a maintainer still needs to review: see the review.

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

Verdict: Approve -- At HEAD every must-fix item from the earlier automated reviews is resolved, and @tianyu-l's design asks are done: no trainable_only flag, no LoRA check in the controller, no path check. #5730 has merged, so trainable-only pushes no longer break MoE recipes. A maintainer still needs to review, since this touches the RL trainer and the generator loader, and @tianyu-l's change request is still open.

What this PR does. Every trainer push now leaves out the parameters with requires_grad=False. The generator records which of its parameters the config freezes (build_inference_model reads them before it freezes everything). It loads those from generator.checkpointer, leaves them out of every load, and refills their FSDP shards from the unsharded storage before each group's all-gather. If parameters are frozen and there is no generator checkpointer, the loader raises at setup.

Example.

LoRA recipe (frozen base, generator.checkpointer=HF):
  trainer push   -> {lora_a, lora_b, buffers}                     38 MB
  generator load -> fetch lora_*; base shards <- chunk(unsharded); all-gather
Full fine-tuning (nothing frozen after #5730):
  trainer push   -> whole model, same as main
LoRA with generator.checkpointer=None:
  generator setup -> ValueError "Set generator.checkpointer ..."

Should consider

  • torchtitan/rl/generator/model.py:735 -- still open from the earlier review, with no reply. Groups whose parameters are all frozen are still resharded, refilled and all-gathered on every sync. Under this recipe that is the vision tower blocks, tok_embeddings and [norm, lm_head]. Their unsharded storage (what CUDA graphs read) is already correct, and the frozen set is the same on every rank, so skipping them can't desync the collectives. Changing the condition to if keyed deletes the and keyed_params guard in load() and the quantized check for groups that are entirely frozen. Perf impact not measured.
  • torchtitan/rl/generator/model.py:633 -- the TODO now names the missing FSDP API (a reshard that keeps the data) but doesn't link an upstream issue. Core principle 3 asks for one.
Details

How the earlier comments stand at HEAD:

  • @wwwjn on decoupling the trigger from generator.checkpointer: resolved. Nothing switches on the checkpointer anymore. The frozen set comes from requires_grad on both sides.
  • @tianyu-l: the flag is gone (monarch/trainer.py, controller.py), and so are the controller's LoRA check and path check. On "derive frozen from the LoRA transform", @wwwjn's reply holds up. LoRATransform freezes through FrozenConfig.build (config/transform/lora.py:143), and trainable_modules (#6003) keeps arbitrary modules trainable. Reading requires_grad right after the build is therefore the only reliable source, and it is the same rule the trainer uses.
  • SGLang hf_assets_path: fixed (sglang/engine.py:276 passes model_path). The trainer key is now canonicalized, _prefetched_keys and its test are gone, and the test that re-read the geometry3k config is gone.

How mismatches fail. The trainer freezes a parameter the generator doesn't: the first load raises "did not fill". The generator freezes one the trainer trains: the generator silently keeps the HF weight. Today both roles build from the same transformed config, and the vLLM/SGLang layer replacements use dataclasses.replace on the GDN/attention configs, which keeps the Frozen* classes. So nothing triggers the silent case. A different generator base also goes unchecked by design, as @tianyu-l asked; the only symptom would be logprob drift.

Intra-generator cost. Even in groups that mix frozen and trainable parameters, each sync all-gathers the whole frozen base of the group across the generator's FSDP (DP) axis, because FSDP unshards a group all at once. The 38 MB figure covers the network transfer only. With generator DP > 1 on a large model, this all-gather is the remaining per-sync cost. Skipping fully frozen groups (above) removes part of it.

Not verified: GPU behavior of the refill under TP > 1 with generator DP > 1. The CPU tests cover 1 and 2 FSDP ranks with uneven shards.

@wwwjn

wwwjn commented Nov 12, 2026

Copy link
Copy Markdown
Contributor Author

@claude Review and check #5844 (comment)

@claude

claude Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wwwjn's task in 2m 1s —— View job


Approve (a maintainer still needs to review): see the review. Your reply in r4546716073 is correct: after #6003 the generator can't work out which parameters are frozen from the built module, so reading requires_grad in build_inference_model is the right way, and the thread can be resolved.

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

Verdict: Approve -- @wwwjn's reply in r4546716073 is correct. After #6003 the generator can't work out which parameters are frozen from the built module tree, so build_inference_model should read requires_grad before it freezes everything. HEAD (69034cc) is the same commit as in the last automated review, and nothing new blocks it. A maintainer still needs to review, and @tianyu-l's change request is still open.

I took that link to be the thread on torchtitan/rl/generator/model.py where @tianyu-l asked whether the frozen set could come from the LoRA transform. I can't resolve discussion IDs from this job.

On r4546716073.

  • LoRATransform freezes at build time. FrozenConfig.build (config/transform/lora.py:144-149) calls requires_grad_(False) on the built module's own parameters. The module class stays the same, and Module doesn't keep its config. So after the build, nothing on the module says that its config froze it.
  • The transform skips trainable_modules subtrees entirely (lora.py:328). With trainable_modules=["vision_encoder"], ordinary non-LoRA modules stay trainable. A rule like "frozen = every parameter except lora_a/lora_b" would wrongly list them as frozen. The trainer pushes them because they have requires_grad, but the loader drops them from every fetch (model.py:654). The generator would keep the HF weights for good, with no error.
  • requires_grad read right after model_config.build() is the same test as Trainer._frozen_param_keys (trainer.py:513), applied to the same transformed config. The read comes before model.requires_grad_(False) and maybe_store_frozen_params_in_param_dtype_ (model.py:117-131), so the order is right. The set is read before vision_encoder is dropped, but extra keys in it do no harm.
  • Since #5730, nothing in the repo sets freeze_gate anymore, so today LoRA is the only thing that freezes parameters. The requires_grad rule also covers any freezer added later, with no change.

So the loader can't compute this parameter itself. The reply settles the thread as it stands.

Example.

LoRATransform(target_modules=[...], trainable_modules=["vision_encoder"])

infer "all but lora_*":
  trainer push       = lora_* + vision_encoder.* + buffers
  generator left out = base + vision_encoder.*
  -> the generator's vision tower never updates, and nothing raises
requires_grad at build (HEAD):
  trainer push       = lora_* + vision_encoder.* + buffers
  generator left out = base
  -> the two sets match

Should consider

These are still open from the earlier review, with no reply:

  • torchtitan/rl/generator/model.py:667 -- groups whose parameters are all frozen (vision blocks, tok_embeddings, [norm, lm_head]) are still resharded, refilled and all-gathered on every sync. Keeping only groups with keyed parameters (if keyed) would skip that work and remove the and keyed_params guard in load().
  • torchtitan/rl/generator/model.py:587 -- the TODO names the missing FSDP API (a reshard that keeps the data) but has no upstream issue link.
Details

How a mismatch between the two frozen sets fails:

  • The trainer freezes a parameter that the generator doesn't: the first load raises "did not fill".
  • The generator freezes a parameter that the trainer trains: the generator silently keeps the HF weight.

Both roles get the same transform in this recipe (geometry3k.py:866-868), so nothing triggers the silent case today. If transforms ever differ per role, add a setup check in the controller that compares the trainer's frozen set with the generator's frozen_param_keys. That check doesn't need to know about LoRA.

Not verified: GPU behavior of the refill with TP > 1 and generator DP > 1.

@wwwjn
wwwjn force-pushed the wwwjn/image-rl/4-rl-lora-adapter-sync branch from 69034cc to 7c48da4 Compare November 12, 2026 05:57

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

Please address comments before merging

Comment thread torchtitan/rl/trainer/trainer.py Outdated
Comment on lines +464 to +469
frozen = self._frozen_param_keys()
model_state_dict = {
key: tensor
for key, tensor in self._model_state_dict().items()
if canonical_fqn(key) not in frozen
}

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 think we can consolidate self._model_state_dict() and self._frozen_param_keys() into one, e.g. self._trainable_model_state_dict(), instead of filtering it every time.

Comment thread torchtitan/rl/generator/model.py Outdated
# No buffers for the parameters loads leave out: they would pin a second
# copy of them in host memory (~100 GB per GPU for an 816B model on 16
# GPUs) that no load fills.
synced_state_dict = {

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
synced_state_dict = {
trainable_state_dict = {

Comment on lines +624 to +625
after, refill this rank's chunk of the unchanged
unsharded weight

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 is tricky

torchtitan/rl/generator/model.py:667 -- groups whose parameters are all frozen (vision blocks, tok_embeddings, [norm, lm_head]) are still resharded, refilled and all-gathered on every sync. Keeping only groups with keyed parameters (if keyed) would skip that work and remove the and keyed_params guard in load().

Here you are basically doing effectively no-op but incur reshard and unshard on frozen params. Please add a TODO: we should try to figure out if there's a way to avoid the "wasted" reshard and unshard on frozen params.

Comment thread torchtitan/rl/generator/model.py Outdated
tok_embeddings), so ``is_sharded`` can be True while the storage is still
freed; allocate unconditionally.
def _restore_sharded_params(
module: FSDPModule, *, refill_from_unsharded: Iterable[Any] = ()

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.

It can be easy to get lost in these naming refill_from_unsharded.

How about let's just use frozen_ and trainable_ prefixes everywhere.

Comment thread torchtitan/rl/generator/model.py Outdated
def _fsdp_load_groups(
model: nn.Module,
) -> tuple[list[tuple[FSDPModule, list[tuple[str, Any]]]], list[str]]:
model: nn.Module, *, left_out_keys: frozenset[str] = frozenset()

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

Z-Ghostshell pushed a commit to Z-Ghostshell/torchtitan that referenced this pull request Nov 12, 2026
…e resharding it (pytorch#5982)

## Human Note
- This is a correctness fix for FSDP sharded lm_head; But need to double
check the understanding of this issue and if i;m calling the correct
helper function

## 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**

1. The engine computes logits with `lm_head` alone, and `norm` runs
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.
2. 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 (`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.
3. Today's fetches finish writing before they return (a blocking pinned
copy, or a stream sync before the TorchStore read), so nothing races
yet. A load that fills shards with stream-ordered device work does: LoRA
adapter-only loads (pytorch#5844) 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
gathered from uninitialized shards at the third weight sync and every
later rollout was garbage (reward 0, trainer/generator logprob diff
-0.96).

**Solution**

1. `_reshard` calls `complete_fsdp_grouped_forward(module, None)`, the
helper the trainer's accelerator-graph validation cleanup already uses,
then `module.reshard()`. The group is IDLE, so the load's unshard copies
in and all-gathers on the current stream.
2. Unchanged: the load order, the buffers, and what each fetch fills.

**Results** (Qwen3.5-35B-A3B Geometry3K LoRA, generator DP 2 x EP 2 with
Dist-MoE and FULL CUDA graphs, adapter-only loads)

| | without | with |
|---|---|---|
| `lm_head` / `norm` after loads | changed at loads 2-5 / 4 | unchanged
over 10 loads |
| trainer/generator logprob diff mean, step 6 | -0.593 | -0.001 |

The 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 standalone `lm_head` call, and requires IDLE. It
fails without this change (FORWARD seen). The generator model, generator
and vLLM wrapper CPU tests pass (74).

Co-authored-by: Chien-Chin Huang <[email protected]>
… only the adapters

LoRA RL trains a few adapters on a frozen base, but every weight sync sent the whole model
(Qwen3.5-27B in bf16: ~54 GB per sync for ~0.3% trainable parameters).

Generators can already load the HF checkpoint themselves (`Generator.Config.checkpointer`,
`ModelStateDictLoader`'s initial load), but the RL loop forbade it, so every weight sync
carried the whole model. Now:

- Every weight sync (the initial one, which also covers resume, included) carries the
  trainable parameters and the buffers: `Trainer.push_model_state_dict` leaves out the
  parameters with `requires_grad=False`. For LoRA that leaves `lora_a` and `lora_b`.
  Since #5730 RL recipes freeze nothing else, so every other recipe still sends the whole
  model. No flag, no new config field.
- Generators load the frozen parameters from `generator.checkpointer`, which the
  controller no longer rejects, and loads leave them out: `_restore_sharded_params`
  refills their shards from the unsharded storage, which CUDA graphs read, before the
  group's unshard. Groups of only frozen parameters (e.g. tok_embeddings, the vision
  tower under LoRA) are skipped. This lives in the engine-agnostic `ModelStateDictLoader`
  (rl/generator/model.py).
- `build_inference_model` reads `requires_grad` right after the build, before it
  freezes every parameter, and returns the frozen keys for `ModelStateDictLoader`. The
  model cannot tell them afterwards: a module does not record whether its config froze
  it (`LoRATransform.trainable_modules`, #6003, keeps any module trainable). With
  frozen parameters and no generator checkpointer the loader raises at setup (no sync
  would fill them), as it does for a quantized frozen parameter (its unsharded weight
  cannot refill its shard). A load that misses any other parameter still raises. The
  cpu_prefetch path's pinned receive buffers cover only what the trainer pushes (for
  Muse Spark 816B, the frozen base's buffers would pin ~102 GB of host memory per GPU
  that no load writes). The generator's HF load defaults to the model's HF assets, like
  the trainer's, for vLLM and SGLang.
- `rl_grpo_qwen3_5_0_8b_geometry3k_lora`: rank-32 LoRA on the language model's attention,
  GatedDeltaNet and MLP projections, generators loading the HF checkpoint.
@fegin
fegin force-pushed the wwwjn/image-rl/4-rl-lora-adapter-sync branch from 7c48da4 to 3899a2f Compare November 12, 2026 20:19
@fegin
fegin merged commit 204b211 into main Nov 12, 2026
wwwjn added a commit that referenced this pull request Nov 13, 2026
…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.
d4l3k added a commit that referenced this pull request Nov 13, 2026
…5996)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.18.0)
(oldest at bottom):
* #6097
* #5997
* __->__ #5996


## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why
RL syncs the trainer's model state dict to the generators through
TorchStore, which adds a store, controller and extra copies around the
transfer. With 14B on one 8xB200 host (trainer FSDP 4, generator TP 2,
NIXL) a TorchStore pull takes 10-13 s (2.3-3.0 GB/s); with this
transport the same pull takes 0.6-0.9 s (RDMA read at ~60 GB/s per
generator rank). `torch.distributed._transport` now provides one-sided
RDMA reads over Mooncake/NIXL, so the generators can read the trainer's
shards directly.

## What changed
- `torchtitan/rl/model_state_dict_transport.py` (new):
- `shard_layout` / `_staged_pieces`: each trainer rank stages, per
generator rank, the intersection of its FSDP box with the generator
rank's box, cast to the generator dtype and 16 B aligned, in one
registered pinned CPU buffer (pinned with cudaHostRegister, since
`pin_memory=True` rounds up to a power of two). Generator ranks that
need the same piece (e.g. a TP-replicated tensor) share one staged copy,
so the buffer is about the trainer shard size at the transfer dtype.
- `_staged_placements`: where a trainer shard cuts a generator shard on
a dim after the first sharded dim, the trainer stages that DTensor with
its later-dim shards moved to the first sharded dim, via one
`redistribute` (an all-to-all within its mesh) in `stage`; e.g. a
row-parallel weight (FSDP `Shard(0)`, TP `Shard(1)`) read by a generator
split on dim 0 is staged as `(Shard(0), Shard(0))`: one read per piece
instead of one per row. A generator TP on dim 1 matching the trainer's
needs no restage. The decision uses every trainer rank's box, so all
trainer ranks agree (the redistribute is a collective).
- `_plan_reads`: each generator rank plans reads from every trainer rank
straight into its prefetch buffers, one contiguous read per piece per
index of the dims before its sharded dim (1 for a 2-D weight, 2 for a
stacked `[2, F, D]` w13 sharded on F). HSDP replicas are spread
round-robin across generator ranks. Raises if the trainer does not cover
a shard exactly, and on `Partial` or uneven `_StridedShard` placements.
- `shared_rank_layouts`: checks every generator reports the same
per-rank layout.
- `ModelStateDictTransport`: `register_trainer_source` + `stage`
(trainer; a collective when restaging), `connect_generator` + `read`
(generator). `read` fails after `Config.read_timeout_s` (default 600 s)
instead of hanging on a stuck transfer; the job must then restart.
- Every generator key must be fully covered by the trainer, or init
raises (TorchStore loads with `strict=False`). Trainer keys no generator
has (e.g. ones the generator drops) are not staged.
- `Config.backend` selects the `torch.distributed._transport` backend:
`"mooncake"` (default) or `"nixl"`.
- Unused until the next PR wires it in behind a config flag.
- Mooncake needs a PyTorch nightly from 2026-11-10 or later (Mooncake
transport pytorch/pytorch#202780, multi-peer
pytorch/pytorch#202536 and
pytorch/pytorch#203461, poller fix
pytorch/pytorch#203623).

The staging buffer is laid out per staged piece, so a later delta sync
can stage and read a subset of pieces without changing the plan.

## Alternatives considered
- Keep TorchStore: its extra hop and copies are the bottleneck measured
above.
- Read directly from trainer GPU memory: a pull would then race the next
optimizer step, and dtype casts would still need a staging copy.
- Monarch RDMA (as `rdma_microbatch.py` uses for microbatches): ties the
trainer and generator cores to Monarch and offers no Mooncake backend;
`torch.distributed._transport` is PyTorch-native and backend-selectable.

## Related drafts
- #5751,
#5872 (delta sync),
#5778 (TorchStore control
plane), #5484 (pinned prefetch
buffers), #5844 and
#5846 (LoRA syncs) change the
TorchStore path. They are independent of this PR; delta and LoRA syncs
can move onto this transport by staging and reading a subset of pieces.

## Size
Implementation +544, tests +451.

## Testing
- `pytest tests/rl/unit_tests/cpu/test_model_state_dict_transport.py`
(19 pass): checks `Config.backend` reaches `new_transport`, and runs
`register_trainer_source`/`stage`/`connect_generator`/`read` over an
in-process fake transport and checks every element lands in the right
place and every read targets a connected trainer rank, with a bf16 cast,
for HSDP 3x4 -> TP 1/2 on either dim (replica assignment across two
generators), a stacked `[2, F, D]` weight sharded on F -> TP 1/2 on F or
D (multi-run reads), mixed dtypes with `preserve_dtype_keys` and an
odd-sized key (alignment), generator ranks sharing a replicated piece
(one staged copy), a generator rank with an empty shard, incomplete or
overlapping coverage and dtype mismatches (raise), mismatched generator
layouts, and rejecting `Partial`/uneven `_StridedShard`. A 4-rank gloo
test stages real FSDP 2 x TP 2 DTensors (row-parallel `(Shard(0),
Shard(1))`, colwise FSDP over TP `(_StridedShard(0), Shard(0))`, stacked
w13 `(_StridedShard(1), Shard(1))`, and a small `(Shard(0), Shard(1))`
key on which 2 ranks have no pieces but must still join the restage) and
reads them into generator TP 2 shards on two layouts, asserting the
restage decision per layout (none when generator TP matches trainer TP
on dim 1; `(Shard(0), Shard(0))` for row-parallel and the small key when
the generator splits dim 0). This catches layout/offset bugs that would
otherwise silently corrupt weights.
- End-to-end numbers are in the next PR.

AI-assisted (Claude).
saforem2 pushed a commit to saforem2/torchtitan that referenced this pull request Nov 15, 2026
…#5844)

pytorch#5844 makes weight syncs carry only trainable parameters and raises when a generator model freezes parameters without a checkpointer. agpt_rl_model_configs always applies LoRA, so every alphabet_sort_agpt and reason_agpt config, and the xpu_trial lora arm, now set generator.checkpointer = CheckpointManager.Config(initial_load_in_hf=True), as upstream's geometry3k LoRA recipe does. Found by Aurora 9091990: 'The model config freezes 227 parameters ... Set generator.checkpointer'.
saforem2 pushed a commit to saforem2/torchtitan that referenced this pull request Nov 15, 2026
Since pytorch#5844 a LoRA generator loads its frozen base with CheckpointManager -> dcp.load. DCP's planning collectives run on the default group, which in the generator is vLLM's pure-XCCL external_launcher group, and oneCCL segfaults in ccl_comp_copy -> memmove (core from Aurora 9092177; also 9092084). The trainer avoids this through patch_init_distributed_for_xpu's hybrid xpu:xccl,cpu:gloo group. Patch _load_initial_weights to pass dcp.load a Gloo group for the duration of the load; applied last in apply_all_xpu_patches because it imports the generator module.
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.

3 participants