Skip to content

[rl] Pin the generator's prefetch buffers for quantized Dist-MoE parameters - #6129

Closed
wolfcomos wants to merge 1 commit into
pytorch:mainfrom
wolfcomos:rl-pinned-prefetch-buffers
Closed

wolfcomos wants to merge 1 commit into
pytorch:mainfrom
wolfcomos:rl-pinned-prefetch-buffers

Conversation

@wolfcomos

Copy link
Copy Markdown
Contributor

Summary (human-written)

Why

With model_state_dict_load_mode="cpu_prefetch", the generator prefetches weights into CPU buffers that ModelStateDictLoader allocates with torch's private _create_cpu_state_dict(pin_memory=True). That helper returns zeros_like(obj, device="cpu") for any local tensor whose data_ptr() is 0, and these zeros are not pinned.

Every quantized Dist-MoE parameter (MXFP8, ...) reports data_ptr() == 0, because its sharded local tensor is the _ShardedFSDPTensor wrapper subclass. So each load copies those expert weights to the GPU from pageable memory. With hot swap, in-flight requests stall for the whole load.

Example.

w = experts.w13.weight            # DTensor over a _ShardedFSDPTensor shard
w._local_tensor.data_ptr()        # 0
buf = _create_cpu_state_dict({"w": w}, pin_memory=True)["w"]
buf._local_tensor.is_pinned()     # False -> pageable H2D on every load

Measured on an earlier base, Qwen3-30B-A3B DAPO recipe, per generator rank:

  • 96 expert buffers (14.5 GB) are unpinned. This was counted with an out-of-tree NVFP4 expert format; MXFP8 experts have the same parameters.
  • load_model_state_dict takes 0.54 s with BF16 experts and 2.1 s with MXFP8 experts.
  • The expert host-to-device copy runs at ~8.5 GB/s, vs ~51 GB/s from pinned memory.

What changed

  • ModelStateDictLoader allocates its prefetch buffers with a new _pinned_cpu_buffers. Each buffer is a plain pinned CPU tensor with its entry's shape and dtype; a DTensor entry keeps its spec over that local tensor.
  • This removes the private torch.distributed._state_dict_utils import. It also removes the obj.to("cpu") copy that helper made of every shard at startup; prefetches overwrite the buffers anyway.
  • test_generator_dist_moe_mxfp8.py: the FULL-graph MXFP8 test now also asserts that every prefetch buffer is pinned. On main this fails for the expert weights.
  • test_generator_model.py: the CPU test monkeypatches _pinned_cpu_buffers in place of _create_cpu_state_dict (mechanical).

Alternatives considered

  • Fix _create_cpu_state_dict in torch: it treats data_ptr() == 0 like an empty tensor. That is worth fixing, but torchtitan would still need this change until its nightly picks up the fix. The torch helper also copies every shard to CPU at startup, which buffers don't need.
  • Re-pin after _create_cpu_state_dict: keeps relying on a private helper whose output is wrong for these tensors.

Numerics

  • Not a computation change: every prefetch overwrites every buffer before a load reads it, and the same bytes reach the GPU.
  • Check pending on this branch's base: MXFP8 recipe, seed 1000, 50 steps. It will compare the trainer/generator logprob_diff and reward against main.

Performance

Earlier measurement (an equivalent fix on an earlier base, NVFP4 W4A16 experts; steps 2-10 have matched lengths):

  • load_model_state_dict: 2.13 s → 0.44 s (BF16 experts: 0.33 s).
  • Expert fetch: 1.65-2.0 s → 0.30-0.32 s.
  • Steps 2-10: 21.8 → 21.0 s/step, equal to BF16 experts.

On this branch's base (pending): MXFP8 recipe, seed 1000, main vs this PR: the load_model_state_dict span and steps 2-10 s/step.

Testing

  • pytest tests/rl/unit_tests/cpu/test_generator_model.py: 9 passed on main and on this branch.
  • torchrun --nproc-per-node=1 -m pytest tests/rl/unit_tests/gpu/test_generator_dist_moe_mxfp8.py on one B200 (as integration_test_rl_b200.yaml runs it): pending. It is expected to fail on main with only the new assertion added, and to pass on this branch.
  • pre-commit run on the changed files: all hooks pass except pyrefly, which needs a local PyTorch build here.

🤖 Generated with Claude Code

…meters

torch's _create_cpu_state_dict(pin_memory=True) returns unpinned zeros for a
local tensor whose data_ptr() is 0, which every _ShardedFSDPTensor (the
sharded wrapper subclass of a quantized Dist-MoE parameter) reports. Every
cpu_prefetch load then copies those experts to the GPU from pageable memory,
while a hot-swap load stalls in-flight requests. Allocate the buffers
directly instead: a plain pinned CPU tensor per entry, and for a DTensor the
same spec over it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@pytorch-bot

pytorch-bot Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 16, 2026
@wolfcomos
wolfcomos marked this pull request as ready for review November 16, 2026 21:55
@pytorch-bot pytorch-bot Bot added ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests labels Nov 16, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 16, 2026 21:55
@tianyu-l
tianyu-l requested a review from d4l3k November 17, 2026 02:37
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 38s —— View job


Approve -- please fill in the human-written summary and post the pending B200 test and MXFP8 perf results before merging. Full review: #6129 (review)

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- please address the items below before merging. The fix is small and at the right layer: torchtitan now allocates its own pinned buffers instead of calling a private torch helper that returns pageable memory for wrapper-subclass shards. A maintainer still needs to review, since this touches torchtitan/rl/generator/.

What this PR does. With cpu_prefetch, ModelStateDictLoader used to build its host buffers with _create_cpu_state_dict(pin_memory=True). For a local tensor whose data_ptr() is 0, that helper returns unpinned zeros_like. Every _ShardedFSDPTensor shard has data_ptr() == 0, since it comes from _make_wrapper_subclass and has no storage. The new _pinned_cpu_buffers creates a plain pinned torch.empty with each entry's shape and dtype. For a DTensor entry it wraps that buffer in the same _spec.

Example.

experts.w13.weight -> DTensor(local=_ShardedFSDPTensor(_tensor=bf16 shard))
before: buffer._local_tensor = zeros_like(...) on CPU, is_pinned() == False
        -> every load does a pageable H2D copy of every expert weight (~8.5 GB/s)
after:  buffer._local_tensor = torch.empty(shape, dtype, pin_memory=True)
        -> pinned H2D (~51 GB/s per the description)

The wrapper copies the inner tensor's size, stride and dtype (_FSDPTensorBase.__new__, torchtitan/quantization/_fsdp_tensor.py:247), so shape and dtype match what the trainer sends. Leaving the buffers uninitialized also matches the old behavior: upstream used torch.empty for the local tensors too, and only the discarded obj.to("cpu") copy goes away.

Must fix

  1. PR description -- "Summary (human-written)" is empty. The author needs to fill it in.
  2. PR description -- the testing, numerics and performance results on this base are all still "pending", and the only perf numbers come from an earlier base with an out-of-tree NVFP4 format. Please post the B200 result for test_generator_dist_moe_mxfp8.py (it should fail on main with only the new assertion added and pass here). Please also post the MXFP8 load_model_state_dict time and s/step on this base, main vs this PR, so the claimed gain is measured on the code being merged.
Details
  • Necessity: the problem is real. _ShardedFSDPTensor (torchtitan/quantization/_fsdp_tensor.py:262) is a wrapper subclass, so data_ptr() is 0 and upstream takes its empty-tensor branch. We can't fix this on the torchtitan tensor side. Dropping the private helper beats re-pinning its output.
  • The DTensor(local, spec, requires_grad=False) constructor plus _local_tensor/_spec is private DTensor usage. I don't see a public alternative: DTensor.from_local moves a CPU local tensor to the mesh's device, which would defeat the purpose. Upstream _create_cpu_state_dict builds the DTensor the same way. A one-line comment saying why from_local isn't used would stop someone from "cleaning it up" later.
  • The other consumers keep working with a plain pinned local tensor: _copy_prefetched_model_state_dict (generator.py:540), torchstore get_state_dict, shard_layout, and ModelStateDictTransport (_local(...).view(-1)). They are arguably simpler than with a subclass.
  • 0-dim entries are now pinned too; upstream returned an unpinned scalar, or for a DTensor the original GPU tensor. That is harmless or better.
  • Test value: the new assertion is folded into an existing GPU test and guards a silent perf regression (pageable H2D). That's reasonable. The numel() == 0 exemption covers empty shards from uneven sharding. The CPU test change is mechanical.
  • Numerics: same bytes reach the GPU, and every prefetch overwrites every buffer before a load reads it. Not a computation change.

Not verified: I could not run the B200 test or measure host-to-device bandwidth here. The claim that from_local moves the local tensor to the mesh's device comes from my reading of upstream DTensor; I didn't run it.

@d4l3k d4l3k left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you submit this as an upstream PR to pytorch? This all looks good but we might as well fix this everywhere since it doesn't depend on anything titan specific

@wolfcomos

Copy link
Copy Markdown
Contributor Author

Can you submit this as an upstream PR to pytorch? This all looks good but we might as well fix this everywhere since it doesn't depend on anything titan specific

Thanks for review! Will submit to pytorch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants