Repository navigation
[rl] Use torchmonarch 0.8.0: drop messages to dead actors, remove the RDMA log workaround - #6199
Conversation
Every torchtitan RL Monarch actor now subclasses TitanActor, which absorbs a delivery failure whose destination actor stopped or failed instead of failing the sender. Requires torchmonarch 0.8.0 for the delivery-failure hooks.
…spam torchmonarch 0.8.0 prints "[RdmaXcel] Failed to get current CUDA context." once per process instead of once per RDMA buffer (meta-pytorch/monarch#5064), so the batcher no longer needs a CUDA context (~256 MiB on GPU 0) to silence it.
2933394 to
de1de59
Compare
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class TitanActor(Actor): |
There was a problem hiding this comment.
Having a titan actor in titan codebase sounds not informative about what it actually does. How about
| class TitanActor(Actor): | |
| class Actor(MonarchActor): |
|
@claude review In particular, please explain what it is about "Drop messages an RL actor sends to a dead actor" in layman language. |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The problem is real (RL runs that finish normally exit with code 130 at shutdown), Monarch 0.8.0 now provides the hook to fix it, and the fix is small. A maintainer still needs to review.
"Drop messages an RL actor sends to a dead actor", in plain terms
Think of the actors as coworkers passing notes. If A sends a note to B and B has already left the building, Monarch's mailroom returns the note to A. By default Monarch treats that as A's problem: A is marked failed, and a failed actor fails the job.
That default makes sense when A is waiting for B to answer. It is wrong in the two cases where nobody is waiting:
- A is replying to B. B asked a question, then left. Nobody needs the answer anymore.
- A sends a one-way message. No one expects a response.
In RL this happens at the end of every run:
rollout worker W: calls generator.generate(prompt) and waits
controller: training done -> stops the rollout workers (W exits)
generator G: finishes generating, sends the reply to W
Monarch: W is gone -> reply bounces -> G is marked failed -> job exits 130
Today Rollouter.close avoids this by waiting for in-flight run_group calls before it stops the workers. With this PR, every RL actor inherits a policy: if a note bounces because the recipient stopped or failed, throw it away and write a debug log. Any other kind of bounce (an endpoint that doesn't exist, an expired TTL, a transport error) still fails the sender, as before.
Why dropping the note doesn't cause hangs: if A asked B something and B is dead, A's await still raises SupervisionError, because Monarch's supervision reports the dead callee to the caller. Dropping the bounced note doesn't change that (last row of the PR's table). And if B crashed, its failure still reaches the controller, which owns it.
Must fix
torchtitan/rl/actors/monarch/actor.py:18-- @tianyu-l's naming comment is not addressed yet. I agree with it. Inside torchtitan, "Titan" says nothing about what the class does. Withclass Actor(MonarchActor)(from monarch.actor import Actor as MonarchActor), call sites readfrom torchtitan.rl.actors.monarch.actor import Actor. The class docstring already explains the behavior. Update the README row and the line-13 sentence to match.tests/rl/unit_tests/cpu/test_rdma_microbatch.py:20imports Monarch'sActordirectly, so leave it as is (it doesn't need the hook) or alias it.torchtitan/rl/actors/monarch/actor.py:21-- this overrides a private Monarch hook, but there is no TODO with an upstream link (see the inline comment).
Should consider
torchtitan/rl/rollout/rollouter.py:201-202,213(outside the diff) -- theclosedocstring ("Monarch fails that actor and the finished job exits 130") and the warning ("the job may exit 130") are wrong after this PR. The drain existed only to work around this bug. Either delete it here (net LoC goes down, and it is the point of the change), or keep it and reword both texts as a temporary safeguard with a TODO pointing at the follow-up. As written, the next reader will think the bug still exists.- No test covers the hook. Because it overrides a private name, a Monarch rename would silently bring the shutdown crash back. A cheap CPU test would catch that: run the monarch#5301 repro ("callee replies after the caller's mesh stopped -> callee still alive") in
tests/rl/unit_tests/cpu/, the same waytest_rdma_microbatch.pyalready spawns actors onthis_host(). Only add it if you think the guard is worth the cost.
Details
- Gate: the problem is real on
main(#5507, monarch#5301). The default policy comes from Monarch, and Monarch now exposes it per actor (monarch#5335), so setting the policy in torchtitan's actor base is the right layer. There is no new dependency, only a version bump. Every Monarch actor undertorchtitan/is converted: I greppedtorchtitan/and the only otherActorsubclass is the test helper_TrainerRank. - Commit 2: removing
create_cuda_context_to_silence_monarch_logis a clean deletion. The function has no callers left, and the TODO it carried (monarch#5049) is resolved in 0.8.0. It also removes ~256 MiB of GPU 0 memory from the batcher process whenever RDMA is on. - Scope: both changes need the same version pin, so bundling them in one PR is reasonable.
Not verified: I couldn't import torchmonarch 0.8.0 in this environment, so I didn't check the _handle_invalid_reference / root_delivery_failure() / InvalidReferenceReason API against the installed package.
Followup questions
|
|
Claude finished @tianyu-l's task in 1m 54s —— View job Short answer: the drain on 1. What's wrong with today's drain? Is it about surplus rollouts?Yes. The async loop always keeps up to That works, but:
Note that this PR adds the hook but keeps the drain, so most of the payoff comes when the drain is deleted. 2. Does this hide errors that should fail?Mostly no, and the PR's tests show it. Case by case:
What you do lose:
3. Why doesn't Monarch make this the default?The Monarch maintainers pushed back on that in monarch#5301:
The hook also can't tell a reply from a call or a one-way send, so Monarch couldn't apply a policy per message kind even if it wanted to. They chose an opt-in instead: the hook in #5335, or per endpoint with Details
Not verified: I couldn't import torchmonarch 0.8.0 here. The claim that a call to a dead callee still fails the caller comes from the CPU, single-host repro in monarch#5301, not a multi-host GPU run. |
tianyu-l
left a comment
There was a problem hiding this comment.
sgtm. Please fix the naming, or let me know if you disagree.
…n comments, add a test - Rename TitanActor to Actor (subclassing Monarch's Actor as MonarchActor). - Rollouter.close: the drain no longer guards against the job exiting 130; reword its docstring and warning. Drop the resolved TODO in the Verifiers generation server. - Add a CPU test: a callee on Actor stays alive after replying to a caller whose actor mesh stopped. It fails with Monarch's Actor.
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
this approach, and what you checked yourself. -->
## Agent details
**TLDR:** Trainer microbatches now go over Monarch RDMA by default:
`async_loop.batcher.rdma_min_tensor_bytes` goes from `None` (by value)
to `1024`. On one host, a 1 GiB microbatch takes 0.55 s by RDMA over
ibverbs vs 1.9 s by value, and every read was byte-exact.
`rdma_min_tensor_bytes=None` keeps the by-value message.
**Problem**
1. The RDMA path for trainer microbatches is opt-in: by default each
trainer rank gets its column of the batch inside the `forward_backward`
RPC message.
2. By value, the controller pickles every microbatch, Monarch copies it,
and the rank unpickles it.
3. That grows with the microbatch: 16 MiB takes 21 ms per call by value
vs 8.4 ms by RDMA, and 1 GiB 1.9 s vs 0.55 s (ibverbs, one host).
**Solution**
1. `Batcher.Config.rdma_min_tensor_bytes` defaults to 1024: tensors of
at least 1 KiB stay in the batcher as RDMA buffers; smaller ones (token
counts) stay in the message.
2. If Monarch has no RDMA backend (`monarch.rdma.get_rdma_backend() ==
"none"`), `MonarchActorSystem.spawn_batcher` raises and says to set
`rdma_min_tensor_bytes=None`. Otherwise Monarch uses ibverbs where the
host has it, else TCP (Monarch's TCP fallback is on by default).
3. RDMA with trainer pipeline parallelism still raises. The error now
says to set `rdma_min_tensor_bytes=None`, and the PP=2 `alphabet_sort`
test recipe sets it.
4. Every RL recipe sets `preprocess_microbatch_groups_lazily=True` (they
already turn accelerator graphs off), so each trainer rank reads its
next microbatches while it trains on the current one.
5. `None` sends microbatches by value, as before.
**Results**
Stress, one host (H100 devserver, CPU tensors, Monarch 0.7): the owner
registers a fresh microbatch with random bytes each step, a reader
process reads it, the owner drops the previous one. 5 steps per size,
medians of steps 2-5. Every read was byte-exact. Read = reader side,
fresh destination included. Call = one actor call, RDMA vs the same
microbatch by value:
```text
per microbatch read, ibverbs read, TCP call: ibverbs / TCP / by value
1023 B 0.12 ms 0.19 ms 2.5 / 3.1 / 2.7 ms (below 1 KiB: by value)
1 KiB 7.8 ms 0.5 ms 11 / 2.9 / 3.2 ms
1 MiB 6.4 ms 1.9 ms 12 / 7.8 / 5.5 ms
16 MiB 3.6 ms 15 ms 8.4 / 19 / 21 ms
256 MiB 83 ms 449 ms 0.17 / 0.49 / 0.56 s
1 GiB 334 ms 1.6 s 0.55 / 1.8 / 1.9 s
```
- 4 readers, 256 MiB each, at once: 81 ms over ibverbs (13 GB/s
together), 630 ms over TCP.
- Registering (in the batcher, at pack time) pins memory over ibverbs:
26 ms at 256 MiB, 264 ms at 1 GiB; under 1 ms over TCP.
- Up to 1 MiB, an ibverbs read costs 6-8 ms, a few ms more than by
value.
GPU, Qwen3-0.6B, H100, batch invariant, lockstep, trainer DP 1 + one TP
1 generator (2 GPUs), 4,096-token microbatches, 5 steps:
```text
loss/mean, step 5 bit_wise/logprob_diff/max read_microbatches/max, steps 1-5
None (by value) 0.00061 0 -
1024 (default), ibverbs 0.00061 0 126, 36, 12, 19, 21 ms
1024, TCP 0.00061 0 57, 15, 10, 14, 17 ms
```
- `loss/mean` is bitwise equal across the three runs at all 5 steps.
Step 1 includes RDMA setup.
- TCP = `MONARCH_RDMA_DISABLE_IBVERBS=1
MONARCH_RDMA_ALLOW_TCP_FALLBACK=1`. The `None` run is from an earlier
build of this change; `None` runs none of the changed code.
- Measured on an earlier version of this PR, before main moved the RDMA
code behind the actor system. Not re-run since.
End to end at recipe size: H100, Qwen3-0.6B, batch invariant, lockstep,
10 steps, one TP 1 generator, 4,096-token microbatches (0.16 MB).
Measured on the opt-in version of this path:
```text
forward_backward trainer DP 1 trainer DP 2
by value 1.393 s 0.909 s
RDMA, reads before compute 1.414 s 0.910 s
RDMA, reads overlapped (lazy) 1.399 s 0.932 s
```
- The rows differ by run-to-run noise.
- At 5.2 GB per step (CPU Monarch, one host, TCP, 4 ranks, reads
included): 9.1-11.1 s by value vs 3.3-4.1 s by RDMA.
You may ask:
- **Why not probe ibverbs at startup?** A failed registration leaves
Monarch's RDMA manager dead in its process, so a probe needs a child
process. Like TorchStore, we only check that Monarch has an RDMA
backend.
- **What about a host that lists ibverbs devices it can't use?** It
fails at the first batch: set `rdma_min_tensor_bytes=None`, or
`MONARCH_RDMA_DISABLE_IBVERBS=1` for TCP in every process (weight sync
included). The docstring says so.
- **Why 1 KiB?** Registering a buffer costs far more than sending a few
bytes, and `RDMABuffer` rejects empty tensors.
- **Isn't RDMA slower for small microbatches?** Per call, by a few ms
(stress table, 1 KiB-1 MiB). End to end at recipe size it is within
noise (table above).
NOTE:
- Builds on main's #6199 (torchmonarch 0.8.0, which removed the
CUDA-context workaround).
- The RL GPU CI now takes the RDMA path (ibverbs or TCP, whichever its
containers have).
- A config that passes its own `TrainingConfig` without
`preprocess_microbatch_groups_lazily=True` reads each microbatch before
compute, ~6-8 ms each over ibverbs at small sizes.
- Lazy on vs off at an earlier head of this PR (6aed435), Qwen3-0.6B
alphabet_sort, trainer TP 1 + one TP 1 generator, 4,096-token
microbatches, 8 steps, RDMA over TCP: `forward_backward` median over
steps 3-8 is 1.84 s with lazy and 1.64 s without. Per microbatch it is
353 vs 396 ms. The two runs sampled different rollouts (3-6 microbatches
per step), so these differences are noise. Lazy can only overlap the
RDMA reads and the input preprocessing, which take 30-60 ms per step
here (~2-4% of `forward_backward`). A lockstep, batch-invariant rerun
was not done: another job took the GPUs.
- Not tested on more than one host, on Intel XPU (#5402, GRPO on XPU) or
on PBS clusters (#5403, the PBS launcher). If the first batch fails
there, set `rdma_min_tensor_bytes=None`.
**Test plan**
- `pytest tests/rl/unit_tests/cpu
tests/unit_tests/cpu/components/test_renderer.py
tests/unit_tests/cpu/config` (repo root, Monarch 0.8.0): 965 passed, 7
skipped. With Verifiers 0.4.0 installed: 1049 passed, 1 skipped. Same
counts as main (a7887db). The skips are skipped on main too.
- `test_rdma_microbatch.py`: by value with `None`; 4 rank processes read
their columns byte-exact over real Monarch TCP across 3 released
batches.
- At an earlier head of this PR (6aed435): every zero-argument RL
recipe that builds here (54 of 56; the other 2 need a torchao nightly or
sglang), rebuilt and validated with `__post_init__` as `ConfigLoader`
does: none fails on RDMA, and all end with lazy preprocessing on and
accelerator graphs off.
- `test_batcher_actor.py`: the batcher process on the default config
sends `input` by RDMA and token counts by value.
- In-process batchers in the tests set `rdma_min_tensor_bytes=None`:
only an actor system provides RDMA registration.
- The stress script and GPU runs above (earlier heads of this PR).
Co-authored-by: Felipe Mello <[email protected]>
Summary (human-written)
With monarch's new stable release, 0.8.0, we can do the following 2 things:
The undeliverable message mechanism is a monarch feature, that titanRL does not need. On the contrary, its default behavior is causing headache during titanRL shutdown (see the 1st problem described in this comment), and future fault tolerant work. A recent Monarch feature meta-pytorch/monarch#5335 enabled us to handle it properly.
This was originally added to silence a log spew bug in monarch RDMABuffer. It was fixed in this release and therefore can be removed from TitanRL.
Why
Two changes enabled by torchmonarch 0.8.0, one commit each. Both need the new
torchmonarch>=0.8.0pin.1. Drop messages an RL actor sends to a dead actor
When a message can't be delivered because its destination actor stopped, Monarch fails the sender by default. That is right for a call request, whose caller waits for it, but wrong for a call reply (the caller is the one that left) or a one-way send (nobody waits). In RL, this turns a finished run into a crash: a generator that replies to
generateafter the rollout worker that called it stopped fails, and the job exits 130.Rollouter.closedrains in-flight rollouts before stopping workers to avoid it, and #5507 needed more bookkeeping to keep that safe (see the discussion there and meta-pytorch/monarch#5301).torchmonarch 0.8.0 exposes the failure reason to Python actors (meta-pytorch/monarch#5335), so titan can set the policy itself.
Example (meta-pytorch/monarch#5301's repro, CPU, torchmonarch 0.8.0, one run per case):
Actor(main)TitanActor(this PR)broadcastto a stopped actorcall_oneto a stopped actorSupervisionError, caller failsSupervisionError, caller aliveThe last row is the reason dropping is safe: a call request to a dead actor still fails the caller's future through supervision, so it does not become a hang.
2. Remove the batcher's CUDA context workaround
With the RDMA path on (
Batcher.Config.rdma_min_tensor_bytes), the batcher created a CUDA context on GPU 0 (~256 MiB) only so that Monarch would not print[RdmaXcel] Failed to get current CUDA context.for every registered buffer (meta-pytorch/monarch#5049). meta-pytorch/monarch#5064 prints it once per process, and it is in 0.8.0.N CPU
RDMABuffers created without a CUDA context, in the client and one actor (ibverbs; the TCP fallback gives the same 0.8.0 counts):What changed
torchtitan/rl/actors/monarch/actor.py:TitanActor(Actor)overrides_handle_invalid_reference. It absorbsInvalidReferenceReason.ActorStopped/ActorFailed(debug log) and leaves every other delivery failure (unbound handler, TTL expiry, transport) at Monarch's default. Sync, since Monarch rejects an async hook on actors with sync endpoints (BatcherActor,_RendezvousStoreActor).TrainerActor,GeneratorActor,BatcherActor,InterGeneratorRouterActor,RolloutWorkerActor,_RendezvousStoreActor) subclassTitanActorinstead ofActor; package README updated.rdma_microbatch.py/batcher.py: deletecreate_cuda_context_to_silence_monarch_logand its call..ci/docker/requirements-rl.txt:torchmonarch>=0.8.0.Not covered: messages the controller sends. Its Monarch client is
RootClientActor, created by Monarch, with no public way to override its hooks. The problem above is actor to actor.Alternatives considered
_handle_delivery_failure_event(all kinds): would also swallow unbound handlers and TTL expiry.monarch.actor.unhandled_fault_hook: only covers the controller, andMeshFailurehas no structured reason, so it would need string matching.Testing
RDMABufferlog count, both CPU: tables above.pytest tests/rl/unit_tests/cpu(CPU): 602 passed. 4 failed and 7 errored on missing or mismatched packages in my env (math_verify,attn_gym.mla,torch_checkpointing.CallbackArgs, a proxy 403); the same tests fail the same way on the base commit a2ea19b. After the second commit,test_rdma_microbatch.pyandtest_batcher_actor.pypass (11 tests), with one[RdmaXcel]line per process.Known issues / follow-ups
Rollouter.closedrain stays in this PR; removing it can follow once a real shutdown confirms it is no longer needed.