Repository navigation
[rl] Stage trainer weight casts in pinned CPU memory - #5107
Conversation
<!-- forkstack:stack:start --> --- Stack (top to bottom): - #5107 [rl] Stage trainer weight casts in pinned CPU memory - -> #5103 [rl] Bind prefetch staging buffers to local NUMA node --- <!-- forkstack:stack:end --> ## Summary Pinned CPU prefetch buffers were allocated without NUMA affinity. UCX could therefore use NICs across both NUMA domains, adding cross-socket traffic and increasing GET latency. A server can contain multiple CPU/memory regions called NUMA nodes. Accessing memory attached to the local NUMA node is faster than reaching memory attached to another node through the CPU interconnect. ``` NUMA node 0 NUMA node 1 CPU cores CPU cores Memory Memory GPUs 0–1 GPUs 2–3 NIC ports A/B NIC ports C/D └────── CPU interconnect ──────┘ ``` ### Before ``` GPU rank on NUMA 0 │ pinned CPU buffers not NUMA-bound │ UCX ┌───┴───────────────┐ ▼ ▼ ibp0p0 / ibp0p1 ibp2p0 / ibp2p1 local cross-NUMA ``` This change binds each generator rank to its GPU-local NUMA node before allocating its pinned staging state dict. ### After ``` GPU rank on NUMA 0 │ bind to NUMA 0 │ pinned CPU buffers │ UCX │ ibp0p0 / ibp0p1 local ports only ``` UCX validation showed every rank using only its local two-port pair. On Qwen-27B, mean steady-state GET improved from 2.77s to 2.68s, while worst GET improved from 3.89s to 2.87s. Co-authored-by: Tushar Jain <[email protected]>
f2ddf78 to
dc4a247
Compare
dc4a247 to
50aa507
Compare
50aa507 to
7485eef
Compare
7485eef to
3b6b854
Compare
6ad33d4 to
d9d1e7b
Compare
d9d1e7b to
ce1c01d
Compare
|
addressed all |
|
@claude Please explain to me
|
|
Claude finished @tianyu-l's task in 2m 9s —— View job How the weight staging stays in sync, and why it uses its own stream
1. What keeps staging and the optimizer step in orderThere are two hazards. The PR handles each one differently. (a) Staging must read the weights after optimizer step N has finished writing them. This is GPU-side ordering, done with
(b) Optimizer step N+1 must not overwrite the weights while the copies for N are still reading them. This is host-side ordering, done by awaiting a task. There's no cross-stream GPU wait for this direction. The host enforces it:
So by the time the optim N+1 kernels are even queued, the copies for N are done on the GPU and TorchStore has finished reading the pinned buffer. The same chain covers reusing the pinned buffer itself: staging N+1 only starts after push N has returned. The cost of using host sync for (b) is that the optimizer step can stall on the push. That stall is what One more condition: fwd/bwd N+1 runs during staging N, so this is only safe if fwd/bwd doesn't change anything in 2. Do we need a separate stream? Why not a
|
| What it does | DCP | This PR | |
|---|---|---|---|
| Separate stream | Lets the GPU run the D2H copies alongside fwd/bwd. Copies on the compute stream would queue behind fwd/bwd N+1. | Yes. As I understand it, DefaultStager with use_async_staging + use_non_blocking_copy creates its own CUDA staging stream. I couldn't open the installed torch source in this run to confirm. |
_staging_stream |
| Completion handle | Tells the host the copy is done. | concurrent.futures.Future from a 1-worker thread pool that synchronizes the staging stream |
The push asyncio.Task (awaited by wait_prev_push) plus the event poll inside it |
So yes, we need a separate stream if we want the overlap; DCP needs one for the same reason. The Future part already has an equivalent here: WeightSyncManager._trainer_push_task is our version of staging_future, and wait_prev_push() is our version of maybe_wait_for_staging(). Wrapping the copy in ThreadPoolExecutor.submit + asyncio.wrap_future would work, but it only moves the wait onto a worker thread (cudaEventSynchronize spin-waits there, as discussed earlier) and adds a second async mechanism on top of the asyncio one the actor already uses.
The real difference from DCP is where staging starts, not Future vs. stream. DCP's stager.stage() is called synchronously on the trainer thread inside save_checkpoint(), right after the optimizer step. The copies are queued at a point where "current stream state" already means "weights are final". That's why DCP doesn't need a separate mark step. We could do the same:
# optimizer_step
grad_norm = engine.optim_step()
self._staging_complete = self._enqueue_staging() # wait_stream + copies + event.record, no await
# push_model_state_dict
await self._wait_staging(self._staging_complete) # poll the event
await ts.put_state_dict(self._staging_state_dict, ...)This puts the wait_stream right next to the copies, removes _mark_weights_ready_for_staging and the init-time call, and makes the ordering obvious when reading optimizer_step. The costs:
optimizer_steppays the CPU time to queue one copy per state-dict entry.- Staging becomes tied to
optimizer_step, so a step that isn't followed by a push (e.g. the last step) would stage for nothing unless it's skipped.
I'd lean toward this version because it reads more clearly, but the current code is correct as written.
Note: forward_backward_steps runs engine.forward_backward synchronously inside the coroutine, so the actor's event loop is blocked for the whole fwd/bwd. During that time the GPU copies still run, but the 1 ms poll and any host-side work in ts.put_state_dict only get a turn when the loop is free. This doesn't affect correctness. It does mean how much of put_state_dict overlaps depends on whether TorchStore/NIXL does its transfer off the event loop. That fits with the Qwen-27B result in the PR description being NIXL-specific.
tianyu-l
left a comment
There was a problem hiding this comment.
Great work! which I spent time to appreciate, lol
Please address final comments
- to make trainer and generator API more symmetric
- to document more
| @@ -323,39 +350,78 @@ async def optimizer_step(self, *, last_step: bool = False) -> OptimizerStepOutpu | |||
|
|
|||
| @sl.log_trace_span("push_model_state_dict") | |||
| async def push_model_state_dict(self) -> None: | |||
There was a problem hiding this comment.
compared with what claude suggested
# optimizer_step
grad_norm = engine.optim_step()
self._staging_complete = self._enqueue_staging() # wait_stream + copies + event.record, no await
# push_model_state_dict
await self._wait_staging(self._staging_complete) # poll the event
await ts.put_state_dict(self._staging_state_dict, ...)
I actually like current approach better because
- it's more symmetric to generator router's
_pull_model_state_dicthttps://github.com/pytorch/torchtitan/blob/main/torchtitan/rl/distributed/routing/inter_generator.py#L220 - the future new API replacement from torchstore might be more local? which I know was one of your consideration
There was a problem hiding this comment.
Right, it seems that would put staging code outside of push_model_state_dict, which is the place where we want to call torchstore and hopefully we replace all this inside torchstore.
I don't think we'd expose 2 API's from torchstore to call in 2 different places - which would mean keeping this extra staging around that we want to get rid of anyway.
Also I guess if we do that then we're not really following the "push" contract which could be a surface that introduces errors later.
ce1c01d to
13cedb2
Compare
13cedb2 to
064c86d
Compare
064c86d to
932e411
Compare
fs-branch: tushar00jain/3
932e411 to
1b1421d
Compare
## Motivation Initialize CPU-offloaded EMA copies directly in their final pinned host storage. `offload_to_cpu=True` currently constructs every parameter and selected-buffer shadow on the accelerator first, then converts the complete set to pinned CPU tensors. Multiple EMA decays amplify this initialization peak. For `K` configured EMA copies and `B` bytes of tracked local parameters and buffers, the current path retains `K*B` bytes of accelerator shadows before offloading starts. The final EMA storage belongs on the CPU under the existing configuration. A model that fits with CPU-offloaded EMA can exhaust accelerator memory during EMA construction. This follows the multi-copy interface added in #5074 and the direct pinned-storage approach used by #5107. ## Changes - Pass the existing offload choice into the private `_EMAParamOptimizer` constructor for both parameters and selected buffers. - Detach each source and use the existing `get_local_tensor` helper for its local shard. Allocate a separate pinned CPU tensor for every EMA key and copy directly into it. - Keep the non-offloaded `detach().clone()` path unchanged. - Remove the post-construction migration loop and its unused helper. Preserve the offload stream, event, scratch-pool, update, save, and load behavior. Update the two existing GPU-test docstrings that referenced the removed helper. The copy uses the default blocking behavior, so each host shadow is readable when construction returns. Every EMA key retains independent storage; changing a live weight or another EMA copy leaves that shadow unchanged. Checkpoint keys, configured decays, half-life schedules, tracked-buffer selection, and dtypes keep their existing owners. ## Resource model For dense local tensors, direct allocation removes the accumulated `K*B` accelerator clones. It also removes the pageable-CPU-to-pinned-CPU copy at initialization. Final pinned storage remains `K*B`, and initialization copies the source once per EMA key. No new configuration, dispatch threshold, or dependency is introduced. Non-dense cross-device copies may use per-tensor contiguous staging inside PyTorch. The claim is removal of the accumulated EMA clones; the platform's copy temporaries retain their own layout-dependent cost. The update pipeline and checkpoint materialization keep their existing memory and transfer behavior. ## Validation ### current revision merged main `65aaaa960698ab5d6e98c874177b41b9c30e9c58` at `92e824be6b71360e62759ae479cccb24b56588db`. restored the dtensor pin-memory note and shortened the checkpoint docstring. the ema execution code is unchanged from `6c3ab4f7`; the two test docstring edits now follow main's directory layout. on python 3.12.14 and pytorch 2.14.1 cpu, the existing ema and reshard suites passed all 44 tests and 44 subtests. changed-file formatting, syntax, license, docstring and spelling checks passed. pyrefly 0.45.1 reported zero errors in the changed production file. upstream [gpu ci](https://github.com/pytorch/torchtitan/actions/runs/38204459291) ran this head with pytorch `2.16.0.dev20261011+cu132`. all 13 ema gpu cases passed. the full single-gpu group returned 181 passed, 46 skipped and 44 deselected. the multi-gpu group returned 34 passed, 11 skipped, 225 deselected and 1 xfailed. upstream lint also passed, including pyrefly and the link checker. [integration tests](https://github.com/pytorch/torchtitan/actions/runs/38214567999) are still running. ```bash python -m pytest tests/unit_tests/cpu/components/optim/test_ema.py tests/unit_tests/cpu/components/optim/test_ema_resharding.py -q python -m pytest tests/unit_tests/gpu/components/optim/test_ema.py --collect-only -q ``` ### historical h100 comparison Compared main `432b95dcf55b3840d7f63ca24a0c585701e70c36` with `6c3ab4f7965733e312456e578843f6a37baf42ee` on H100 80 GB HBM3, using Torch `2.16.0.dev20261010+cu132`, Triton `3.9.0+gitfc8d31a5`, Python 3.12 and driver 580.95.05. Both checkouts use the full project dependency manifest in the same offline environment; `pip check` and actual model imports pass. ### Initialization memory and time Four fresh processes run in main/candidate/candidate/main order. Each process performs the same ten cases in the same order after an 8 MiB warmup. Each case times one complete `EMA.Config.build()` plus CUDA completion; live parameter/buffer creation and output verification are outside timing. Allocator caches can carry across cases. The table reports the arithmetic mean of the two process observations per arm. Both observations agree on every memory peak. B is the logical size of tracked local tensors; K is the number of EMA copies. Extra peak is `max_memory_allocated - memory_allocated_before_build`, with the peak reset after the live tensors exist. Final pinned storage is identical between arms at K×B. | B (MiB) | K | Layout | Main extra GPU peak (MiB) | Candidate extra GPU peak (MiB) | Main build (ms) | Candidate build (ms) | Time change | |---:|---:|---|---:|---:|---:|---:|---:| | 64 | 1 | contiguous | 64 | 0 | 50.595 | 34.172 | -32.46% | | 64 | 3 | contiguous | 192 | 0 | 137.377 | 80.124 | -41.68% | | 256 | 1 | contiguous | 256 | 0 | 200.951 | 127.384 | -36.61% | | 256 | 3 | contiguous | 768 | 0 | 502.480 | 260.863 | -48.08% | | 64 | 3 | transpose | 192 | 0 | 75.224 | 28.840 | -61.66% | | 64 | 3 | holed | 192 | 8 | 92.804 | 39.584 | -57.35% | The holed input has 128 MiB of underlying live storage for 64 MiB of logical data. Its absolute GPU peak falls from 320 to 136 MiB; the remaining 8 MiB is a per-tensor copy temporary. For contiguous B256/K3, absolute peak falls from 1,024 to 256 MiB and final pinned storage remains 768 MiB. The two process build times are 520.445/484.515 ms on main and 258.904/262.822 ms in the candidate. A separate fresh-process capacity scenario imposes a 2 GiB PyTorch allocator budget with 1 GiB of live tracked tensors and K=3. Main reaches OOM during EMA construction, after the complete source exists. The candidate completes with a 1 GiB GPU allocated peak and 3 GiB of independent pinned shadows. That budget excludes CUDA context and external allocations. <details> <summary>GPU-resident controls with offload_to_cpu=False</summary> The clone path and measured memory peaks retain their existing behavior. The small control below records a 0.110 ms increase; construction speedups apply to CPU offload. | B (MiB) | K | Extra GPU peak in both arms (MiB) | Main build (ms) | Candidate build (ms) | Time change | |---:|---:|---:|---:|---:|---:| | 64 | 1 | 64 | 0.885 | 0.995 | +12.42% | | 64 | 3 | 192 | 1.889 | 1.934 | +2.35% | | 256 | 1 | 256 | 1.244 | 1.226 | -1.47% | | 256 | 3 | 768 | 2.919 | 2.960 | +1.41% | </details> ### Values, ownership and training - Each arm passes 22 platform-allocation cases and 41 EMA lifecycle cases. The matrix covers CPU/CUDA sources, FP32/BF16/FP64/complex64, contiguous/transposed/holed/empty/scalar layouts, frozen parameters, selected buffers and multiple EMA keys. Checks cover complete initial values, independent pinned storage, live-input mutation, three CUDA-source updates, save/load, empty-state reseeding and one-rank FSDP2 with plain buffers. CPU-source cases cover construction. - Four fresh processes run ten actual debug-Llama training steps each in ABBA order, with `seed=42`, deterministic algorithms enabled and TF32 disabled. The six-layer, dim-256, vocab-2048 model has 6,163,712 parameters and uses the real `Optim.step` path, fused AdamW, clipping, LR scheduling, two fixed decays, one half-life EMA and a tracked buffer. - The three subsequent runs compare every step's complete model tensors, gradients, optimizer state, scheduler state, EMA state, loss and gradient norm against the first main run. All comparisons are bitwise equal. Each process checkpoints model/optimizer/scheduler/EMA after step 5, restores into fresh objects, and compares steps 6–10 against uninterrupted execution. The returned final snapshots also compare byte-for-byte: 316 tensors and 43,146,055 elements, all finite. ### Distributed contract Both arms pass nine scenarios on each of two H100 ranks using native NCCL: - Two named CUDA meshes, each with a DTensor parameter and a plain tracked buffer. Three EMA keys preserve initial values, independent pinned storage and local-shard metadata across three updates checked against separate pointwise CUDA `lerp` calculations. Placements cover uneven and even `Shard(0)`, an empty local shard, `Replicate`, and transposed `Shard(1)`. - Actual FSDP2 parameter sharding with uneven and empty local shards at construction. - A source tensor on one device with the caller's current device set to the other. Construction preserves the caller's device; this scenario covers initialization. - Balanced FSDP2 DCP save, zeroed-shadow load and one subsequent update, with exact values and pinned-storage identity preserved. Uneven checkpoint export and changes in world size retain their existing implementation and are outside this distributed scenario. ### Existing regression coverage and static checks Both arms pass the existing CPU EMA and reshard suites, 44 tests each, and the existing native GPU EMA suite, 13 tests each with no skips: ```bash python -m pytest tests/unit_tests/cpu/test_ema.py tests/unit_tests/cpu/test_ema_resharding.py -q python -m pytest tests/unit_tests/gpu/test_ema.py -q ``` Formatting, flake8, AST, license, docstring and spelling checks pass for both changed files, along with `git diff --check`. Full-tree pre-commit retains main's existing F401 at `torchtitan/experiments/graph_trainer/tests/test_graph_pp_passes.py:84`. A separate Linux pyrefly run reports the same six optional-model `transformers` import errors on both arms and zero EMA-file diagnostics. The link checker has no installed binary in the local hook environment. The measurements cover EMA construction and the exercised training/checkpoint contracts. GH200 NVLink-C2C performance and full multi-node training throughput remain unmeasured. Signed-off-by: ZenAlexa <[email protected]>
Stack (top to bottom):
Summary
The RL trainer previously cast model parameters to the generator dtype on GPU before TorchStore copied them to CPU. This temporarily materialized another model-sized GPU state dict.
This change allocates a persistent pinned CPU mirror of the complete model state dict, that
Before each transfer, we copy the complete snapshot into staging before passing it to TorchStore.
This removes the temporary GPU cast copy and gives TorchStore a stable CPU snapshot rather than live trainer tensors.
The change also overlaps both the following transfers with fwd/bwd
Test plan
Validated on Qwen-27B that both staging and transfer to torchstore using NIXL overlaps with training.