Repository navigation
[rl] generator: move the engine-agnostic model build, state dict load and paged attention out of vllm/ - #5811
Conversation
|
@claude review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. This is a mechanical move. Each step runs in the same order, and the second consumer (#5812, SGLang) already calls every new entry point.
What this PR does. It moves three things out of generator/vllm/ into engine-agnostic modules, because none of them depends on vLLM:
- The TorchTitan model build, the initial HF load, and the per-FSDP-group model state dict load go to
inference_model.py. - The FA3/FA4 activation and the paged-KV
varlen_attn_outcall go topaged_attention.py.
VLLMModelWrapper now calls build_inference_model and load_initial_weights, and holds a ModelStateDictLoader. VLLMEngine reaches the load and the pinned buffers through that loader.
Example.
# before (vllm/engine.py)
self._get_model().load_model_state_dict(fetch)
self._get_model()._prefetched_model_state_dict
# after
self._get_model().model_state_dict_loader.load(fetch)
self._get_model().model_state_dict_loader.prefetched_model_state_dictThe wrapper's __init__ used to run about 100 lines of build/parallelize/materialize code. Now it runs build_inference_model -> _initialize_dist_moe_runtime -> load_initial_weights -> _inject_attention_sinks -> _patch_vllm_all_reduce -> maybe_apply_numa_binding -> ModelStateDictLoader(...). The loader's constructor groups the parameters by FSDP group, allocates the pinned buffers, and unshards the model, the same as the old inline code did.
Must fix
- PR description: the "Summary (human-written)" section is empty, so the author needs to fill it in. Also, the load tests didn't move completely unchanged.
_Wrapperand the manual_unshard_and_free_sharded_paramsloop were dropped becauseModelStateDictLoader.__init__now does that unshard. That's fine, but the description should say so.
Should consider
torchtitan/rl/generator/inference_model.py:227-- the loader could do the NUMA binding itself, so engines don't need to call it in the right order before building it (inline).torchtitan/rl/generator/inference_model.py:33--get_attention_dimensionsfits better inpaged_attention.pythan in the model build/load module (inline).
Details
- Ordering check. The only step that moved relative to the others is
_fsdp_load_groupsplus thegpu_fetchquantized-param check, which now runs aftermaybe_apply_numa_binding. Neither depends on the binding. The vLLM dtype check now runs before theParallelismContextis built, and that has no side effects. - Leftover callers. No in-repo callers remain of
wrapper.load_model_state_dict,wrapper._prefetched_model_state_dict,_maybe_initial_load_weights,_checkpointer_config,model_wrapper._fsdp_load_groups/_unshard_and_free_sharded_params, orattention.get_attention_dimensions. Thegenerator._prefetched_model_state_dicthits are a separate attribute onGenerator. - Imports.
inference_model.pyimports no vLLM, soregistry.pycan importget_attention_dimensionsat top level without the old deferred import. - Paged attention.
paged_varlen_attention_outgets the same arguments as before.cu_seqlens_kfor FA2 is built onquery[:num_actual_tokens].device, the same device as before.num_splits=1for FA2 / batch-invariant mode,enable_gqa, andreturn_auxstill apply under the same conditions. - Unchanged generic-code calls. The moved code still calls
torch.cuda.empty_cache()andtorch.cuda.get_device_capability()in modules that are now engine-agnostic. I left these alone: changing them would be a drive-by fix in a move-only PR, and FA3/FA4 is CUDA-only anyway.
Not verified: the GPU bitwise-parity and MXFP8 Dist-MoE results in the description.
| if model_state_dict_load_mode == "cpu_prefetch": | ||
| # Built while the model is still sharded. The sharded state dict has the | ||
| # dtypes the trainer sends (see `Trainer._put_model_state_dict`); | ||
| # torchstore's RDMA transport copies bytes and asserts matching dtypes. | ||
| with torch.device("cpu"): | ||
| self.prefetched_model_state_dict = _create_cpu_state_dict( | ||
| model.state_dict(), pin_memory=True | ||
| ) |
There was a problem hiding this comment.
Should consider: the docstring at L199 makes every engine call maybe_apply_numa_binding before it builds the loader. The vLLM wrapper (vllm/model_wrapper.py:359) and the SGLang wrapper in #5812 both repeat load_initial_weights -> maybe_apply_numa_binding -> ModelStateDictLoader(...). If an engine misses that step, nothing errors: the pinned buffers just land on the wrong NUMA node. The loader is the one allocating them, so it could bind as the first thing in __init__, using torch.accelerator.current_device_index() / torch.accelerator.current_accelerator().type the way #5812 does. vLLM calls it unconditionally today, so binding unconditionally in __init__ keeps the behavior the same. Then you can delete the bind call from both wrappers and the ordering note from the docstring.
| from torchtitan.tools.utils import set_default_dtype | ||
|
|
||
|
|
||
| def get_attention_dimensions( |
There was a problem hiding this comment.
Should consider (nit): the module docstring says this file covers how the generator builds, initially loads, and state-dict-loads the model. get_attention_dimensions does none of those. It reads an attention config for the engines' registries and layer replacement. paged_attention.py (the engine-agnostic attention helpers) looks like a better home, so inference_model.py doesn't turn into a catch-all as more shared pieces arrive (#5812 already adds compute_logits here).
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. HEAD is still 71efa43, the commit the previous review approved. The code hasn't changed and only the description was edited, so the earlier assessment holds: this is a mechanical move.
Since the last review
- Resolved: the description now says that the load tests dropped
_Wrapperand the manual_unshard_and_free_sharded_paramsloop, becauseModelStateDictLoader.__init__now does that unshard. - Still open: the "Summary (human-written)" section is still the template placeholder.
Must fix
- PR description: the author needs to write the "Summary (human-written)" section (see "AI-assisted contributions" in
CONTRIBUTING.md).
Should consider (still open, see the earlier inline comments)
torchtitan/rl/generator/inference_model.py:234: do the NUMA binding insideModelStateDictLoader.__init__. Each engine wrapper would then no longer have to callmaybe_apply_numa_bindingin the right order (vllm/model_wrapper.py:359, and again in #5812).torchtitan/rl/generator/inference_model.py:33:get_attention_dimensionsbelongs inpaged_attention.py, not in the model build/load module.
A maintainer still needs to review.
Not verified: the GPU bitwise-parity and MXFP8 Dist-MoE results in the description.
32e653c to
91fd522
Compare
| device, | ||
| ) | ||
| self._maybe_initial_load_weights() | ||
| load_initial_weights(self.model, self.config, checkpointer_config) |
There was a problem hiding this comment.
Is it worth it to make this a method of ModelStateDictLoader
There was a problem hiding this comment.
[Reply from Claude (AI agent), on behalf of the PR author]
Done: ModelStateDictLoader.__init__ takes checkpointer_config and loads the initial weights first (None skips it, as in the RL loop). The load stays a module-private function (_load_initial_weights), since it uses no loader state; it reads the model config from model.config. Both wrappers now build the loader right after the model.
One ordering change follows: the TP all-reduce routing (_patch_vllm_all_reduce / route_tp_all_reduce) sends every sum all-reduce to the engine's TP group, so it now runs after the loader instead of between the initial load and the loader.
There was a problem hiding this comment.
should we rename this file to model.py? anyways it's inside the generator/ folder so it has to be about inference
There was a problem hiding this comment.
[Reply from Claude (AI agent), on behalf of the PR author]
Done: generator/model.py, and its test test_generator_model.py.
91fd522 to
583c47b
Compare
583c47b to
c4abbdf
Compare
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The changes since the last approval are your two requested follow-ups, plus moving the paged attention helper into a new package. The code still does the same thing; only the description is out of date.
Since the last approval (the rebase onto #5963 doesn't touch these files)
- Resolved:
inference_model.pyis nowgenerator/model.py, and its test is nowtest_generator_model.py. - Resolved:
ModelStateDictLoader.__init__now takescheckpointer_configand does the initial load itself, through the private_load_initial_weights, which readsmodel.config(set atdecoder.py:248, the same vLLM-replaced config as before). The tests passcheckpointer_config=None. - New:
paged_attention.pyis nowgenerator/attention/attention.py, in a new package.
Example.
# before (last approval)
load_initial_weights(model, config, checkpointer_config)
maybe_apply_numa_binding(...)
loader = ModelStateDictLoader(model, model_state_dict_load_mode=mode)
# now
maybe_apply_numa_binding(...)
loader = ModelStateDictLoader(model, checkpointer_config=checkpointer_config, model_state_dict_load_mode=mode)Must fix
- PR description. The "Summary (human-written)" section is still the template placeholder. "What changed" is also out of date in two ways:
- It names
inference_model.py,paged_attention.py,load_initial_weightsandtest_inference_model.py. - It says the only reorders are
_fsdp_load_groupsand the vLLM dtype check, butvllm/model_wrapper.pynow runsbuild -> dist-MoE runtime -> NUMA bind -> loader (initial HF load, groups, pinned buffers, unshard) -> sinks -> TP all-reduce patch. That means the initial HF load now runs after the process is bound to the GPU's NUMA node, and the sink injection and the all-reduce patch now run after the unshard. Neither of the last two has an effect: sinks are read per call, and the patch still comes after the load. The NUMA change should be stated.
- It names
torchtitan/rl/generator/attention/__init__.py:7-- this package holds one module and nothing else is added to it in #5812. Flatten it togenerator/attention.pyand moveget_attention_dimensionsthere (see the inline comment).
Should consider (still open)
torchtitan/rl/generator/model.py:191: do the NUMA binding as the first step ofModelStateDictLoader.__init__. Both wrappers (vllm/model_wrapper.py:348, and #5812) still callmaybe_apply_numa_bindingjust before building the loader, and the docstring still asks callers to do it. Now that the loader also does the initial load, putting the bind inside the loader would also fix where the HF load runs.
Details
- Paged attention. Without FA4 there is a single call, and
call_seqused_kisseqused_k. So thecu_seqlens_kthatpaged_varlen_attention_outnow builds per call for FA2 matches the one the old code built once. - Leftover names. No in-repo references remain to
inference_model,paged_attentionorload_initial_weights. #5812 already uses the newcheckpointer_config=loader API and thegenerator.attention.attentionimport. - NUMA effect. With
AffinityMode.NODE, the CPU work of the HF load (safetensors reads,from_hf) is now limited to the GPU-local node's cores. I expect this to be neutral or a small gain, but I didn't measure it.
A maintainer still needs to review.
Not verified: the GPU bitwise-parity and MXFP8 Dist-MoE results, and their re-run after the loader change.
| """Engine-agnostic attention kernels over paged state, shared by the engines' attention | ||
| backends.""" |
There was a problem hiding this comment.
Must fix: this package holds a single module (attention.py, one function) next to an __init__.py that has only a docstring. #5812 doesn't add anything to it; SGLang's backend just imports paged_varlen_attention_out from it. .claude/rules/design.md says to flatten folders that hold one or two files. Please make it a single module, torchtitan/rl/generator/attention.py, and update the imports in vllm/attention/attention.py and in #5812.
That module is also the natural home for get_attention_dimensions (generator/model.py:33), which resolves the earlier should-consider. attention.py imports no vLLM, so registry.py can still import it at top level.
There was a problem hiding this comment.
[From Claude (AI agent), on behalf of @tianyu-l] Keeping the package: later PRs in this stack add to it -- #5817 adds generator/attention/gdn.py (the paged GDN both engines share) and #5819 adds generator/attention/kda.py -- so flattening here would be undone two PRs up. The description now says so. get_attention_dimensions stays in generator/model.py for now: it reads the model config, not attention kernels, and its callers (the engines' wrappers and registries) already import from generator/model.py.
c4abbdf to
8eb665a
Compare
8eb665a to
7a28356
Compare
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The code at 7a28356 is the same as what I last approved; the rebase onto latest main doesn't touch these files. The description now matches the code. The only blocking item left is the human-written summary.
Since the last review
- Resolved: "What changed" now names
generator/model.py,generator/attention/attention.pyandtest_generator_model.py. It also gives the actual__init__order (build -> Dist-MoE runtime -> NUMA bind -> loader -> sinks -> TP all-reduce patch) and says the initial HF load now runs after the NUMA binding. - Resolved (withdrawn): flattening
generator/attention/. #5817 addsgenerator/attention/gdn.pyand #5819 addsgenerator/attention/kda.py, so this package will hold three modules. Keepingget_attention_dimensionsingenerator/model.pyis fine. - Still open: the "Summary (human-written)" section is still the template comment.
Example.
# vllm/engine.py, before -> after
self._get_model().load_model_state_dict(fetch)
self._get_model().model_state_dict_loader.load(fetch)Must fix
- PR description: the author needs to write the "Summary (human-written)" section (see "AI-assisted contributions" in
CONTRIBUTING.md). An agent can't fill this in.
Should consider
- The commit message is out of date. It still names
inference_model.py,load_initial_weightsandpaged_attention.py, and it says "same calls in the same order", but the NUMA bind now runs before the initial load. If the merge uses the commit message rather than the PR body, update it to match. - Still open from earlier:
torchtitan/rl/generator/model.py:944asks callers to bind NUMA before buildingModelStateDictLoader. Both wrappers (vllm/model_wrapper.py:1594in the diff, and #5812) repeat that call. Binding as the first step ofModelStateDictLoader.__init__would remove that ordering rule. This is optional.
A maintainer still needs to review.
Not verified: the GPU bitwise-parity and MXFP8 Dist-MoE results in the description.
… and paged attention out of vllm/ Move the TorchTitan model build, the initial HF load and the FSDP per-group model state dict load from VLLMModelWrapper into generator/inference_model.py (build_inference_model, load_initial_weights, ModelStateDictLoader), and the torch varlen paged-KV kernel call from the vLLM CUSTOM backend into generator/paged_attention.py, so a second engine can share them. Mechanical: same calls in the same order.
7a28356 to
0c6e3cd
Compare
## 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
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
6. #5998 [rl] Muse Spark image prompts and a SLAKE LoRA GRPO recipe for
Muse Spark 816B
7. #6016 [rl][docs] README: bring the RL model support table up to date
## Why
RL prompts are token ids only: the rollout worker, the router, the
generator and vLLM pass a bare `prompt_token_ids`, so an image prompt
from #5823's renderer has nowhere to carry its images, and the generator
has no way to run the TorchTitan vision encoder. This PR carries image
prompts from the renderer to vLLM (Qwen3.5); text runs are unchanged
apart from the `Prompt` wrapper.
**Example.** Before: `generate(prompt_token_ids=[...])`. After, an image
travels as file bytes plus where its placeholder run sits:
```
rollout worker generator (every TP rank) vLLM
-------------- ------------------------- ----
render() -> Prompt VisionProcessor (CPU): embed_multimodal: vision encoder,
token_ids (placeholder runs) -----> resize_and_normalize + patchify -----> once per mm hash while cached
images: PromptImage(hash_value, LRU cache of pixel values by hash embed_input_ids: image embeddings
grid_thw, data=file bytes) image_prompt_to_engine_input -> mm_input over the placeholders
image_placeholders forward(3D M-RoPE positions)
```
## What changed
**One generation input.** `Prompt(token_ids, images=(),
image_placeholders=())` replaces the bare `prompt_token_ids` everywhere
a prompt travels: `TokenEnvOutput.next_prompt`, `GenerateFn`, the
router, `Generator.generate` and `EngineRequest`. An image is a run of
placeholder tokens in `token_ids`; `Prompt.image_placeholders` says
where each run is, and its `PromptImage(hash_value, source_path,
grid_thw, data)` carries the image file's bytes (Geometry3K median 15
KB), so no process past the rollout worker needs the dataset's file
system. This is the shape vLLM (`mm_input`), SGLang and HF processors
take at the engine boundary, so no layer converts it.
**Rollouts store deltas.** A `RolloutTurn` stores only the images after
its shared prefix (`prompt_delta_images`,
`prompt_delta_image_placeholders`), like its tokens. `split_prompt` ends
the shared prefix at the first image that differs from the previous
turn's (another file with the same placeholder count, or a moved image),
so every changed image is in the delta. TokenEnv always calls
`render()`, passes the previous prompt's `multi_modal_data` to the
bridge when it has images, and reads the image files in a worker thread.
**One image preprocessing config.** `Controller.Config.vision_processor`
(the model's `VisionProcessor.Config` from #5873, next to `tokenizer`;
None = text only) is the only place image preprocessing is configured.
The controller and the rollout workers pass it to
`renderer.build(tokenizer=..., vision_processor=...)` (#5823), and the
generator takes it as a build argument. The controller requires a
generator model that is a `MultimodalModel` with a vision encoder. It
stays a config and not a property of the model type: every real Qwen3.5
flavor ships the vision encoder, and text RL recipes use them without
serving images.
**Generator.** With a vision processor, `VLLMEngine` turns each image
file into pixel values on the CPU, as the SFT dataloader does, keeps
them in an LRU cache by image hash (vLLM's `LRUCache`, 1 GiB:
preprocessing takes 6.5 ms per Geometry3K image on the engine loop
thread, and every sample of a group carries the same images), and
submits vLLM's `mm_input` directly, so vLLM's Hugging Face processor
never runs. vLLM still requires a registered multimodal processor for
the model class; it only sizes the encoder budget and profiles memory
with the vision processor's largest image (`_largest_patch_grid`, which
is not always square). A request whose image file does not decode is
rejected at admission like any request vLLM rejects: its rollout fails
and the engine keeps serving.
**Model wrapper.** `VLLMMultimodalModelWrapper` runs the model's
`get_vision_embeds` (made public) on the packed pixel values, writes the
image embeddings over the placeholder tokens, and computes M-RoPE
positions with `get_mrope_positions`, as the trainer does.
`model_config_to_hf_config_dict(serves_images=True)` declares M-RoPE to
vLLM and rejects a model whose attention is not `MRoPE.Config`. The
generator forward now returns plain tensors (spmd_types), so the DTensor
unwrap after it is gone. The generator's shared model build
(`build_inference_model`, #5811) drops the vision encoder unless the
wrapper serves images (`keep_vision_encoder`).
**Stale embeddings.** vLLM keeps an image's encoder output after its
requests finish (only `reset_encoder_cache` clears it), and the vision
weights train. Image mm hashes are therefore salted like the prefix
cache with the request's pinned policy version (`hash@version`). With
`reset_kv_cache_on_model_state_dict_load`, hashes are bare and the
engine resets the encoder cache on every load.
Until the trainer takes image inputs (next PR), the controller rejects
`vision_processor`, so image prompts never train on their placeholder
tokens alone. Verifiers environments reject it too (their env server
builds its own renderer).
### Why the deltas are safe
The generator always gets the full prompt; only stored turns are deltas,
and the trainer rebuilds exactly the input the generator saw:
1. Image offsets are full-prompt positions from the renderer
(`render()`; the Qwen3.5 bridge seeds its tokens with the previous
prompt, so its offsets are absolute too). TokenEnv copies them into the
delta unchanged: no offset arithmetic anywhere.
2. `split_prompt` keeps an image in the shared prefix only if it equals
the previous turn's image at the same index (hash, offset and length);
otherwise the prefix ends at its first placeholder. An identical image
has the same pad tokens at the same place, so the prefix never ends
inside an image.
3. So the previous turn's images inside the prefix are exactly this
turn's prefix images, and (previous images with offset < prefix) + delta
= the turn's full images, by induction from turn 0 (prefix 0). #5825's
`TrainingSampleBuilder` rebuilds them this way.
4. A training sample starts at a full prompt's first token, so
full-prompt offsets are sample offsets, and M-RoPE positions come from
the same `get_mrope_positions` over identical content on both sides.
5. A turn extends a training sample only when its prefix covers the
previous prompt + completion. A changed image shortens the prefix, so a
completion is never trained with an image it was not generated from.
Two things could break this, and each is caught: a rollout producer that
builds turns without TokenEnv (#5825's builder rejects a delta image
outside its delta), and a renderer bridge with tail-relative offsets
(generator and trainer would be wrong together; each image renderer
needs a multi-turn test like #5825's real-renderer
`test_multiturn_images.py` for Qwen3.5).
## Numerics / performance
- Text path: RL loss guard (`rl_grpo_qwen3_0_6b_varlen_batch_invariant`,
seed 42, deterministic, trainer TP4 + one generator TP4, on-policy, 10
steps) gives `loss/mean`, `trainer/grad_norm/mean` and the
generator-vs-trainer logprob diff (max 0) bitwise equal to the PR below
at all 10 steps (TensorBoard values, `scripts/rl/loss_compare.py`; on
b9b3620, this PR before the rename to `VisionProcessor`, which changes
no computation). This covers the `Prompt` wrapper and the generator
forward without the DTensor unwrap.
- Image path, measured on an earlier revision of this PR (SLAKE medical
VQA, Qwen3.5-0.8B): generator-only accuracy with images 0.81 vs 0.51
text-only (TP1 and TP2 identical); generator vs TorchTitan forward
logprobs on image prompts mean abs diff 0.0166 vs 0.0150 for the text
control; 128 requests over 4 images ran the vision encoder 4 times. The
end-to-end image run comes with #5825.
## Testing
- `test_vllm_multimodal_wrapper.py`: the engine input places each image
on its placeholders, with the pixel values whose patch count matches the
renderer's grid; M-RoPE input positions; the largest patch grid (square,
non-square, NaViT); profiling inputs; the HF config declares M-RoPE only
when serving images; the controller rejects a vision processor for a
model without a vision encoder; image embeddings land on the placeholder
tokens vLLM's mask marks, in order (`masked_scatter_`, which never syncs
the host).
- `test_generator.py`: admission salts image hashes with the pinned
version (bare in reset mode), preprocesses each file once while cached,
rejects image requests without a vision processor, and rejects only the
request whose image file does not decode; the encoder cache resets with
the KV cache.
- `test_token_env.py`, `test_rollout_utils.py`: images across turns, the
bridge extends earlier images, delta images, `split_prompt` ends the
prefix at a changed or moved image, rejection of pixels and non-image
modalities, a changed file.
- `test_rollout_worker.py`, `test_rollout_recorder.py`: the rollout
sends and records delta images, without their bytes.
- `pytest tests/rl/unit_tests/cpu`: 575 passed, 8 skipped.
… only the adapters (#5844) ## 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 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 ## 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 #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`, #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` (#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`, #5894.)
Summary (human-written)
Why
The generator's TorchTitan model build, its initial HF load, the FSDP
per-group model state dict load, and the paged-KV call into the trainer's
varlen FlashAttention live inside
generator/vllm/, although none of them isvLLM-specific. The SGLang engine stacked on top of this PR needs the same
code; without this move it would have to copy about 500 lines of FSDP storage
handling.
Example.
What changed
Mostly mechanical: the moved bodies are unchanged. The vLLM wrapper's
__init__now runs build -> Dist-MoE runtime -> NUMA binding ->
ModelStateDictLoader(initialHF load,
_fsdp_load_groupsand thegpu_fetchquantized-parameter check, pinnedreceive buffers, unshard) -> attention sinks -> TP all-reduce patch, and its dtype
check runs before the
ParallelismContextis built. Against main:maybe_apply_numa_binding(main loads first,then binds). Its host allocations are then first-touched on the GPU's NUMA node,
as the pinned receive buffers already were.
effect: sinks are read per call, and the patch still comes after the initial load.
Files:
torchtitan/rl/generator/model.py(new):build_inference_model,ModelStateDictLoader(the initial load, the_fsdp_load_groups,reshard/restore/unshard helpers and the
load_model_state_dictbody fromvllm/model_wrapper.py), andget_attention_dimensions(fromvllm/attention/attention.py).torchtitan/rl/generator/attention/attention.py(new): the FA3/FA4 activation andthe
varlen_attn_outcall (cu_seqlens_k handling,num_splits=1for FA2 andbatch-invariant mode) from the vLLM CUSTOM backend. The package also gets the
SGLang stack's paged GDN ([rl] generator: SGLang GDN linear attention #5817) and KDA ([rl] generator: SGLang KDA linear attention #5819) helpers.
vllm/model_wrapper.py,vllm/attention/attention.py,vllm/engine.py,vllm/registry.py: call the shared code; the wrapper exposesmodel_state_dict_loader.test_vllm_wrapper.pytotest_generator_model.py. Their_Wrapperand manual_unshard_and_free_sharded_paramsloop are dropped, sinceModelStateDictLoader.__init__now does that unshard; other tests follow therenames.
Reviewers can skim the moved bodies; the call sites in
vllm/model_wrapper.pyare the part to check.
Numerics
No computation change. The vLLM generator still matches the trainer bitwise:
test_bitwise_parity.py::TestBitwiseParityVarlentest_bitwise_parity.py::TestBitwiseParityQwen35DebugVarlen(syncs trainer weights throughModelStateDictLoader)test_generator_dist_moe_mxfp8.py(cpu_prefetch load of MXFP8 Dist-MoE weights)Testing
pytest tests/rl/unit_tests/cpu: 546 passed, 7 skipped.Known issues / follow-ups
TestBitwiseParityQwen35DebugVarlenfails one bitwise assertion in about 1of 4 runs (max delta ~2e-3) on
maintoo.