Skip to content

[rl] Select TorchStore's control plane and run the RL loss guard on its service - #5778

Draft
brandondfeng wants to merge 1 commit into
gh/brandondfeng/1/basefrom
gh/brandondfeng/1/head
Draft

brandondfeng wants to merge 1 commit into
gh/brandondfeng/1/basefrom
gh/brandondfeng/1/head

Conversation

@brandondfeng

@brandondfeng brandondfeng commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary (human-written)

TitanRL's Monarch actor system always calls ts.initialize with the default and never hands ranks an address so a recipe can't pick TorchStore's new coordinator service. I added a control-plane setting ("monarch" or "service") to the actor system's config because the actor system runs the setup, and whatever ts.initialize returns now goes to every trainer and generator client. A new CI job reruns the RL loss guard on a service twin of its recipe against the existing golden so any difference in the synced weights shows up as a loss mismatch, and the controller's close now always stops the meshes and the service even after a failure or a cancellation unless one of those stops hangs. I ran the RL CPU suite on torch 2.15 and 2.16 and without torchmonarch, and the loss guard on an A100 matched the golden on all 10 steps on both control planes.

Context

Solution

  • MonarchActorSystem.Config gains torchstore_control_plane ("monarch" by default, or "service"), and what ts.initialize returns reaches every trainer and generator client. The trainer's and generator's initialize_torchstore_client takes a required keyword-only address, None on Monarch's control plane
  • The controller's close now calls the actor system's stop from a finally, then closes the metric backends. stop shuts the service down even after a failed client setup or a cancel in a mesh stop
  • Service twins of two CI recipes change only the control plane. A new 8-GPU RL job reruns the guard on its twin against the existing golden, then runs the other twin as a new rl_service suite
  • The RL README shows how to select "service" and warns that the coordinator service and the volume servers unpickle each request that passes a JSON hello. So "service" belongs on a trusted network

Test Plan

  • RL CPU unit suite: 537 passed vs 489 at the parent on torch 2.16 dev, 535 vs 487 on 2.15 dev, and 411 vs 407 without torchmonarch, where the parent's 30 failures stay
  • On 8 x A100 both loss guards match an A100 golden on all 10 steps. They ran on an earlier TorchTitan main before this commit's latest fixes, none of which changes a run that ends normally
  • The service guard logs service selection lines and coordinator connects but no Monarch line. The default guard logs Monarch selection lines and no service line
  • Not checked: whether another host or job can reach the new job's coordinator service and trainer ranks' volume servers, which listen without authentication, or its container can request id-token: write. Both depend on the runners' setup
  • TorchTitan's RL CI installs TorchStore main, where 24 of the 50 new cases fail: 22 reject control_plane or address and 2 need ts.ControlPlane. The RL CPU job stays red until TorchStore's control-plane selection lands
# $PINS holds main's pinned packages and an alias that lets torch's SDPBackend pickle, and $TORCHSTORE is a local TorchStore build with only the control-plane selection for the unit runs and with the coordinator service and the in-process volume servers for the guards
# RL CPU unit suite with GPUs hidden, at the parent and at this commit, in each env
CUDA_VISIBLE_DEVICES= PYTHONPATH=$PINS:$PWD:$TORCHSTORE python -m pytest tests/rl/unit_tests/cpu --strict-markers -q -p no:cacheprovider -rfEs --continue-on-collection-errors
# The new job's script passes shellcheck
python -c "import yaml; print(yaml.safe_load(open('.github/workflows/integration_test_8gpu_rl.yaml'))['jobs']['build-test-service']['with']['script'])" > service_job.sh && shellcheck -s bash service_job.sh
# RL loss guard on 8 x A100 with this change on an earlier TorchTitan main, against an A100 golden exported from TorchTitan main before the control-plane selection: the service variant, then the default
PYTHONPATH=$PINS:$PWD:$TORCHSTORE python scripts/rl/loss_compare.py --hf-assets-path "$MODEL_PATH" --dump-folder rl_loss_guard_service --module torchtitan_recipes.tests.rl.alphabet_sort --config rl_grpo_qwen3_0_6b_varlen_batch_invariant_service --import-result "$GOLDEN" --assert-equal
PYTHONPATH=$PINS:$PWD:$TORCHSTORE python scripts/rl/loss_compare.py --hf-assets-path "$MODEL_PATH" --dump-folder rl_loss_guard --import-result "$GOLDEN" --assert-equal
# Lint, with pyrefly 0.45.1 on PATH
PYTHONPATH=$PINS SKIP=lychee-link-checker pre-commit run --from-ref HEAD~1 --to-ref HEAD

BC-breaking: yes, even the default Monarch path needs a TorchStore with the control-plane selection, initialize_torchstore_client takes a required keyword-only address, ActorSystem.stop also stops a rollout worker pool and lets the other processes stop after a first cancel but ends the stops at a second and shuts the service down either way, ActorSystem.stop_rollout_workers forgets its pool before it awaits the pool's stop, and even after a cancel Controller.close finishes that stop before the metric backends close

[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 3, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 3, 2026
brandondfeng added a commit that referenced this pull request Nov 3, 2026
…ts service

## Summary (human-written)
TitanRL's Monarch actor system always calls `ts.initialize` with the default and never hands ranks an address so a recipe can't pick TorchStore's new coordinator service. I added a control-plane setting ("monarch" or "service") to the actor system's config because the actor system runs the setup, and whatever `ts.initialize` returns now goes to every trainer and generator client. A new CI job reruns the RL loss guard on a service twin of its recipe against the existing golden so any difference in the synced weights shows up as a loss mismatch, and the controller's close now always stops the meshes and the service even after a failure or a cancellation unless one of those stops hangs. I ran the RL CPU suite on torch 2.15 and 2.16 and without torchmonarch, and the loss guard on an A100 matched the golden on all 10 steps on both control planes.

## Context
- TorchStore's control-plane selection (meta-pytorch/torchstore#253 to meta-pytorch/torchstore#265, meta-pytorch/torchstore#277, and meta-pytorch/torchstore#281) adds `control_plane=` to `ts.initialize` and `address=` to `ts.client`. TorchStore's coordinator service (meta-pytorch/torchstore#282 to meta-pytorch/torchstore#289) adds a "service" control plane whose address `ts.initialize` returns
- The Monarch actor system calls `ts.initialize` without a control plane and sets up every trainer and generator client with no address. So a recipe cannot pick the coordinator service
- CI runs the RL loss guard, which asserts bitwise-equal losses against a committed golden, only on TorchStore's default Monarch control plane. A difference in the weights that "service" syncs would go unnoticed
- CI installs TorchStore main, so this lands only once it has the control-plane selection, the coordinator service, and TorchStore's in-process volume servers. It must be reverted first if any of them is

## Solution
- `MonarchActorSystem.Config` gains `torchstore_control_plane` ("monarch" by default, or "service"), and what `ts.initialize` returns reaches every trainer and generator client. The trainer's and generator's `initialize_torchstore_client` takes a required keyword-only `address`, None on Monarch's control plane
- The controller's close now calls the actor system's `stop` from a `finally`, then closes the metric backends. `stop` shuts the service down even after a failed client setup or a cancel in a mesh stop
- Service twins of two CI recipes change only the control plane. A new 8-GPU RL job reruns the guard on its twin against the existing golden, then runs the other twin as a new `rl_service` suite
- The RL README shows how to select "service" and warns that the coordinator service and the volume servers unpickle each request that passes a JSON hello. So "service" belongs on a trusted network

## Test Plan
- RL CPU unit suite: 537 passed vs 489 at the parent on torch 2.16 dev, 535 vs 487 on 2.15 dev, and 411 vs 407 without `torchmonarch`, where the parent's 30 failures stay
- On 8 x A100 both loss guards match an A100 golden on all 10 steps. They ran on an earlier TorchTitan main before this commit's latest fixes, none of which changes a run that ends normally
- The service guard logs service selection lines and coordinator connects but no Monarch line. The default guard logs Monarch selection lines and no service line
- Not checked: whether another host or job can reach the new job's coordinator service and trainer ranks' volume servers, which listen without authentication, or its container can request `id-token: write`. Both depend on the runners' setup
- TorchTitan's RL CI installs TorchStore main, where 24 of the 50 new cases fail: 22 reject `control_plane` or `address` and 2 need `ts.ControlPlane`. The RL CPU job stays red until TorchStore's control-plane selection lands
```bash
# $PINS holds main's pinned packages and an alias that lets torch's SDPBackend pickle, and $TORCHSTORE is a local TorchStore build with only the control-plane selection for the unit runs and with the coordinator service and the in-process volume servers for the guards
# RL CPU unit suite with GPUs hidden, at the parent and at this commit, in each env
CUDA_VISIBLE_DEVICES= PYTHONPATH=$PINS:$PWD:$TORCHSTORE python -m pytest tests/rl/unit_tests/cpu --strict-markers -q -p no:cacheprovider -rfEs --continue-on-collection-errors
# The new job's script passes shellcheck
python -c "import yaml; print(yaml.safe_load(open('.github/workflows/integration_test_8gpu_rl.yaml'))['jobs']['build-test-service']['with']['script'])" > service_job.sh && shellcheck -s bash service_job.sh
# RL loss guard on 8 x A100 with this change on an earlier TorchTitan main, against an A100 golden exported from TorchTitan main before the control-plane selection: the service variant, then the default
PYTHONPATH=$PINS:$PWD:$TORCHSTORE python scripts/rl/loss_compare.py --hf-assets-path "$MODEL_PATH" --dump-folder rl_loss_guard_service --module torchtitan_recipes.tests.rl.alphabet_sort --config rl_grpo_qwen3_0_6b_varlen_batch_invariant_service --import-result "$GOLDEN" --assert-equal
PYTHONPATH=$PINS:$PWD:$TORCHSTORE python scripts/rl/loss_compare.py --hf-assets-path "$MODEL_PATH" --dump-folder rl_loss_guard --import-result "$GOLDEN" --assert-equal
# Lint, with pyrefly 0.45.1 on PATH
PYTHONPATH=$PINS SKIP=lychee-link-checker pre-commit run --from-ref HEAD~1 --to-ref HEAD
```

BC-breaking: yes, even the default Monarch path needs a TorchStore with the control-plane selection, `initialize_torchstore_client` takes a required keyword-only `address`, `ActorSystem.stop` also stops a rollout worker pool and lets the other processes stop after a first cancel but ends the stops at a second and shuts the service down either way, `ActorSystem.stop_rollout_workers` forgets its pool before it awaits the pool's stop, and even after a cancel `Controller.close` finishes that stop before the metric backends close
ghstack-source-id: fa26ad3
Pull-Request: #5778
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).

This branch has not been deployed

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

Labels

ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant