Repository navigation
Transfer model state directly to generator GPU - #6147
tushar00jain wants to merge 1 commit into
Conversation
a1b0701 to
b18cbfe
Compare
b18cbfe to
8b45248
Compare
8b10893 to
b84ff0d
Compare
8b45248 to
6269b95
Compare
6269b95 to
e24debf
Compare
b84ff0d to
750ac0e
Compare
|
Claude finished @tushar00jain's task in 4m 25s —— View job Request changes: posted review -- |
There was a problem hiding this comment.
Verdict: Request changes -- The direct GPU path likely fails on ranks whose FSDP shard of a tensor is empty, and TorchStore + quantized gpu_fetch now fails at the first load instead of at init. Both fixes are small.
What this PR does. With model_state_dict_load_mode="gpu_fetch", ModelStateDictTransport now reads trainer staging directly into the generator's GPU tensors, one FSDP group at a time. It used to require CPU prefetch buffers. For each group, read_into registers the group's sharded GPU storage (or a temporary contiguous buffer for packed keys), reads the group, unpacks any packed keys, and unregisters the storage. Delta sync adds changed_keys to the push metadata. The loader then skips FSDP groups with no changed key and reads changed groups whole. Quantized params are filled through their high-precision _tensor and requantized by the existing unshard.
Example. Delta sync, two decoder layers, and only layers.1.weight changed since the last push:
before (cpu_prefetch): read changed ranges into pinned CPU -> copy every group CPU->GPU
before (gpu_fetch): ValueError in Controller.__post_init__ (transport required TorchStore=None)
after (gpu_fetch): prefetch records keys={"layers.1.weight"}
load: skip group layers.0; register layers.1 shards, read
layers.1.{weight,bias} from baseline, all-gather; skip buffers
Must fix
torchtitan/rl/model_state_dict_transport.py:674-692:read_intoregisters every key, including zero-element local shards (uneven generator FSDP).connect_generatoravoids this on purpose because backends reject empty registrations. Skipnumel() == 0. (inline)torchtitan/rl/generator/model.py:555-559: the quantized + TorchStoregpu_fetchrejection moved from loader init to the first load. Raise it inGenerator.initialize_torchstore_client, or ban TorchStore +gpu_fetchinController.__post_init__. (inline)- PR description: it has no "Summary (human-written)" section (see the
pr-descriptionskill).
Should consider
local_storageis threaded throughGenerationEngine.load_model_state_dict, both engines,EngineLoop, andModelStateDictLoader.loadonly to choose betweenfsdp_param.sharded_param(TorchStore and CPU copy need the DTensor) and the raw/high-precision local storage. The name doesn't say that. If TorchStore +gpu_fetchis banned (must-fix 2), the loader can derive it from its ownmodel_state_dict_load_mode, and the flag disappears from five signatures.torchtitan/rl/generator/engine_loop.py:557-564: redundantkeys is Nonebranch. (inline, suggestion)torchtitan/rl/generator/generator.py:501-505: theset_model_state_dict_fetchcall inconnect_model_state_dict_transportis always overwritten by the prefetch before any load. (inline)tests/rl/unit_tests/cpu/test_generator_model.py:76-83: low-value test of a private helper on aSimpleNamespace. (inline)- No integration test runs
gpu_fetch, through either transport. The new path (GPU RDMA registration, packed unpack on GPU, quantized refill) is covered only by CPU fakes. Consider switching an existing RL integration config togpu_fetch+sync_mode="delta"rather than adding one. Separately,torchtitan_recipes/tests/rl/alphabet_sort.py:999says "TorchStore is still the only path for gpu_fetch", which this PR makes stale, and that config doesn't setgpu_fetchanyway. MODEL_STATE_DICT_TRANSPORT.md: the rewrite drops "A timeout leaves reads ... undefined; restart the job." On the GPU path a timeout is worse:finallyunregisters memory with reads possibly still in flight, thenloadkeeps unsharding and freeing the group's storage. Keep the restart note.
Questions
- The MAST numbers cover full sync only. Is there a delta-sync
gpu_fetchrun, and a loss/grad_norm match againstcpu_prefetchfor the same seed?
Details
Gate. The problem is real: GB300 hosts run short of CPU memory, and the table shows generator RSS dropping from 81 GiB to 6.5 GiB. The PR deletes the Controller.__post_init__ ban and the old TODO (#6070). gpu_fetch is opt-in, so the 2.4x slower pull doesn't touch the default path, and #6237 in the stack works on it. No direction conflict.
Delta correctness. I checked the ordering. Controller awaits the pull task before starting the next push (controller.py:1416-1426). Every load is preceded by exactly one prefetch (inter_generator.py:216-222), so recording only the latest push's changed_keys doesn't lose changes. read_into reads from baseline_buffer, which finish_stage brings up to date for changed ranges, so unchanged keys in a changed group read current values. Every generator rank derives the same key set from the same metadata tuple intersected with identical layout keys, so all ranks skip the same groups and the FSDP all-gathers don't hang.
Layout equivalence. model_state_dict_layout is now computed from the GPU sharded state dict instead of the pinned CPU copy. _create_cpu_state_dict preserves shapes, dtypes, and placements, so shared_rank_layouts sees the same values for cpu_prefetch.
Not verified: that Transport.read accepts timeout=, the unregister_memory semantics with reads in flight, and backend behavior on empty registrations (taken from the existing comment). All need a GPU/NIXL run.
| for key, tensor in tensors.items(): | ||
| packed = self._gpu_packed.get(key) | ||
| destination_tensor = ( | ||
| torch.empty_like(tensor, memory_format=torch.contiguous_format) | ||
| if packed is not None | ||
| else tensor | ||
| ) | ||
| if packed is not None: | ||
| packed_buffers[key] = destination_tensor | ||
| destination = ( | ||
| destination_tensor.data_ptr(), | ||
| destination_tensor.nbytes, | ||
| destination_tensor.device, | ||
| ) | ||
| if destination not in registered: | ||
| registered[destination] = self._transport.register_memory( | ||
| destination_tensor.view(-1) | ||
| ) | ||
| memories[key] = registered[destination] |
There was a problem hiding this comment.
This loop registers every key in state_dict, including keys whose local shard has zero elements. connect_generator above deliberately registers only keys that have reads, because "backends reject registering empty tensors" (line 589).
Generator FSDP shards over data_parallel_degree, and with uneven sharding the ranks past the last chunk hold an empty local tensor. model.py:677 handles this same case for frozen params. With DP > 1 and a parameter whose dim 0 is smaller than the FSDP degree, register_memory sees an empty tensor and the load fails on that rank. Unverified on GPU: this rests on the existing comment about backend behavior.
Smallest fix: skip keys that have no reads, which matches connect_generator:
for key, tensor in tensors.items():
if tensor.numel() == 0:
continue(read_into still returns every key, so load's missing-key check passes.)
| if self._gpu_fetch_has_quantized_params and not local_storage: | ||
| raise ValueError( | ||
| "model_state_dict_load_mode='gpu_fetch' requires " | ||
| "ModelStateDictTransport for quantized parameters" | ||
| ) |
There was a problem hiding this comment.
This used to raise in __init__. Now gpu_fetch + quantized + TorchStore (model_state_dict_transport=None) gets past init and fails on the first load, after the trainer has already staged its push. That load failure then stops the engine loop on every generator rank. CLAUDE.md principle 8 wants unsupported configurations rejected as early as possible.
The TorchStore path is the only one that calls Generator.initialize_torchstore_client, so the check fits there. Raise when model_state_dict_load_mode == "gpu_fetch" and the loader has quantized params. Then this check and the local_storage argument (see the body) can go away. Alternatively, ban TorchStore + gpu_fetch outright in Controller.__post_init__, now that the transport covers gpu_fetch.
| if self._model_state_dict_keys is None: | ||
| self._engine.load_model_state_dict(self._fetch_model_state_dict) | ||
| else: | ||
| self._engine.load_model_state_dict( | ||
| self._fetch_model_state_dict, | ||
| keys=self._model_state_dict_keys, | ||
| local_storage=self._model_state_dict_local_storage, | ||
| ) |
There was a problem hiding this comment.
This branch isn't needed. keys=None, local_storage=False are the defaults of load_model_state_dict, so always pass them through:
| if self._model_state_dict_keys is None: | |
| self._engine.load_model_state_dict(self._fetch_model_state_dict) | |
| else: | |
| self._engine.load_model_state_dict( | |
| self._fetch_model_state_dict, | |
| keys=self._model_state_dict_keys, | |
| local_storage=self._model_state_dict_local_storage, | |
| ) | |
| self._engine.load_model_state_dict( | |
| self._fetch_model_state_dict, | |
| keys=self._model_state_dict_keys, | |
| local_storage=self._model_state_dict_local_storage, | |
| ) |
| self._engine_loop.set_model_state_dict_fetch( | ||
| self._model_state_dict_transport.read_into, | ||
| keys=self._model_state_dict_layout.keys(), | ||
| local_storage=True, | ||
| ) |
There was a problem hiding this comment.
This call is redundant. Every load goes through InterGeneratorRouter.pull_model_state_dict, which awaits prefetch_model_state_dict first, including the initial pull in Controller setup. The first prefetch has full=True and sets these same keys, so this set is always overwritten before any load reads it. Deleting it leaves one place that decides the keys.
| def test_direct_fetch_uses_quantized_high_precision_storage() -> None: | ||
| class _QuantizedShard(_ShardedFSDPTensor): | ||
| pass | ||
|
|
||
| high_precision = torch.zeros(4) | ||
| fsdp_param = SimpleNamespace(_sharded_local_tensor=_QuantizedShard(high_precision)) | ||
|
|
||
| assert generator_model._writable_sharded_param_storage(fsdp_param) is high_precision |
There was a problem hiding this comment.
This test calls a two-line private helper on a SimpleNamespace stand-in for FSDPParam. It doesn't exercise a real FSDP param or the quantized load, so it catches no regression the helper's own code wouldn't make obvious (.claude/rules/tests.md). Delete it, along with the SimpleNamespace and _ShardedFSDPTensor imports. If quantized gpu_fetch needs a guard, enable it in an existing GPU test that builds a quantized generator instead.
71df3ab to
653d5be
Compare
750ac0e to
51f09a5
Compare
d4l3k
left a comment
There was a problem hiding this comment.
Can we focus this on trainer -> gpu without delta for now? I think we need some more discussion on how to handle decompression on the GPU (nvcomp etc)
653d5be to
bd98728
Compare
51f09a5 to
51b484b
Compare
51b484b to
bf2280a
Compare
bd98728 to
cd1b515
Compare
cd1b515 to
169207e
Compare
bf2280a to
0fad7e6
Compare
Load full or changed FSDP parameter groups from the trainer CPU transport buffers directly into generator-local GPU storage. Reuse the existing FSDP materialization and requantization path while retaining cpu_prefetch staging and full synchronization. Test Plan: .venv/bin/python -m pytest tests/rl/unit_tests/cpu/test_model_state_dict_transport.py tests/rl/unit_tests/cpu/test_generator_model.py -q -o addopts= --tb=short git diff --check Authored with assistance from an AI coding assistant. fs-branch: direct-gpu-weight-sync/1
Why
ModelStateDictTransportpreviously required a full generator CPU staging copy. This adds direct trainer-CPU to generator-GPU loading, including quantized models and delta synchronization.What changed
Dynamically register GPU memory for RDMA then read into it instead of the state dict staged on the CPU.
No new configuration options. Existing options now compose as follows:
For GPU delta loading, changed keys determine which FSDP groups changed. Only those complete groups are transferred and requantized.
The existing CPU paths and full synchronization remain unchanged.
Testing
pytest tests/rl/unit_tests/cpu/test_model_state_dict_transport.py \ tests/rl/unit_tests/cpu/test_generator_model.pyQwen3.5 27B (53.8 GB bf16) on MAST, 2 GB300 hosts (4 NICs each), DAPO-Math recipe: trainer FSDP 2 x TP 2 on one host, 4 TP 1 vLLM generators on the other (each pulls the full model), 6 steps of 4 prompts x 16 samples, NIXL 1.5.0 (bundled UCX 1.23.0), expandable segments on. main is
main(e95a8c4) with its default transport (NIXL, full sync,cpu_prefetch); the other two columns run this PR's code with full sync and differ only ingenerator.model_state_dict_load_mode. Pull times are for the slowest generator.cpu_prefetchgpu_fetchTrainer staging, same runs (trainer rank 0).
cpu_prefetchgpu_fetchforward_backwardincl. overlapped staging (steps 2-6)Memory, same runs (max over processes and steps).
cpu_prefetchgpu_fetchgpu_fetchdrops the generator's 50.10 GiB pinned prefetch buffer (generator RSS 81 -> 6.5 GiB) but the pull is ~2.4x slower: the whole 53.8 GB read happens inside the load, one FSDP group at a time (~65 groups), registering and unregistering each group's GPU memory with NIXL on every load.Stack (top to bottom):