Repository navigation
GPU direct weight sync - #6237
tushar00jain wants to merge 1 commit into
Conversation
|
@claude review |
|
Claude finished @tushar00jain's task in 4m 2s —— View job Request changes: end-to-end tok/s drops 14% vs. main with no explanation, and |
There was a problem hiding this comment.
Verdict: Request changes -- The design (two registered staging buffers, prefetching the next changed group) is the right fix for per-pull registration cost. But the reported end-to-end throughput drops 14% vs. main without explanation, and the fetch's completion contract changed silently.
What this PR does. gpu_fetch no longer registers and unregisters each FSDP group's destination on every pull. It registers two GPU staging buffers once, each sized for the largest load group. read_into(group i) waits for group i's RDMA read, starts group i+1's read into the other buffer, then copies group i out of its buffer into the shards. The copy runs on the current stream, and an event guards buffer reuse. The engine now exposes model_state_dict_load_groups so the transport knows the fetch order up front.
Example. Delta load where groups [a] [b] [c] exist and only a, c changed:
before: read_into({a}): register a, RDMA a, wait, unregister
read_into({c}): register c, RDMA c, wait, unregister
after: changed_keys -> {a, c}
read_into({a}): RDMA a -> slot0, wait; start RDMA c -> slot1; copy slot0 -> a
read_into({c}): prefetch hit; wait; copy slot1 -> c (b skipped, no registration)
Must fix
- PR description: "tok/s full step" is 10.1k on main, 9.4k on the previous PR and 8.7k here. That is a 14% drop vs. main and 7% vs. the previous PR, while pulls got 30% faster and blocking pull / step time got smaller. Trainer blocking also grew from 0-4 ms to 0-15 ms. Please explain where the time goes (noise across runs? contention between the prefetch RDMA and generation?), or show a rerun. This PR's only purpose is performance, so the end-to-end number has to support it.
torchtitan/rl/model_state_dict_transport.py:771--read_intoreturns with copies only stream-ordered. That contradictsGeneratorModel.load's "must finish writing before it returns" contract (torchtitan/rl/generator/model.py,loaddocstring). Update the contract, or synchronize.torchtitan/rl/model_state_dict_transport.py:728-- the group is taken from the first key with no check. Mixed-group input silently loads wrong bytes. Add an assert.torchtitan/rl/model_state_dict_transport.py:806--_finish_gpu_prefetchleaves failed works in place ifwait()raises (suggestion inline).
Should consider
torchtitan/rl/model_state_dict_transport.py:703--changed_keysnow mutates state shared with the engine-loop thread. Document the ordering invariant, or drop the stale prefetch on the engine thread.torchtitan/rl/model_state_dict_transport.py:726-- allocate the staging buffers at connect, so a headroom OOM fails at startup, not on the first sync.tests/rl/unit_tests/cpu/test_model_state_dict_transport.py--assert generator._gpu_staging_nbytes == m._GPU_STAGING_ALIGNMENTonly snapshots a private layout constant. The read counts and value checks already cover the behavior, so drop it.
Details
- Stale-prefetch safety: within one load,
load()fetches exactly the groups that intersectkeys, andkeysis the lastchanged_keysresult (EngineLoop.set_model_state_dict_fetchreplaces the keys rather than merging them). So the prefetch target always matches the nextread_into, and no prefetch is left after the last group of a successful load. A prefetch can only outlive its load when a load fails partway, and the_finish_gpu_prefetchcall inchanged_keyscovers that case. That is why finding 4 matters. - The connect-time
set_model_state_dict_fetch(keys=layout.keys())runs before anychanged_keys, so_gpu_load_keysis empty and a load at that point gets no prefetching. Correct, just slower. Fine if that load never happens in practice. - The partition check in
connect_generator_gpucorrectly catches key-naming drift between_fsdp_load_groupsandmodel.state_dict().
Not verified: whether FSDP2's explicit unshard() runs on the current stream (finding 2), and anything about GPU behavior or performance. A maintainer still needs to review.
| event.record() | ||
| return state_dict.keys() |
There was a problem hiding this comment.
read_into now returns while the staging-to-shard copies are still queued on the current stream. The old code waited for the RDMA reads and synchronized after unpacking. GeneratorModel.load's docstring still says a fetch "must finish writing before it returns". Correctness now depends on _unshard_and_free_sharded_params (module.unshard() all-gather copy-in, then free_storage) being ordered after the current stream. I believe FSDP2 runs an explicit, non-forward unshard() on the current stream, but I couldn't check that here (unverified). If that's the intended contract, update the load() docstring to "stream-ordered on the current stream" and say why it's safe. Otherwise, synchronize event before returning.
| return state_dict.keys() | ||
| if not self._gpu_staging: | ||
| self._allocate_gpu_staging(next(iter(tensors.values())).device) | ||
| group = self._gpu_group_of_key[next(iter(tensors))] |
There was a problem hiding this comment.
The group comes from the first key alone, and the copy-out uses _gpu_staging_offsets, which are per-group offsets. If a caller ever passes keys from two groups, the extra key's offset points into bytes of the wrong group, and you get silently wrong weights instead of an error. Today load() respects the contract, but nothing enforces it, and model_state_dict_load_groups is a second copy of load()'s fetch order. Make the invariant explicit:
assert tensors.keys() <= self._gpu_groups[group], "read_into keys must be one load group"| def _finish_gpu_prefetch(self) -> None: | ||
| """Wait for and drop the prefetched group, if any.""" | ||
| if self._gpu_prefetch is not None: | ||
| for work in self._gpu_prefetch[2]: | ||
| work.wait() | ||
| unpacked = False | ||
| with torch.no_grad(): | ||
| for key, buffer in packed_buffers.items(): | ||
| unpacked = True | ||
| tensor = tensors[key] | ||
| flat = buffer.view(-1) | ||
| for piece in self._gpu_packed[key]: | ||
| view = flat[ | ||
| piece.offset : piece.offset + math.prod(piece.shape) | ||
| ].view(piece.shape) | ||
| tensor[piece.index].copy_(view, non_blocking=True) | ||
| if unpacked and torch.accelerator.is_available(): | ||
| torch.accelerator.current_stream().synchronize() | ||
| finally: | ||
| for memory in registered.values(): | ||
| self._transport.unregister_memory(memory) | ||
| return state_dict.keys() | ||
| self._gpu_prefetch = None |
There was a problem hiding this comment.
If work.wait() raises (for example on a read_timeout_s timeout), _gpu_prefetch is never cleared. Every later changed_keys / read_into then waits on the same failed works again. This is the failure path the call in changed_keys exists to handle. Clear it first:
| def _finish_gpu_prefetch(self) -> None: | |
| """Wait for and drop the prefetched group, if any.""" | |
| if self._gpu_prefetch is not None: | |
| for work in self._gpu_prefetch[2]: | |
| work.wait() | |
| unpacked = False | |
| with torch.no_grad(): | |
| for key, buffer in packed_buffers.items(): | |
| unpacked = True | |
| tensor = tensors[key] | |
| flat = buffer.view(-1) | |
| for piece in self._gpu_packed[key]: | |
| view = flat[ | |
| piece.offset : piece.offset + math.prod(piece.shape) | |
| ].view(piece.shape) | |
| tensor[piece.index].copy_(view, non_blocking=True) | |
| if unpacked and torch.accelerator.is_available(): | |
| torch.accelerator.current_stream().synchronize() | |
| finally: | |
| for memory in registered.values(): | |
| self._transport.unregister_memory(memory) | |
| return state_dict.keys() | |
| self._gpu_prefetch = None | |
| def _finish_gpu_prefetch(self) -> None: | |
| """Wait for and drop the prefetched group, if any.""" | |
| prefetch, self._gpu_prefetch = self._gpu_prefetch, None | |
| if prefetch is not None: | |
| for work in prefetch[2]: | |
| work.wait() |
| ``read_into`` prefetches only the groups holding one of them.""" | ||
| assert self._gpu_reads is not None, "connect_generator_gpu must be called first" | ||
| # A load that failed part way can leave a prefetch in flight. | ||
| self._finish_gpu_prefetch() |
There was a problem hiding this comment.
changed_keys used to be pure. It now mutates _gpu_prefetch and _gpu_load_keys and blocks on RDMA works. It runs on the actor thread (Generator.prefetch_model_state_dict), while read_into runs on the engine-loop thread (EngineLoop._load_model_state_dict). The two share this state without a lock. That's only safe if the controller never calls prefetch while a load is in flight. I think the trainer-restaging protocol already guarantees this, but it's an implicit ordering invariant. Please state it in a comment here, or move the stale-prefetch drop onto the engine thread (for example, at the start of read_into when group is the load's first group).
| try: | ||
| if not tensors: | ||
| return state_dict.keys() | ||
| if not self._gpu_staging: |
There was a problem hiding this comment.
The 2 x largest-group buffers (4.74 GiB in your run) are allocated lazily on the first load, after vLLM/SGLang have sized the KV cache. With less headroom (higher gpu_memory_utilization, bigger groups), this OOMs mid-run on the first weight sync instead of at startup. Consider allocating and registering in connect_generator_gpu, on torch.accelerator.current_device_index(). That fails fast, and you can drop the if not self._gpu_staging branch.
71df3ab to
653d5be
Compare
4d7e404 to
1f3bc96
Compare
d4l3k
left a comment
There was a problem hiding this comment.
Can we do a hybrid approach? This seems like a reasonable strategy but wondering if we can do dynamic registration for the staging buffer. If we only have to register one buffer it should be much cheaper as opposed to registering every buffer
cd1b515 to
9a23c06
Compare
5ec30d7 to
24bd234
Compare
9a23c06 to
850293f
Compare
24bd234 to
063bdca
Compare
063bdca to
7083c3e
Compare
850293f to
7c42edd
Compare
7083c3e to
be2d9cf
Compare
7c42edd to
896c159
Compare
|
@claude review again mark resolved comments as resolved |
|
Claude finished @tushar00jain's task in 4m 7s —— View job Needs discussion: all four of my earlier must-fix findings are fixed at 8d4a56a. What's left is a decision for @d4l3k: their draft #6127 does the same thing with one buffer, and their change request is still open. Review Earlier threads not marked resolvedI couldn't mark the threads resolved: this job has no tool for resolving review threads, and
My earlier REQUEST_CHANGES review still shows as blocking. A maintainer can dismiss it, or ask me to review again once the remaining items are done. |
@d4l3k according to claude, dynamic registration after kvcache has been allocated can oom and won't give memory back to kvcache anyway. so keeping the buffer pre-allocated to avoid that |
There was a problem hiding this comment.
Verdict: Needs discussion -- My earlier code findings are fixed at 8d4a56a. What's left is a maintainer decision: @d4l3k's draft #6127 implements the same feature with one registered buffer and no overlap, and their change request is still open. There are also three small items below.
What this PR does. With gpu_fetch, the transport now reads straight into GPU weights. Before, gpu_fetch had to use TorchStore: on main, Controller.Config.__post_init__ raises for transport + gpu_fetch. Each generator rank allocates and registers two staging buffers at connect time, each the size of the largest FSDP load group. read_into(group i) waits for group i's reads, starts group i+1's reads into the other buffer, then copies group i out on the current stream. An event recorded after the copies guards each buffer's reuse.
Example. Groups [emb] [l0] [l1] [buffers]:
read_into(emb): read emb -> A, wait; start l0 -> B; copy A -> emb, record A
read_into(l0): wait l0; sync A; start l1 -> A; copy B -> l0, record B
read_into(l1): wait l1; sync B; start buffers -> B; copy A -> l1, record A
read_into(buffers): wait; (last group: no prefetch) copy B -> buffers
Earlier findings
- tok/s drop: rerun. Now 9.5k vs. 9.2k, see "Should consider".
read_intowrite-completion contract: resolved. RDMA now writes only into the staging buffers, soload()'s "writing outside the current stream" clause no longer applies to the destinations.- Mixed-group input: resolved by the
state_dict.keys() == ...assert. _finish_gpu_prefetchfailure path: resolved. It was removed, and a failed load is fatal (EngineLoop._load_model_state_dictre-raises).- Cross-thread
changed_keysstate, lazy allocation, private-constant test: all resolved.
Must fix
- PR description: "Why" describes #6147, which was closed unmerged, as if it were the baseline. On
main,gpu_fetchcan't use the transport at all. The measured win overmainis generator peak RSS (81 -> 6.5 GiB) and pull time (1.5 -> 1.15 s), so say that. Also, "memory overhead is limited to the largest FSDP group" should be 2x the largest group. torchtitan/rl/README.md:64still saysgpu_fetchrequiresmodel_state_dict_transport=None.torchtitan_recipes/tests/rl/alphabet_sort.py:999justifiestransport=Nonewith "TorchStore is still the only path for gpu_fetch", but that config doesn't even setgpu_fetch. Update both.- No CI runs the new GPU path. No integration config sets
gpu_fetch, and the CPU unit tests run withevent=None, so the event and stream ordering that prevents silently wrong weights is untested. Setgenerator.model_state_dict_load_mode = "gpu_fetch"on one existing RL integration config that uses the default transport.
Should consider
- tok/s full step is still 3% below
main(9.2k vs. 9.5k). Pulls are 25% faster and the blocking-pull share is lower. Say whether 3% is within run-to-run noise.
Questions
- @d4l3k (hybrid / #6127): the author's reply says dynamic registration after the KV cache is allocated can OOM. But
connect_generator_gpualso allocates after the engine (and its KV cache) is built. So the real difference is failing at startup vs. on a pull, not whether the memory fits. Per-pull allocation would also not free anything between pulls: the caching allocator keeps the block reserved (peak reserved is unchanged here), and each pull would pay registration again. The open trade-off is one buffer (#6127: 2.37 GiB, no overlap) vs. two (this PR: 4.74 GiB, overlap, plus the event and prefetch logic). @tushar00jain, a pull time with a single buffer and no prefetch would settle whether the second buffer earns its memory. Which PR should land?
Not verified: GPU behavior and performance. The claim that FSDP2's explicit unshard() outside forward runs on the current stream is from reading FSDP2, not from a run. A maintainer still needs to review.
`gpu_fetch` registered every FSDP group's freshly reallocated GPU storage with the transport on every load and read it while the generator was paused, so a 27B pull took 3.6-4.1 s against 1.5-1.7 s for `cpu_prefetch`. The generator now reads each group into one of two GPU staging buffers, which each load allocates and registers at its first group and releases after its last. Load group `i` is read into buffer `i % 2`: while one group is copied out of its buffer into the GPU shards and goes through the FSDP all-gather, the next group of the same load is read into the other buffer. Each buffer is the size of the largest load group, computed from the layout of each group in load order (`ModelStateDictLoader.model_state_dict_load_groups`). Prefetching stays within one load, since the trainer may restage after it. CPU prefetch is unchanged. Test Plan: ``` python -m pytest -q -o addopts= tests/rl/unit_tests/cpu/test_model_state_dict_transport.py tests/rl/unit_tests/cpu/test_generator_model.py tests/rl/unit_tests/cpu/test_engine_loop.py ``` Authored with assistance from an AI coding assistant. fs-branch: tushar00jain/6
|
updated to free memory after use |
|
could you rebase and run bot check? |
Why
On
main,model_state_dict_load_mode="gpu_fetch"can't useModelStateDictTransport: the controller rejects it, sogpu_fetchgoes through TorchStore, and the transport needscpu_prefetch, which pins a full copy of the model in each generator's host memory (81 GiB peak RSS for 27B). A basic implementation (#6147, closed) registered each FSDP group's freshly reallocated GPU storage on every pull, then read it and waited for it before the next group started. Nothing overlapped, so a 27B pull took 3.6-4.1 s.What changed
ModelStateDictTransportnow also servesmodel_state_dict_load_mode="gpu_fetch": the controller no longer requirescpu_prefetchwith it. Quantized parameters remain unsupported withgpu_fetch.Two GPU staging buffers A and B, each the size of the largest FSDP group and registered once. The next group is read while the current one loads:
This registers the memory once, and the memory overhead is limited to two of the largest FSDP group, not the whole model. Against
main, generator peak RSS drops from 81 to 6.5 GiB and steady pulls from 1.52-1.64 s to 1.12-1.18 s.Test Plan:
The
rl_grpo_fsdp2_gen_tp2_no_compileintegration test now runsgpu_fetchwith the default transport.Same setup as the PR2 tables, full sync,
gpu_fetch, expandable segments on. main ismain(e95a8c4,cpu_prefetch). The other column usesgpu_fetchon this PR's code. Pull times are for the slowest generator.gpu_fetchtok/s full step includes the trainer's wait for rollouts, which ranges 36-129 s per step in both runs while
forward_backwardstays at 32-40 s, so its difference is rollout-length noise rather than the pull.Trainer staging, same runs (trainer rank 0).
gpu_fetchforward_backwardincl. overlapped staging (steps 2-6)Memory, same runs (max over processes and steps).
gpu_fetchThe two GPU staging buffers are registered once, and the next FSDP group is read while the current one loads. They fit in vLLM's headroom: KV cache and peak reserved are unchanged.
Authored with assistance from an AI coding assistant.
Stack (top to bottom):