Skip to content

[rl] Migrate RDMA microbatches from Monarch RDMA to torch.distributed._transport - #6163

Draft
d4l3k wants to merge 4 commits into
gh/d4l3k/11/basefrom
gh/d4l3k/11/head
Draft

d4l3k wants to merge 4 commits into
gh/d4l3k/11/basefrom
gh/d4l3k/11/head

Conversation

@d4l3k

@d4l3k d4l3k commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Stack from ghstack (oldest at bottom):

TitanRL's RDMA microbatch path (Batcher.Config.rdma_min_tensor_bytes, default 1 KiB) used Monarch RDMA (RDMABuffer) plus Monarch-specific registration plumbing. This moves it to torch.distributed._transport (NIXL), the same API ModelStateDictTransport uses. The code lives in torchtitan/rl/transport/rdma_microbatch.py.

  • RDMAMicrobatch (frozen dataclass) replaces MonarchRDMAMicrobatch. The batcher copies a microbatch's large tensors back to back (16-byte aligned) into one owner pool range and pickles only a RemoteBuffer slice and the owner URL. A trainer rank does one read per microbatch and connects once per owner.
  • Owner pool: NIXL readers cache remote registrations by address and can't update their key ([Feature Request] Support agent metadata updates ai-dynamo/nixl#1267). Registering each batch broke reads once a later batch reused a freed address with a new key (NIXL_ERR_NOT_ALLOWED, then timeouts). The pool registers grow-only CPU chunks once and never unregisters them; drop() returns ranges to a free list. Cost: one CPU memcpy per large tensor.
  • NIXL is hardcoded; no backend knob. Mooncake is no longer supported for microbatches.
  • The controller releases the oldest batch only after a successful gather. A failed step skips the release and ends the run, since other ranks' reads may still be in flight.
  • Removed torchtitan/rl/actors/monarch/rdma_microbatch.py and Batcher(register_rdma_microbatch=...).

Known limitations / follow-ups: the owner's NIXL progress thread spins a core (same as ModelStateDictTransport); pool growth is uncapped; owner/reader transports are module globals (moving them into the batcher overlaps the RegisteredBufferPool work in #6469/#6334); no end-to-end perf comparison yet. A read after drop() returns wrong data instead of failing (ranges are reused), so a failed step must end the run, as it does today.

Lines: implementation +318 / -228, tests +217 / -96.

Test plan:

  • pytest tests/rl/unit_tests/cpu/transport/test_rdma_microbatch.py tests/rl/unit_tests/cpu/test_batcher_actor.py tests/rl/unit_tests/cpu/test_batcher.py tests/rl/unit_tests/cpu/test_trainer.py: 49 passed. Includes the 4-rank cross-process test over real NIXL, the round trip with unaligned tensors (exercises padding), and test_reads_stay_correct_when_owner_memory_is_reused (real NIXL, UCX_RCACHE_ENABLE=n), which fails on the per-batch registration design.
  • Removed redundant tests: owner-process self read (covered by test_reads_stay_correct_when_owner_memory_is_reused and the 4-rank test); "only registered microbatches are RDMA" (covered by tests/rl/unit_tests/cpu/test_trainer.py); read/copy failure parametrizations (error paths removed).
  • Cross-process repro (owner and reader processes, 6 batches of 64 MiB tensors, UCX rc_mlx5): all reads correct.

[ghstack-poisoned]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 17, 2026
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.

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.

I had a tiny refactor which moves this file to /rl/transport/ folder, so please adapt.

@d4l3k

d4l3k commented Dec 1, 2026

Copy link
Copy Markdown
Member Author

@claude review this

d4l3k added a commit that referenced this pull request Dec 1, 2026
@claude

claude Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @d4l3k's task in 6m 23s —— View job


Request changes: this switches the default RL microbatch path to NIXL without any end-to-end step-time or batcher-memory numbers, and the description has two wrong claims. Review: #6163 (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: Request changes -- this swaps the transport on the default RL data path but gives no end-to-end step-time or batcher-memory comparison.

What this PR does. The batcher-to-trainer microbatch path stops using Monarch RDMABuffer and uses torch.distributed._transport (NIXL) instead. The batcher copies each large tensor into a registered CPU pool. Pool chunks are never unregistered, which works around nixl#1267. Each trainer rank registers a fresh buffer and issues one read per tensor. drop() returns ranges to a free list for later batches. Batcher(register_rdma_microbatch=...) and the Monarch implementation are deleted.

Example.

batcher, per microbatch of a batch
  before: RDMABuffer(view of mb.input), one per tensor >= 1 KiB      (zero-copy; drop() unregisters)
  after:  memcpy mb.input, ... into one aligned range of a >= 64 MiB registered chunk
          pickled: RemoteBuffer slice per tensor + owner url
trainer rank
  before: RDMAAction().read_remote(...) per tensor; await submit()
  after:  register fresh buffer; transport.read per tensor; wait_all(timeout=60); unregister
release (controller `finally`, after forward_backward)
  before: buffers unregistered: a late read fails
  after:  range reused by the next batch: a late read returns newer data

Must fix

  1. Description.

    • It calls this the "opt-in" path, but rdma_min_tensor_bytes defaults to 1024 and no recipe in torchtitan_recipes/rl turns it off (only the alphabet-sort test sets None). So every RL run changes transport.
    • It also says the PR removes "the CUDA-context workaround in the batcher" / "the CUDA-context hack", but no such code exists in the base branch or the diff.
    • Fix both statements.
  2. Main-path performance evidence. The default path now pays for:

    • one CPU memcpy per tensor in a GIL-bound batcher;
    • a NIXL progress thread spinning a core in the batcher process;
    • a register_memory of pageable memory per microbatch read;
    • a pool that never shrinks.

    CLAUDE.md #6: performance and memory of the main training path must not silently change. Please add a before/after run on one representative recipe with medians of timing/step/forward_backward, the wait_for_microbatch span / read_s, and batcher RSS. Cross-host if possible, since that is what RDMA is for.

  3. torchtitan/rl/trainer/batcher.py:279 -- rdma_backend exposes Mooncake, which hasn't been tested on this path; delete the knob and hardcode NIXL (inline).

  4. torchtitan/rl/transport/rdma_microbatch.py:147 -- the RDMAMicrobatch Protocol now has a single implementation in the same module; give the dataclass that name instead (inline).

Should consider

  • rdma_microbatch.py:265 -- the owner and reader layouts are identical, so one read per microbatch works today (inline).
  • rdma_microbatch.py:276, :324 -- error-path cleanup only helps a run that is already ending. Deleting it removes about 15 lines and two tests (inline).
  • rdma_microbatch.py:121 -- module-global owner/reader state; let the Batcher and the trainer own them (inline).
  • controller.py:1479 (not in diff) -- release also runs when the step failed, so other ranks' in-flight reads can now get the next batch's bytes. Today the raise ends the run. To make that structural rather than a docstring rule, release only after gather succeeds; a failing run then just leaks one batch.
  • test_rdma_microbatch.py:509 -- redundant real-NIXL test (inline).

Questions

  • rdma_microbatch.py:314 -- is a per-read connect() free (inline)?
  • Coordination. wwwjn's stack builds a second never-unregister pool over torch transport for the same NIXL bug: RegisteredBufferPool in #6469, reused by #6334, citing pytorch#206300 rather than nixl#1267. Separately, #6303 deletes test_rdma_microbatch.py and moves packing to the trainer leaders. Could you and @wwwjn agree on one pool in rl/transport/ and one upstream link, so the repo doesn't end up with two copies of the workaround?
Details
  • Gate. The motivation holds up. It removes the injected register_rdma_microbatch plumbing and Monarch's RDMA backend check, and puts both RDMA paths on the transport ModelStateDictTransport already uses (default since #6125). That matches where #6334/#6469 are heading.
  • Reviewed and found OK:
    • _PoolChunk.release merges with the next free range, then the previous one.
    • Owner and reader offsets iterate the same tree_leaves order.
    • Zero-byte tensors can't reach the pool (min_bytes >= 1).
    • Reads run on the prefetcher's own thread, so no actor loop blocks.
    • The controller releases only after every DP slice's forward_backward returns.
  • tianyu-l's comment (move to rl/transport/) is addressed at HEAD.
  • Overlap searches: "rdma microbatch", "nixl", "batcher.py in:path rl". Found #5862, #6302, #6303, #6324, #6469, #6334 (wwwjn data-plane stack, drafts) and #6283 (batcher placement with RDMA).
  • Size of the suggested trims: dropping rdma_backend (-15), the Protocol (-30), the error-path cleanup plus its tests (-50), and the redundant test (-25).

Not verified: torch.distributed._transport semantics (repeated connect, per-slice metadata size, several agents per process), and any GPU or multi-host performance.

Comment thread torchtitan/rl/trainer/batcher.py Outdated
Comment on lines +279 to +281
rdma_backend: Literal["mooncake", "nixl"] = "nixl"
"""The `torch.distributed._transport` backend for `rdma_min_tensor_bytes`. NIXL (UCX) falls back to
TCP without RDMA devices; Mooncake needs RDMA devices or `MC_FORCE_TCP=1`."""

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.

Must fix: rdma_backend adds a knob whose only non-default value hasn't been tested. The description says "Mooncake untested", and nothing in-repo sets it. Mooncake is also a different case from ModelStateDictTransport.Config.backend: this path puts two agents in one process (owner and reader), keeps chunks registered forever and slices remote buffers per tensor, and none of that has been tried on Mooncake. rules/config.md: "Expose only options a verified recipe uses."

Smallest fix: delete the field and the __post_init__ check at L307-308, then hardcode "nixl" in rdma_microbatch.py. That removes the backend field and params on TransportRDMAMicrobatch, the per-backend dict keys, and the if backend == "nixl" kwargs branch in _reader_transport. Add Mooncake back in the PR that verifies it end to end.

Comment on lines +146 to +149
@runtime_checkable
class RDMAMicrobatch(Protocol):
"""A `TrainingMicrobatch` whose large tensors stay in its owner, the process that registered it.

Example:
rdma_microbatch = register_rdma_microbatch( # owner
microbatch, min_bytes=1024, batch_index=0, dp_rank=1, microbatch_index=2
)
microbatch = await rdma_microbatch.read() # trainer rank
await rdma_microbatch.drop() # owner, after every rank has read it
"""
Implemented by `TransportRDMAMicrobatch`."""

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.

Must fix: RDMAMicrobatch existed so each actor system could provide its own implementation. This PR deletes the only actor-system implementation and makes the transport one framework-free, and the docstring now says "Implemented by TransportRDMAMicrobatch". What's left is a Protocol with a single implementation in the same module (rules/design.md: no base class with a single subclass).

Smallest fix: delete the Protocol and name the dataclass RDMAMicrobatch. Then trainer.py, actors/monarch/trainer.py and test_trainer.py (spec=RDMAMicrobatch) stay unchanged, isinstance(..., RDMAMicrobatch) still works on the dataclass, and the Transport* rename across files goes away.

Comment on lines +265 to +273
chunk.buffer[offset : offset + tensor.nbytes].view(tensor.dtype).view(
tensor.shape
).copy_(tensor)
tensor_ref = _TensorRef(
chunk.remote_buffer.slice(offset, tensor.nbytes),
tensor.shape,
tensor.dtype,
)
offset += _aligned(tensor.nbytes)

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 consider: this already gives you one read per microbatch, which the description lists as a follow-up. The owner lays the large tensors out back to back from offset, each _aligned. read() builds exactly the same layout from 0 (L305-309). So the reader can fill its whole buffer with a single read:

# register(): one slice for the whole range
remote=chunk.remote_buffer.slice(start, nbytes)
# read(): one read
works = [transport.read(memory.to_mutable_view(0, nbytes), self.remote, async_op=True)]

_TensorRef then only needs shape and dtype. That drops the per-tensor slice() calls and the per-tensor remote-buffer metadata in each pickled message, and gives N-1 fewer reads per microbatch. It over-reads at most 15 padding bytes per tensor. Unverified: how large NIXL's per-slice metadata is.

Comment on lines +276 to +283
try:
# tree_map_only visits the large tensors in tree_leaves order.
fields = pytree.tree_map_only(is_large, copy_tensor, fields)
except BaseException:
with _transports_lock:
for range_chunk, range_offset, range_nbytes in registered:
range_chunk.release(range_offset, range_nbytes)
raise

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 consider: this release-on-error branch only protects a run that is already ending. copy_ into a CPU slice fails only on a malformed tensor, and the batcher builds only CPU tensors. If it does fail, add_training_samples raises and the run ends, so a leaked range doesn't matter. Deleting the branch also lets you delete test_register_releases_pool_range_when_copy_fails, whose meta-device tensor exists only to trigger it.

Suggested change
try:
# tree_map_only visits the large tensors in tree_leaves order.
fields = pytree.tree_map_only(is_large, copy_tensor, fields)
except BaseException:
with _transports_lock:
for range_chunk, range_offset, range_nbytes in registered:
range_chunk.release(range_offset, range_nbytes)
raise
# tree_map_only visits the large tensors in tree_leaves order.
fields = pytree.tree_map_only(is_large, copy_tensor, fields)

Comment on lines +324 to +333
try:
# Submit errors raise after draining submitted reads; transfer errors may only surface as the timeout.
await wait_all(reads, timeout=_READ_TIMEOUT_S)
except (TimeoutError, asyncio.CancelledError):
# Reads may still be in flight: leave the buffer registered; the step fails.
raise
except BaseException:
transport.unregister_memory(memory)
raise
transport.unregister_memory(memory)

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 consider: the three-way split only decides whether a dying step's reader buffer gets unregistered. A failed read fails the step, the prefetcher shuts down and the run ends. Leaving the buffer registered on every error is simpler, and it is safer: you can never unregister while a transfer is in flight, whatever kind of error was raised. This also lets you delete the three-case test_read_failure_unregisters_only_when_reads_are_done.

Suggested change
try:
# Submit errors raise after draining submitted reads; transfer errors may only surface as the timeout.
await wait_all(reads, timeout=_READ_TIMEOUT_S)
except (TimeoutError, asyncio.CancelledError):
# Reads may still be in flight: leave the buffer registered; the step fails.
raise
except BaseException:
transport.unregister_memory(memory)
raise
transport.unregister_memory(memory)
# On any error the buffer stays registered: reads may still be in flight, and the step fails.
await wait_all(reads, timeout=_READ_TIMEOUT_S)
transport.unregister_memory(memory)

Comment on lines +121 to +123
_owners: dict[str, tuple[Any, bytes, _OwnerPool]] = {}
_readers: dict[str, Any] = {}
_transports_lock = threading.Lock()

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 consider: the owner state is module-global: process-wide dicts, a lock, start_owner(), the registered field that __reduce__ has to keep out of the pickle, and tests that monkeypatch _owners/_readers. Yet only one component uses each side. The Batcher is the only owner and already tracks _batches_being_read. The trainer is the only reader.

rules/design.md says the component that consumes a value owns it. Under that rule, Batcher.__init__ would build the transport, bind() and _OwnerPool, pass them to register(..., pool=...), and keep each batch's (chunk, offset, nbytes) ranges next to _batches_being_read. That removes start_owner, registered, __reduce__ and drop(), plus the owner lock: register and drop both run on the batcher actor's loop. The reader transport could likewise be owned by the trainer and passed to the prefetcher. #6469 makes the same choice: BaseRolloutWorker owns its pool. Unverified: whether NIXL allows several agents per process if two Batchers exist (tests only).

# tensors removed the ~4 ms per microbatch in `TrainingEngine._forward_backward_body`'s TODO.
buffer = torch.empty(nbytes, dtype=torch.uint8)
transport = _reader_transport(self.backend)
transport.connect(self.url)

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.

Question: connect(self.url) runs on every microbatch read, but every microbatch from a given batcher carries the same URL. ModelStateDictTransport.connect_generator connects once per source. Is a repeated connect with an already-known URL a cheap no-op in NIXL, or does it re-fetch and re-parse the agent metadata each time? If it isn't free, remember which URLs this reader has already connected to. Unverified: I couldn't read the torch.distributed._transport source from here.



@pytest.mark.usefixtures("real_nixl")
def test_owner_process_reads_its_own_microbatch() -> None:

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 consider: this test duplicates two others that stay. test_reads_stay_correct_when_owner_memory_is_reused already registers and reads in one process over real NIXL. test_four_ranks_read_their_columns_exactly_across_released_batches compares every field over real NIXL against the by-value batcher. Delete this one to save a real-NIXL agent setup in CPU CI.

d4l3k added a commit that referenced this pull request Dec 2, 2026
@d4l3k

d4l3k commented Dec 2, 2026

Copy link
Copy Markdown
Member Author

@claude review this

@claude

claude Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @d4l3k's task in 3m 43s —— View job


Request changes: the code issues from the last review are fixed, but the PR still switches the default RL microbatch path with no end-to-end step-time or batcher-memory numbers, and the description still claims it removes a CUDA-context workaround that doesn't exist. Review: #6163 (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: Request changes -- the code issues from the last review are fixed, but the PR still changes the transport on the default RL data path without any end-to-end step-time or batcher-memory numbers. The description says so itself: "no end-to-end perf comparison yet".

What this PR does. Batcher-to-trainer microbatches move from Monarch RDMABuffer to NIXL over torch.distributed._transport. The batcher copies a microbatch's large tensors back to back (16 B aligned) into a range of a registered CPU pool that is never unregistered, which works around nixl#1267. It pickles one RemoteBuffer slice and the owner URL. Each trainer rank connects to an owner once and issues one read per microbatch. The controller releases the oldest batch only after gather succeeds.

Example.

batcher, per microbatch
  before: RDMABuffer(view) per tensor >= 1 KiB                (zero-copy; drop() unregisters)
  after:  memcpy large tensors into one pool range; pickled: remote.slice(start, nbytes) + url
trainer rank
  before: one RDMAAction, N read_remote; await submit()
  after:  connect(url) once per owner; register buffer; 1 read; wait_all(60 s); unregister;
          the tensors are views into that buffer
release
  before: in `finally`, so a failed step also released
  after:  only after a successful gather; a failed step leaks the batch and the run ends

Since the last review

  • Resolved: the rdma_backend knob is gone and NIXL is hardcoded. The Protocol is gone and the dataclass is now named RDMAMicrobatch. The "opt-in" wording is fixed.
  • Suggestions you adopted, re-checked at HEAD and OK: one read per microbatch (register and read walk the refs in the same tree_leaves order, and every offset is a multiple of 16), the error-path cleanup removed, connect once per URL, release only after a successful gather (any exception from _trainer_loop ends the run), and the redundant real-NIXL test removed.

Must fix

  1. Description (still open, in part): it says the PR removes "the batcher's CUDA-context workaround". No such code exists in origin/gh/d4l3k/11/base (I grepped the base trainer/batcher.py, actors/monarch/batcher.py and actors/monarch/rdma_microbatch.py) or in the diff. Delete that phrase.
  2. Main-path performance evidence (still open): every RL run now pays for a CPU memcpy per large tensor in the GIL-bound batcher, a spinning NIXL progress thread in the batcher process, a register_memory of pageable memory per microbatch read, and a pool that never shrinks. CLAUDE.md #6 says main-path performance and memory must not change silently. Please add a before/after run on one representative recipe, cross-host if possible, with medians of timing/step/forward_backward, the wait_for_microbatch span / read_s, and batcher RSS.

Should consider

  • torchtitan/rl/README.md:233 and scripts/install_rl_env.sh:99-101 -- these say Mooncake is used for RDMA microbatches. It isn't anymore (inline).
  • The owner and reader transports are still module globals. The description defers this because it overlaps #6469/#6334. That's fine as a follow-up if the coordination question below gets an answer.

Questions

  • Coordination (still open): wwwjn's drafts #6469/#6334 build a second never-unregister pool over torch transport for the same NIXL problem (citing pytorch#206300). #5862 (non-draft WIP) unifies the RDMA object for microbatches and prompts. Which pool in rl/transport/ is the one source of truth, and which upstream link goes in the TODO? Landing this first is fine if #6469 then reuses _OwnerPool.
  • #6423 (tianyu-l, open) renames Batcher to TrainingBatchBuilder, so whichever PR lands second needs a rebase.
Details
  • Gate. Still passes. The PR removes the injected registration plumbing and Monarch's RDMA backend check, and puts both RDMA paths on the transport ModelStateDictTransport already uses.
  • Checked at HEAD:
    • _PoolChunk.release merges with the next range, then the previous one.
    • Pool growth (max(nbytes, pool_nbytes, 64 MiB)) keeps the total under about 2x peak.
    • __reduce__ passes arguments in field order and leaves out registered.
    • register holds the lock only to allocate; the copy writes a range no one else owns.
    • The prefetcher uses one reader thread (max_workers=1), so holding _transports_lock during connect doesn't serialize anything.
    • No leftover references to MonarchRDMAMicrobatch, register_rdma_microbatch, MONARCH_RDMA_* or monarch.rdma in the repo.
    • CPU RL CI installs NIXL (unit_test_cpu_rl.yaml:53), so the real-NIXL tests run.
    • The model_wrapper.py docstring edit fixes a stale Monarch-RDMA reason; rl/_env.py gives DeepEP/CUDA graphs as the reason for expandable segments.
  • Overlap searches: "rdma microbatch", "RegisteredBufferPool", "nixl". They found #5862, #6302, #6303, #6324, #6334, #6469 (wwwjn), #5764 (felipemello1, streamed RDMA reads) and #6423 (Batcher rename).

Not verified: the RemoteBuffer.length / no-argument to_mutable_view() API (the real-NIXL tests exercise them; I couldn't read the torch source), and any GPU or multi-host performance.

Comment thread torchtitan/rl/README.md Outdated
matching PyTorch, torchvision and vLLM CUDA nightlies, TorchStore and
batch-invariant ops (git main, without dependencies so they cannot replace the
nightly torch), Mooncake and NIXL for `ModelStateDictTransport`, and the Flash
nightly torch), Mooncake and NIXL for `ModelStateDictTransport` and RDMA microbatches, and the Flash

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 consider: this line says RDMA microbatches use Mooncake too, but rdma_microbatch.py now hardcodes new_transport("nixl"), and the description says Mooncake is no longer supported on this path. scripts/install_rl_env.sh:99-101 has the same wording. A reader would expect Mooncake to work for microbatches.

Suggested change
nightly torch), Mooncake and NIXL for `ModelStateDictTransport` and RDMA microbatches, and the Flash
nightly torch), Mooncake and NIXL for `ModelStateDictTransport` (NIXL also for RDMA microbatches), and the Flash

d4l3k added a commit that referenced this pull request Dec 2, 2026
@d4l3k

d4l3k commented Dec 2, 2026

Copy link
Copy Markdown
Member Author

@claude review this

@claude

claude Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @d4l3k's task in 1m 28s —— View job


Request changes: the docs and description issues are fixed, but this still switches the default RL microbatch path with no end-to-end step-time or batcher-memory numbers. Review: #6163 (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: Request changes -- one item is left. The PR still changes the transport on the default RL data path (rdma_min_tensor_bytes=1024) and gives no end-to-end step-time or batcher-memory numbers. The description itself says "no end-to-end perf comparison yet".

What this PR does. Batcher-to-trainer microbatches move from Monarch RDMABuffer to NIXL over torch.distributed._transport. The batcher copies each microbatch's large tensors back to back (16 B aligned) into a range of a registered CPU pool. The pool is never unregistered, which works around nixl#1267. Only the shapes, dtypes, one RemoteBuffer slice and the owner URL are pickled. A trainer rank connects once per owner and does one read per microbatch. The controller releases the oldest batch only after gather succeeds.

Example.

batcher, per microbatch
  before: RDMABuffer(view) per tensor >= 1 KiB                (zero-copy; drop() unregisters)
  after:  memcpy the large tensors into one pool range; pickled: remote.slice(start, nbytes) + url
trainer rank
  before: one RDMAAction, N read_remote; await submit()
  after:  connect(url) once per owner; register buffer; 1 read; wait_all(60 s); unregister;
          the fields are views into that buffer
release
  before: in `finally`, so a failed step also released
  after:  only after a successful gather; a failed step leaks the batch and the run ends

Since the last review

The only new commit is b93af9f (docs).

  • Resolved: the description no longer mentions a CUDA-context workaround.
  • Resolved: torchtitan/rl/README.md and scripts/install_rl_env.sh now say NIXL alone serves RDMA microbatches.
  • I re-checked the code at HEAD (rdma_microbatch.py, batcher.py, controller.py) and found no new problems.

Must fix

  1. Main-path performance evidence (still open). Every RL run now pays for:

    • a CPU memcpy per large tensor in the GIL-bound batcher;
    • a spinning NIXL progress thread in the batcher process;
    • a register_memory of pageable memory per microbatch read;
    • a pool that never shrinks.

    CLAUDE.md #6 says main-path performance and memory must not change silently. Please add a before/after run on one representative recipe, cross-host if possible. Report medians of timing/step/forward_backward, the wait_for_microbatch span / read_s, and batcher RSS. If the numbers match, this is ready to approve.

Questions

  • Coordination (still open): wwwjn's #6469 builds a second never-unregister pool over torch transport for the same NIXL problem, citing pytorch#206300 rather than nixl#1267. #5862 unifies the RDMA object for microbatches and prompts. Landing this first is fine if #6469 then reuses _OwnerPool and the two PRs agree on one upstream link for the TODO. Could you and @wwwjn confirm?
  • #6423 (Batcher -> TrainingBatchBuilder rename) and #6427 on top of it touch the same files, so whichever lands second needs a rebase.
Details
  • Gate. Still passes. The PR deletes the injected register_rdma_microbatch plumbing and Monarch's RDMA backend check. Both RDMA paths now use the transport that ModelStateDictTransport already uses.
  • Checked at HEAD:
    • register and read walk the _TensorRefs in the same tree_leaves order with the same _aligned offsets.
    • Every view starts at a multiple of 16, so .view(dtype) is valid for any dtype.
    • __reduce__ passes the arguments in field order and leaves out registered.
    • drop() clears registered, so a second drop() is a no-op.
    • The only maybe_release_oldest_batch call (controller.py:1481) runs after every rank's forward_backward returns, and before the NaN break.
    • An exception from the gather propagates out of _trainer_loop, so the skipped release can't shift the FIFO for a later step.
  • Overlap searches: "rdma microbatch", "RegisteredBufferPool". Found #5862, #6302, #6303, #6324, #6469 (wwwjn), #5764 (felipemello1), #6423 and #6427 (tianyu-l).

Not verified: the semantics of RemoteBuffer.length and the no-argument to_mutable_view() (the real-NIXL CPU tests exercise them), and any GPU or multi-host performance.

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

[rl] One RDMA transport: move microbatches and prompts to torch.distributed._transport

2 participants