Repository navigation
[rl] Batch generator weight reads when the transport supports it - #6393
samnordmann wants to merge 3 commits into
Conversation
Use the existing byte-range plan and configured deadline. Keep individual reads on older PyTorch wheels and for a singleton plan.
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows. |
…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.
|
@claude review |
|
Claude finished @tianyu-l's task in 1m 55s —— View job Request changes: the PR relies on an unmerged PyTorch API (pytorch/pytorch#205093) through a |
There was a problem hiding this comment.
Verdict: Request changes -- this PR builds on an unmerged PyTorch API through a getattr version shim. Once pytorch/pytorch#205093 lands, calling read_batch_async unconditionally is a net deletion and needs no second path.
What this PR does. ModelStateDictTransport.read checks whether the transport has read_batch_async. If it does and the plan has more than one piece, it submits all (local, remote) pairs in one call. Otherwise it uses the existing loop of read(..., async_op=True) followed by wait_all. The tests monkeypatch a fake read_batch_async onto _FakeTransport to cover the new branch.
Example. A generator rank pulls 288 tensors from 2 trainers:
main: 288 x transport.read(local, remote, async_op=True) in a thread, then wait_all(works)
PR: torch without #205093 -> same as main (every PyTorch build today)
torch with #205093 -> one read_batch_async(reads); with #205182, NIXL
issues one request per (trainer, memory type pair)
-> 9.17 ms -> 0.76 ms reported
Must fix
torchtitan/rl/transport/model_state_dict.py:500-504-- thegetattrcheck probes for an API no PyTorch build has yet, and it would keep two paths after the API lands. Thelen > 1guard isn't needed, because upstream's default batch handles one piece the same as the loop. Wait for #205093, raise the nightly floor, and callread_batch_asyncunconditionally (see the inline comment).tests/rl/unit_tests/cpu/transport/test_model_state_dict.py:267-308, 322-333-- the new parametrizations only test which branch gets picked. Once there's one path, give_FakeTransportaread_batch_asyncinstead, so every existing test runs it.torchtitan/rl/transport/MODEL_STATE_DICT_TRANSPORT.md:90-95-- the doc describes the fallback, and its grouping claim depends on #205182, which is also unmerged.
Questions
- With #205093 alone (no NIXL grouping from #205182), the batch just loops the same per-pair reads, so the 9.17 -> 0.76 ms number needs both upstream PRs. Can you confirm which upstream builds the measurement used? Also, how much of the end-to-end weight-sync time is the read phase? For a change this small a single number is enough.
Details
- Upstream API, read from
gh pr diffof pytorch/pytorch#205093:Transport.read_batch_async(transfers, *, timeout)dispatches throughasyncio.to_threadand awaitswait_allon one_BatchWork. The default_submit_batchvalidates every pair, then callsread(..., async_op=True)for each non-empty one. So the unconditional call matches today's loop on backends without native batching (Mooncake), and the call doesn't block the event loop. MODEL_STATE_DICT_TRANSPORT.md:25already requires a PyTorch nightly from 2026-11-10 or later. A newer floor is the existing mechanism; a runtime fallback for older wheels isn't. The checklist bans "speculative checks ... or version shims".- Size of the alternative: in
model_state_dict.py, delete the 6-lineto_thread+wait_allblock and thewait_allimport, and add one line. In the tests, move the timeout assertion from the patchedwait_allinto a_FakeTransport.read_batch_async. - Overlap searches (
read_batch_async,model_state_dict transport,nixl): #6309 (delta transport) and #6127 (gpu_fetch) also changemodel_state_dict.py, but none of them changesread()the same way. Coordinate the rebase if #6127 lands first.
Not verified: the GB200 timings and NIXL grouping behavior (#205182) -- no GPU or NIXL here.
Before merge: fill in the human-written summary is already done; no action.
| # Older wheels only support individual reads. A single piece cannot be grouped. | ||
| read_batch = getattr(self._transport, "read_batch_async", None) | ||
| if read_batch is not None and len(self._reads) > 1: | ||
| await read_batch(self._reads, timeout=self._read_timeout_s) | ||
| return |
There was a problem hiding this comment.
getattr(..., "read_batch_async", None) probes for an API that no PyTorch build has: pytorch/pytorch#205093 is still open. Until it lands this branch never runs outside the monkeypatched tests. Once it lands, keeping both paths is a version shim the rules don't allow, since torchtitan RL already requires a recent nightly (MODEL_STATE_DICT_TRANSPORT.md:25).
The len(self._reads) > 1 guard isn't needed either. Upstream's default _submit_batch just loops read(..., async_op=True), skips zero-length pairs, and runs dispatch through asyncio.to_thread. A one-piece batch behaves the same as the current loop.
Smallest fix: wait for #205093, raise the nightly floor in the doc, and replace the whole body after the if not self._reads: return with one line:
await self._transport.read_batch_async(self._reads, timeout=self._read_timeout_s)That also removes the asyncio.to_thread loop and the wait_all import. The PR goes from +5 to roughly -6 lines in this file.
| @pytest.mark.parametrize("rows", [0, 2]) | ||
| def test_zero_or_one_read(monkeypatch, rows): | ||
| read_batch = AsyncMock() | ||
| monkeypatch.setattr(_FakeTransport, "read_batch_async", read_batch, raising=False) | ||
| full = torch.arange(6, dtype=torch.float32).reshape(2, 3) | ||
| (out,) = _transfer( | ||
| monkeypatch, | ||
| [{"w": (torch.zeros(2, 3), ((0, 0), (2, 3)))}], | ||
| [{"w": (((0, 0), (0, 3)), torch.float32)}], | ||
| [{"w": (full, ((0, 0), (2, 3)))}], | ||
| [{"w": (((0, 0), (rows, 3)), torch.float32)}], | ||
| ) | ||
| assert out["w"].shape == (0, 3) | ||
| torch.testing.assert_close(out["w"], full[:rows]) | ||
| read_batch.assert_not_awaited() |
There was a problem hiding this comment.
This test only covers the len > 1 routing branch. rows=0 returns before either path, so assert_not_awaited can't fail there. Once the call is unconditional (see the comment on model_state_dict.py), this parametrization and the batched parametrization of test_mixed_dtypes aren't needed. Instead, give _FakeTransport a read_batch_async that does the per-pair copy and asserts the timeout, the same way the fake wait_all in _transfer does now. Every existing test then runs the one remaining path, and test_no_reads can stay as it was.
| 3. Pull: each generator rank submits multiple planned reads as one batch when | ||
| the PyTorch transport provides `read_batch_async`. NIXL can group pieces from | ||
| the same trainer and memory types into one request. Older PyTorch wheels | ||
| submit each read individually. The deadline is 60s plus the time this rank's | ||
| bytes take at `min_read_bytes_per_s`. A timeout can leave reads in flight; | ||
| restart the job. |
There was a problem hiding this comment.
"Older PyTorch wheels submit each read individually" describes a fallback that should go away (see the comment on model_state_dict.py). The claim that NIXL groups pieces into one request depends on pytorch/pytorch#205182, which is also unmerged. Once both land: "each generator rank submits its planned reads as one batch (read_batch_async); NIXL groups pieces from the same trainer and memory types into one request", and raise the nightly date on line 25.
Summary (human-written)
During weight sync, each generator rank already knows which byte ranges it needs from the trainers, but it submits a separate read for each range. This change submits the ranges together when
read_batch_asyncis available, so NIXL can group compatible reads. Single-range plans and older PyTorch versions keep the existing path. On two GB200 hosts, batching reduced the read phase for 288 tensors from 9.17 ms to 0.76 msDetails (AI-assisted)
The generator already knows every byte range it needs from the trainer. For a multi-piece plan, submit those ranges together when PyTorch provides
read_batch_async. NIXL can then issue one request per trainer and pair of memory types. Single-piece plans and older PyTorch wheels keep the existing read loop.On two GB200 hosts, a BF16 Transformer weight plan with 288 tensors (2.29 MiB) went from 9.17 to 0.76 ms for the read. For 48 tensors (24.05 MiB) it went from 1.72 to 1.42 ms. Fresh direct NIXL took 0.45 and 1.25 ms respectively. These are paired pinned-CPU RDMA reads with GPU staging and loading outside the read timer. Every loaded weight was checked. Both PyTorch paths used the same transport revision, registrations and buffers. All 21 TorchTitan weight-transport tests passed on Linux, including the four-rank DTensor case.
The PyTorch batch API and native grouping are under review. Reusable prepared requests could reduce repeated setup further and would need a separate PyTorch API. Batch API · NIXL grouping