Skip to content

[rl] Generator weight-sync buffers: allocate pinned directly, keep attention scales, fail on unpublished keys; one CPU thread at init - #5484

Draft
felipemello1 wants to merge 2 commits into
mainfrom
felipemello1/weight-sync-buffers/1-keep-attention-scales
Draft

felipemello1 wants to merge 2 commits into
mainfrom
felipemello1/weight-sync-buffers/1-keep-attention-scales

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

TLDR: Four generator fixes. The first three are about the pinned CPU buffers that receive weight syncs, which VLLMModelWrapper.__init__ builds once:

  1. Allocate them pinned directly, without a staging copy: 64 GiB 51.4 s -> 13.7 s on every generator start (H100 host).
  2. Fill them with the model's values, so vLLM's attention scales stay 1.0 after a sync instead of 0.0. An FP8 KV cache would divide by 0.
  3. Fail the pull when the trainer didn't publish a generator weight. Today that weight silently keeps its init value.
  4. Set vLLM's one-CPU-thread runtime at init. On a 4-layer Qwen3.5-35B-A3B, OffsetRMSNorm compiles 13 -> 9 times; in an RL smoke, recompiles go 24 -> 17.

NOTE: measured on H100 only; needs retesting on Blackwell. (Change 4's compile counts don't depend on the GPU.)

1. Pinned buffers without a staging copy

  1. Today: __init__ builds the buffers with torch's _create_cpu_state_dict(self.model.state_dict(), pin_memory=True).
  2. The waste: for each DTensor weight, it copies the local shard to pageable CPU memory, allocates a pinned tensor, and drops the copy.
  3. Cost: 64 GiB of FSDP-sharded bf16 weights take 51.4 s on one H100 host. Qwen3.5-35B-A3B on GB300 (65 GiB per engine, an earlier main) takes about 50 s per engine, before the first weight sync.
  4. This PR: _empty_pinned_like(tensor) allocates torch.empty(local_shape, dtype, device="cpu", pin_memory=True) and wraps it in a DTensor with the weight's spec (mesh, placements, global shape).
  5. Unchanged: each buffer's DTensor spec, the NUMA binding before allocation, and every TorchStore call.
Building the buffers. FSDP-sharded bf16 Linear weights, 1 rank, H100 host, torch 2.15.0.dev20261005
8 GiB      6.5 s -> 1.7 s
64 GiB    51.4 s -> 13.7 s

Standalone VLLMGenerator init, Qwen3.5-4B-Base, TP1, 1x H100, warm compile caches, 9.0 GiB of buffers.
4 runs each on a shared host (load average ~180), measured before the fill copy (2) was added (+0.2 s).
vLLM "Model loading"          12.5 / 11.4 / 11.1 / 10.6 s  ->  4.9 / 3.5 / 7.5 / 5.1 s
VLLMGenerator init (median)   28.0 s  ->  22.2 s

End to end, 3 steps of Qwen3-0.6B alphabet sort (trainer and generator on one H100): weight sync works; trainer vs generator logprob diff -0.0018 (main -0.0016); step-0 validation reward 0.190 (main 0.192).

NOTE: allocating pinned memory still takes 13.7 s per 64 GiB; the TODO in __init__ suggests a background thread during vLLM's memory profiling.

2. vLLM's attention scales keep their init value

  1. vLLM's Attention registers 4 scale buffers per layer (_k_scale, _v_scale, _q_scale, _prob_scale), and the trainer has none of them.
  2. TorchStore fills only the keys the trainer publishes, and the pull loads every key with strict=True. So after the first sync, the scales are whatever the buffer held.
  3. Only FP8 paths read them, and TorchTitan asserts the FP8 KV cache off, so generation is unchanged today.
  4. This PR: right after allocating the buffers, _copy_state_dict copies the model's values into them, and _VLLMAttention._init_self_buffers sets the scales to vLLM's default 1.0 (they are built on meta, and vLLM fills them only after __init__).
Qwen3.5-4B-Base, 1x H100, in-process vLLM engine. Fill only the trainer's keys, then run main's pull.
32 attention scales after 1 sync (measured on change 2 alone, before change 1):
  main 0.0, main + copy only 0.0, + default scales 1.0 (TP1 and TP2)
greedy decode before vs after the sync: identical in all runs
startup: +0.21 s for 9.02 GiB (the old _create_cpu_state_dict took 10.8-12.8 s)

3. Fail the pull on an unpublished generator weight

  1. The pull fetches only keys that are both published and in the pinned dict, so a generator key the trainer didn't publish keeps its old value, with no error.
  2. load_state_dict(strict=True) can't see it, because the pinned dict comes from the generator's own model. In RL, the old value is the init: random weights, or zeros for an expert_bias_E buffer.
  3. Nothing hits this today: 0 unpublished keys across the 32 of 35 alphabet-sort RL recipes that build. But the trainer and generator model configs are separate objects, and the controller compares only their class.
  4. This PR: prefetch_model_state_dict compares the pinned dict's keys with the keys the pull returned, and raises RuntimeError naming the first 5. vLLM's attention scales (.vllm_attn. keys) are exempt. Keys the trainer publishes but the generator doesn't hold aren't fetched, so they aren't checked.
trainer vs generator keys, 32 RL recipes (meta device, CPU):   unpublished keys 0
same probe, 9 recipes in dapo_math, search_r1, verifiers_dapo_math, verifiers_terminal_bench: 0
  (not built: 3 of 35 alphabet-sort recipes (dist_moe, DeepEP, newer torchao), the DeepEP search_r1
  perf recipe, the Muse Spark GB300 recipe; Terminal-Bench recipes built with Verifiers stubbed)
check cost per pull (1920 keys, CPU):                          0.03 ms
2x H100, trainer 1 GPU + generator 1 GPU, 2 train steps:
  Kimi K3 debug (MoE, 16 expert_bias_E buffers)   3 pulls, no error
  Qwen3-0.6B (tied lm_head.weight)                3 pulls, no error
  trainer drops layers.1.feed_forward.expert_bias_E:
    RuntimeError: The trainer did not publish 1 of the generator's weights (first 5: ['layers.1.feed_forward.expert_bias_E']). Check that the trainer and generator model configs match.
  trainer drops lm_head.weight (tied):
    RuntimeError: The trainer did not publish 1 of the generator's weights (first 5: ['lm_head.weight']). ...

The two "trainer drops ..." runs are negative controls: a local edit removed one key from the trainer's staging dict.

4. One CPU thread from model init

  1. When warmup ends, vLLM sets the thread that runs the model to one CPU thread, unless OMP_NUM_THREADS is set. RL generator processes don't set it, so warmup runs at the host's core count (192 here).
  2. torch.compile guards on the thread count, so each region compiled during warmup compiles again at the first step that runs eager (FULL_DECODE_ONLY mixed steps, NONE, or steps above the capture cap).
  3. It's headroom, not a crash today: a region raises at its 17th version (recompile_limit=16), and a 9B replay already uses 13 of 16 on the worst region.
  4. This PR: __init__ calls vLLM's own set_torch_threads_for_runtime before vLLM's first compile, so vLLM's later call changes nothing. A user-set OMP_NUM_THREADS is still left alone.
4-layer Qwen3.5-35B-A3B-Base, TP1, H100, FULL_DECODE_ONLY, 7 batches (1-64 prompts x 700 tokens), TORCH_LOGS=recompiles, A-B-A-B
                                   before        after
OffsetRMSNorm compiles             13, 13        9, 9
norm, activation, gate, RoPE       4 each        3 each
num_threads guard failures         48, 48        0, 0
3-step RL smoke (Qwen3.5 debugmodel, FULL_DECODE_ONLY, 2 GPUs): recompiles 24 -> 17, num_threads guard failures 45 -> 0,
  bit_wise/logprob_diff/max 0.012 -> 0.011 (last of 3 steps)

Decode step medians, over all 7 batches and both rounds (14 pairs): within -0.32/+0.35 ms of base, higher in 10 of 14. The largest gap is 8 prompts, round 2: 2.43 -> 2.71 ms. Model load (8-12 s) and engine init (20-24 s) vary by the same amount in both arms.

You may ask:

  • Why not load only the keys TorchStore filled? A generator-only parameter would still be lost: each pull re-allocates the sharded storage without values.
  • Why not strict=True in TorchStore? The routing client doesn't support it: each rank reads only the keys it registered.
  • Why not OMP_NUM_THREADS=1? It also puts the actor thread that copies prefetched weights on one thread: a 2 GiB CPU copy takes 12.7 ms at 192 threads and 163.6 ms at 1.
  • Why not make the 4 scales non-persistent? That fixes only these 4. Another vLLM attention buffer the trainer doesn't publish would get uninitialized memory on every sync; any other unpublished buffer now raises (3).
  • Why copy every value if unpublished keys now raise (3)? Only vLLM's attention scales need it, but one _copy_state_dict is simpler than picking keys and costs 0.2 s per 9 GiB.
  • Why not check parameters only? That misses persistent buffers (16 expert_bias_E in the Kimi K3 debug model) and the tied lm_head.weight.
  • Why not raise recompile_limit? That hides the duplicate compiles instead of removing them.

NOTE: a value vLLM sets after __init__ (e.g. calibrated FP8 KV scales from a quant_config) would still be reset on every sync. That isn't reachable today: the generator builds its attention with quant_config=None.
NOTE: quantized FSDP weights (e.g. MXFP8) used to get unpinned buffers (the old path treats a tensor subclass as empty); they now get pinned ones. A probe with such a weight loaded the prefetched value exactly, but without the fill copy (2); not run with it.

Test plan

CUDA_VISIBLE_DEVICES= pytest -q tests/rl/unit_tests/cpu
CUDA_VISIBLE_DEVICES=0 pytest -q tests/rl/unit_tests/gpu/test_prefetch_buffers.py
  • test_empty_pinned_like_keeps_spec_without_reading_weights: the old copying path fails it.
  • test_prefetch_model_state_dict_raises_when_a_weight_is_not_published: fails on main.
  • Scales: a GPU probe, not in this PR (~2 min per run, TP1 and TP2): build one engine, fill only the trainer's keys, run the pull, print the scales.
  • The thread change has no unit test (the call has no logic). Quick check on a generator run: with TORCH_LOGS=recompiles, grep -c 'GLOBAL_STATE changed: num_threads' on the log is above 0 on main and 0 here.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 18, 2026
Felipe Mello added 2 commits October 22, 2026 23:51
…d check every key, one CPU thread at init

Four fixes to the generator's pinned CPU receive buffers for weight sync,
built once in VLLMModelWrapper.__init__:

1. Allocate them pinned directly (_empty_pinned_like) instead of torch's
   _create_cpu_state_dict, which copied every shard to pageable CPU memory
   first: 64 GiB 51.4 s -> 13.7 s (H100 host).
2. Fill them with the model's values (_copy_state_dict) and give vLLM's
   attention scales their 1.0 default, so keys the trainer doesn't publish
   keep their init value instead of 0.0.
3. prefetch_model_state_dict raises when the trainer did not publish a
   generator weight (vLLM attention scales exempt), instead of silently
   keeping its init value.
4. Call vLLM's set_torch_threads_for_runtime at init, so regions compiled
   during warmup don't recompile when vLLM drops to one CPU thread.
@felipemello1
felipemello1 force-pushed the felipemello1/weight-sync-buffers/1-keep-attention-scales branch from c9031a0 to ee6214f Compare October 23, 2026 07:24
@felipemello1 felipemello1 changed the title [rl] keep vLLM attention scales across generator weight syncs [rl] Generator weight-sync buffers: allocate pinned directly, keep attention scales, fail on unpublished keys; one CPU thread at init Oct 23, 2026
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).
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Status note for the rebase. Not fixed yet.

Main redesigned this code: the pinned weight-sync buffers moved to torchtitan/rl/generator/model.py, behind model_state_dict_load_mode. The 4 changes on today's main (4122eaf):

  1. Pinned buffers without a staging copy: still applies. Main still builds them with _create_cpu_state_dict(..., pin_memory=True) in the default cpu_prefetch mode (generator/model.py:507). Measured win: generator start 51.4 -> 13.7 s per 64 GiB of buffers (H100).
  2. vLLM attention scales: no longer needed. Main keeps them out of the state dict (ddbea8b).
  3. Fail on a weight the trainer didn't publish: half done. GeneratorModel.load raises when a fetch leaves a parameter unfilled (generator/model.py:565-570). In gpu_fetch mode the fetch returns only the keys it read, so this catches it. In cpu_prefetch mode the network read skips unpublished keys (strict=False, generator/generator.py:527), but the copy from the pinned buffers returns every key (generator.py:540-541). So an unpublished weight keeps its init value with no error.
  4. One CPU thread at init: better done with a per-process thread setting, in its own PR. Leave it out.

Proposal: re-cut this PR to changes 1 and 3, in main's generator/model.py and generator.py, about 25 lines.

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