Skip to content

[rl] Select the actor framework by config: ActorSystem, implemented for Monarch - #5391

Merged
tianyu-l merged 3 commits into
mainfrom
rl-monarch-actors
Oct 18, 2026
Merged

tianyu-l merged 3 commits into
mainfrom
rl-monarch-actors

Conversation

@tianyu-l

@tianyu-l tianyu-l commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #5317.

Why

The controller, the rollouter, the trainer, the batcher and train.py used Monarch directly: train.py provisioned the GPU proc meshes; the controller spawned the router and batcher processes, set up torch elastic, spawned every actor, sliced the trainer by DP rank and stopped the meshes; the rollouter spawned and stopped its worker pool; the batcher and the trainer exchanged MonarchRDMAMicrobatches. Running the RL loop on another actor framework (e.g. Ray) would mean editing all of them.

This PR puts actor placement behind an interface selected by config, the way Generator.Config.engine selects the inference engine (#5317).

What changed

  • actors/system.py: ActorSystem, framework-agnostic. It provisions processes, spawns each service, initializes TorchStore (storage on the trainer's processes, plus every trainer and generator actor's client), stops the processes, and shuts its client down. The name follows Akka/Pekko's actor system (see its docstring). Its docstring also defines the call convention its handles follow: .call() with .get(rank) on the result, .call_one(), .choose(), .stream(), .broadcast() (Monarch's endpoint calls; another framework wraps its handles to provide them).
    • spawn_trainer(config, dp_degree=...) returns a TrainerHandle: all-ranks, rank-0 and per-DP-rank handles. The actor system slices the trainer by DP rank and checks the (dp, cp, tp) layout with get_dp_rank, so the controller no longer slices meshes.
    • spawn_generator_router(router_config, generator_config=...) spawns the generators and the router over them, and returns only the router: the controller reaches the generators through the router.
    • spawn_batcher, spawn_rollout_workers / stop_rollout_workers.
  • Controller.Config.actor_system selects the implementation; the default MonarchActorSystem.Config() is imported lazily. Controller.setup_async(actor_system=...) also accepts one the launcher built, e.g. a MonarchActorSystem on hosts it allocated (host_meshes, generator_env constructor arguments), so launchers that bring their own hosts keep working. train.py only builds, runs and closes the controller, then calls the actor system's shutdown().
  • actors/monarch/system.py: MonarchActorSystem. actors/monarch/provisioning.py takes train.py's proc mesh provisioning (PerHostProvisioner, HostMeshes, spawn_proc_mesh, the spawn bootstraps) plus spawn_cpu_procs and the client shutdown.
  • actors/monarch/router.py: InterGeneratorRouterActor, the endpoints and the singleton check. InterGeneratorRouter is now a plain class with public async methods, like Trainer and Generator.
  • RDMA microbatches (separate commit). MonarchRDMAMicrobatch moves to actors/monarch/rdma_microbatch.py. The batcher and the trainer use an RDMAMicrobatch protocol (read, drop, the batch/DP rank/microbatch indices) in trainer/rdma_microbatch.py, next to RDMAMicrobatchPrefetcher; BatcherActor injects MonarchRDMAMicrobatch.register into Batcher.
  • Fix: VerifiersRollouter.setup_async takes actor_system (unused: rollouts run in the Verifiers EnvServer), plus a test that its signature matches Rollouter.setup_async.

After this PR no module outside actors/monarch/ imports Monarch, except the controller's lazy default config. actors/monarch/README.md describes the package and the call convention that remains outside it.

Behavior

  • Processes and actors are created in the same order as before: GPU meshes, router and batcher processes, torch elastic, trainer, generators, router, batcher, rollout workers, TorchStore. The trainer's DP-rank layout check now runs right after the trainer spawns instead of after TorchStore init. Teardown order is unchanged.
  • ts.initialize(mesh=trainer_mesh) and the per-actor TorchStore client setup move into ActorSystem.initialize_torchstore() (with a TODO to move it to a model state dict transport).
  • A batcher with rdma_min_tensor_bytes set but no registration raises ValueError.

Testing

  • RL CPU unit tests: 497 passed, 8 skipped. The Verifiers tests (skipped without verifiers) pass with verifiers==0.3.1: 37 passed, 1 skipped. New tests cover provisioning order and launcher host meshes, trainer DP-rank grouping and the layout check, teardown order with the batcher, and the Batcher's missing-registration error.
  • pre-commit run on the changed files: clean.
  • GPU A/B against main (dc9ea005e), GB300, Qwen3 debug model with random init and a deterministic varying reward, 6 steps:
    • on-policy, batch-invariant, 1 trainer GPU + 1 generator GPU: all non-timing metrics bitwise identical (only time-to-first-token differs);
    • same, with a DP=2 trainer and rdma_min_tensor_bytes=1024 (3 GPUs, per-DP-rank columns over RDMA): bitwise identical;
    • async (target_offpolicy_steps=3): finishes all steps on both. Both then hit the same teardown error on main and here (the rollout worker mesh stops while a router reply is in flight).

@tianyu-l
tianyu-l added this pull request to stack #5318 October 14, 2026 09:47
@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Oct 14, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 14, 2026
@tianyu-l tianyu-l added the ciflow/b200 Trigger B200 CI label Oct 14, 2026
Comment thread torchtitan/rl/actors/system.py Outdated
self, config: Generator.Config, **kwargs: Any
) -> list[ServiceHandle]:
"""Spawn the provisioned generators; ``kwargs`` go to ``Generator``'s
constructor."""

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.

This interface can be remove. Controller only needs spawn_generator_router to get the generation stack.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, done. spawn_generator_router(router_config, generator_config=..., **generator_kwargs) now spawns the generators and the router over them and returns only the router. The one other use of the generator handles, TorchStore client setup, moved into initialize_torchstore().

self, config: RolloutWorker.Config, *, num_workers: int, num_threads: int
) -> Any:
"""Spawn a pool of ``num_workers`` rollout worker processes on the
controller host, each running ``num_threads`` rollout threads."""

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.

The rollout_workers related methods feel weird since they are used to created a private field in Rollouter.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I kept these, because the pool is an implementation detail of the default Rollouter: VerifiersRollouter runs rollouts in its Verifiers EnvServer and spawns no pool. If the controller spawned the pool and passed it in, it would spawn processes the Verifiers rollouter never uses, or need a "does this rollouter want a pool" flag. So the rollouter still spawns its pool through the actor system it is given.

While checking this I found that VerifiersRollouter.setup_async did not take actor_system, so the verifiers recipes would have failed. Fixed, with a test that its signature matches Rollouter.setup_async. Happy to switch to a controller-owned pool if you prefer it.

@pzhan9

pzhan9 commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

The dependency inversion itself makes sense if the goal is to support multiple backends. But it does come with a price since it requires more work when the interface gets complicated. e.g. #5285 would need more careful design to conform with the ActorSystem interface.

logger = logging.getLogger(__name__)


class MonarchActorSystem(ActorSystem):

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.

The abstraction and APIs make sense to me, but I'm kind of confused about the name System. My proposal is maybe ActorRuntime , or what's your consideration of this class

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added this reasoning to the ActorSystem docstring: the name follows Akka/Pekko's actor system, the container that creates, places and stops actors. This class owns placement and lifecycle (provision, spawn_*, stop, shutdown), not only how actors execute, which "runtime" would suggest.

@felipemello1

Copy link
Copy Markdown
Contributor

message from claude:

@tianyu-l one concern before this merges: launchers that bring their own hosts.

  1. On main, Controller.setup_async(trainer_mesh=..., generator_meshes=...) lets a launcher allocate hosts itself and hand the controller ready proc meshes.
  2. FairTitan's Slurm launcher depends on that. It loads host meshes from its Slurm allocation, calls spawn_proc_mesh(..., host_meshes=host_meshes, generator_env=...), and passes the result to setup_async: launcher/rl/main.py#L49-L60 (internal repo).
  3. In this PR, setup_async() takes no meshes, and MonarchActorSystem.provision always calls spawn_proc_mesh(..., host_meshes=None) (torchtitan/rl/actors/monarch/system.py:69). spawn_proc_mesh still accepts host_meshes, but nothing can pass them in, so that launcher breaks.

Could MonarchActorSystem keep a way to take caller-provided HostMeshes, for example a constructor argument or an overridable provision? Happy to send it as a follow-up if you'd rather land this as is.

@tianyu-l

Copy link
Copy Markdown
Contributor Author

The dependency inversion itself makes sense if the goal is to support multiple backends. But it does come with a price since it requires more work when the interface gets complicated. e.g. #5285 would need more careful design to conform with the ActorSystem interface.

@pzhan9 agreed, it has a cost: each new service adds an ActorSystem method plus its adapter. Rebasing onto #5285 and #5309 showed what that looks like in practice:

  • the batcher: spawn_batcher;
  • per-DP-rank trainer handles: spawn_trainer returns a TrainerHandle with by_dp_rank, built by the actor system, which also runs the (dp, cp, tp) layout check;
  • fire-and-forget calls: .broadcast() joins the call convention;
  • RDMA microbatches (separate commit): MonarchRDMAMicrobatch moved to actors/monarch/. The batcher and the trainer use an RDMAMicrobatch protocol, and BatcherActor injects the registration.

With your spawn_generators suggestion, the interface stays at about as many methods as before. A GPU A/B against main with a DP=2 trainer reading RDMA microbatches is bitwise identical on every training metric.

@tianyu-l

Copy link
Copy Markdown
Contributor Author

@felipemello1 thanks for catching this, fixed in this PR. MonarchActorSystem takes host_meshes and generator_env constructor arguments, which it passes to spawn_proc_mesh, and Controller.setup_async(actor_system=...) accepts a system the launcher built:

actor_system = config.actor_system.build(host_meshes=host_meshes, generator_env=generator_env)
await controller.setup_async(actor_system=actor_system)

setup_async() with no argument builds config.actor_system as before. A unit test checks that provision passes both through to spawn_proc_mesh.

Base automatically changed from rl-generator-split to main October 17, 2026 23:48
…or Monarch

The controller, rollouter and train.py used Monarch directly to provision
proc meshes, set up torch elastic, spawn every service and stop the meshes.
Put that behind an interface selected by config, the way Generator.Config.engine
selects the inference engine:

- actors/system.py: ActorSystem, which provisions processes, spawns each
  service (trainer, generators, generator router, rollout workers), initializes
  TorchStore on the trainer's processes, stops them, and shuts its client
  down. It documents the call convention its handles follow (.call() with
  .get(rank), .call_one(), .choose(), .stream()). ServiceHandle carries a
  service's all-ranks and rank-0 handles, so the controller and router no
  longer slice meshes.
- Controller.Config.actor_system selects it (default MonarchActorSystem.Config(),
  imported lazily). The controller provisions and spawns through it in
  setup_async and stops it in close; the rollouter spawns and stops its worker
  pool through it; train.py only builds, runs and closes the controller and shuts
  the actor system's client down.
- actors/monarch/system.py: MonarchActorSystem. actors/monarch/provisioning.py
  takes train.py's proc mesh provisioning (PerHostProvisioner, HostMeshes,
  spawn_proc_mesh, spawn bootstraps) plus spawn_cpu_procs and shutdown.
- actors/monarch/router.py: InterGeneratorRouterActor, the endpoints and the
  singleton check. InterGeneratorRouter is now a plain class with public async
  methods, like Trainer and Generator.

Processes and actors are created in the same order as before: GPU meshes,
router process, torch elastic, trainer, generators, router, rollout workers,
TorchStore. Teardown order is unchanged too.
…DMAMicrobatch interface

The batcher and the trainer used MonarchRDMAMicrobatch directly, so both
imported monarch.rdma. They now use an RDMAMicrobatch protocol (read, drop,
and the batch/DP rank/microbatch indices) and an injected
RegisterRDMAMicrobatch; BatcherActor passes MonarchRDMAMicrobatch.register.
RDMAMicrobatchPrefetcher stays in the trainer, as it only calls read().
A batcher with rdma_min_tensor_bytes set and no registration raises.
@tianyu-l
tianyu-l merged commit f1bb643 into main Oct 18, 2026
@tianyu-l
tianyu-l deleted the rl-monarch-actors branch October 18, 2026 00:51
meta-codesync Bot pushed a commit that referenced this pull request Oct 19, 2026
Summary:
Follow up #5391.

Update launcher provisioning imports and controller setup to use the ActorSystem API. Pass allocated host meshes to the configured actor system and apply RL environment defaults before importing torch-dependent modules.

Remove redundant tests that compare method names, signatures, or a default configuration type. Existing behavioral tests cover router dispatch, Verifiers setup with the controller's arguments, Monarch provisioning, and trainer rank grouping.

Reviewed By: fegin

Differential Revision: D125905793

Pull Request resolved: #5535
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

None yet

Development

Successfully merging this pull request may close these issues.

4 participants