Skip to content

[rl] LoRA RL: initial weight sync carries the frozen base, no checkpoint reads in generators - #5846

Draft
wwwjn wants to merge 5 commits into
wwwjn/image-rl/4-rl-lora-adapter-syncfrom
wwwjn/image-rl/lora-initial-sync-from-trainer
Draft

wwwjn wants to merge 5 commits into
wwwjn/image-rl/4-rl-lora-adapter-syncfrom
wwwjn/image-rl/lora-initial-sync-from-trainer

Conversation

@wwwjn

@wwwjn wwwjn commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Draft follow-up to #5844: LoRA generators read no checkpoint; the initial weight sync carries the frozen base once, and later syncs carry only the adapters.

In #5844, LoRA generators load the base from the HF checkpoint themselves. With many generator replicas every replica reads the checkpoint from storage at once (80 reads with 10 nodes x 8 GPUs at DP=1), which costs storage bandwidth and, on object stores such as S3, money.

  • The initial weight sync carries the whole model unless the generators loaded the checkpoint; every later sync carries only the trainable parameters plus the buffers (for LoRA, the adapters). Without frozen parameters that is the whole model, so full fine-tuning syncs do not change.
  • A generator that loaded no checkpoint must fill every parameter on its first load; later loads may fill a subset and keep the other weights.
  • rl_grpo_qwen3_5_0_8b_geometry3k_lora drops the generator checkpointer. Setting it still works (the [rl] LoRA RL: generators load the base checkpoint, weight syncs carry only the adapters #5844 path).

Trade-off: after its first load a generator cannot tell a parameter the trainer skipped from one a load missed by mistake; it keeps the old weight either way.

This is how verl handles it by default (vLLM load_format="dummy", the first sync pushes the base, then adapters only); with load_format=safetensors the engine loads the checkpoint and the base sync is skipped, as in #5844.

Evidence

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, rank 0 TorchStore timings:

#5844 (generators load the base) this PR (initial sync carries it)
initial weight sync 38 MB 2.25 GB, generator pull 0.78 s
later weight syncs, median 38 MB, pull 0.30 s 38 MB, pull 0.27 s
step time, steps 2-30, mean 8.6 s 8.5 s
trainer-generator logprob difference, mean per token -0.0006 -0.0007
validation reward (601 test problems), start -> end 0.291 -> 0.371 0.268 -> 0.334

Step-0 validation differs by 0.02 between runs with the same weights, so the reward rows are within run-to-run noise. The initial full sync is a one-time cost; its pull scales with the model (~20-25 s for a 54 GB bf16 model at the 2.2-2.9 GB/s measured here), while the #5844 path instead reads the checkpoint once per generator replica.

Test

The unit tests of #5844, with: a generator without a checkpoint must fill every parameter on its first load and may fill a subset afterwards; the trainer loop pushes only trainable parameters after the initial sync.

wwwjn added 5 commits November 4, 2026 11:36
…nce Qwen3.5 renderer

RL image prompts need each image's placeholder count at render time, and the
same pixels in the generator and the trainer. This adds the pieces, all driven
by one `ImageSpec` (Qwen3-VL / Qwen3.5 defaults):

- `lookup_image`: reads an image file, hashes it into a content key and
  computes its patch grid from the header, without decoding pixels.
- `decode_image_files` / `decode_image_files_flat`: decode image files and
  resize them to uint8 (the uint8 half of `process_image`, now
  `decode_and_resize_image` + `normalize_image`).
- `patchify` / `patchify_flat`: normalize and cut into patches on the images'
  device; CPU and GPU give bitwise-equal patches.
- `get_mrope_positions`: 3D M-RoPE positions from placeholder offsets and
  grids (equal to `MultiModalCollator._build_mrope_positions` for one
  document).
- `Qwen35ImageRefRenderer`: the renderers library's Qwen3.5 renderer with
  `_process_image` replaced by `lookup_image`, so rendering emits placeholder
  runs and content keys but no pixel_values.

Test: unit tests for the image utilities (patches equal `process_image` +
`vision_to_patches`, a changed file is detected, grids checked at decode),
GPU vs CPU patchify, M-RoPE positions vs the collator, and the renderer
(token ids equal the library renderer's). On Geometry3K's 2,101 train images
the renderer's token ids equal the library renderer's, at ~1.1 ms vs ~7.5 ms
per prompt.
Carries image prompts from the renderer to vLLM and serves them with the
TorchTitan vision encoder (Qwen3.5).

- `Prompt(token_ids, images)` is the one generation input: TokenEnv renders
  it (`TokenEnvOutput.next_prompt`), and `GenerateFn`, the router,
  `Generator.generate` and `EngineRequest` take it. An image is a run of
  placeholder tokens in `token_ids`; its `PromptImage(key, path, grid_thw,
  offset, length, data)` names the file that fills them and carries the
  file's bytes (Geometry3K median 14 KB), so no process past the rollout
  worker needs the dataset's file system. `RolloutTurn.prompt_images` records
  them; the recorder writes them without the bytes.
- TokenEnv always calls `render()` (`render_ids()` is `render().token_ids` for
  every renderer TorchTitan accepts) and passes the previous prompt's
  `multi_modal_data` to the bridge when it has images.
- `GenerationEngine.Config.image_spec`: with it set, `VLLMEngine` decodes and
  resizes each image file (a small LRU by content key; outside the
  per-request try, so a corrupt file fails loudly) and submits vLLM's
  `mm_input` directly, so vLLM's Hugging Face processor never runs.
  `VLLMMultimodalModelWrapper` patchifies on the GPU, runs the model's
  `get_vision_embeds` (made public), scatters image embeddings over the
  placeholders and computes M-RoPE positions with `get_mrope_positions`.
  `register_to_vllm` validates the model (vision encoder, patching equal to
  the spec, MRoPE attention) before the build.
- Image mm hashes are salted with the request's pinned policy version
  (`key@version`): vLLM keeps an image's encoder output after its requests
  finish and only `reset_encoder_cache` clears it, and the vision weights
  train. With `reset_kv_cache_on_model_state_dict_load`, hashes are bare
  and the engine resets the encoder cache on every load.
- `Controller.Config.rdma_min_image_bytes` (default None) sends image files
  of at least that size from the rollout worker to generator rank 0 as RDMA
  buffers (`RDMAPrompt`, Monarch's `MonarchRDMAPrompt`), like
  `Batcher.Config.rdma_min_tensor_bytes` for trainer microbatches: the
  `generate` call through the router carries only the buffer handles, rank 0
  reads the files in one RDMA action, and the rollout worker drops the
  buffers when the call returns, raises or is cancelled.
- Until the trainer takes image inputs (next PR), the controller rejects
  `generator.engine.image_spec`, so image prompts never train on their
  placeholder tokens alone.

Text-only runs are unchanged apart from the `Prompt` wrapper.

Test: unit tests for TokenEnv (images across turns, a bridge that extends
earlier images, rejection of pixels and non-image modalities), the rollout
loop and recorder, `image_prompt` and M-RoPE input positions, HF config and
model validation, engine admission (salted hashes, reset mode, rejection
without an image spec), rank 0's file sharing, the RDMA prompt path
(GenerateFn registers only prompts with large files and drops them on
return, error and cancellation; registration pickles; rank 0 reads; a real
Monarch round trip over TCP; config validation), and the temporary guard.
The trainer side of image RL (Qwen3.5), and an end-to-end recipe.

- Training samples carry their turns' images (`TrainingSample.images`); a turn
  that swaps an image in place branches like a token edit.
- The batcher ships each distinct image file once per microbatch
  (`image_files` + sizes), the bank row of every placeholder token, `grid_thw`
  and 3D M-RoPE positions (`get_mrope_positions`, as the generator computes
  them). `TrainingMicrobatch.to_input_dict` decodes the files on the CPU and
  patchifies on the trainer's device. Packing prefers a microbatch that
  already holds a sample's image, so a group's samples share one encoding.
  Placeholder counts are checked against the grids; samples with images and
  no `Batcher.Config.image_spec` raise.
- Qwen3.5 under CP keeps bank rows the batch provides (several placeholder
  runs can share one encoded image).
- `Controller.Config` requires `generator.engine.image_spec ==
  async_loop.batcher.image_spec` (replacing the previous PR's guard).
- `rl/examples/geometry3k` (Hugging Face `hiyouga/geometry3k`; the dataset
  writes the parquet's images to files once, since rendering reads image
  files) and `rl_grpo_qwen3_5_0_8b_geometry3k` (4 GPUs). Rewards reuse the
  DAPO math Math-Verify grader on the last `\boxed{}`.

Test: unit tests for image training samples, the batcher (bank rows, one
file per distinct image, packing by image, placeholder checks, text samples
in image mode), RDMA microbatches with image inputs, the vision bank, a
multi-turn image rollout through training samples, the Geometry3K dataset,
env, grading and recipe, and the image spec check.
… 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`,
`VLLMModelWrapper._maybe_initial_load_weights`); RL recipes left it unset, so the initial
weight sync carried the whole model. Now:

- The controller derives what each push carries from the generator config: with a
  generator checkpointer, every weight sync (the initial one, which also covers resume,
  included) carries only the parameters that train, plus the buffers; for LoRA that is
  `lora_a` and `lora_b`. Without one, every sync carries the whole model as before.
  `Trainer.push_model_state_dict(trainable_only=...)`.
- Generators that loaded the checkpoint accept loads that fill a subset of the parameters:
  a parameter the load leaves out keeps its weight (its shard is copied back from the
  unsharded storage, which CUDA graphs read, before the group's unshard). Generators that
  did not still raise when a load misses a parameter. The cpu_prefetch path copies only the
  keys the last prefetch read. The generator's HF load defaults to the model's HF assets,
  like the trainer's.
- The controller allowed no generator checkpointer in the RL loop. It now allows one that
  loads the trainer's initial HF checkpoint (same `initial_load_path`), since the generator
  keeps what it loaded for the parameters that do not train; and it raises unless the
  trainer and the generator have the same LoRA projections (fqn, rank, alpha).
- `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.
…int reads in generators

Follow-up to the previous PR, where LoRA generators load the base from the HF checkpoint
themselves: with many generator replicas (80 at DP=1 on 10 nodes x 8 GPUs) every replica
reads the checkpoint from storage at once.

- The initial weight sync carries the whole model again unless the generators loaded the
  checkpoint; every later sync carries only the trainable parameters plus the buffers (for
  LoRA, the adapters). Without frozen parameters that is the whole model, as before.
- A generator that loaded no checkpoint must fill every parameter on its first load; later
  loads may fill a subset and keep the other weights.
- `rl_grpo_qwen3_5_0_8b_geometry3k_lora` drops the generator checkpointer.
@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 force-pushed the wwwjn/image-rl/4-rl-lora-adapter-sync branch 8 times, most recently from 0b0f93d to a363476 Compare November 10, 2026 00:25
@wwwjn
wwwjn force-pushed the wwwjn/image-rl/4-rl-lora-adapter-sync branch 14 times, most recently from 840d9b2 to 268e16f Compare November 12, 2026 05:20
@wwwjn
wwwjn force-pushed the wwwjn/image-rl/4-rl-lora-adapter-sync branch 2 times, most recently from 69034cc to 7c48da4 Compare November 12, 2026 05:57
@fegin
fegin force-pushed the wwwjn/image-rl/4-rl-lora-adapter-sync branch from 7c48da4 to 3899a2f Compare November 12, 2026 20:19
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).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

1 participant