Repository navigation
[WIP][rl] One RDMA object for microbatches and prompts; rollout workers send images as RDMA handles - #5862
[WIP][rl] One RDMA object for microbatches and prompts; rollout workers send images as RDMA handles#5862wwwjn wants to merge 1 commit into
Conversation
pzhan9
left a comment
There was a problem hiding this comment.
overall lgtm.
Please review the PR carefully to ensure the RDMABuffer lifetime is managed correctly, and we will not have orphan buffers on the sender side.
| sampling.stop_token_ids is not None | ||
| ), f"{request_id}: stop_token_ids must be set from the renderer" | ||
| if isinstance(prompt, RDMAObject): | ||
| prompt = await prompt.read() |
There was a problem hiding this comment.
edit: You probably can delay the read after it is gloo broadcasted to other ranks. Then it will be more optimal. I take this back. Actually broadcast the RDMABuffer to other ranks would mean they need fetch from controller independently. That might be worse, if the ranks are on the same host.
There was a problem hiding this comment.
Thanks, I will keep the current place of read
| sent: Prompt | RDMAObject[Prompt] = prompt | ||
| if min_bytes is not None and prompt.token_ids.nbytes >= min_bytes: | ||
| assert self._register_rdma_object is not None | ||
| sent = self._register_rdma_object(prompt, min_bytes=min_bytes) |
There was a problem hiding this comment.
Should ask your agent to run some micro benches for places this PR coverts to opt in RDMABuffer, just to make sure we do not accidentally make things slower.
| try: | ||
| completion = await self.generate_fn( | ||
| prompt_token_ids, | ||
| Prompt(token_ids=np.asarray(prompt_token_ids, dtype=np.int32)), |
There was a problem hiding this comment.
We could use RDMA here too, right? Then we can change Generator.generate's signature to prompt: RDMAObject[Prompt],, instead of prompt: Prompt | RDMAObject[Prompt].
Basically we always wrap Prompt with RDMAObject, but whether it uses RDMABuffer internally is still optional.
|
This PR is currently not doing "register once, and passing handler everywhere" idea. Need another update and take care of the release of the handler |
1d1bbe9 to
7451a05
Compare
7451a05 to
68c52d7
Compare
|
@claude review |
|
Claude finished @tianyu-l's task in 3m 50s —— View job Request changes -- see the review (if that link doesn't open the review, it is the latest review on the Files changed tab). |
There was a problem hiding this comment.
Verdict: Request changes -- #5824 has merged, so this branch conflicts with main's Prompt. And the per-call register/drop lifetime is the design you said yourself still needs reworking.
What this PR does. It puts the batcher's RDMA microbatch and a new RDMA prompt behind one framework-agnostic RDMAObject[T], implemented by MonarchRDMAObject, which walks dataclass and pytree leaves. It adds an opt-in RolloutWorker.Config.rdma_min_prompt_bytes. With it set, the worker registers a long prompt before each generate_fn call, so only a handle goes through the router, and generator rank 0 reads the token ids from the worker. The worker drops the buffers when the call returns. The microbatch path keeps the same buffers and reads, and the PR shows bitwise-identical loss and grad_norm.
Example. A group of 8 siblings with one shared 16K-token first-turn prompt, 3 turns each:
main: 24 generate calls, each sends its prompt by value through worker -> router -> generator
this PR: 24 register + 24 RDMA reads + 24 drops; the shared first-turn prompt is registered 8 times,
and each later turn registers its full growing prompt again
intended: register the shared payload once per group, pass the handle everywhere, drop in run_group
Must fix
torchtitan/rl/rollout/types.py:32-- #5824 merged and added its ownPrompt(token_ids: list[int], images,__post_init__). This branch conflicts, and itsnp.ndarrayPromptis a second definition. The rebase has to choose between array token ids and sending only image bytes by RDMA. The "Follow-up (#5824)" section of the description is out of date.torchtitan/rl/rollout/rollouter.py:602-- the handle lifetime is one call. Siblings and turns re-register the same data, and with images each one copies the image bytes. Register once per group and drop inrun_group'sfinally. This is your own open comment.torchtitan/rl/generator/generator.py:413-- pzhan9's two comments are unaddressed: always passRDMAObject[Prompt](generation_server.py:216), which removes the union from six signatures plus theisinstancebranches, and run microbenchmarks (rollouter.py:604). There are no timings for the knob, and none for the default path's new list -> int32 array -> list conversion on every turn.
Should consider
torchtitan/rl/actors/monarch/rollout_worker.py:48-- 4 workers by default x ~256 MiB of CUDA context on the controller host's GPU 0, spent only to silence a log line. State the total in the docstring, or drop it.tests/rl/unit_tests/cpu/test_rdma_object.py:271-- the validation-only test and the router and generator unit tests are covered by the end-to-end Monarch test. Delete them.
Questions
- For token-only prompts (64 KiB at 16K tokens), is there any setting where an extra RDMA round trip from generator rank 0 back to the controller host beats two by-value hops? If not, should the knob cover only image bytes, so a user knows how to set it?
Details
- Gate: putting RDMA registration in the rollout worker instead of the controller follows tianyu-l's #5824 comments, and the framework-agnostic protocol in
rl/actors/rdma.pywith the Monarch code inactors/monarch/follows the ownership rules. The parts in question are the lifetime model and the value of RDMA for token ids alone. Both have to be decided again after the rebase onto main's imagePrompt. - The
RDMAMicrobatchrefactor (trainer/rdma_microbatch.py,trainer/batcher.py,actors/monarch/batcher.py) is mechanical and keeps the same buffer and read behavior. The bitwise numerics in the description cover it. _map_leavesrebuilds dataclasses withdataclasses.replace, which runs__post_init__. Main'sPrompt.__post_init__only compareslen(images)withlen(image_placeholders), so it still passes with_BytesRefleaves. A future validator that checks leaf types would break registration.
Not verified: GPU-host placement of the controller (for the CUDA-context cost); no perf runs.
|
Please rebase and address claude comments |
68c52d7 to
1508dbf
Compare
|
@wwwjn could you interact with pr-review skill and claude bot to get AI approval first? |
|
@claude review again |
|
Claude finished @wwwjn's task in 2m 30s —— View job Approve -- the earlier must-fix items are fixed; please update the stale description and name the workload for the knob before merging. See the review (if that link doesn't open the review, it is the latest review on the Files changed tab). |
…plan Stack: #5862 -> #6268 (hop metrics) -> #6269 (slots by group id) -> slim group -> batcher split -> this. Why: the batcher packed every microbatch of a step, so each step's bytes went worker -> controller -> batcher -> controller -> every trainer rank (pp * cp * tp copies per DP replica): four bulk pickles, two of them through the controller's event loop, and serial image preprocessing on every trainer rank. What changes: 1. The rollout worker returns its group split (`FinishedRolloutGroup(summary, arrays, recorder_lines)`); the work buffer holds it. `split_rollout_group` -> (`RolloutGroupSummary`, `RolloutGroupArrays`): the summary is the group with every ndarray field emptied (same dtype and trailing shape, not a view) and image files emptied, plus its turn lengths; the arrays hold every ndarray field by name and each image file once. `join_rollout_group` reverses it. Before splitting, the worker runs `check_prompt_prefixes` on every rollout, the one check that reads token values (in the batcher split PR it ran in `add_group`). 2. The batcher gets only summaries and returns the step's `StepPlan`: no tensors (`TrainerStepBatch` is deleted). `MicrobatchPacker` is a `Configurable`; its config (`per_sample_pad_multiple`, `num_mtp_layers`, `build_mrope_positions`) moves under `Batcher.Config.microbatch_packer`, so the planner and the packer read one source. The trainer builds the packer from it, with `pad_id`, `temperature` and `vision_processor`. 3. The controller keeps each trainable group's summary and arrays until its step, without the group metrics the batcher logs from its copy (`FinishedRolloutGroup.without_metrics`). It then sends each DP replica's leader (pipeline stage 0, CP and TP rank 0) its plan column and only the rollouts that column names (`Trainer.receive_replica_column`), under its own span and step timer (`timing/step/send_replica_columns`). `forward_backward` carries the group count and the global token counts. 4. On every trainer rank a `MicrobatchGroupReader` thread makes the step's microbatch groups up to two ahead of the one the engine waits on: the leader materializes and packs each group (`MicrobatchPacker.pack_planned`, which checks each sample's length and each microbatch's token counts against its specs) and broadcasts it, with its packing time, over a per-replica gloo group; the other ranks receive it; every rank preprocesses images. The replica groups come from the trainer's dense mesh (`build_dp_replica_group`). A leader that fails to pack broadcasts its error, so the replica fails instead of hanging. PP works from the start: every stage of a replica is in its group. The leader materializes one rollout group at a time and drops its arrays once its samples exist, and drops each microbatch group's samples once it is packed. 5. Deleted: the RDMA microbatch path (`Batcher.Config.rdma_min_tensor_bytes`, `RDMAMicrobatch`, `RDMAMicrobatchPrefetcher`, `maybe_release_oldest_batch`, the trainer's RDMA identity check, the controller's RDMA warning and PP rejection), the now-unused tensor and dataclass paths of `MonarchRDMAObject` (it registers bytes only: prompt image files), and `share_image_data` (the split keeps one copy per image). Cost: the leaders pack only once forward_backward starts. With training.preprocess_microbatch_groups_lazily=False (the default), the engine reads every microbatch group before its first forward, so the column send and the leaders' materialize, pack and broadcast are on the step's critical path; with it on, the first group still waits for the column's materialize. Sending the columns during the previous step (a follow-up) hides them. Unchanged: the plan (FFD/LPT/zig-zag), the packing, the samples and the numerics; the push/pull ordering; #5862's image-file path.
…plan Stack: #5862 -> #6268 (hop metrics) -> #6269 (slots by group id) -> slim group -> batcher split -> this. Why: the batcher packed every microbatch of a step, so each step's bytes went worker -> controller -> batcher -> controller -> every trainer rank (pp * cp * tp copies per DP replica): four bulk pickles, two of them through the controller's event loop, and serial image preprocessing on every trainer rank. What changes: 1. The rollout worker packs each finished group once (`pack_rollout_group`, new `rollout/packed_group.py`) and returns `FinishedRolloutGroup(summary, packed, recorder_lines)`; the work buffer holds it. The summary (`RolloutGroupSummary`, moved to `rollout/types.py`) is the group with every ndarray field emptied (same dtype and trailing shape) and image files emptied, plus its turn lengths. `PackedRolloutGroup` holds the bytes as uint8 regions of one buffer: per rollout, the rollout pickled without its arrays, then every ndarray field by name (64-byte aligned); per distinct image file, its bytes. `select` keeps the named rollouts' regions and their images' without copying; `unpack_rollout_group` rebuilds the rollouts, with arrays viewing the regions. Before packing, the worker runs `check_prompt_prefixes` on every rollout, the one check that reads token values (in the batcher split PR it ran in `add_group`). 2. The batcher gets only summaries and returns the step's `StepPlan`: no tensors (`TrainerStepBatch` is deleted). `MicrobatchPacker` is a `Configurable`; its config (`per_sample_pad_multiple`, `num_mtp_layers`, `build_mrope_positions`) moves under `Batcher.Config.microbatch_packer`, so the planner and the packer read one source. The trainer builds the packer from it, with `pad_id`, `temperature` and `vision_processor`. 3. The controller keeps only each trainable group's packed regions until its step: one GC-tracked object per group, not the per-turn object graph, which held for several steps made its full collections frequent and slow. It then sends each DP replica's leader (pipeline stage 0, CP and TP rank 0) its plan column and only the rollouts that column names (`Trainer.receive_replica_column`), under its own span and step timer (`timing/step/send_replica_columns`). `forward_backward` carries the group count and the global token counts. 4. On every trainer rank a `MicrobatchGroupReader` thread makes the step's microbatch groups up to two ahead of the one the engine waits on: the leader materializes and packs each group (`MicrobatchPacker.pack_planned`, which checks each sample's length and each microbatch's token counts against its specs) and broadcasts it, with its packing time, over a per-replica gloo group; the other ranks receive it; every rank preprocesses images. The replica groups come from the trainer's dense mesh (`build_dp_replica_group`). A leader that fails to pack broadcasts its error, so the replica fails instead of hanging. PP works from the start: every stage of a replica is in its group. The leader unpacks and materializes one rollout group at a time and drops its bytes once its samples exist, and drops each microbatch group's samples once it is packed. 5. Deleted: the RDMA microbatch path (`Batcher.Config.rdma_min_tensor_bytes`, `RDMAMicrobatch`, `RDMAMicrobatchPrefetcher`, `maybe_release_oldest_batch`, the trainer's RDMA identity check, the controller's RDMA warning and PP rejection), the now-unused tensor and dataclass paths of `MonarchRDMAObject` (it registers bytes only: prompt image files), and `share_image_data` (the packed group keeps one copy per image). Cost: the leaders pack only once forward_backward starts. With training.preprocess_microbatch_groups_lazily=False (the default), the engine reads every microbatch group before its first forward, so the column send and the leaders' materialize, pack and broadcast are on the step's critical path; with it on, the first group still waits for the column's materialize. Sending the columns during the previous step (a follow-up) hides them. Unchanged: the plan (FFD/LPT/zig-zag), the packing, the samples and the numerics; the push/pull ordering; #5862's image-file path.
…plan Stack: #5862 -> #6268 (hop metrics) -> #6269 (slots by group id) -> slim group -> batcher split -> this. Why: the batcher packed every microbatch of a step, so each step's bytes went worker -> controller -> batcher -> controller -> every trainer rank (pp * cp * tp copies per DP replica): four bulk pickles, two of them through the controller's event loop, and serial image preprocessing on every trainer rank. What changes: 1. The rollout worker packs each finished group once (`pack_rollout_group`, new `rollout/packed_group.py`) and returns `FinishedRolloutGroup(summary, packed, recorder_lines)`; the work buffer holds it. The summary (`RolloutGroupSummary`, moved to `rollout/types.py`) is the group with every ndarray field emptied (same dtype and trailing shape) and image files emptied, plus its turn lengths. `PackedRolloutGroup` holds the bytes as uint8 regions of one buffer: per rollout, the rollout pickled without its arrays, then every ndarray field by name (64-byte aligned); per distinct image file, its bytes. `select` keeps the named rollouts' regions and their images' without copying; `unpack_rollout_group` rebuilds the rollouts, with arrays viewing the regions. Before packing, the worker runs `check_prompt_prefixes` on every rollout, the one check that reads token values (in the batcher split PR it ran in `add_group`). 2. The batcher gets only summaries and returns the step's `StepPlan`: no tensors (`TrainerStepBatch` is deleted). `MicrobatchPacker` is a `Configurable`; its config (`per_sample_pad_multiple`, `num_mtp_layers`, `build_mrope_positions`) moves under `Batcher.Config.microbatch_packer`, so the planner and the packer read one source. The trainer builds the packer from it, with `pad_id`, `temperature` and `vision_processor`. 3. The controller keeps only each trainable group's packed regions until its step: one GC-tracked object per group, not the per-turn object graph, which held for several steps made its full collections frequent and slow. It then sends each DP replica's leader (pipeline stage 0, CP and TP rank 0) its plan column and only the rollouts that column names (`Trainer.receive_replica_column`), under its own span and step timer (`timing/step/send_replica_columns`). `forward_backward` carries the group count and the global token counts. 4. On every trainer rank a `MicrobatchGroupReader` thread makes the step's microbatch groups up to two ahead of the one the engine waits on: the leader materializes and packs each group (`MicrobatchPacker.pack_planned`, which checks each sample's length and each microbatch's token counts against its specs) and broadcasts it, with its packing time, over a per-replica gloo group; the other ranks receive it; every rank preprocesses images. The replica groups come from the trainer's dense mesh (`build_dp_replica_group`). A leader that fails to pack broadcasts its error, so the replica fails instead of hanging. PP works from the start: every stage of a replica is in its group. The leader unpacks and materializes one rollout group at a time and drops its bytes once its samples exist, and drops each microbatch group's samples once it is packed. 5. Deleted: the RDMA microbatch path (`Batcher.Config.rdma_min_tensor_bytes`, `RDMAMicrobatch`, `RDMAMicrobatchPrefetcher`, `maybe_release_oldest_batch`, the trainer's RDMA identity check, the controller's RDMA warning and PP rejection), the now-unused tensor and dataclass paths of `MonarchRDMAObject` (it registers bytes only: prompt image files), and `share_image_data` (the packed group keeps one copy per image). Cost: the leaders pack only once forward_backward starts. With training.preprocess_microbatch_groups_lazily=False (the default), the engine reads every microbatch group before its first forward, so the column send and the leaders' materialize, pack and broadcast are on the step's critical path; with it on, the first group still waits for the column's materialize. Sending the columns during the previous step (a follow-up) hides them. Unchanged: the plan (FFD/LPT/zig-zag), the packing, the samples and the numerics; the push/pull ordering; #5862's image-file path.
d1a7e4d to
a2b3e76
Compare
…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.
…nd images as RDMA handles
a2b3e76 to
04a45a4
Compare
|
@claude review again |
|
Claude finished @wwwjn's task in 2m 28s —— View job Needs discussion -- see the review (if that link doesn't open the review, it is the latest review on the Files changed tab). The code at 04a45a4 is sound, but #6334 and #6163 rewrite this PR's RDMA layer, so a maintainer needs to pick the RDMA stack first. |
There was a problem hiding this comment.
Verdict: Needs discussion -- the code at 04a45a4 is sound. But your own stack's top PR (#6334) deletes RDMAObject, RegisterRDMAObject, MonarchRDMAObject and test_rdma_object.py, which is most of what this PR adds. #6163 also moves the microbatch path off Monarch RDMA. Maintainers need to choose the RDMA stack before this abstraction lands. This review replaces my 2026-11-18 approval, which predates #6334.
What this PR does. One framework-agnostic RDMAObject[T] (Monarch: MonarchRDMAObject) backs both the batcher's microbatches and an opt-in path for prompt image files. With rdma_min_image_bytes set, RDMAImageFiles registers each large file once per group, keyed by its content hash. Every sibling and turn sends that handle, generator rank 0 reads it, and run_group's finally drops it. GenerateFn always takes an RDMAPrompt, which is the whole prompt by value when the knob is off.
Example. One group, 8 siblings x 3 turns, one 5 MB image:
knob off: 24 generate calls, each carries 5 MB through worker -> router -> generator
knob on: 1 registration; 24 calls carry a handle; rank 0 does 24 RDMA reads; 1 drop at group end
#6334: same flow, but the file sits in the worker's torch-transport (NIXL) pool and
RDMAObject / MonarchRDMAObject are deleted
Earlier must-fix items
- Stale description: resolved. The "What" and "Tests" sections now match the code (no
_ArrayRef, and the real-Monarch test is the one that reaches generator rank 0). - Knob with no in-repo consumer: still open. No recipe sets
rdma_min_image_bytes, and the description gives synthetic file sizes but no dataset. #6334 measures Qwen3.5-0.8B Geometry3K at 2048 px. If that is the workload, say so here, with its file sizes.
Must fix
-
Overlapping work (no single line). #6334 says "Deleted:
rl/transport/rdma_object.py(RDMAObject,RegisterRDMAObject),rl/actors/monarch/rdma_object.py(MonarchRDMAObject) and their test file". #6163 (d4l3k) replaces MonarchRDMABufferfor microbatches withtorch.distributed._transport. Landing this PR as written adds about 430 lines (the protocols, the Monarch implementation and its tests) that the stack then removes. Please get a maintainer decision on one of these:- land this PR as the interim base, and say in the description that #6334 or #6163 supersedes the Monarch implementation;
- shrink this PR to what the later stack keeps (
RDMAPrompt,RDMAImageFiles, therun_grouplifetime, and theregister_rdma_objectrename that #6302 needs) and put the image path straight on the transport #6323/#6334 picks.
Either way, coordinate with #6163 so that the microbatch path isn't migrated twice.
Details
- Checked at HEAD: every
GenerateFnandGenerator.generatecaller wraps its prompt inRDMAPrompt(the rollouter, the Verifiers generation server, the token_env docstring, and the test fakes).EngineRequeststill takes a barePrompt(generate.py:120, the engine-loop tests), which is correct.hash_valueis the file's content hash, so keying on it can't return another image's bytes. The CUDA-context workaround is gone fromactors/monarch/rollout_worker.py. The microbatch path keeps the same leaves and reads; the bitwise TensorBoard comparison in the description covers it. - Overlap search:
RDMA,rollout worker image,rollouter. Found #6163 (draft), #6283, #6301, #6302, #6303, #6323 and #6334 (this author's stack, with #5862 at its base) and #5764. - The earlier should-consider (the
drop()exception inrun_group'sfinallymasks the gather's) is unchanged and still low risk.
Not verified: cross-host RDMA timings and the knob-on Geometry3K run (they need GPU hosts).
Before merge: fill in the human-written summary.
Human Note
rollout_worker -> generator, andbatcher->trainer. This is a base for data plane refactorTLDR
RDMAObject[T]andMonarchRDMAObject[T]replaceMonarchRDMAMicrobatch: one abstraction for the RDMA microbatch and the RDMA prompt (#5824 review), with loss and grad norm bitwise identical to main. Opt-in knobBaseRolloutWorker.Config.rdma_min_image_byteskeeps large prompt image files in the rollout worker, one RDMA buffer per group, read by generator rank 0. Across hosts it is ~2x faster from 5 MB per file and slower below 1 MB, so it is off by default.Why
What
rl/transport/rdma_object.pyreplacesrl/transport/rdma_microbatch.py: framework-agnostic protocolsRDMAObject[T](read(),drop()) andRegisterRDMAObject, plus the types below.rl/actors/monarch/rdma_object.py:MonarchRDMAObject[T]replacesactors/monarch/rdma_microbatch.py;register(value, *, min_bytes)swaps large tensor or bytes leaves for buffers.RDMAMicrobatchis a dataclass:RDMAObject[TrainingMicrobatch]plusbatch_index,dp_rank,microbatch_index; same tensors as on main.RDMAPrompt: the prompt with kept files'dataemptied, plus oneRDMAObject[bytes] | Noneper image;read()returns the fullPrompt. Knob off: the whole prompt by value.RDMAImageFiles.register(prompt)keeps each file of at leastmin_bytesonce per group, not per call;MessageEnvRolloutWorker.run_groupcallsdrop()in itsfinally, after every generate call returned.RolloutWorkerActorinjectsMonarchRDMAObject.registeronly when the knob is set.Generator.generatestampsarrival_time, then reads the files (TODO: even on a pixel-cache hit; TP > 1 still broadcasts the bytes).Breaking changes (RL extension points)
GenerateFnandGenerator.generatetake anRDMAPrompt(wasPrompt): wrap withRDMAPrompt(prompt), read withawait prompt.read().MessageEnvRolloutWorker._run_single_rollouttakesimage_files.Batcher(..., register_rdma_microbatch=)->register_rdma_object=.Microbenchmarks
fair-cw job 2689293, 4 GB300 hosts, ibverbs: 4 owners (rollout workers) on one host, one reader (generator rank 0) on each other host, one hop; a group's 16 requests share one file. Seconds per burst, mean of 2:
Prompt1.66 ms,RDMAPrompt(prompt)1.63 ms (median of 300): no overhead.Tests
pytest tests/rl/unit_tests/cpu: 774 passed, 8 skipped, 4 failed; the 4 also fail on main076f2e88b(770 passed): recipe tests whosetorch_checkpointing.storage.fsspec_storageimport fails locally.076f2e88b, squashed to one commit. This head,rl_grpo_qwen3_0_6b_varlen_batch_invariant(seed 42, deterministic, trainer TP 2 + one generator TP 2, 10 steps): 62/62 shared non-timing TensorBoard tags equal to main at every step; both read microbatches by RDMA.rl_grpo_qwen3_5_0_8b_geometry3k,rdma_min_image_bytes=1, 5 steps, earlier head 5543059: prompts and image hashes match knob off; loss and reward within knob-off run-to-run noise.test_rollout_worker.py::test_group_keeps_each_image_file_once_until_its_last_generate_call(fails with the per-call lifetime);test_rdma_object.py: over real Monarch only the file handle reaches generator rank 0.Later in the data-plane stack
RDMAMicrobatch. [WIP] [rl] Prompt image files share the rollout worker's torch transport pool #6334 moves prompt image files onto the torch transport (NIXL) pool that [WIP] [rl] Trainer DP replica leaders read their rollouts from the rollout workers and pack them #6303 adds, and deletesRDMAObjectandMonarchRDMAObject, so a rollout worker runs one RDMA stack.