Skip to content

[rl] Sync the model state dict with ModelStateDictTransport behind a config flag - #5997

Merged
d4l3k merged 18 commits into
mainfrom
gh/d4l3k/7/head
Nov 14, 2026
Merged

d4l3k merged 18 commits into
mainfrom
gh/d4l3k/7/head

Conversation

@d4l3k

@d4l3k d4l3k commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

Stack from ghstack (oldest at bottom):

Summary (human-written)

Why

Wires the previous PR's ModelStateDictTransport into the RL loop as an opt-in replacement for TorchStore, so it can be rolled out per job. With 14B on one 8xB200 (183 GB) host it cuts the generator pull from 10-13 s to 0.6-0.9 s with pytorch/pytorch#204113 (1.7-2.35 s without it).

What changed

  • Controller.Config.model_state_dict_transport: ModelStateDictTransport.Config | None. None (the default) keeps TorchStore. Setting it requires generator.model_state_dict_load_mode="cpu_prefetch", which is validated at config time.
  • ActorSystem.initialize_model_state_dict_transport (Monarch impl): every generator reports its ranks' shard_layouts (which must match), the trainer ranks register staging buffers for it, and every generator rank connects and plans its reads.
  • Trainer: push stages (cast and, where needed, restage on GPU, D2H into the staging buffer) on the push stream from the actor thread before its first await, then awaits the stream in a worker thread. Restaging is a collective, so the controller sends the push before the next forward_backward; Monarch starts concurrent endpoints from one sender in send order, so every rank stages before its training collectives.
  • scripts/install_rl_env.sh installs mooncake-transfer-engine-cuda13==0.3.14, nixl==1.5.0 and nixl-cu13==1.5.0 with --no-deps (nixl-cu13 requires torch).
  • Generator prefetch: read() into the registered prefetch buffers replaces the TorchStore get. The load into the model is unchanged.
  • torchtitan/rl/MODEL_STATE_DICT_TRANSPORT.md: layout diagram and lifecycle.

User-facing changes

Before After
TorchStore only config.model_state_dict_transport = ModelStateDictTransport.Config(backend="mooncake" or "nixl")

Numerics

The trainer casts every tensor not in preserve_dtype_keys to transfer_dtype before the transfer; buffers and preserve_dtype_params keep their dtype. A dtype mismatch with the generator raises at init. The generator load is unchanged.

scripts/rl/loss_compare.py (Qwen3-0.6B, deterministic, seed 42, 10 steps) with this flag matches TorchStore exactly: --assert-equal passes on loss for all 10 steps.

Performance

14B (29.6 GB bf16), one 8xB200 (183 GB) host with 8x400G NICs, trainer FSDP 4 (GPUs 0,2,3,4), one generator TP 2 (GPUs 5,6), 10 steps. Baseline: main 8a33dbf + TorchStore 804ae43 over NIXL.

TorchStore + NIXL This PR (Mooncake)
Generator pull 10.0-13.2 s 0.62-0.90 s
of which RDMA read 9-12 s 0.20-0.35 s (~60 GB/s per generator rank, ~120 GB/s total)
of which H2D load - 0.37-0.49 s
Trainer push 3.2-4.0 s 0.5-0.9 s
blocking the trainer 2.1-3.2 s ~0
Throughput 60-74 tok/s 610-880 tok/s
Peak GPU, trainer / generator 85.0 / 37.4 GB 78.3 / 37.4 GB
Peak RSS, trainer / generator 10.4 / 38.6 GiB 11.2 / 25.4 GiB
Init span 63.3 s 62.5 s

Qwen3.5 27B (53.8 GB bf16) on MAST, 2 GB300 hosts (4 NICs each), DAPO-Math recipe: trainer FSDP 2 x TP 2 on one host, 4 TP 1 vLLM generators on the other (each pulls the full model), 6 steps of 4 prompts x 16 samples. Baseline: same recipe on TorchStore over NIXL. Pull times are for the slowest generator.

TorchStore + NIXL This PR (Mooncake) This PR (NIXL)
First pull 22.5 s 4.6 s 0.95 s
Steady pulls (pulls 2-7) 15.6-16.8 s 2.2-2.8 s (fastest generator 1.2-1.4 s) 0.96-1.08 s
Effective rate, all 4 generators ~13 GB/s 77-98 GB/s ~200-225 GB/s (50-56 GB/s per generator)
Blocking pull / step time (steps 2-6) 0.20-0.28 0-0.064 0-0.034
tok/s full step, mean of steps 2-6 13.0k 16.9k 15.7k
Trainer model GPU memory 31.75 GiB 31.75 GiB 31.75 GiB
Generator KV cache 196.22 GiB 196.22 GiB 196.22 GiB

The tok/s values vary with rollout length (baseline 7.8k-15.8k per step, Mooncake 11.2k-20.8k, NIXL 3.2k-20.1k). The MAST logs do not record host RSS.

Trainer staging, same 27B runs (trainer rank 0). Staging runs on the push stream overlapped with the next forward_backward; the trainer blocks only on push's wait (timing/step/blocking_trainer_push_model_state_dict). This layout (FSDP 2 x TP 2 -> TP 1) still restages row-parallel weights.

TorchStore + NIXL This PR (Mooncake / NIXL)
Trainer blocking per step 0-3 ms 0-3 ms
Full stage, not overlapped 0.39-0.41 s 0.12 s
forward_backward incl. overlapped staging 44.8-45.3 s 44.5-45.3 s
Init push 2.19 s 0.17-0.19 s

The Mooncake numbers depend on pytorch/pytorch#203623 (poller race; without it the run hangs) and pytorch/pytorch#204113 (register host memory with a NUMA-detected location; without it numa1 buffers use numa0 NICs and the read takes 1.3-1.7 s).

Size

Implementation +230/-22 (incl. 8 lines in scripts/install_rl_env.sh), docs +104/-8, tests +46 (a trainer test checking push stages on the push stream from the actor thread before its first await and synchronizes in a worker thread, plus a new attribute in existing tests); the unit tests in the previous PR cover the layout and read plan.

Testing

  • 10-step 14B runs on 8xB200 with both configurations (table above); the transport run completed with rc=0.
  • 6-step 27B runs on MAST with all three configurations (table above); all completed 6 steps. The NIXL run used the same torch and this stack's model_state_dict_transport.py, nixl 1.5.0 over UCX with UCX_NET_DEVICES set to the 4 NICs, UCX_TLS=rc,cuda_copy,self and UCX_MAX_RMA_RAILS=4.
  • Loss compare above on 8xB200 (TorchStore arm exported, transport arm imported with --assert-equal), on a revision whose torchtitan/ code is identical to this stack (later changes are tests and docs only).
  • The 14B runs used an earlier revision of this stack whose staging buffer used pin_memory=True (rounded up to a power of two) instead of cudaHostRegister; later review fixes (names, read timeout, hardcoded backend, docs/tests) do not change the transfer path. The 27B MAST run uses a revision with the same staging, read and stream-sync code, differing only in names, config plumbing and the generator-layout check, with torch 2.16.0.dev20261030+cu132 plus [Transport] [Mooncake] Don't drop a reused batch id when settling a transfer pytorch#203623 and [transport] mooncake: register host memory with NUMA-detected location pytorch#204113.
  • pytest tests/rl/unit_tests/cpu/{test_generator,test_model_state_dict_transport,test_trainer,test_engine_loop,test_async_controller,test_shutdown}.py (188 pass).
  • pre-commit run on the changed files passes (pyrefly skipped; it also fails on main).

Known issues / follow-ups

  • Only model_state_dict_load_mode="cpu_prefetch" is supported; gpu_fetch still needs TorchStore, so the TorchStore path stays until this covers it.
  • The torch pinned by scripts/install_rl_env.sh (via vLLM, 2026-11-07) predates [Transport] [Mooncake] Don't drop a reused batch id when settling a transfer pytorch#203623, so the stock env can time out on a read until the pin moves to 2026-11-10 or later.
  • No CI job runs the flag end to end (it needs RDMA NICs); the unit tests cover the layout, read plan and trainer staging.
  • Delta sync: stage and read only the changed pieces.
  • The H2D load from the prefetch buffers (0.4 s) now dominates the pull.
  • Restaging a tensor whose first sharded dim is not the outermost sharded mesh axis (e.g. MoE experts (Shard(1), Shard(0)) -> (Shard(0), Shard(0))) can make DTensor gather it over that axis on the GPU during staging (untested at scale), costing transient memory at large EP.
  • Reads per pull scale with keys x trainer ranks (one per contiguous run); a batched read upstream in torch.distributed._transport would cut the per-read overhead. Init metadata (every trainer rank's pieces for every generator rank) scales the same way.
  • Every trainer DP rank keeps its own pinned staging copy of its shard; with replicated parameters (HSDP replicas, EP replicas of dense weights) this duplicates host memory across replicas.

AI-assisted (Claude).

d4l3k added 2 commits November 9, 2026 17:48
[ghstack-poisoned]
[ghstack-poisoned]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 10, 2026

@kapilsh kapilsh left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

LGTM! couple of small comments

Comment thread torchtitan/rl/actors/monarch/system.py Resolved
Comment on lines +1133 to 1137
Controller: await pull N-1 (push N must not overwrite pushed weights mid-pull)
Controller: start push N -> pull N -> release groups, in the background
|-> Trainer: TorchStore put_state_dict of policy N
|-> Trainer: TorchStore put_state_dict (or ModelStateDictTransport stage) of policy N
|-> Generators: load policy N (cpu_prefetch: prefetch it into pinned CPU memory first)
|-> Group buffer: admit the next rollout groups

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Do we need to keep torchstore around here?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I wanted to land this incrementally, once we do numerics testing e2e and switch the default we can deprecate torchstore

d4l3k added a commit that referenced this pull request Nov 10, 2026
…config flag

## 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
Wires the previous PR's `ModelStateDictTransport` into the RL loop as an opt-in replacement for TorchStore, so it can be rolled out per job. With 14B on one 8xB200 (183 GB) host it cuts the generator pull from 10-13 s to 0.6-0.9 s with pytorch/pytorch#204113 (1.7-2.35 s without it).

## What changed
- `Controller.Config.model_state_dict_transport: ModelStateDictTransport.Config | None`. None (the default) keeps TorchStore. Setting it requires `generator.model_state_dict_load_mode="cpu_prefetch"`, which is validated at config time.
- `ActorSystem.initialize_model_state_dict_transport` (Monarch impl): every generator reports its ranks' `shard_layout`s (which must match), the trainer ranks register staging buffers for it, and every generator rank connects and plans its reads.
- Trainer: staging (cast and restage on GPU, D2H into the staging buffer) runs on the push stream from the actor thread, once per optimizer step, by whichever of `push` and the next `forward_backward` reaches each rank first. Restaging is a collective, so this keeps it in the same order relative to training's collectives on every rank regardless of message order. `push` then awaits the stream in a worker thread.
- `scripts/install_rl_env.sh` installs `mooncake-transfer-engine-cuda13==0.3.14`, `nixl==1.5.0` and `nixl-cu13==1.5.0`.
- Generator prefetch: `read()` into the registered prefetch buffers replaces the TorchStore get. The load into the model is unchanged.
- `torchtitan/rl/MODEL_STATE_DICT_TRANSPORT.md`: layout diagram and lifecycle.

## User-facing changes
| Before | After |
| --- | --- |
| TorchStore only | `config.model_state_dict_transport = ModelStateDictTransport.Config(backend="mooncake" or "nixl")` |

## Numerics
The trainer casts every tensor not in `preserve_dtype_keys` to `transfer_dtype` before the transfer; buffers and `preserve_dtype_params` keep their dtype. A dtype mismatch with the generator raises at init. The generator load is unchanged.

`scripts/rl/loss_compare.py` (Qwen3-0.6B, deterministic, seed 42, 10 steps) with this flag matches TorchStore exactly: `--assert-equal` passes on loss for all 10 steps.

## Performance
14B (29.6 GB bf16), one 8xB200 (183 GB) host with 8x400G NICs, trainer FSDP 4 (GPUs 0,2,3,4), one generator TP 2 (GPUs 5,6), 10 steps. Baseline: `main` 8a33dbf + TorchStore 804ae43 over NIXL.

| | TorchStore + NIXL | This PR (Mooncake) |
| --- | --- | --- |
| Generator pull | 10.0-13.2 s | 0.62-0.90 s |
|   of which RDMA read | 9-12 s | 0.20-0.35 s (~60 GB/s per generator rank, ~120 GB/s total) |
|   of which H2D load | - | 0.37-0.49 s |
| Trainer push | 3.2-4.0 s | 0.5-0.9 s |
|   blocking the trainer | 2.1-3.2 s | ~0 |
| Throughput | 60-74 tok/s | 610-880 tok/s |
| Peak GPU, trainer / generator | 85.0 / 37.4 GB | 78.3 / 37.4 GB |
| Peak RSS, trainer / generator | 10.4 / 38.6 GiB | 11.2 / 25.4 GiB |
| Init span | 63.3 s | 62.5 s |

Qwen3.5 27B (53.8 GB bf16) on MAST, 2 GB300 hosts (4 NICs each), DAPO-Math recipe: trainer FSDP 2 x TP 2 on one host, 4 TP 1 vLLM generators on the other (each pulls the full model), 6 steps of 4 prompts x 16 samples. Baseline: same recipe on TorchStore over NIXL. Pull times are for the slowest generator.

| | TorchStore + NIXL | This PR (Mooncake) | This PR (NIXL) |
| --- | --- | --- | --- |
| First pull | 22.5 s | 4.6 s | 0.95 s |
| Steady pulls (pulls 2-7) | 15.6-16.8 s | 2.2-2.8 s (fastest generator 1.2-1.4 s) | 0.96-1.08 s |
| Effective rate, all 4 generators | ~13 GB/s | 77-98 GB/s | ~200-225 GB/s (50-56 GB/s per generator) |
| Blocking pull / step time (steps 2-6) | 0.20-0.28 | 0-0.064 | 0-0.034 |
| tok/s full step, mean of steps 2-6 | 13.0k | 16.9k | 15.7k |
| Trainer model GPU memory | 31.75 GiB | 31.75 GiB | 31.75 GiB |
| Generator KV cache | 196.22 GiB | 196.22 GiB | 196.22 GiB |

The tok/s values vary with rollout length (baseline 7.8k-15.8k per step, Mooncake 11.2k-20.8k, NIXL 3.2k-20.1k). The MAST logs do not record host RSS.

The Mooncake numbers depend on pytorch/pytorch#203623 (poller race; without it the run hangs) and pytorch/pytorch#204113 (register host memory with a NUMA-detected location; without it numa1 buffers use numa0 NICs and the read takes 1.3-1.7 s).

## Size
Implementation +218/-18 (incl. 6 lines in `scripts/install_rl_env.sh`), docs +101/-8, tests +65 (a trainer test checking `forward_backward` and `push` stage once per optimizer step on the push stream from the actor thread and `push` synchronizes in a worker thread, plus a new attribute in existing tests); the unit tests in the previous PR cover the layout and read plan.

## Testing
- 10-step 14B runs on 8xB200 with both configurations (table above); the transport run completed with rc=0.
- 6-step 27B runs on MAST with all three configurations (table above); all completed 6 steps. The NIXL run used the same torch and this stack's `model_state_dict_transport.py`, nixl 1.5.0 over UCX with `UCX_NET_DEVICES` set to the 4 NICs, `UCX_TLS=rc,cuda_copy,self` and `UCX_MAX_RMA_RAILS=4`.
- Loss compare above on 8xB200 (TorchStore arm exported, transport arm imported with `--assert-equal`), on a revision whose `torchtitan/` code is identical to this stack (later changes are tests and docs only).
- The 14B runs used an earlier revision of this stack whose staging buffer used `pin_memory=True` (rounded up to a power of two) instead of cudaHostRegister; later review fixes (names, read timeout, hardcoded backend, docs/tests) do not change the transfer path. The 27B MAST run uses a revision with the same staging, read and stream-sync code, differing only in names, config plumbing and the generator-layout check, with torch 2.16.0.dev20261030+cu132 plus pytorch/pytorch#203623 and pytorch/pytorch#204113.
- `pytest tests/rl/unit_tests/cpu/{test_generator,test_model_state_dict_transport,test_trainer,test_engine_loop,test_async_controller,test_shutdown}.py` (188 pass).
- `pre-commit run` on the changed files passes (pyrefly skipped; it also fails on `main`).

## Known issues / follow-ups
- Only `model_state_dict_load_mode="cpu_prefetch"` is supported; `gpu_fetch` still needs TorchStore, so the TorchStore path stays until this covers it.
- The torch pinned by `scripts/install_rl_env.sh` (via vLLM, 2026-11-07) predates pytorch/pytorch#203623, so the stock env can time out on a read until the pin moves to 2026-11-10 or later.
- No CI job runs the flag end to end (it needs RDMA NICs); the unit tests cover the layout, read plan and trainer staging.
- Delta sync: stage and read only the changed pieces.
- The H2D load from the prefetch buffers (0.4 s) now dominates the pull.
- Restaging a tensor whose first sharded dim is not the outermost sharded mesh axis (e.g. MoE experts `(Shard(1), Shard(0))` -> `(Shard(0), Shard(0))`) can make DTensor gather it over that axis on the GPU during staging (untested at scale), costing transient memory at large EP.
- Reads per pull scale with keys x trainer ranks (one per contiguous run); a batched read upstream in `torch.distributed._transport` would cut the per-read overhead. Init metadata (every trainer rank's pieces for every generator rank) scales the same way.
- Every trainer DP rank keeps its own pinned staging copy of its shard; with replicated parameters (HSDP replicas, EP replicas of dense weights) this duplicates host memory across replicas.

AI-assisted (Claude).

ghstack-source-id: 92c1efb
Pull-Request: #5997
d4l3k added a commit that referenced this pull request Nov 11, 2026
…config flag

## 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
Wires the previous PR's `ModelStateDictTransport` into the RL loop as an opt-in replacement for TorchStore, so it can be rolled out per job. With 14B on one 8xB200 (183 GB) host it cuts the generator pull from 10-13 s to 0.6-0.9 s with pytorch/pytorch#204113 (1.7-2.35 s without it).

## What changed
- `Controller.Config.model_state_dict_transport: ModelStateDictTransport.Config | None`. None (the default) keeps TorchStore. Setting it requires `generator.model_state_dict_load_mode="cpu_prefetch"`, which is validated at config time.
- `ActorSystem.initialize_model_state_dict_transport` (Monarch impl): every generator reports its ranks' `shard_layout`s (which must match), the trainer ranks register staging buffers for it, and every generator rank connects and plans its reads.
- Trainer: staging (cast and restage on GPU, D2H into the staging buffer) runs on the push stream from the actor thread, once per optimizer step, by whichever of `push` and the next `forward_backward` reaches each rank first. Restaging is a collective, so this keeps it in the same order relative to training's collectives on every rank regardless of message order. `push` then awaits the stream in a worker thread.
- `scripts/install_rl_env.sh` installs `mooncake-transfer-engine-cuda13==0.3.14`, `nixl==1.5.0` and `nixl-cu13==1.5.0`.
- Generator prefetch: `read()` into the registered prefetch buffers replaces the TorchStore get. The load into the model is unchanged.
- `torchtitan/rl/MODEL_STATE_DICT_TRANSPORT.md`: layout diagram and lifecycle.

## User-facing changes
| Before | After |
| --- | --- |
| TorchStore only | `config.model_state_dict_transport = ModelStateDictTransport.Config(backend="mooncake" or "nixl")` |

## Numerics
The trainer casts every tensor not in `preserve_dtype_keys` to `transfer_dtype` before the transfer; buffers and `preserve_dtype_params` keep their dtype. A dtype mismatch with the generator raises at init. The generator load is unchanged.

`scripts/rl/loss_compare.py` (Qwen3-0.6B, deterministic, seed 42, 10 steps) with this flag matches TorchStore exactly: `--assert-equal` passes on loss for all 10 steps.

## Performance
14B (29.6 GB bf16), one 8xB200 (183 GB) host with 8x400G NICs, trainer FSDP 4 (GPUs 0,2,3,4), one generator TP 2 (GPUs 5,6), 10 steps. Baseline: `main` 8a33dbf + TorchStore 804ae43 over NIXL.

| | TorchStore + NIXL | This PR (Mooncake) |
| --- | --- | --- |
| Generator pull | 10.0-13.2 s | 0.62-0.90 s |
|   of which RDMA read | 9-12 s | 0.20-0.35 s (~60 GB/s per generator rank, ~120 GB/s total) |
|   of which H2D load | - | 0.37-0.49 s |
| Trainer push | 3.2-4.0 s | 0.5-0.9 s |
|   blocking the trainer | 2.1-3.2 s | ~0 |
| Throughput | 60-74 tok/s | 610-880 tok/s |
| Peak GPU, trainer / generator | 85.0 / 37.4 GB | 78.3 / 37.4 GB |
| Peak RSS, trainer / generator | 10.4 / 38.6 GiB | 11.2 / 25.4 GiB |
| Init span | 63.3 s | 62.5 s |

Qwen3.5 27B (53.8 GB bf16) on MAST, 2 GB300 hosts (4 NICs each), DAPO-Math recipe: trainer FSDP 2 x TP 2 on one host, 4 TP 1 vLLM generators on the other (each pulls the full model), 6 steps of 4 prompts x 16 samples. Baseline: same recipe on TorchStore over NIXL. Pull times are for the slowest generator.

| | TorchStore + NIXL | This PR (Mooncake) | This PR (NIXL) |
| --- | --- | --- | --- |
| First pull | 22.5 s | 4.6 s | 0.95 s |
| Steady pulls (pulls 2-7) | 15.6-16.8 s | 2.2-2.8 s (fastest generator 1.2-1.4 s) | 0.96-1.08 s |
| Effective rate, all 4 generators | ~13 GB/s | 77-98 GB/s | ~200-225 GB/s (50-56 GB/s per generator) |
| Blocking pull / step time (steps 2-6) | 0.20-0.28 | 0-0.064 | 0-0.034 |
| tok/s full step, mean of steps 2-6 | 13.0k | 16.9k | 15.7k |
| Trainer model GPU memory | 31.75 GiB | 31.75 GiB | 31.75 GiB |
| Generator KV cache | 196.22 GiB | 196.22 GiB | 196.22 GiB |

The tok/s values vary with rollout length (baseline 7.8k-15.8k per step, Mooncake 11.2k-20.8k, NIXL 3.2k-20.1k). The MAST logs do not record host RSS.

The Mooncake numbers depend on pytorch/pytorch#203623 (poller race; without it the run hangs) and pytorch/pytorch#204113 (register host memory with a NUMA-detected location; without it numa1 buffers use numa0 NICs and the read takes 1.3-1.7 s).

## Size
Implementation +218/-18 (incl. 6 lines in `scripts/install_rl_env.sh`), docs +101/-8, tests +65 (a trainer test checking `forward_backward` and `push` stage once per optimizer step on the push stream from the actor thread and `push` synchronizes in a worker thread, plus a new attribute in existing tests); the unit tests in the previous PR cover the layout and read plan.

## Testing
- 10-step 14B runs on 8xB200 with both configurations (table above); the transport run completed with rc=0.
- 6-step 27B runs on MAST with all three configurations (table above); all completed 6 steps. The NIXL run used the same torch and this stack's `model_state_dict_transport.py`, nixl 1.5.0 over UCX with `UCX_NET_DEVICES` set to the 4 NICs, `UCX_TLS=rc,cuda_copy,self` and `UCX_MAX_RMA_RAILS=4`.
- Loss compare above on 8xB200 (TorchStore arm exported, transport arm imported with `--assert-equal`), on a revision whose `torchtitan/` code is identical to this stack (later changes are tests and docs only).
- The 14B runs used an earlier revision of this stack whose staging buffer used `pin_memory=True` (rounded up to a power of two) instead of cudaHostRegister; later review fixes (names, read timeout, hardcoded backend, docs/tests) do not change the transfer path. The 27B MAST run uses a revision with the same staging, read and stream-sync code, differing only in names, config plumbing and the generator-layout check, with torch 2.16.0.dev20261030+cu132 plus pytorch/pytorch#203623 and pytorch/pytorch#204113.
- `pytest tests/rl/unit_tests/cpu/{test_generator,test_model_state_dict_transport,test_trainer,test_engine_loop,test_async_controller,test_shutdown}.py` (188 pass).
- `pre-commit run` on the changed files passes (pyrefly skipped; it also fails on `main`).

## Known issues / follow-ups
- Only `model_state_dict_load_mode="cpu_prefetch"` is supported; `gpu_fetch` still needs TorchStore, so the TorchStore path stays until this covers it.
- The torch pinned by `scripts/install_rl_env.sh` (via vLLM, 2026-11-07) predates pytorch/pytorch#203623, so the stock env can time out on a read until the pin moves to 2026-11-10 or later.
- No CI job runs the flag end to end (it needs RDMA NICs); the unit tests cover the layout, read plan and trainer staging.
- Delta sync: stage and read only the changed pieces.
- The H2D load from the prefetch buffers (0.4 s) now dominates the pull.
- Restaging a tensor whose first sharded dim is not the outermost sharded mesh axis (e.g. MoE experts `(Shard(1), Shard(0))` -> `(Shard(0), Shard(0))`) can make DTensor gather it over that axis on the GPU during staging (untested at scale), costing transient memory at large EP.
- Reads per pull scale with keys x trainer ranks (one per contiguous run); a batched read upstream in `torch.distributed._transport` would cut the per-read overhead. Init metadata (every trainer rank's pieces for every generator rank) scales the same way.
- Every trainer DP rank keeps its own pinned staging copy of its shard; with replicated parameters (HSDP replicas, EP replicas of dense weights) this duplicates host memory across replicas.

AI-assisted (Claude).

ghstack-source-id: 4c5d209
Pull-Request: #5997
d4l3k added a commit that referenced this pull request Nov 11, 2026
…config flag

## 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
Wires the previous PR's `ModelStateDictTransport` into the RL loop as an opt-in replacement for TorchStore, so it can be rolled out per job. With 14B on one 8xB200 (183 GB) host it cuts the generator pull from 10-13 s to 0.6-0.9 s with pytorch/pytorch#204113 (1.7-2.35 s without it).

## What changed
- `Controller.Config.model_state_dict_transport: ModelStateDictTransport.Config | None`. None (the default) keeps TorchStore. Setting it requires `generator.model_state_dict_load_mode="cpu_prefetch"`, which is validated at config time.
- `ActorSystem.initialize_model_state_dict_transport` (Monarch impl): every generator reports its ranks' `shard_layout`s (which must match), the trainer ranks register staging buffers for it, and every generator rank connects and plans its reads.
- Trainer: staging (cast and restage on GPU, D2H into the staging buffer) runs on the push stream from the actor thread, once per optimizer step, by whichever of `push` and the next `forward_backward` reaches each rank first. Restaging is a collective, so this keeps it in the same order relative to training's collectives on every rank regardless of message order. `push` then awaits the stream in a worker thread.
- `scripts/install_rl_env.sh` installs `mooncake-transfer-engine-cuda13==0.3.14`, `nixl==1.5.0` and `nixl-cu13==1.5.0`.
- Generator prefetch: `read()` into the registered prefetch buffers replaces the TorchStore get. The load into the model is unchanged.
- `torchtitan/rl/MODEL_STATE_DICT_TRANSPORT.md`: layout diagram and lifecycle.

## User-facing changes
| Before | After |
| --- | --- |
| TorchStore only | `config.model_state_dict_transport = ModelStateDictTransport.Config(backend="mooncake" or "nixl")` |

## Numerics
The trainer casts every tensor not in `preserve_dtype_keys` to `transfer_dtype` before the transfer; buffers and `preserve_dtype_params` keep their dtype. A dtype mismatch with the generator raises at init. The generator load is unchanged.

`scripts/rl/loss_compare.py` (Qwen3-0.6B, deterministic, seed 42, 10 steps) with this flag matches TorchStore exactly: `--assert-equal` passes on loss for all 10 steps.

## Performance
14B (29.6 GB bf16), one 8xB200 (183 GB) host with 8x400G NICs, trainer FSDP 4 (GPUs 0,2,3,4), one generator TP 2 (GPUs 5,6), 10 steps. Baseline: `main` 8a33dbf + TorchStore 804ae43 over NIXL.

| | TorchStore + NIXL | This PR (Mooncake) |
| --- | --- | --- |
| Generator pull | 10.0-13.2 s | 0.62-0.90 s |
|   of which RDMA read | 9-12 s | 0.20-0.35 s (~60 GB/s per generator rank, ~120 GB/s total) |
|   of which H2D load | - | 0.37-0.49 s |
| Trainer push | 3.2-4.0 s | 0.5-0.9 s |
|   blocking the trainer | 2.1-3.2 s | ~0 |
| Throughput | 60-74 tok/s | 610-880 tok/s |
| Peak GPU, trainer / generator | 85.0 / 37.4 GB | 78.3 / 37.4 GB |
| Peak RSS, trainer / generator | 10.4 / 38.6 GiB | 11.2 / 25.4 GiB |
| Init span | 63.3 s | 62.5 s |

Qwen3.5 27B (53.8 GB bf16) on MAST, 2 GB300 hosts (4 NICs each), DAPO-Math recipe: trainer FSDP 2 x TP 2 on one host, 4 TP 1 vLLM generators on the other (each pulls the full model), 6 steps of 4 prompts x 16 samples. Baseline: same recipe on TorchStore over NIXL. Pull times are for the slowest generator.

| | TorchStore + NIXL | This PR (Mooncake) | This PR (NIXL) |
| --- | --- | --- | --- |
| First pull | 22.5 s | 4.6 s | 0.95 s |
| Steady pulls (pulls 2-7) | 15.6-16.8 s | 2.2-2.8 s (fastest generator 1.2-1.4 s) | 0.96-1.08 s |
| Effective rate, all 4 generators | ~13 GB/s | 77-98 GB/s | ~200-225 GB/s (50-56 GB/s per generator) |
| Blocking pull / step time (steps 2-6) | 0.20-0.28 | 0-0.064 | 0-0.034 |
| tok/s full step, mean of steps 2-6 | 13.0k | 16.9k | 15.7k |
| Trainer model GPU memory | 31.75 GiB | 31.75 GiB | 31.75 GiB |
| Generator KV cache | 196.22 GiB | 196.22 GiB | 196.22 GiB |

The tok/s values vary with rollout length (baseline 7.8k-15.8k per step, Mooncake 11.2k-20.8k, NIXL 3.2k-20.1k). The MAST logs do not record host RSS.

The Mooncake numbers depend on pytorch/pytorch#203623 (poller race; without it the run hangs) and pytorch/pytorch#204113 (register host memory with a NUMA-detected location; without it numa1 buffers use numa0 NICs and the read takes 1.3-1.7 s).

## Size
Implementation +218/-18 (incl. 6 lines in `scripts/install_rl_env.sh`), docs +102/-8, tests +65 (a trainer test checking `forward_backward` and `push` stage once per optimizer step on the push stream from the actor thread and `push` synchronizes in a worker thread, plus a new attribute in existing tests); the unit tests in the previous PR cover the layout and read plan.

## Testing
- 10-step 14B runs on 8xB200 with both configurations (table above); the transport run completed with rc=0.
- 6-step 27B runs on MAST with all three configurations (table above); all completed 6 steps. The NIXL run used the same torch and this stack's `model_state_dict_transport.py`, nixl 1.5.0 over UCX with `UCX_NET_DEVICES` set to the 4 NICs, `UCX_TLS=rc,cuda_copy,self` and `UCX_MAX_RMA_RAILS=4`.
- Loss compare above on 8xB200 (TorchStore arm exported, transport arm imported with `--assert-equal`), on a revision whose `torchtitan/` code is identical to this stack (later changes are tests and docs only).
- The 14B runs used an earlier revision of this stack whose staging buffer used `pin_memory=True` (rounded up to a power of two) instead of cudaHostRegister; later review fixes (names, read timeout, hardcoded backend, docs/tests) do not change the transfer path. The 27B MAST run uses a revision with the same staging, read and stream-sync code, differing only in names, config plumbing and the generator-layout check, with torch 2.16.0.dev20261030+cu132 plus pytorch/pytorch#203623 and pytorch/pytorch#204113.
- `pytest tests/rl/unit_tests/cpu/{test_generator,test_model_state_dict_transport,test_trainer,test_engine_loop,test_async_controller,test_shutdown}.py` (188 pass).
- `pre-commit run` on the changed files passes (pyrefly skipped; it also fails on `main`).

## Known issues / follow-ups
- Only `model_state_dict_load_mode="cpu_prefetch"` is supported; `gpu_fetch` still needs TorchStore, so the TorchStore path stays until this covers it.
- The torch pinned by `scripts/install_rl_env.sh` (via vLLM, 2026-11-07) predates pytorch/pytorch#203623, so the stock env can time out on a read until the pin moves to 2026-11-10 or later.
- No CI job runs the flag end to end (it needs RDMA NICs); the unit tests cover the layout, read plan and trainer staging.
- Delta sync: stage and read only the changed pieces.
- The H2D load from the prefetch buffers (0.4 s) now dominates the pull.
- Restaging a tensor whose first sharded dim is not the outermost sharded mesh axis (e.g. MoE experts `(Shard(1), Shard(0))` -> `(Shard(0), Shard(0))`) can make DTensor gather it over that axis on the GPU during staging (untested at scale), costing transient memory at large EP.
- Reads per pull scale with keys x trainer ranks (one per contiguous run); a batched read upstream in `torch.distributed._transport` would cut the per-read overhead. Init metadata (every trainer rank's pieces for every generator rank) scales the same way.
- Every trainer DP rank keeps its own pinned staging copy of its shard; with replicated parameters (HSDP replicas, EP replicas of dense weights) this duplicates host memory across replicas.

AI-assisted (Claude).

ghstack-source-id: 95da8a1
Pull-Request: #5997
@d4l3k
d4l3k marked this pull request as ready for review November 11, 2026 20:31
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 11, 2026
d4l3k added a commit that referenced this pull request Nov 11, 2026
…config flag

## 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
Wires the previous PR's `ModelStateDictTransport` into the RL loop as an opt-in replacement for TorchStore, so it can be rolled out per job. With 14B on one 8xB200 (183 GB) host it cuts the generator pull from 10-13 s to 0.6-0.9 s with pytorch/pytorch#204113 (1.7-2.35 s without it).

## What changed
- `Controller.Config.model_state_dict_transport: ModelStateDictTransport.Config | None`. None (the default) keeps TorchStore. Setting it requires `generator.model_state_dict_load_mode="cpu_prefetch"`, which is validated at config time.
- `ActorSystem.initialize_model_state_dict_transport` (Monarch impl): every generator reports its ranks' `shard_layout`s (which must match), the trainer ranks register staging buffers for it, and every generator rank connects and plans its reads.
- Trainer: staging (cast and restage on GPU, D2H into the staging buffer) runs on the push stream from the actor thread, once per optimizer step, by whichever of `push` and the next `forward_backward` reaches each rank first. Restaging is a collective, so this keeps it in the same order relative to training's collectives on every rank regardless of message order. `push` then awaits the stream in a worker thread.
- `scripts/install_rl_env.sh` installs `mooncake-transfer-engine-cuda13==0.3.14`, `nixl==1.5.0` and `nixl-cu13==1.5.0`.
- Generator prefetch: `read()` into the registered prefetch buffers replaces the TorchStore get. The load into the model is unchanged.
- `torchtitan/rl/MODEL_STATE_DICT_TRANSPORT.md`: layout diagram and lifecycle.

## User-facing changes
| Before | After |
| --- | --- |
| TorchStore only | `config.model_state_dict_transport = ModelStateDictTransport.Config(backend="mooncake" or "nixl")` |

## Numerics
The trainer casts every tensor not in `preserve_dtype_keys` to `transfer_dtype` before the transfer; buffers and `preserve_dtype_params` keep their dtype. A dtype mismatch with the generator raises at init. The generator load is unchanged.

`scripts/rl/loss_compare.py` (Qwen3-0.6B, deterministic, seed 42, 10 steps) with this flag matches TorchStore exactly: `--assert-equal` passes on loss for all 10 steps.

## Performance
14B (29.6 GB bf16), one 8xB200 (183 GB) host with 8x400G NICs, trainer FSDP 4 (GPUs 0,2,3,4), one generator TP 2 (GPUs 5,6), 10 steps. Baseline: `main` 8a33dbf + TorchStore 804ae43 over NIXL.

| | TorchStore + NIXL | This PR (Mooncake) |
| --- | --- | --- |
| Generator pull | 10.0-13.2 s | 0.62-0.90 s |
|   of which RDMA read | 9-12 s | 0.20-0.35 s (~60 GB/s per generator rank, ~120 GB/s total) |
|   of which H2D load | - | 0.37-0.49 s |
| Trainer push | 3.2-4.0 s | 0.5-0.9 s |
|   blocking the trainer | 2.1-3.2 s | ~0 |
| Throughput | 60-74 tok/s | 610-880 tok/s |
| Peak GPU, trainer / generator | 85.0 / 37.4 GB | 78.3 / 37.4 GB |
| Peak RSS, trainer / generator | 10.4 / 38.6 GiB | 11.2 / 25.4 GiB |
| Init span | 63.3 s | 62.5 s |

Qwen3.5 27B (53.8 GB bf16) on MAST, 2 GB300 hosts (4 NICs each), DAPO-Math recipe: trainer FSDP 2 x TP 2 on one host, 4 TP 1 vLLM generators on the other (each pulls the full model), 6 steps of 4 prompts x 16 samples. Baseline: same recipe on TorchStore over NIXL. Pull times are for the slowest generator.

| | TorchStore + NIXL | This PR (Mooncake) | This PR (NIXL) |
| --- | --- | --- | --- |
| First pull | 22.5 s | 4.6 s | 0.95 s |
| Steady pulls (pulls 2-7) | 15.6-16.8 s | 2.2-2.8 s (fastest generator 1.2-1.4 s) | 0.96-1.08 s |
| Effective rate, all 4 generators | ~13 GB/s | 77-98 GB/s | ~200-225 GB/s (50-56 GB/s per generator) |
| Blocking pull / step time (steps 2-6) | 0.20-0.28 | 0-0.064 | 0-0.034 |
| tok/s full step, mean of steps 2-6 | 13.0k | 16.9k | 15.7k |
| Trainer model GPU memory | 31.75 GiB | 31.75 GiB | 31.75 GiB |
| Generator KV cache | 196.22 GiB | 196.22 GiB | 196.22 GiB |

The tok/s values vary with rollout length (baseline 7.8k-15.8k per step, Mooncake 11.2k-20.8k, NIXL 3.2k-20.1k). The MAST logs do not record host RSS.

The Mooncake numbers depend on pytorch/pytorch#203623 (poller race; without it the run hangs) and pytorch/pytorch#204113 (register host memory with a NUMA-detected location; without it numa1 buffers use numa0 NICs and the read takes 1.3-1.7 s).

## Size
Implementation +218/-18 (incl. 6 lines in `scripts/install_rl_env.sh`), docs +102/-8, tests +65 (a trainer test checking `forward_backward` and `push` stage once per optimizer step on the push stream from the actor thread and `push` synchronizes in a worker thread, plus a new attribute in existing tests); the unit tests in the previous PR cover the layout and read plan.

## Testing
- 10-step 14B runs on 8xB200 with both configurations (table above); the transport run completed with rc=0.
- 6-step 27B runs on MAST with all three configurations (table above); all completed 6 steps. The NIXL run used the same torch and this stack's `model_state_dict_transport.py`, nixl 1.5.0 over UCX with `UCX_NET_DEVICES` set to the 4 NICs, `UCX_TLS=rc,cuda_copy,self` and `UCX_MAX_RMA_RAILS=4`.
- Loss compare above on 8xB200 (TorchStore arm exported, transport arm imported with `--assert-equal`), on a revision whose `torchtitan/` code is identical to this stack (later changes are tests and docs only).
- The 14B runs used an earlier revision of this stack whose staging buffer used `pin_memory=True` (rounded up to a power of two) instead of cudaHostRegister; later review fixes (names, read timeout, hardcoded backend, docs/tests) do not change the transfer path. The 27B MAST run uses a revision with the same staging, read and stream-sync code, differing only in names, config plumbing and the generator-layout check, with torch 2.16.0.dev20261030+cu132 plus pytorch/pytorch#203623 and pytorch/pytorch#204113.
- `pytest tests/rl/unit_tests/cpu/{test_generator,test_model_state_dict_transport,test_trainer,test_engine_loop,test_async_controller,test_shutdown}.py` (188 pass).
- `pre-commit run` on the changed files passes (pyrefly skipped; it also fails on `main`).

## Known issues / follow-ups
- Only `model_state_dict_load_mode="cpu_prefetch"` is supported; `gpu_fetch` still needs TorchStore, so the TorchStore path stays until this covers it.
- The torch pinned by `scripts/install_rl_env.sh` (via vLLM, 2026-11-07) predates pytorch/pytorch#203623, so the stock env can time out on a read until the pin moves to 2026-11-10 or later.
- No CI job runs the flag end to end (it needs RDMA NICs); the unit tests cover the layout, read plan and trainer staging.
- Delta sync: stage and read only the changed pieces.
- The H2D load from the prefetch buffers (0.4 s) now dominates the pull.
- Restaging a tensor whose first sharded dim is not the outermost sharded mesh axis (e.g. MoE experts `(Shard(1), Shard(0))` -> `(Shard(0), Shard(0))`) can make DTensor gather it over that axis on the GPU during staging (untested at scale), costing transient memory at large EP.
- Reads per pull scale with keys x trainer ranks (one per contiguous run); a batched read upstream in `torch.distributed._transport` would cut the per-read overhead. Init metadata (every trainer rank's pieces for every generator rank) scales the same way.
- Every trainer DP rank keeps its own pinned staging copy of its shard; with replicated parameters (HSDP replicas, EP replicas of dense weights) this duplicates host memory across replicas.

AI-assisted (Claude).

ghstack-source-id: 1024af6
Pull-Request: #5997
@tushar00jain

tushar00jain commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Is all the setup happening in the beginning? I think @kapilsh mentioned we wanted to avoid this so that the trainer can start training without having to wait for all the generators. e.g. we could have the registration happened in parallel with training and only pause when the trainer needs the information to stage the tensors?

@felipemello1

Copy link
Copy Markdown
Contributor

from claude to felipe: a TLDR image of this PR, drawn from its diff at ca3fb54d2.

With the new model_state_dict_transport flag set, generators read the trainer's pinned staging buffers with one-sided RDMA reads instead of going through TorchStore, so a 14B pull on one 8xB200 host takes 0.62-0.90 s instead of 10.0-13.2 s, and the push blocks the trainer for about 0 s instead of 2.1-3.2 s.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 4m 37s —— View job


Approve (please fill in the human-written summary before merging); see the review.

Comment thread torchtitan/rl/trainer/trainer.py Outdated
Comment on lines +300 to +301
# Staging issues collectives: stage before this step's, whichever of
# this call and the push reaches each rank first.

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.

sorry sounds counter-intuitive --
from the controller code https://github.com/pytorch/torchtitan/blob/main/torchtitan/rl/controller/controller.py#L1317-L1390
why would one trainer rank get to push first and another get to fwd_bwd first? I thought there's barrier in between

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.

If Monarch guarantees in-order delivery per sender (please confirm), then _stage_model_state_dict() in forward_backward, the _model_state_dict_staged flag, and most of test_push_model_state_dict_stages_once_per_optimizer_step never run in practice. Delete them, or make the order explicit in the controller, as suggested in the last review. If Monarch doesn't guarantee that order, say so in the comment at trainer.py:300.

Makes sense. Actually, afaik, Monarch guarantees message order (cc @pzhan9), so let's try remove this _stage_model_state_dict call? Even if it doesn't guarantee, I personally would prefer we explicit set the order (by controller, see claude bot comment below) instead of making it flexible.

Comment thread torchtitan/rl/trainer/trainer.py Outdated
Comment on lines +495 to +497
stream = self._push_model_state_dict_stream
with stream if stream is not None else nullcontext():
self._model_state_dict_transport.stage(self._model_state_dict())

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.

just to double check: is it not possible that this code snippet is executed twice, one by each callsites?

Comment on lines +385 to +392
if (
self.model_state_dict_transport is not None
and self.generator.model_state_dict_load_mode != "cpu_prefetch"
):
raise ValueError(
"model_state_dict_transport requires "
'generator.model_state_dict_load_mode="cpu_prefetch"'
)

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.

can link to #6070

Comment thread torchtitan/rl/actors/monarch/system.py Outdated
for generator in self._generators
)
)
rank_layouts = shared_rank_layouts([list(r.values()) for r in results])

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.

Suggested change
rank_layouts = shared_rank_layouts([list(r.values()) for r in results])
generator_rank_layouts = shared_rank_layouts([list(r.values()) for r in results])

Comment on lines +525 to +529
def register_model_state_dict_source(
self,
config: ModelStateDictTransport.Config,
rank_layouts: list[dict[str, TensorShard]],
) -> TrainerSource:

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.

let's keep at most one positional arg, and use kwargs -- similar for other APIs

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve (please fill in the human-written summary and address @tianyu-l's comments before merging); see the 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 only commit since the last automated review (2653b2d) changes docs and the install_rl_env.sh comment in this PR; its code changes are in #5996. @tianyu-l's review from today came after that commit, so none of it is addressed yet.

Since the last review

  • Resolved: scripts/install_rl_env.sh:11 now explains why --no-deps is needed (nixl-cu13 requires torch, nixl requires nixl-cu12).
  • Resolved: @d4l3k answered @tushar00jain's question about deferring init (init takes ~10 s; overlap it later if it matters).
  • Still open: the "Summary (human-written)" section of the description is empty.

Must fix

  1. The description's "Summary (human-written)" is still empty.
  2. @tianyu-l's comments on trainer.py:301 and trainer.py:497 need replies. Answers from the code:
    • Can a rank get forward/backward before the push? There is no barrier between push N and forward/backward N+1. push_task is created at controller.py:1268 and not awaited. But it starts at the loop's next await (sync_log_step.call, controller.py:1156), and that is before forward_backward.call is sent at controller.py:1202. So the controller always sends the push to every rank first. The forward/backward branch only runs if Monarch delivers that later by_dp_rank message before the earlier all_ranks message. If Monarch guarantees in-order delivery per sender (please confirm), then _stage_model_state_dict() in forward_backward, the _model_state_dict_staged flag, and most of test_push_model_state_dict_stages_once_per_optimizer_step never run in practice. Delete them, or make the order explicit in the controller, as suggested in the last review. If Monarch doesn't guarantee that order, say so in the comment at trainer.py:300.
    • Can staging run twice? No. _stage_model_state_dict has no await, and both callers are async endpoints on the actor's event loop. Concurrent endpoints only interleave at awaits, so the flag check and self._model_state_dict_staged = True happen with no other endpoint in between.
  3. @tianyu-l's small edits are not applied yet:
    • controller.py:392: link #6070 from the cpu_prefetch check.
    • actors/monarch/system.py:227: rename rank_layouts to generator_rank_layouts.
    • trainer.py:529: allow at most one positional argument and pass the rest as keywords. This applies to register_model_state_dict_source (rank_layouts) and its actor endpoint, and to connect_model_state_dict_transport (sources), with their call sites in system.py.
Details
  • Initial push (controller.py:746) is awaited before training starts, and _model_state_dict_staged starts False, so the first push stages.
  • The doc rewrite in MODEL_STATE_DICT_TRANSPORT.md:216-227 (restage only when a trainer shard cuts a generator shard after the trainer's first sharded dim) matches the #5996 change. That code belongs to #5996, so it is not reviewed here.
  • The default-backend question (mooncake vs nixl) belongs to #5996.

Not verified: Monarch's per-sender message ordering across all_ranks and by_dp_rank slices. A maintainer still needs to review, since this touches the RL controller and trainer.

d4l3k added a commit that referenced this pull request Nov 13, 2026
…config flag

## 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
Wires the previous PR's `ModelStateDictTransport` into the RL loop as an opt-in replacement for TorchStore, so it can be rolled out per job. With 14B on one 8xB200 (183 GB) host it cuts the generator pull from 10-13 s to 0.6-0.9 s with pytorch/pytorch#204113 (1.7-2.35 s without it).

## What changed
- `Controller.Config.model_state_dict_transport: ModelStateDictTransport.Config | None`. None (the default) keeps TorchStore. Setting it requires `generator.model_state_dict_load_mode="cpu_prefetch"`, which is validated at config time.
- `ActorSystem.initialize_model_state_dict_transport` (Monarch impl): every generator reports its ranks' `shard_layout`s (which must match), the trainer ranks register staging buffers for it, and every generator rank connects and plans its reads.
- Trainer: staging (cast and, where needed, restage on GPU, D2H into the staging buffer) runs on the push stream from the actor thread, once per optimizer step, by whichever of `push` and the next `forward_backward` reaches each rank first. Restaging is a collective, so this keeps it in the same order relative to training's collectives on every rank regardless of message order. `push` then awaits the stream in a worker thread.
- `scripts/install_rl_env.sh` installs `mooncake-transfer-engine-cuda13==0.3.14`, `nixl==1.5.0` and `nixl-cu13==1.5.0` with `--no-deps` (nixl-cu13 requires torch).
- Generator prefetch: `read()` into the registered prefetch buffers replaces the TorchStore get. The load into the model is unchanged.
- `torchtitan/rl/MODEL_STATE_DICT_TRANSPORT.md`: layout diagram and lifecycle.

## User-facing changes
| Before | After |
| --- | --- |
| TorchStore only | `config.model_state_dict_transport = ModelStateDictTransport.Config(backend="mooncake" or "nixl")` |

## Numerics
The trainer casts every tensor not in `preserve_dtype_keys` to `transfer_dtype` before the transfer; buffers and `preserve_dtype_params` keep their dtype. A dtype mismatch with the generator raises at init. The generator load is unchanged.

`scripts/rl/loss_compare.py` (Qwen3-0.6B, deterministic, seed 42, 10 steps) with this flag matches TorchStore exactly: `--assert-equal` passes on loss for all 10 steps.

## Performance
14B (29.6 GB bf16), one 8xB200 (183 GB) host with 8x400G NICs, trainer FSDP 4 (GPUs 0,2,3,4), one generator TP 2 (GPUs 5,6), 10 steps. Baseline: `main` 8a33dbf + TorchStore 804ae43 over NIXL.

| | TorchStore + NIXL | This PR (Mooncake) |
| --- | --- | --- |
| Generator pull | 10.0-13.2 s | 0.62-0.90 s |
|   of which RDMA read | 9-12 s | 0.20-0.35 s (~60 GB/s per generator rank, ~120 GB/s total) |
|   of which H2D load | - | 0.37-0.49 s |
| Trainer push | 3.2-4.0 s | 0.5-0.9 s |
|   blocking the trainer | 2.1-3.2 s | ~0 |
| Throughput | 60-74 tok/s | 610-880 tok/s |
| Peak GPU, trainer / generator | 85.0 / 37.4 GB | 78.3 / 37.4 GB |
| Peak RSS, trainer / generator | 10.4 / 38.6 GiB | 11.2 / 25.4 GiB |
| Init span | 63.3 s | 62.5 s |

Qwen3.5 27B (53.8 GB bf16) on MAST, 2 GB300 hosts (4 NICs each), DAPO-Math recipe: trainer FSDP 2 x TP 2 on one host, 4 TP 1 vLLM generators on the other (each pulls the full model), 6 steps of 4 prompts x 16 samples. Baseline: same recipe on TorchStore over NIXL. Pull times are for the slowest generator.

| | TorchStore + NIXL | This PR (Mooncake) | This PR (NIXL) |
| --- | --- | --- | --- |
| First pull | 22.5 s | 4.6 s | 0.95 s |
| Steady pulls (pulls 2-7) | 15.6-16.8 s | 2.2-2.8 s (fastest generator 1.2-1.4 s) | 0.96-1.08 s |
| Effective rate, all 4 generators | ~13 GB/s | 77-98 GB/s | ~200-225 GB/s (50-56 GB/s per generator) |
| Blocking pull / step time (steps 2-6) | 0.20-0.28 | 0-0.064 | 0-0.034 |
| tok/s full step, mean of steps 2-6 | 13.0k | 16.9k | 15.7k |
| Trainer model GPU memory | 31.75 GiB | 31.75 GiB | 31.75 GiB |
| Generator KV cache | 196.22 GiB | 196.22 GiB | 196.22 GiB |

The tok/s values vary with rollout length (baseline 7.8k-15.8k per step, Mooncake 11.2k-20.8k, NIXL 3.2k-20.1k). The MAST logs do not record host RSS.

Trainer staging, same 27B runs (trainer rank 0). Staging runs on the push stream overlapped with the next `forward_backward`; the trainer blocks only on `push`'s wait (`timing/step/blocking_trainer_push_model_state_dict`). This layout (FSDP 2 x TP 2 -> TP 1) still restages row-parallel weights.

| | TorchStore + NIXL | This PR (Mooncake / NIXL) |
| --- | --- | --- |
| Trainer blocking per step | 0-3 ms | 0-3 ms |
| Full stage, not overlapped | 0.39-0.41 s | 0.12 s |
| `forward_backward` incl. overlapped staging | 44.8-45.3 s | 44.5-45.3 s |
| Init push | 2.19 s | 0.17-0.19 s |

The Mooncake numbers depend on pytorch/pytorch#203623 (poller race; without it the run hangs) and pytorch/pytorch#204113 (register host memory with a NUMA-detected location; without it numa1 buffers use numa0 NICs and the read takes 1.3-1.7 s).

## Size
Implementation +229/-18 (incl. 8 lines in `scripts/install_rl_env.sh`), docs +104/-8, tests +65 (a trainer test checking `forward_backward` and `push` stage once per optimizer step on the push stream from the actor thread and `push` synchronizes in a worker thread, plus a new attribute in existing tests); the unit tests in the previous PR cover the layout and read plan.

## Testing
- 10-step 14B runs on 8xB200 with both configurations (table above); the transport run completed with rc=0.
- 6-step 27B runs on MAST with all three configurations (table above); all completed 6 steps. The NIXL run used the same torch and this stack's `model_state_dict_transport.py`, nixl 1.5.0 over UCX with `UCX_NET_DEVICES` set to the 4 NICs, `UCX_TLS=rc,cuda_copy,self` and `UCX_MAX_RMA_RAILS=4`.
- Loss compare above on 8xB200 (TorchStore arm exported, transport arm imported with `--assert-equal`), on a revision whose `torchtitan/` code is identical to this stack (later changes are tests and docs only).
- The 14B runs used an earlier revision of this stack whose staging buffer used `pin_memory=True` (rounded up to a power of two) instead of cudaHostRegister; later review fixes (names, read timeout, hardcoded backend, docs/tests) do not change the transfer path. The 27B MAST run uses a revision with the same staging, read and stream-sync code, differing only in names, config plumbing and the generator-layout check, with torch 2.16.0.dev20261030+cu132 plus pytorch/pytorch#203623 and pytorch/pytorch#204113.
- `pytest tests/rl/unit_tests/cpu/{test_generator,test_model_state_dict_transport,test_trainer,test_engine_loop,test_async_controller,test_shutdown}.py` (188 pass).
- `pre-commit run` on the changed files passes (pyrefly skipped; it also fails on `main`).

## Known issues / follow-ups
- Only `model_state_dict_load_mode="cpu_prefetch"` is supported; `gpu_fetch` still needs TorchStore, so the TorchStore path stays until this covers it.
- The torch pinned by `scripts/install_rl_env.sh` (via vLLM, 2026-11-07) predates pytorch/pytorch#203623, so the stock env can time out on a read until the pin moves to 2026-11-10 or later.
- No CI job runs the flag end to end (it needs RDMA NICs); the unit tests cover the layout, read plan and trainer staging.
- Delta sync: stage and read only the changed pieces.
- The H2D load from the prefetch buffers (0.4 s) now dominates the pull.
- Restaging a tensor whose first sharded dim is not the outermost sharded mesh axis (e.g. MoE experts `(Shard(1), Shard(0))` -> `(Shard(0), Shard(0))`) can make DTensor gather it over that axis on the GPU during staging (untested at scale), costing transient memory at large EP.
- Reads per pull scale with keys x trainer ranks (one per contiguous run); a batched read upstream in `torch.distributed._transport` would cut the per-read overhead. Init metadata (every trainer rank's pieces for every generator rank) scales the same way.
- Every trainer DP rank keeps its own pinned staging copy of its shard; with replicated parameters (HSDP replicas, EP replicas of dense weights) this duplicates host memory across replicas.

AI-assisted (Claude).

ghstack-source-id: c360b8f
Pull-Request: #5997

@tianyu-l tianyu-l 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.

one more comment, o/w LGTM

Comment thread torchtitan/rl/actors/monarch/system.py Outdated
generator_rank_layouts = shared_rank_layouts(
[list(r.values()) for r in results]
)
sources = list(

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.

nit

Suggested change
sources = list(
trainer_sources = list(

Comment thread torchtitan/rl/generator/generator.py Outdated
self,
config: ModelStateDictTransport.Config,
*,
sources: list[TrainerSource],

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.

Suggested change
sources: list[TrainerSource],
trainer_sources: list[TrainerSource],

Comment thread torchtitan/rl/trainer/trainer.py Outdated
Comment on lines +300 to +301
# Staging issues collectives: stage before this step's, whichever of
# this call and the push reaches each rank first.

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.

If Monarch guarantees in-order delivery per sender (please confirm), then _stage_model_state_dict() in forward_backward, the _model_state_dict_staged flag, and most of test_push_model_state_dict_stages_once_per_optimizer_step never run in practice. Delete them, or make the order explicit in the controller, as suggested in the last review. If Monarch doesn't guarantee that order, say so in the comment at trainer.py:300.

Makes sense. Actually, afaik, Monarch guarantees message order (cc @pzhan9), so let's try remove this _stage_model_state_dict call? Even if it doesn't guarantee, I personally would prefer we explicit set the order (by controller, see claude bot comment below) instead of making it flexible.

…kward; trainer_sources rename

[ghstack-poisoned]
d4l3k added a commit that referenced this pull request Nov 13, 2026
…config flag

## 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
Wires the previous PR's `ModelStateDictTransport` into the RL loop as an opt-in replacement for TorchStore, so it can be rolled out per job. With 14B on one 8xB200 (183 GB) host it cuts the generator pull from 10-13 s to 0.6-0.9 s with pytorch/pytorch#204113 (1.7-2.35 s without it).

## What changed
- `Controller.Config.model_state_dict_transport: ModelStateDictTransport.Config | None`. None (the default) keeps TorchStore. Setting it requires `generator.model_state_dict_load_mode="cpu_prefetch"`, which is validated at config time.
- `ActorSystem.initialize_model_state_dict_transport` (Monarch impl): every generator reports its ranks' `shard_layout`s (which must match), the trainer ranks register staging buffers for it, and every generator rank connects and plans its reads.
- Trainer: `push` stages (cast and, where needed, restage on GPU, D2H into the staging buffer) on the push stream from the actor thread before its first `await`, then awaits the stream in a worker thread. Restaging is a collective, so the controller sends the push before the next `forward_backward`; Monarch starts concurrent endpoints from one sender in send order, so every rank stages before its training collectives.
- `scripts/install_rl_env.sh` installs `mooncake-transfer-engine-cuda13==0.3.14`, `nixl==1.5.0` and `nixl-cu13==1.5.0` with `--no-deps` (nixl-cu13 requires torch).
- Generator prefetch: `read()` into the registered prefetch buffers replaces the TorchStore get. The load into the model is unchanged.
- `torchtitan/rl/MODEL_STATE_DICT_TRANSPORT.md`: layout diagram and lifecycle.

## User-facing changes
| Before | After |
| --- | --- |
| TorchStore only | `config.model_state_dict_transport = ModelStateDictTransport.Config(backend="mooncake" or "nixl")` |

## Numerics
The trainer casts every tensor not in `preserve_dtype_keys` to `transfer_dtype` before the transfer; buffers and `preserve_dtype_params` keep their dtype. A dtype mismatch with the generator raises at init. The generator load is unchanged.

`scripts/rl/loss_compare.py` (Qwen3-0.6B, deterministic, seed 42, 10 steps) with this flag matches TorchStore exactly: `--assert-equal` passes on loss for all 10 steps.

## Performance
14B (29.6 GB bf16), one 8xB200 (183 GB) host with 8x400G NICs, trainer FSDP 4 (GPUs 0,2,3,4), one generator TP 2 (GPUs 5,6), 10 steps. Baseline: `main` 8a33dbf + TorchStore 804ae43 over NIXL.

| | TorchStore + NIXL | This PR (Mooncake) |
| --- | --- | --- |
| Generator pull | 10.0-13.2 s | 0.62-0.90 s |
|   of which RDMA read | 9-12 s | 0.20-0.35 s (~60 GB/s per generator rank, ~120 GB/s total) |
|   of which H2D load | - | 0.37-0.49 s |
| Trainer push | 3.2-4.0 s | 0.5-0.9 s |
|   blocking the trainer | 2.1-3.2 s | ~0 |
| Throughput | 60-74 tok/s | 610-880 tok/s |
| Peak GPU, trainer / generator | 85.0 / 37.4 GB | 78.3 / 37.4 GB |
| Peak RSS, trainer / generator | 10.4 / 38.6 GiB | 11.2 / 25.4 GiB |
| Init span | 63.3 s | 62.5 s |

Qwen3.5 27B (53.8 GB bf16) on MAST, 2 GB300 hosts (4 NICs each), DAPO-Math recipe: trainer FSDP 2 x TP 2 on one host, 4 TP 1 vLLM generators on the other (each pulls the full model), 6 steps of 4 prompts x 16 samples. Baseline: same recipe on TorchStore over NIXL. Pull times are for the slowest generator.

| | TorchStore + NIXL | This PR (Mooncake) | This PR (NIXL) |
| --- | --- | --- | --- |
| First pull | 22.5 s | 4.6 s | 0.95 s |
| Steady pulls (pulls 2-7) | 15.6-16.8 s | 2.2-2.8 s (fastest generator 1.2-1.4 s) | 0.96-1.08 s |
| Effective rate, all 4 generators | ~13 GB/s | 77-98 GB/s | ~200-225 GB/s (50-56 GB/s per generator) |
| Blocking pull / step time (steps 2-6) | 0.20-0.28 | 0-0.064 | 0-0.034 |
| tok/s full step, mean of steps 2-6 | 13.0k | 16.9k | 15.7k |
| Trainer model GPU memory | 31.75 GiB | 31.75 GiB | 31.75 GiB |
| Generator KV cache | 196.22 GiB | 196.22 GiB | 196.22 GiB |

The tok/s values vary with rollout length (baseline 7.8k-15.8k per step, Mooncake 11.2k-20.8k, NIXL 3.2k-20.1k). The MAST logs do not record host RSS.

Trainer staging, same 27B runs (trainer rank 0). Staging runs on the push stream overlapped with the next `forward_backward`; the trainer blocks only on `push`'s wait (`timing/step/blocking_trainer_push_model_state_dict`). This layout (FSDP 2 x TP 2 -> TP 1) still restages row-parallel weights.

| | TorchStore + NIXL | This PR (Mooncake / NIXL) |
| --- | --- | --- |
| Trainer blocking per step | 0-3 ms | 0-3 ms |
| Full stage, not overlapped | 0.39-0.41 s | 0.12 s |
| `forward_backward` incl. overlapped staging | 44.8-45.3 s | 44.5-45.3 s |
| Init push | 2.19 s | 0.17-0.19 s |

The Mooncake numbers depend on pytorch/pytorch#203623 (poller race; without it the run hangs) and pytorch/pytorch#204113 (register host memory with a NUMA-detected location; without it numa1 buffers use numa0 NICs and the read takes 1.3-1.7 s).

## Size
Implementation +230/-22 (incl. 8 lines in `scripts/install_rl_env.sh`), docs +104/-8, tests +46 (a trainer test checking `push` stages on the push stream from the actor thread before its first `await` and synchronizes in a worker thread, plus a new attribute in existing tests); the unit tests in the previous PR cover the layout and read plan.

## Testing
- 10-step 14B runs on 8xB200 with both configurations (table above); the transport run completed with rc=0.
- 6-step 27B runs on MAST with all three configurations (table above); all completed 6 steps. The NIXL run used the same torch and this stack's `model_state_dict_transport.py`, nixl 1.5.0 over UCX with `UCX_NET_DEVICES` set to the 4 NICs, `UCX_TLS=rc,cuda_copy,self` and `UCX_MAX_RMA_RAILS=4`.
- Loss compare above on 8xB200 (TorchStore arm exported, transport arm imported with `--assert-equal`), on a revision whose `torchtitan/` code is identical to this stack (later changes are tests and docs only).
- The 14B runs used an earlier revision of this stack whose staging buffer used `pin_memory=True` (rounded up to a power of two) instead of cudaHostRegister; later review fixes (names, read timeout, hardcoded backend, docs/tests) do not change the transfer path. The 27B MAST run uses a revision with the same staging, read and stream-sync code, differing only in names, config plumbing and the generator-layout check, with torch 2.16.0.dev20261030+cu132 plus pytorch/pytorch#203623 and pytorch/pytorch#204113.
- `pytest tests/rl/unit_tests/cpu/{test_generator,test_model_state_dict_transport,test_trainer,test_engine_loop,test_async_controller,test_shutdown}.py` (188 pass).
- `pre-commit run` on the changed files passes (pyrefly skipped; it also fails on `main`).

## Known issues / follow-ups
- Only `model_state_dict_load_mode="cpu_prefetch"` is supported; `gpu_fetch` still needs TorchStore, so the TorchStore path stays until this covers it.
- The torch pinned by `scripts/install_rl_env.sh` (via vLLM, 2026-11-07) predates pytorch/pytorch#203623, so the stock env can time out on a read until the pin moves to 2026-11-10 or later.
- No CI job runs the flag end to end (it needs RDMA NICs); the unit tests cover the layout, read plan and trainer staging.
- Delta sync: stage and read only the changed pieces.
- The H2D load from the prefetch buffers (0.4 s) now dominates the pull.
- Restaging a tensor whose first sharded dim is not the outermost sharded mesh axis (e.g. MoE experts `(Shard(1), Shard(0))` -> `(Shard(0), Shard(0))`) can make DTensor gather it over that axis on the GPU during staging (untested at scale), costing transient memory at large EP.
- Reads per pull scale with keys x trainer ranks (one per contiguous run); a batched read upstream in `torch.distributed._transport` would cut the per-read overhead. Init metadata (every trainer rank's pieces for every generator rank) scales the same way.
- Every trainer DP rank keeps its own pinned staging copy of its shard; with replicated parameters (HSDP replicas, EP replicas of dense weights) this duplicates host memory across replicas.

AI-assisted (Claude).

ghstack-source-id: 7d03b40
Pull-Request: #5997
[ghstack-poisoned]
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).
@d4l3k
d4l3k changed the base branch from gh/d4l3k/7/base to main November 13, 2026 23:57
@d4l3k
d4l3k merged commit 631d544 into main Nov 14, 2026
d4l3k added a commit that referenced this pull request Nov 17, 2026
…6097)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.18.0)
(oldest at bottom):
* __->__ #6097
* #5997


## 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
#5997 restages each DTensor on
the trainer (a redistribute collective per tensor) whenever a staged
piece would not be a contiguous run of the generator shard, e.g. a
row-parallel weight read by generator ranks split on dim 0. Scalability
concern:
#5996 (comment)
(tracked in #6096). This is
the third option from
#5996 (comment):
an intermediate buffer on the generator side.

## What changed
- `_plan_reads`: each piece is one read into the key's prefetch buffer,
at consecutive offsets in piece offset order. A key stays in place iff
every piece is one contiguous run of the generator shard; otherwise it
is packed.
- New `copy_prefetched_` (called by
`Generator._copy_prefetched_model_state_dict`): plain keys copy as
before; packed keys copy each piece into place (async H2D, one stream
sync per call before the next read can reuse the buffers).
- Trainer: `stage()` only casts and copies local shards;
`_staged_placements` and the redistribute are removed, so staging has no
collectives.
- Doc updated.

No extra bytes are read: each piece is still read exactly once. The cost
moves to a strided copy per packed piece at load.

Lines: implementation +137/-168, tests +32/-37.

Test plan:
- `pytest tests/rl/unit_tests/cpu/test_model_state_dict_transport.py
tests/rl/unit_tests/cpu/test_trainer.py`: 35 passed. `_transfer` now
loads through `copy_prefetched_`; `TestStageDTensors.test_fsdp_tp_to_tp`
checks which keys are packed for two generator layouts.
- Disabling the packed branch fails `test_stacked_pieces` (3 cases) and
`test_fsdp_tp_to_tp`.
- Random fuzz (400 1-4D shapes, random trainer/generator grid
partitions) through `_plan_reads`/`read`/`copy_prefetched_`: values
match; packed classification matches a brute-force contiguity check.
- GB200: packed `[2, 4096, 2048]` bf16 key in 4 pieces loads in ~0.18 ms
(vs 0.11 ms unpacked); overwriting the prefetch buffer right after
`copy_prefetched_` leaves the result intact (fails without the sync).
- Full RL CPU suite: same failures as the parent PR (env: vllm/monarch).
- Memory/perf bench (`ModelStateDictTransport` only, no RL loop;
Llama3-8B shapes, 32 layers, fp32 trainer DTensors with the torchtitan
FSDP+TP plan, bf16 generator, NIXL, median of 5 iterations, max over
ranks, 0 mismatched keys everywhere). Reads are single-host UCX loopback
(`UCX_TLS=rc,sm,self,cuda_copy`) on shared GPUs, so read times are not
representative of cross-host RDMA. 8x B200, trainer FSDP 4 x TP 2:

| generator | embed/output | version | reads | stage ms | stage GPU peak
| read ms | load ms | load GPU peak |
|---|---|---|---|---|---|---|---|---|
| 8 x TP1 | yes | #5997 | 2068 | 66 | 136 MB | 2430 | 519 | 0 |
| 8 x TP1 | yes | this PR | 2068 | 82 | 136 MB | 2470 | 367 | 15 MB |
| 8 x TP1 | no | #5997 | 2052 | 59 | 59 MB | 2230 | 446 | 0 |
| 8 x TP1 | no | this PR | 2052 | 59 | 29 MB | 2120 | 466 | 15 MB |
| 1 x 8 ranks, dim 0 | yes | #5997 | 291 | 58 | 136 MB | 203 | 79 | 0 |
| 1 x 8 ranks, dim 0 | yes | this PR | 355 | 65 | 146 MB | 270 | 82 | 7
MB |
| 1 x 8 ranks, dim 0 | no | #5997 | 289 | 70 | 59 MB | 226 | 82 | 0 |
| 1 x 8 ranks, dim 0 | no | this PR | 353 | 47 | 29 MB | 166 | 51 | 7 MB
|

- Trainer: the restage temp is gone (stage peak 59 -> 29 MB without
embeddings); with embeddings both are bound by the embedding/output
cast. Staging buffer size is unchanged.
- Generator: load adds a GPU temp of the largest packed piece (7-15 MB
here, 29-59 MB on 2x GB200 TP 2). No extra CPU memory.
- Reads: same count for TP1 generators; +22% (291 -> 355) for dim-0
generators, since pieces of row-parallel weights are no longer merged by
the restage. Bytes read are unchanged.
- Times: differences are within run-to-run noise (2x GB200 dim-0 stage
repeated 75-234 ms on #5997). 2x GB200 TP 2 showed the same pattern.
tianyu-l added a commit that referenced this pull request Nov 26, 2026
…er override; agent self-review; rl/transport (#6407)

## 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

Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it
approved,
30 then got a formal "request changes" from a maintainer, and about 20
more got
substantive inline asks. In nearly all of them the bot either saw the
problem
and approved anyway, or never asked the questions maintainers ask most
("does
the repo already do this?", "who should own this?"). The opposite
failure, the
bot blocking something a maintainer was fine with, is rare: in the PRs
we
sampled, 2 of its 81 must-fix items were wrong and about a third were
minor
(the empty human-written summary was the biggest source).

**Example** (#6112, controller sizes the rollout worker pool):

```
before: bot approved 10 times; tianyu-l then blocked: "the controller reads
        rollouter.rollouts_per_worker to compute a count it hands back to the
        Rollouter -- violates encapsulation"
after:  same commit, new skill -> Request changes, must-fix #1:
        "controller.py:589 -- wrong owner for the worker count ..."
```

There was also no way for a code owner to overrule the bot except
dismissing
its review in the GitHub UI, and a later `@claude review again` would
block
again.

## What changed

**Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`):
- Verdict rules: Approve only when every remaining item is an edit the
bot
could write itself. Anything the author still owes (a design change, an
unexplained golden change, evidence the PR rests on) is Request changes;
anything only a maintainer can decide is Needs discussion. A hedge like
"a
  maintainer should decide" can't come with Approve.
- Always must-fix: a violated written rule, a silent wrong result, a
second
  definition of an existing concept, a gate finding.
- Design gate: new questions for the existing counterpart, in-repo
ownership,
and the design behind a bug; "ban only what doesn't work on main"; read
the
numbers behind a claim. The overlapping-PR search is mandatory and
reported.
- Re-review covers every commit since the last full review, including
code
taken from the bot's own suggestions. A scoped question gets a
`COMMENT`, not
  a whole-PR verdict.
- The bot fact-checks its own proposed fixes, and cites a source for
claims
  about external tools or marks them unverified (never must-fix).
- An empty "Summary (human-written)" is a one-line "Before merge" note
that
  never affects the verdict.
- Checklist: config ownership direction, general shared wrappers, dead
code the
PR creates, model variants as flavors, a mechanical pass over every new
or
  changed function.

**Code owner override** (`SKILL.md`, `claude-code.yml`,
`CONTRIBUTING.md`): a
code owner comments `@claude override` (optionally `@claude override
2,3:
<reason>`); the bot approves if nothing else is open and doesn't
re-raise the
overridden items. A code owner's GitHub approval or "LGTM" is not an
override,
so a teammate can approve without the bot dropping its findings.
Dismissing the
bot's review still unblocks the PR, but isn't an override: the bot can't
tell
who dismissed it.

**Agent self-review** (`CLAUDE.md`, `pr-description`): an agent
preparing a PR
runs `pr-review` in branch mode first and records unaddressed items in
an
optional "Self-review" section. PRs written without an agent are
unaffected; a
missing section is never a finding.

Where each new rule comes from (maintainer asks the bot missed):

| Change | PRs |
| --- | --- |
| No Approve with open design/evidence items or a "maintainer should
decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 |
| Author waiver can't clear a must-fix | #6201, #6202, #6203 |
| Existing counterpart; one source of truth | #5228, #6169, #5881,
#5823, #5824, #6059, #5812 |
| Responsibility owner; config ownership direction | #6112, #6332,
#5802, #5803, #6325 |
| Fix the design behind the bug; a TODO doesn't justify a workaround |
#5572, #5689, #5657 |
| Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819,
#5543 |
| Re-review covers all new commits; scoped asks don't approve | #5824,
#5842 |
| Mandatory overlap search | #5885, #6248 |
| Ban only what doesn't work on main | #5543 |
| Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868
|

**Rules**: `design.md` gets the one-general-wrapper rule (moved from
`models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the
consumer owning its values; `config.md` gets ownership direction and "a
Config
doesn't read runtime state"; `direction.md` calls all-to-all the MoE
reference
implementation, so a new vendor-specific dispatch path (e.g. #6242)
needs a
reason the existing backends can't serve.

**Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/`
-> d4l3k.

**Mechanical, skim**: `torchtitan/rl/transport/` holds data movement
between RL
actors.
- `rl/model_state_dict_transport.py` ->
`rl/transport/model_state_dict.py`
- `rl/MODEL_STATE_DICT_TRANSPORT.md` ->
`rl/transport/MODEL_STATE_DICT_TRANSPORT.md`
- `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py`
- tests:
`tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py`
->
`tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py`
- imports, READMEs and `scripts/install_rl_env.sh` updated; no code
changes.

## User-facing changes

| Before | After |
| --- | --- |
| Overrule the bot: dismiss its review in the UI, and it blocks again on
the next run | `@claude override [items]: <reason>`; the bot approves
and doesn't re-raise them |
| Empty human-written summary: bot must-fix | One "Before merge" line,
no effect on the verdict |
| `from torchtitan.rl.model_state_dict_transport import ...` | `from
torchtitan.rl.transport.model_state_dict import ...` |
| `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from
torchtitan.rl.transport.rdma_microbatch import ...` |

## Testing

Backtest: the new skill run locally (nothing posted) on each PR at the
commit
and thread state the bot originally saw.

| PR | Bot then | New skill | What the maintainer asked |
| --- | --- | --- | --- |
| #6112 | Approve | Request changes | worker-count ownership (caught) |
| #5837 | Approve | Request changes | apply to `dp_shard` too (caught) |
| #5572 | Approve | Request changes | delete the injection design
(caught) |
| #6201 | Approve after author waived pins | Request changes, waiver
ignored | pins broke GPU tests after merge (caught) |
| #6007 | Approve | Request changes | fold K3.1 into K3 (caught) |
| #5543 | Request changes: "ban it" | Request changes: keep main's path
| don't break gpt-oss + DeepEP (fixed) |
| #6144, #5905 (controls) | Approve | Approve | -- |
| #6137 (control) | Approve | Needs discussion | -- (merge gate on an
upstream API) |

Code owner override, simulated on #6201: override by a code owner lifts
the
named item; `@claude override` from the author changes nothing; a code
owner's
"LGTM" approval followed by "review again" keeps Request changes.

Transport move: 83 RL CPU unit tests pass locally
(`transport/test_model_state_dict.py`, `test_trainer.py`,
`test_engine_loop.py`). `transport/test_rdma_microbatch.py`,
`test_generator.py` and
`test_batcher_actor.py` fail to collect in my env on `origin/main` too
(stale
attention-gym / Monarch), so CI is the check for those.

## Known issues / follow-ups
- Open PRs that edit the moved files rebase cleanly (git follows the
renames),
but new imports of the old module paths will break: #6309 (adds a delta
transport that should live in `rl/transport/`), #6237, #6176, #6177,
#5862,
  and drafts #6127, #6393, #6163, #5764.
- The Actions bot can't read dependency source (e.g. SGLang); follow-up
for the
  workflow.

## Self-review
pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch
mode diffs
against `origin/main` and skips description findings before a
description
exists; the "Config doesn't read runtime state" rule no longer
contradicts
hardware validation; dismissal dropped as an override form (the bot
can't tell
who dismissed); `test_rdma_microbatch.py` added to the transport area.
Not
addressed:
- One concern per PR -- the five changes ship together at the
maintainer's
  request.
- Open PRs touching the moved files -- listed above; the maintainer will
  coordinate.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

5 participants