Repository navigation
[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
Conversation
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
force-pushed
the
felipemello1/weight-sync-buffers/1-keep-attention-scales
branch
from
October 23, 2026 07:24
c9031a0 to
ee6214f
Compare
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).
Contributor
Author
|
Reply from claude: Status note for the rebase. Not fixed yet. Main redesigned this code: the pinned weight-sync buffers moved to
Proposal: re-cut this PR to changes 1 and 3, in main's |
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
TLDR: Four generator fixes. The first three are about the pinned CPU buffers that receive weight syncs, which
VLLMModelWrapper.__init__builds once:OffsetRMSNormcompiles 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
__init__builds the buffers with torch's_create_cpu_state_dict(self.model.state_dict(), pin_memory=True)._empty_pinned_like(tensor)allocatestorch.empty(local_shape, dtype, device="cpu", pin_memory=True)and wraps it in a DTensor with the weight's spec (mesh, placements, global shape).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
Attentionregisters 4 scale buffers per layer (_k_scale,_v_scale,_q_scale,_prob_scale), and the trainer has none of them.strict=True. So after the first sync, the scales are whatever the buffer held._copy_state_dictcopies the model's values into them, and_VLLMAttention._init_self_bufferssets the scales to vLLM's default 1.0 (they are built on meta, and vLLM fills them only after__init__).3. Fail the pull on an unpublished generator weight
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 anexpert_bias_Ebuffer.prefetch_model_state_dictcompares the pinned dict's keys with the keys the pull returned, and raisesRuntimeErrornaming 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.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
OMP_NUM_THREADSis set. RL generator processes don't set it, so warmup runs at the host's core count (192 here).recompile_limit=16), and a 9B replay already uses 13 of 16 on the worst region.__init__calls vLLM's ownset_torch_threads_for_runtimebefore vLLM's first compile, so vLLM's later call changes nothing. A user-setOMP_NUM_THREADSis still left alone.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:
strict=Truein TorchStore? The routing client doesn't support it: each rank reads only the keys it registered.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._copy_state_dictis simpler than picking keys and costs 0.2 s per 9 GiB.expert_bias_Ein the Kimi K3 debug model) and the tiedlm_head.weight.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 aquant_config) would still be reset on every sync. That isn't reachable today: the generator builds its attention withquant_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
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.TORCH_LOGS=recompiles,grep -c 'GLOBAL_STATE changed: num_threads'on the log is above 0 on main and 0 here.