Repository navigation
[rl] Graceful shutdown GRPO - #3238
Conversation
ef30d76 to
dbff97a
Compare
dbff97a to
ad3c0ad
Compare
Make `torchtitan/experiments/rl/grpo.py` shut down cleanly on success, exception, and Ctrl-C. Three problems addressed: 1. `VLLMGenerator.__del__` called `torch.cuda.empty_cache()` at interpreter teardown, when `torch` may already be `None` — `AttributeError: 'NoneType' object has no attribute 'cuda'`. 2. `main()` had no `try/finally`, so `RLTrainer.shutdown()` never ran. 3. With shutdown running, `[W ProcessGroupNCCL.cpp:1647] destroy_process_group() was not called` still printed on exit, and Ctrl-C did not interrupt the train loop because the default asyncio handler is not reliably invoked while Monarch's blocking `endpoint.call().get()` RPCs are in flight. Fixes: - Delete `VLLMGenerator.__del__`; add `@endpoint async def shutdown` on `VLLMGenerator` and `PolicyTrainer`. Generator shutdown mirrors `AsyncLLM.shutdown` order: `renderer.shutdown` → `engine_core.shutdown` → `cleanup_dist_env_and_memory`. Trainer shutdown calls `destroy_process_group()` if initialized. (Endpoint name is `shutdown` because `Actor.stop` is reserved by the Monarch base class.) - `RLTrainer.shutdown()` calls actor `shutdown` endpoints before `mesh.stop()`, sequential, best-effort (failures are logged and the next step still runs). Logs a "Shutting down" line at start so users see a breadcrumb on every exit path. - `main()` wraps `setup` + `train` under a small `_cancel_on_sigint()` context manager that installs a SIGINT handler routing Ctrl-C through asyncio cancellation; shutdown always runs in `finally`. The handler logs a "KeyboardInterrupt received" line when fired. The `__main__` wrapper swallows `KeyboardInterrupt` / `CancelledError` after shutdown completes. - `train()` gets a single `await asyncio.sleep(0)` per step so the signal-driven cancel can land between blocking RPCs. Cooperative cancellation note: Ctrl-C does not interrupt a Monarch RPC already in flight. Cancellation is delivered at the next step-boundary yield, so the in-flight step plus a small number of subsequent short steps may complete before the process exits cleanly. SIGINT exits with code 0 by design. SIGTERM is not handled in this PR (default OS behavior); validation has no extra yield (a Ctrl-C during pre/post-validation waits for the single blocking RPC to return before shutdown runs). Verified on `CUDA_VISIBLE_DEVICES=4,5` with TP=1/TP=1: normal exit log is clean (no `Exception ignored`, no NCCL warning, no traceback); SIGINT after Step 0 exits cleanly within ~12s. Eight CPU unit tests added.
ad3c0ad to
12185c5
Compare
There was a problem hiding this comment.
Is this CPU test? Should we create something like https://github.com/pytorch/torchtitan/blob/main/.github/workflows/unit_test_cpu.yaml to guard it in CI (e.g. under the "rl" tag @wwwjn is working on)
There was a problem hiding this comment.
Right, RL CPU unit test is not added to CI in this PR yet. @felipemello1 Do you want to update it to be included? It can also triggered by rl tag
There was a problem hiding this comment.
test_close sounds ambiguous (I thought it was testing numerics being close on first sight) -- maybe use test_actor_close or test_teardown
There was a problem hiding this comment.
changed to shutdown, but it makes me think that we should use shutdown/cleanup. It seems to be most of the libraries also use. I am fine to keep it as "close" though
|
|
||
|
|
||
| @contextlib.contextmanager | ||
| def _cancel_on_signal() -> Iterator[None]: |
There was a problem hiding this comment.
Do we not need this in pretrain because torchrun handles it?
Is this blessed way of handling things if using monarch? @JenniferWang
There was a problem hiding this comment.
tldr: deleted it and replaced .get() with await
turns out, i was addressing a symptom, not a root cause. The script as is, if you try to ctrol+c, it doesnt get interrupted.
the root cause is because we were using .get() instead of await. It works, but cant be interrupted.
So, first I added this loop = asyncio.get_running_loop() so we could "enter" the loop, and also added the await sleep(0). I tested it, and I only needed the await sleep(0) to let the keyboard interruption jump in.
But, even better: i changed the .get() to await. Now, as soon as i press ctrol+c, it interrupts, instead of having to wait until await sleep(0).
We can delete both this handler and the sleep(0).
good catch!
There was a problem hiding this comment.
I'd like to get a bit more clarify.
It seems we are changing everything from get() to await, basically using await for sync semantics. Is this expected? I would like to have clear separation between
- we need async somewhere to make the job exit gracefully
- showcasing how we should do sync RL training (using
get()most of the time)
There was a problem hiding this comment.
@dulinriley the expert in shutdown noises from Monarch.
There was a problem hiding this comment.
My understanding is that there's no real sync endpoint call in monarch (or Ray). So if you need async to make cleanup works, that smells wrong and I agree with @tianyu-l on the separation of consideration.
There was a problem hiding this comment.
A little bit more context: previously I decided to using .get() to implement Sync RL learning, because https://meta-pytorch.org/monarch/stable/generated/examples/getting_started.html#sending-a-simple-message this is a blocking API call
There was a problem hiding this comment.
So when you call .get() on the main thread, you go here:
https://github.com/meta-pytorch/monarch/blob/main/monarch_hyperactor/src/runtime.rs#L201
That releases the GIL, and awaits for the Rust tokio future to complete.
Every 100 ms it tries to reacquire the GIL and call the interpreter signal checker.
So if you're not seeing the script be responsive to Ctrl-C, there are three main possibilities:
- Was your SIGINT signal handler overwritten? Monarch doesn't override this from the default, which is installed by the Python runtime normally. In python you can do:
import signal; signal.getsignal(signal.SIGINT)and see if it's the default or something else. This may not be sufficient to tell you because Python itself overwrites the default to give you KeyboardInterrupt - The signal_safe_block_on either (a) didn't run the part of the future doing the loop or (b) was unable to acquire the GIL. Why would it not be able to acquire the GIL? Maybe if you are Ctrl-C'ing some very long running native code, it may not release the GIL in a timely fashion, especially if it is itself stuck in some endless loop.
- Is this not running on the main thread? In that case our implementation just blocks forever
For other reference, here's the CPython default SIGINT handler: https://github.com/python/cpython/blob/main/Modules/signalmodule.c#L226C5-L226C18
It just sets a flag in the interpreter to raise an exception at its next opportunity.
So if you're stuck in native code (C++ or Rust) it won't normally do anything until you actually check for exceptions and raise.
My recommendation to debug: when this happens, attach lldb / gdb and dump the stacks of all threads. We need to see if any thread is holding the GIL for longer than it needs to.
There was a problem hiding this comment.
As for the earlier question:
showcasing how we should do sync RL training (using get() most of the time)
Monarch has no real way to do fully synchronous work. The basic actor communication mechanism is not call and response, it's just a 1-way "send". You don't even know that the send was able to complete and leave your machine yet by the time it returns. We implement call-response by adding an address that the recipient can send back to with a response (a PortRef<T>). So it's inherently async, you're waiting for a different actor to drive their own message handling loop until they can send something back
We simulate synchronous work by just blocking your thread until the future has completed. So other than avoiding async on your functions, you don't get any benefits from using .get() and might have some drawbacks if your main thread could be doing other async work at the same time.
cc @zdevito who might have suggestions about how best to show sync RL training
Replace ``endpoint.call(args).get()`` with ``await endpoint.call(args)`` at every RPC site in ``setup``, ``_collect_rollouts`` (now ``async``), ``validate``, and ``train``. The previous shape was async-in-name-only: each ``async def`` blocked its OS thread on ``.get()``, so the asyncio loop never spun and SIGINT cancellation was starved. Earlier patches worked around that with an explicit ``loop.add_signal_handler`` plus a per-step ``await asyncio.sleep(0)`` yield. With proper awaits at every RPC, neither workaround is needed: - ``asyncio.run``'s default SIGINT handler delivers cancellation through the natural await points; - Ctrl-C lands at the next RPC boundary (~one RPC) instead of the next step boundary (~one step). Net: ``_cancel_on_signal`` removed; per-step ``asyncio.sleep(0)`` removed; ``signal``/``contextlib``/``Iterator`` imports removed. Training dynamics are bit-identical to the prior shape (same Loss, Reward, Logprob diff per step on the smoke config). ``test_close.py`` renamed to ``test_shutdown.py`` to reflect what the file tests; the underlying actor/orchestrator method is still ``close``.
There was a problem hiding this comment.
Right, RL CPU unit test is not added to CI in this PR yet. @felipemello1 Do you want to update it to be included? It can also triggered by rl tag
|
|
||
| # push weights from trainer | ||
| self.trainer.push_model_state_dict.call().get() | ||
| await self.trainer.push_model_state_dict.call() |
There was a problem hiding this comment.
Why we need to change it to Monarch Async API? I used .get() becuase this is a blocking API which is strictly Sync calls
|
|
||
|
|
||
| @contextlib.contextmanager | ||
| def _cancel_on_signal() -> Iterator[None]: |
There was a problem hiding this comment.
A little bit more context: previously I decided to using .get() to implement Sync RL learning, because https://meta-pytorch.org/monarch/stable/generated/examples/getting_started.html#sending-a-simple-message this is a blocking API call
Restore the original ``endpoint.call(args).get()`` shape at every RPC site in ``setup``, ``_collect_rollouts`` (back to ``def``), ``validate``, and ``train``. Restore the per-step ``await asyncio.sleep(0)`` yield in ``train``. Ctrl-C still works without a custom signal handler: the per-step yield gives the asyncio loop a chance to deliver SIGINT cancellation between blocking RPCs. The await-RPC alternative ships tighter cancellation latency but trades that against the cancel-mid-RPC race the team has not yet weighed in on. Per-actor ``close`` endpoints, ``RLTrainer.close()`` orchestration, and ``main()``'s ``try/except/finally`` shape are unchanged.
| # Yield to the event loop once per step so a pending Ctrl-C | ||
| # cancellation can land here (between blocking Monarch RPCs). | ||
| await asyncio.sleep(0) |
There was a problem hiding this comment.
please leave a TODO for proper fix
|
One minor thing: you said you did this:
Actors already have a One caveat: cleanup is called with a time-bound, so I wouldn't recommend doing anything that takes > 3 seconds. This can be overridden with the environment variable |
|
This PR might fix your hang with ctrl-c: I think our atexit handler was stopping the script from completing shutdown. We will also disallow calling Future.get() inside an asyncio loop maybe by next release |
Thanks @dulinriley ! So, to confirm my understanding: we should NOT call .get() inside of |
yes confirmed. Only call .get() in a synchronous context. If you are in an async function just await it instead |
… commit `659a0d`). This CL imports TorchTitan head and stabilizes the build. Supporting feature gaps to be done in follow-up CLs. **For a summary of major changes and disabled tests see [internal link]** In this CL, we bypass the [ban](https://github.com/pytorch/torchtitan/blob/1c40dd26a91b0489249011a53d1da69061b03d38/torchtitan/models/common/config_utils.py#L85) of SDPA backend for language models in `models/common/config_utils.py` so our monkey patch to apply splash attention kernel works. Deprecation of sdpa backend on TPU and supporting document packing in the SplashAttention kernel is handled in child cl/954755047 In OSS, torch>=2.12 is **required**. After this update several files import `DataParallelMeshDims` from `torch.distributed.fsdp` which is only available in torch >=2.12 It disables the following tests: b/540005818 Disabled for numerical divergences: - test_train_minimal_distributed llama3_fsdp - test_train_minimal_distributed llama3_simplefsdp - test_train_minimal_distributed qwen3_simplefsdp - test_flux_qkv_split TestFluxSingleStreamUnbind Disabled for other reasons: - b/540119277 test_fused_swiglu_override - circular import issue with spmd_type - b/540048441 graph trainer tests (upstream refactored trace_train_step into minimal_fx_tracer API): - b/540049946 deepseek_v3_tp_dtensor - Linear: output DTensor has placements (Shard(dim=1),), but out_src_shardings expects (Shard(dim=2),) Tested on OSS with image built from torch 2.12: - redacted SimpleFSDP Compiled: [10,925 TPS]([internal link]) (10,0922 at head) - FLUX SimpleFSDP Compiled (F32 + BF16 MP): [3,737 TPS]([internal link]) (3652 at head) - Llama3 SimpleFSDP Compiled: [5,444 TPS]([internal link]) (5384 at head) See the list of commits: pytorch/torchtitan@627126f...659a0d2 #MIGRATION_3P_PY_TORCHTITAN__DEFAULT - 95ae6a0 ci: regenerate qwen3_moe_rocm_mi350x.txt baseline with ac... by Rishi Sinha <[email protected]> - db5da4b Refactor pipeline parallel helpers for graph PP reuse (#2... by sanketpurandare <[email protected]> - 6065055 Revert precompile PRs (pytorch#3107, pytorch#3178) to fix CI (pytorch#3212) by Bob Ren <[email protected]> - 179d9e1 CP AllGather on the wrong dimension (pytorch#3206) by francesco-bertolotti <[email protected]> - f522db0 Fix commands in DSV3 readme (pytorch#3116) by Daniel Vega-Myhre <[email protected]> - 0b148a2 [CI] Run integration tests in parallel (pytorch#3144) by Yuankai Chen <[email protected]> - 080c1d4 [GraphTrainer] Annotate loss region with module_fqn (pytorch#3207) by Sherlock Huang <[email protected]> - b2cd149 Observability: structured logging + training instrumentat... by Felipe Mello <[email protected]> - 706ed8d [GraphTrainer] Annotate generated FX code with user sourc... by Aditya Venkataraman <[email protected]> - af8d243 [GraphTrainer] Skip identity-slice rewrite when start/end... by Aditya Venkataraman <[email protected]> - d3c96e8 [mxfp8] Fix MXFP8GroupedExpertsConverter to actually swap... by Aditya Venkataraman <[email protected]> - d341407 [MoE] Pad token count to a multiple of sp_size in AllToAl... by Jiani Wang <[email protected]> - 2ae1340 [rl] add import torch to provisioner bootstrap to avoid c... by Shuhua Yu <[email protected]> - 0b6a29e [rl] Set PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True... by Felipe Mello <[email protected]> - 2c237ae refactor get_attention_masks to use positions instead of ... by liangel-02 <[email protected]> - 74bac7e [graph_trainer] FSDP AG RS overlap (pytorch#3156) by Yiming Zhou <[email protected]> - b6830b2 Upgrades torchtitan-ubuntu docker image to 22.04 and CTK ... by Syed Tousif Ahmed <[email protected]> - 5fa7af6 [float8] Quantize GroupedExperts params during conversion... by Aditya Venkataraman <[email protected]> - e62ab09 [rl] Fix CI loss=0 and logprob=NaN (pytorch#3232) by Jiani Wang <[email protected]> - f32a5bb [GraphTrainer] Overhaul README for accuracy and clarity (... by Sherlock Huang <[email protected]> - e425316 [rl] Remove VLLMGenerator.__del__ cleanup method (pytorch#3224) by Danielle Pintz <[email protected]> - ef54395 [graph_trainer] Move all FSDP-specific passes to fsdp_pas... by Yiming Zhou <[email protected]> - 301384b [GraphTrainer] Register BlockMask pytree node in aot_fx_t... by Bob Ren <[email protected]> - a24b247 [graph_trainer] Disable cpu_offload_all CI test for upstr... by Sherlock Huang <[email protected]> - 2dfee86 [GraphTrainer] Update manifesto: hardware heterogeneity, ... by Sherlock Huang <[email protected]> - c6cfaa2 Re-land "Enable bucketing pass in precompile path" (pytorch#3107... by Bob Ren <[email protected]> - ae5ff10 [cpu-offloading] Implement prefetching for cpu offloading... by Michael Lazos <[email protected]> - 046fdbb Support mark_unbacked in minimal_fx_tracer (pytorch#3046) by Tugsbayasgalan Manlaibaatar <[email protected]> - 8599818 [rl] Add a tag to trigger RL CI runs (pytorch#3230) by Jiani Wang <[email protected]> - 466da8c [graph_trainer] Port remat_using_tags_for_fwd_loss_bwd_gr... by Sherlock Huang <[email protected]> - 94d5f59 Re-land "Fix FlexAttention precompile bitwise determinist... by Bob Ren <[email protected]> - e2fea3f Wrong token count in validation when CP>1 (pytorch#3257) by francesco-bertolotti <[email protected]> - 1d392ca [torchtitan][llama4_parallelize] fixing fsdp_mesh_info bu... by anshul-si <[email protected]> - d91a9fc [Qwen3VL] remove local_map for dtensor interpolation (pytorch#29... by Shuhua Yu <[email protected]> - 19f88a3 profiler: drop duplicate dataclass fields (pytorch#3227) by Felipe Mello <[email protected]> - 52f3142 [GraphTrainer] Log graph pass names and total time (pytorch#3261) by Sherlock Huang <[email protected]> - bf2842d [GraphTrainer] Add memory policy registry and extra graph... by Syed Tousif Ahmed <[email protected]> - 4ebb089 Tests HybridEP integration with GraphTrainer (pytorch#3184) by Syed Tousif Ahmed <[email protected]> - da6ff79 [rl] Graceful shutdown GRPO (pytorch#3238) by Felipe Mello <[email protected]> - 54887a3 [GraphTrainer] Add compile.disable_passes to selectively ... by Sherlock Huang <[email protected]> - 4ed3c53 [codex] Fix weight tying parameter accounting (pytorch#3225) by 岛石 <[email protected]> - 5638c49 [codex] Fix shared BOS and EOS token inference (pytorch#3279) by 岛石 <[email protected]> - ecd117e [graph_trainer] Pass global_valid_tokens into loss_fn ins... by Yidi Wu <[email protected]> - 0fae167 [graph_trainer] AutoParallel AOT FX Trace Integration (#2... by sanketpurandare <[email protected]> - 74181b1 [LoRA] Add LoRA converter and rename quantization to conv... by Yifan Mao <[email protected]> - 0d8f57c Remove unnecessary clone from ChunkedCELoss (pytorch#3272) by Jiani Wang <[email protected]> - 28b83bd Merge lora and float8 tests (pytorch#3310) by Yifan Mao <[email protected]> - e917ff4 Avoid repeat_interleave output-size sync (pytorch#3274) by Simon Fan <[email protected]> - acece3b [graph_trainer] Disable flexattn integration test due to ... by Sherlock Huang <[email protected]> - 8ba1c6b Support kwargs in minimal_fx_tracer (pytorch#3262) by Tugsbayasgalan Manlaibaatar <[email protected]> - d107aa4 [Quantization] Use class factory for MXFP8/Float8 Grouped... by Yifan Mao <[email protected]> - ca4c7f2 [rl] Register customized config parser to vllm + less vll... by Jiani Wang <[email protected]> - 0b5e899 Fix precompile tests (pytorch#3316) by Tugsbayasgalan Manlaibaatar <[email protected]> - 0fadde3 [graph_trainer] Fix AutoParallel input_fn to include posi... by Ivan Kobzarev <[email protected]> - 2ceff82 [graph_trainer] Add log_timer utility for tracing step ti... by Sherlock Huang <[email protected]> - e9dbff6 [graph_trainer] Refactor selective activation remat to in... by Tugsbayasgalan Manlaibaatar <[email protected]> - b301dfa Remove MoE expert for-loop fallback (pytorch#3308) by sanketpurandare <[email protected]> - 1a0fe3e [graph_trainer] Refactor passes.py into focused modules (... by Sherlock Huang <[email protected]> - d57df09 Make ChunkedCELoss support torch.autograd.grad (pytorch#3249) by Yidi Wu <[email protected]> - 5ca23a5 [GraphTrainer] Add Context Parallel support (pytorch#3305) by Aditya Venkataraman <[email protected]> - 7f070c9 Enhance Lychee Link Checker (Resiliency & Performance) (#... by Andrei-Aksionov <[email protected]> - 7f602b9 Add AGENTS.md symlinks for Codex usage (pytorch#3326) by sanketpurandare <[email protected]> - 34801c0 [graph_trainer] Improve SAC tagging and CPU offload pass ... by Sherlock Huang <[email protected]> - 1a22c2d [graph_trainer] Remove deprecated AOT compile mode (pytorch#3327) by Sherlock Huang <[email protected]> - 7b418ab Revert "Avoid repeat_interleave output-size sync (pytorch#3274)"... by Simon Fan <[email protected]> - 6f2fa2f [rl] switch to vllm v2 engine (pytorch#3330) by Jiani Wang <[email protected]> - 1690e0a [cpu-offloading] Encode last consumer as dep arg in ao.wa... by Michael Lazos <[email protected]> - cee4982 [graph_trainer] Fix SAC remat to produce fresh FakeTensor... by Ivan Kobzarev <[email protected]> - d4a3c63 [graph_trainer] Generalize minimal_fx_tracer to module + ... by Tugsbayasgalan Manlaibaatar <[email protected]> - 4614e30 [graph_trainer] Support multiple FSDP PGs in overlap_fsdp... by Sherlock Huang <[email protected]> - 3781d1d Back out "[graph_trainer] Fix SAC remat to produce fresh ... by Sherlock Huang <[email protected]> - a2a0d99 RL: observability spans across trainer/generator/controll... by Felipe Mello <[email protected]> - 8cdfdc2 [rl] Better initial weight loading (pytorch#3318) by Jiani Wang <[email protected]> - f0795f0 [RL] - Enable experiment metrics (pytorch#3237) by Felipe Mello <[email protected]> - b64292b [graph_trainer] Remove fsdp_reshard_after_fwd_pass (pytorch#3370) by Sherlock Huang <[email protected]> - a670699 [graph_trainer] Skip dense numerics tests due to upstream... by Sherlock Huang <[email protected]> - cb7bf09 ci: declare workflow-level `contents: read` on 2 workflow... by Arpit Jain <[email protected]> - d64eabc [Full DTensor] Config-based Full DTensor for Llama3 (pytorch#3159) by Chien-Chin Huang <[email protected]> - a866d04 Fix memory snapshot pickle protocol for compatibility wit... by francesco-bertolotti <[email protected]> - 9f9ae4d [graph_trainer] Fix H100 CI failure from DeepEP compilati... by Sherlock Huang <[email protected]> - c9126af [graph_trainer] Add bucketing ops to precompile serializa... by Ivan Kobzarev <[email protected]> - 013890b [graph_trainer] Defer cudagraph compatibility check to pa... by Ivan Kobzarev <[email protected]> - 6a1b334 Fix optimizer state and module state coupling (pytorch#3356) by Tugsbayasgalan Manlaibaatar <[email protected]> - 4238c35 Re-enable compile for gpt-oss integration tests (pytorch#3373) by Aditya Venkataraman <[email protected]> - ebfceeb [rl] Add TITO generator and gen metrics (pytorch#3391) by Felipe Mello <[email protected]> - cf3c431 [graph_trainer] Re-enable FlexAttention tests after upstr... by Sherlock Huang <[email protected]> - 8aa96ac [graph_trainer] Fix eager SAC policy mm counter to reset ... by Ivan Kobzarev <[email protected]> - 52a292d [graph_trainer] Gate overlap_fsdp_ag_rs_pass behind a con... by Yiming Zhou <[email protected]> - 2057b56 [rl] fix CI timeout issue by properly tear down for vllm ... by Jiani Wang <[email protected]> - cfe97c6 [rl] use wandb=False in CI (pytorch#3408) by Felipe Mello <[email protected]> - 83e4904 [graph_trainer] Rework full_inductor_compilation_pass via... by Tugsbayasgalan Manlaibaatar <[email protected]> - 963c20c [MoE][5/n] Refactor MoE to clean DTensor boundaries for s... by Jessica Zhong <[email protected]> - da38566 [MoE][6/n] Extract local_reorder, split DeepEP/HybridEP d... by Jessica Zhong <[email protected]> - 3f721b4 [graph_trainer] Fix fsdp_passes compat with BitsetAncesto... by Ivan Kobzarev <[email protected]> - b585282 Fix imports for latest DeepEP (pytorch#3414) by Steffen Hirschmann <[email protected]> - c2a3771 [loss] Fix ChunkedCELoss + TP gradient placement mismatch... by Chien-Chin Huang <[email protected]> - 19c567f Debug Numerics with DebugMode (pytorch#3323) by Shangdi Yu <[email protected]> - 78b08dd [graph_trainer] Add DeepSeek V3 16B SDPA config (pytorch#3361) by sanketpurandare <[email protected]> - af33f76 [Module] Replace from_nn_module with native Module subcla... by Chien-Chin Huang <[email protected]> - 58b0344 Add FSDP symmetric memory configuration and related tests... by Masaki <[email protected]> (And 259 more changes) PiperOrigin-RevId: 956923721
Problem
torchtitan/experiments/rl/grpo.pyexits noisily today. Three symptoms:1. Finalizer error at exit.
VLLMGenerator.__del__callstorch.cuda.empty_cache()during interpreter shutdown, whentorchmay already beNone:(Already addressed by #3224 in upstream/main; this PR no longer overlaps with that change.)
2.
main()never tears down. Notry/finally, so process meshes and actors are not stopped on normal exit, on exception, or on Ctrl-C.3. NCCL leak warning + unresponsive Ctrl-C. Even with cleanup wired up,
[W ProcessGroupNCCL.cpp:1647] destroy_process_group() was not calledstill prints because nothing inside the worker destroys the process group. And Ctrl-C does nothing — Python's default SIGINT cancellation is not reliably invoked while Monarch's blockingendpoint.call(...).get()calls hold the main thread.Solution
Per-actor
closeendpointVLLMGenerator.__del__is removed. Each actor gets a@endpoint async def closethat releases its own resources:closedoesVLLMGeneratorrenderer.shutdown→engine_core.shutdown→ vLLM'scleanup_dist_env_and_memory()(destroys NCCL groups, runs GC, empties accelerator cache). Same order vLLM's ownAsyncLLM.shutdownuses.PolicyTrainertorch.distributed.destroy_process_group()if initialized.Endpoints are named
closebecauseActor.stopis reserved by Monarch.RLTrainer.close()calls each actor'sclosefirst, then stops the proc meshes.awaitat every Monarch RPCThe train loop previously used
endpoint.call(args).get()everywhere — sync waits insideasync def. That blocks the OS thread, freezing the asyncio loop, which is why Python's default SIGINT cancellation never landed. Replacing every.call().get()withawait endpoint.call(...)(eight sites acrosssetup,_collect_rollouts,validate,train) yields control to the loop on every RPC — and that's enough for Ctrl-C to work without any custom signal-handling code.Ctrl-C flow
No custom signal handler. No explicit yield. The awaited RPCs are the cancellation points.
Verification
CUDA_VISIBLE_DEVICES=4,5, TP=1/TP=1:pytest torchtitan/experiments/rl/tests/test_shutdown.py -vClosingbreadcrumb presentInterrupted; attempting graceful shutdown...andClosingbreadcrumbs present"Clean log" =
grep -cE "Exception ignored\|VLLMGenerator.__del__\|AttributeError\|destroy_process_group\|Traceback"returns 0.Training dynamics are bit-identical to the prior
.call().get()shape (same Loss, Reward, Logprob diff per step on the smoke config —awaitand.get()wait on the same Future, only the thread vs coroutine blocking differs).pre-commit run(file-scoped on the four changed files): all hooks pass; pyrefly skipped (binary missing in env), lychee skipped.Out of scope (intentionally)
close()running. One extraloop.add_signal_handler(signal.SIGTERM, ...)line to add later if a deployment requires it.mesh.stop()kills the process. Memory-safe (workers are separate processes); ungraceful for the in-flight RPC. Forge accepts the same trade-off; could be addressed withasyncio.shieldif needed.Test plan
Exception ignored, no NCCL warning)pre-commitcleanpre-commit run --all-files(deferred — pyrefly binary missing in this env)