Skip to content

[WIP][rl] One RDMA object for microbatches and prompts; rollout workers send images as RDMA handles - #5862

Open
wwwjn wants to merge 1 commit into
mainfrom
wwwjn/rl-rdma-object
Open

wwwjn wants to merge 1 commit into
mainfrom
wwwjn/rl-rdma-object

Conversation

@wwwjn

@wwwjn wwwjn commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Human Note

  • This is a change to make RDMA transfer path (rollout worker -> generator) for image only;
  • Image are sent as bytes which is good use case for RDMA; token_ids are list[int] that will be convert to array/tensor then send through RDMA
  • This PR only send image as handler, and introduced/unfied the RDMAObject concept for both rollout_worker -> generator, and batcher->trainer. This is a base for data plane refactor
image

TLDR
RDMAObject[T] and MonarchRDMAObject[T] replace MonarchRDMAMicrobatch: one abstraction for the RDMA microbatch and the RDMA prompt (#5824 review), with loss and grad norm bitwise identical to main. Opt-in knob BaseRolloutWorker.Config.rdma_min_image_bytes keeps 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

  1. [rl] Image prompts through rollouts and the vLLM generator #5824 review: one abstraction for the RDMA prompt and microbatch, no RDMA in the controller.
  2. Image files, not token ids (64 KiB at 16K tokens), are worth keeping in the worker: a group's siblings and later turns resend them.
  3. Inline, 10 MB files with 16,384 requests in flight ran the rollout worker host out of memory.
main, knob off  worker --prompt + image bytes--------------> generator rank 0
knob on         worker --RDMAPrompt(prompt, file handles)--> generator rank 0 ==RDMA read==> worker

What

  1. rl/transport/rdma_object.py replaces rl/transport/rdma_microbatch.py: framework-agnostic protocols RDMAObject[T] (read(), drop()) and RegisterRDMAObject, plus the types below.
  2. rl/actors/monarch/rdma_object.py: MonarchRDMAObject[T] replaces actors/monarch/rdma_microbatch.py; register(value, *, min_bytes) swaps large tensor or bytes leaves for buffers.
  3. RDMAMicrobatch is a dataclass: RDMAObject[TrainingMicrobatch] plus batch_index, dp_rank, microbatch_index; same tensors as on main.
  4. RDMAPrompt: the prompt with kept files' data emptied, plus one RDMAObject[bytes] | None per image; read() returns the full Prompt. Knob off: the whole prompt by value.
  5. RDMAImageFiles.register(prompt) keeps each file of at least min_bytes once per group, not per call; MessageEnvRolloutWorker.run_group calls drop() in its finally, after every generate call returned.
  6. RolloutWorkerActor injects MonarchRDMAObject.register only when the knob is set. Generator.generate stamps arrival_time, then reads the files (TODO: even on a pixel-cache hit; TP > 1 still broadcasts the bytes).

Breaking changes (RL extension points)

  • GenerateFn and Generator.generate take an RDMAPrompt (was Prompt): wrap with RDMAPrompt(prompt), read with await prompt.read().
  • MessageEnvRolloutWorker._run_single_rollout takes image_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:

image     P=32 (N=2,048)                       P=256 (N=16,384)
          inline   RDMA,      RDMA,            inline   RDMA,
                   per group  per call                  per group
87 KB     0.12     0.70       0.99             0.94     5.30
254 KB    0.13     0.67       1.00             1.18     5.32
1 MB      0.45     0.75       1.08             2.89     5.64
2 MB      0.81     0.96       1.06             6.42     6.60
5 MB      2.38     1.04       1.81            17.25     9.38
10 MB     4.72     1.69       1.73             inline ran the owner host out of memory; RDMA not run
  • inline = knob off; per group = this PR (13x less registration time than per call); per call = reviewed head 68c52d7, P=32 only. Reader CPU: ~12-20 ms per RDMA read, under 1 ms inline.
  • Break-even ~2 MB, 2.8x faster at 10 MB, 2-6x slower below 1 MB. Knob off, 16K-token prompt: main Prompt 1.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 main 076f2e88b (770 passed): recipe tests whose torch_checkpointing.storage.fsspec_storage import fails locally.
  • Rebased onto main 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

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 5, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 5, 2026

@pzhan9 pzhan9 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.

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.

Comment thread torchtitan/rl/generator/generator.py Outdated
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()

@pzhan9 pzhan9 Nov 5, 2026 •

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks, I will keep the current place of read

Comment thread torchtitan/rl/rollout/rollouter.py Outdated
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)

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.

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)),

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.

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.

@wwwjn

wwwjn commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

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

@wwwjn
wwwjn marked this pull request as ready for review November 10, 2026 19:12
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 10, 2026
@wwwjn
wwwjn force-pushed the wwwjn/rl-rdma-object branch from 1d1bbe9 to 7451a05 Compare November 10, 2026 19:24
@wwwjn
wwwjn changed the base branch from main to wwwjn/image-rl/3-train-image-prompts November 10, 2026 19:24
@wwwjn
wwwjn force-pushed the wwwjn/rl-rdma-object branch from 7451a05 to 68c52d7 Compare November 10, 2026 19:44
@wwwjn
wwwjn requested a review from d4l3k as a code owner November 10, 2026 19:44
@wwwjn
wwwjn changed the base branch from wwwjn/image-rl/3-train-image-prompts to main November 10, 2026 19:44
@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 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).

@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: 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

  1. torchtitan/rl/rollout/types.py:32 -- #5824 merged and added its own Prompt (token_ids: list[int], images, __post_init__). This branch conflicts, and its np.ndarray Prompt is 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.
  2. 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 in run_group's finally. This is your own open comment.
  3. torchtitan/rl/generator/generator.py:413 -- pzhan9's two comments are unaddressed: always pass RDMAObject[Prompt] (generation_server.py:216), which removes the union from six signatures plus the isinstance branches, 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.py with the Monarch code in actors/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 image Prompt.
  • The RDMAMicrobatch refactor (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_leaves rebuilds dataclasses with dataclasses.replace, which runs __post_init__. Main's Prompt.__post_init__ only compares len(images) with len(image_placeholders), so it still passes with _BytesRef leaves. 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.

Comment thread torchtitan/rl/rollout/rollouter.py Resolved
Comment thread torchtitan/rl/rollout/types.py Resolved
Comment thread torchtitan/rl/generator/generator.py Resolved
@tianyu-l

Copy link
Copy Markdown
Contributor

Please rebase and address claude comments

@wwwjn
wwwjn force-pushed the wwwjn/rl-rdma-object branch from 68c52d7 to 1508dbf Compare November 17, 2026 17:34
@wwwjn wwwjn changed the title [rl] One RDMA object for microbatches and prompts; rollout workers send prompts as RDMA handles [rl] One RDMA object for microbatches and prompts; rollout workers send images as RDMA handles Nov 17, 2026
@tianyu-l

Copy link
Copy Markdown
Contributor

@wwwjn could you interact with pr-review skill and claude bot to get AI approval first?

@wwwjn

wwwjn commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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).

wwwjn added a commit that referenced this pull request Nov 20, 2026
…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.
wwwjn added a commit that referenced this pull request Nov 20, 2026
…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.
wwwjn added a commit that referenced this pull request Nov 22, 2026
…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.
@wwwjn
wwwjn force-pushed the wwwjn/rl-rdma-object branch from d1a7e4d to a2b3e76 Compare November 23, 2026 20:35
@wwwjn
wwwjn added this pull request to stack #6343 November 23, 2026 21:31
@wwwjn
wwwjn removed this pull request from stack #6343 November 24, 2026 20:05
@wwwjn
wwwjn added this pull request to stack #6362 November 24, 2026 20:15
@wwwjn
wwwjn removed this pull request from stack #6362 November 24, 2026 22:25
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.
@wwwjn
wwwjn force-pushed the wwwjn/rl-rdma-object branch from a2b3e76 to 04a45a4 Compare November 30, 2026 19:58
@wwwjn

wwwjn commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

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.

@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: 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

  1. 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).
  2. 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

  1. 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 Monarch RDMABuffer for microbatches with torch.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, the run_group lifetime, and the register_rdma_object rename 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 GenerateFn and Generator.generate caller wraps its prompt in RDMAPrompt (the rollouter, the Verifiers generation server, the token_env docstring, and the test fakes). EngineRequest still takes a bare Prompt (generate.py:120, the engine-loop tests), which is correct. hash_value is the file's content hash, so keying on it can't return another image's bytes. The CUDA-context workaround is gone from actors/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 in run_group's finally masks 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.

This branch has not been deployed

No deployments
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.

3 participants