Repository navigation
Implement delta model state dict transport - #6309
tushar00jain wants to merge 1 commit into
Conversation
f08c937 to
6d4e66d
Compare
6d4e66d to
e656bd5
Compare
e656bd5 to
abcc251
Compare
abcc251 to
6b79270
Compare
6b79270 to
86e665d
Compare
|
@claude review |
There was a problem hiding this comment.
Verdict: Needs discussion -- three open PRs implement the same feature (#6309, #6311, #6176). Maintainers should pick one before line-level polish. At the scale measured here, the pull is already hidden behind forward/backward, so the value case still needs to be made.
What this PR does. Adds ModelStateDictDeltaTransport. After the first push, the trainer diffs its staging buffer against the previous push on the GPU, in 64 MiB windows. It then zstd-compresses one [gaps | XORs] record per changed staged piece into a registered delta buffer. Each generator rank RDMA-reads only its own pieces' records and XORs the changes in on the GPU during the load. CPU threads then write the same changes back into the prefetch buffers in the background.
Example. Qwen3.5-27B, push N+1 changes about 2% of the bf16 words.
- Full sync: each generator reads 53.8 GB (2538 RDMA reads).
- Delta sync: each generator reads about 1 GB (about 215 reads). It decompresses those, copies the push-N prefetch buffer to the GPU as before, and XORs the changed words in there.
- Fallbacks to a whole read: first push, missed push, more than 1/16 of a window changed, or a buffer overflow.
Must fix
- PR description. "Summary (human-written)" is empty. Under Numerics, "Mean reward 0.277 vs 0.250" can only be run-to-run noise if the weights are bitwise identical. Say so, or drop it, and treat the 10.2k -> 10.7k tok/s (5 steps) result with the same caution.
model_state_dict_transport.py:349--sync_modestring selects the subclass; use aConfigsubclass instead (config.md).model_state_dict_delta_transport.py:277-- a trainer rank that stages nothing silently forces whole reads on every pull.model_state_dict_delta_transport.py:27-- imports five_privatenames from the base module; decide now rather than leave a TODO.MODEL_STATE_DICT_DELTA_TRANSPORT.md:3-- the doc says "main's" for the base class, has a typo, and leaves the fallback section empty.
Should consider
model_state_dict_delta_transport.py:254-- casts the whole local shard once per piece per window; cast only the piece.model_state_dict_transport.py:63-- base metadata carries delta-only fields; move them to a delta subclass.model_state_dict_delta_transport.py:408-- pinned allocations on every pull through the caching host allocator (possible source of the unexplained generator RSS).model_state_dict_delta_transport.py:54-- 32 codec threads per rank, which at 8 ranks per node is 256 per node.
Questions
- Which PR lands? #6311 (per-window records, also open) by your own numbers compresses 3x faster (0.08-0.12 s vs 0.23-0.35 s) and needs 4 RDMA reads instead of about 215, with "same pull time". #6176 is a third approach. The table compares against #6142 (closed), not #6311. Please close the PRs you are not pursuing, and coordinate with @wolfcomos on #6176.
- Where does this matter? Blocking pull per step is 0-0.045 for full sync vs 0-0.032 for delta, and the pull (about 1.5 s) overlaps about 35 s of forward/backward. What configuration puts the pull on the critical path: more generators per trainer, lower bandwidth, or sync RL? A measurement or estimate there would justify the +1746 lines, the
zstandarddependency, and the +5.6 / +17.8 GiB RSS on trainer / generator. - Is
load_groupsneeded? It is plumbed through the engine ABC, vLLM, SGLang, the loader, the generator and the baseconnect_generator, and_Groupexists only to batch one H2D copy and one cumsum per FSDP group. Was computing per-key positions on the CPU at decode time and copying them per key measured as too slow? That alternative would delete the plumbing in 6 files.
Details
Checked, and found no problems with:
- Gaps -> positions. The running sum with per-piece
shiftsin_Group.pack/positions_ongives the right positions. Keys stay contiguous because the changes are sorted by key. - Window -> piece slicing.
searchsortedover the sortednonzero_staticpositions, plus the offset(window.lo - start) // 2, picks each piece's part of the window correctly. - Padding. The padding between pieces comes from
old, so it never shows up as a change. - Odd-byte pieces. Rejected at
connect_generator. - Ordering. The controller awaits pull N before push N+1 (
controller.py:1430-1438), so overwriting the delta buffer infinishis safe.sourcesandmetadata_by_trainer_rankboth come from.values()on the same trainer mesh, so their orders match. - Unloaded reads. A read that was never loaded is written back by
write_back_restbefore the next read's deltas are applied. - Trainer restart. It resets
pushto 0, and the generator'spush == last + 1check forces a whole read.
Remaining assumption: every load is preceded by a read. A second load with no read in between would copy from the prefetch buffers while the background write-back is still running. The router never does this today, but nothing asserts it.
Not verified: GPU timings, the RSS attribution, and the thread oversubscription; these need a multi-rank-per-node run.
86e665d to
cb0d20b
Compare
cb0d20b to
8994728
Compare
|
@claude review again independent of discussion on what which implementation should be picked and mark resolved comments as resolved |
|
Claude finished @tushar00jain's task in 4m 38s —— View job Needs discussion: the earlier must-fix items are fixed. Three small items remain, and the choice between the PRs is still with the maintainers. I can't resolve review threads from this job, so the review lists which ones you can resolve. See the review. |
47779d4 to
534fd7a
Compare
… piece Alternative to delta-weight-sync/1 (one record per 64 MiB window of the staging buffer): with sync_mode="delta", each push after the first sends only the bf16 words that changed since the preceding push, as one zstd-compressed record per staged piece: the gap before each changed word and the word XOR its old value. The trainer compares each piece with its staging buffer on the GPU in chunks of at most 64 MiB, which bounds its scratch memory, stages each changed word's position and XOR, and finish_stage compresses one record per piece into a registered delta buffer. The push returns a DeltaRecord per piece (offset, size, gap width, count), which the controller forwards to the generators. A generator rank reads the records of exactly the pieces it reads, decompresses them on CPU threads, packs them per FSDP load group, and XORs them into the weights its load copies; CPU threads then apply them to the prefetch buffers in the background. The first push, a missed push, and a push with more than 1/16 of a chunk's words changed are read whole. fs-branch: tushar00jain/9
534fd7a to
0b802a4
Compare
…er override; agent self-review; rl/transport (#6407) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it approved, 30 then got a formal "request changes" from a maintainer, and about 20 more got substantive inline asks. In nearly all of them the bot either saw the problem and approved anyway, or never asked the questions maintainers ask most ("does the repo already do this?", "who should own this?"). The opposite failure, the bot blocking something a maintainer was fine with, is rare: in the PRs we sampled, 2 of its 81 must-fix items were wrong and about a third were minor (the empty human-written summary was the biggest source). **Example** (#6112, controller sizes the rollout worker pool): ``` before: bot approved 10 times; tianyu-l then blocked: "the controller reads rollouter.rollouts_per_worker to compute a count it hands back to the Rollouter -- violates encapsulation" after: same commit, new skill -> Request changes, must-fix #1: "controller.py:589 -- wrong owner for the worker count ..." ``` There was also no way for a code owner to overrule the bot except dismissing its review in the GitHub UI, and a later `@claude review again` would block again. ## What changed **Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`): - Verdict rules: Approve only when every remaining item is an edit the bot could write itself. Anything the author still owes (a design change, an unexplained golden change, evidence the PR rests on) is Request changes; anything only a maintainer can decide is Needs discussion. A hedge like "a maintainer should decide" can't come with Approve. - Always must-fix: a violated written rule, a silent wrong result, a second definition of an existing concept, a gate finding. - Design gate: new questions for the existing counterpart, in-repo ownership, and the design behind a bug; "ban only what doesn't work on main"; read the numbers behind a claim. The overlapping-PR search is mandatory and reported. - Re-review covers every commit since the last full review, including code taken from the bot's own suggestions. A scoped question gets a `COMMENT`, not a whole-PR verdict. - The bot fact-checks its own proposed fixes, and cites a source for claims about external tools or marks them unverified (never must-fix). - An empty "Summary (human-written)" is a one-line "Before merge" note that never affects the verdict. - Checklist: config ownership direction, general shared wrappers, dead code the PR creates, model variants as flavors, a mechanical pass over every new or changed function. **Code owner override** (`SKILL.md`, `claude-code.yml`, `CONTRIBUTING.md`): a code owner comments `@claude override` (optionally `@claude override 2,3: <reason>`); the bot approves if nothing else is open and doesn't re-raise the overridden items. A code owner's GitHub approval or "LGTM" is not an override, so a teammate can approve without the bot dropping its findings. Dismissing the bot's review still unblocks the PR, but isn't an override: the bot can't tell who dismissed it. **Agent self-review** (`CLAUDE.md`, `pr-description`): an agent preparing a PR runs `pr-review` in branch mode first and records unaddressed items in an optional "Self-review" section. PRs written without an agent are unaffected; a missing section is never a finding. Where each new rule comes from (maintainer asks the bot missed): | Change | PRs | | --- | --- | | No Approve with open design/evidence items or a "maintainer should decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 | | Author waiver can't clear a must-fix | #6201, #6202, #6203 | | Existing counterpart; one source of truth | #5228, #6169, #5881, #5823, #5824, #6059, #5812 | | Responsibility owner; config ownership direction | #6112, #6332, #5802, #5803, #6325 | | Fix the design behind the bug; a TODO doesn't justify a workaround | #5572, #5689, #5657 | | Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819, #5543 | | Re-review covers all new commits; scoped asks don't approve | #5824, #5842 | | Mandatory overlap search | #5885, #6248 | | Ban only what doesn't work on main | #5543 | | Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868 | **Rules**: `design.md` gets the one-general-wrapper rule (moved from `models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the consumer owning its values; `config.md` gets ownership direction and "a Config doesn't read runtime state"; `direction.md` calls all-to-all the MoE reference implementation, so a new vendor-specific dispatch path (e.g. #6242) needs a reason the existing backends can't serve. **Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/` -> d4l3k. **Mechanical, skim**: `torchtitan/rl/transport/` holds data movement between RL actors. - `rl/model_state_dict_transport.py` -> `rl/transport/model_state_dict.py` - `rl/MODEL_STATE_DICT_TRANSPORT.md` -> `rl/transport/MODEL_STATE_DICT_TRANSPORT.md` - `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py` - tests: `tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py` -> `tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py` - imports, READMEs and `scripts/install_rl_env.sh` updated; no code changes. ## User-facing changes | Before | After | | --- | --- | | Overrule the bot: dismiss its review in the UI, and it blocks again on the next run | `@claude override [items]: <reason>`; the bot approves and doesn't re-raise them | | Empty human-written summary: bot must-fix | One "Before merge" line, no effect on the verdict | | `from torchtitan.rl.model_state_dict_transport import ...` | `from torchtitan.rl.transport.model_state_dict import ...` | | `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from torchtitan.rl.transport.rdma_microbatch import ...` | ## Testing Backtest: the new skill run locally (nothing posted) on each PR at the commit and thread state the bot originally saw. | PR | Bot then | New skill | What the maintainer asked | | --- | --- | --- | --- | | #6112 | Approve | Request changes | worker-count ownership (caught) | | #5837 | Approve | Request changes | apply to `dp_shard` too (caught) | | #5572 | Approve | Request changes | delete the injection design (caught) | | #6201 | Approve after author waived pins | Request changes, waiver ignored | pins broke GPU tests after merge (caught) | | #6007 | Approve | Request changes | fold K3.1 into K3 (caught) | | #5543 | Request changes: "ban it" | Request changes: keep main's path | don't break gpt-oss + DeepEP (fixed) | | #6144, #5905 (controls) | Approve | Approve | -- | | #6137 (control) | Approve | Needs discussion | -- (merge gate on an upstream API) | Code owner override, simulated on #6201: override by a code owner lifts the named item; `@claude override` from the author changes nothing; a code owner's "LGTM" approval followed by "review again" keeps Request changes. Transport move: 83 RL CPU unit tests pass locally (`transport/test_model_state_dict.py`, `test_trainer.py`, `test_engine_loop.py`). `transport/test_rdma_microbatch.py`, `test_generator.py` and `test_batcher_actor.py` fail to collect in my env on `origin/main` too (stale attention-gym / Monarch), so CI is the check for those. ## Known issues / follow-ups - Open PRs that edit the moved files rebase cleanly (git follows the renames), but new imports of the old module paths will break: #6309 (adds a delta transport that should live in `rl/transport/`), #6237, #6176, #6177, #5862, and drafts #6127, #6393, #6163, #5764. - The Actions bot can't read dependency source (e.g. SGLang); follow-up for the workflow. ## Self-review pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch mode diffs against `origin/main` and skips description findings before a description exists; the "Config doesn't read runtime state" rule no longer contradicts hardware validation; dismissal dropped as an override form (the bot can't tell who dismissed); `test_rdma_microbatch.py` added to the transport area. Not addressed: - One concern per PR -- the five changes ship together at the maintainer's request. - Open PRs touching the moved files -- listed above; the maintainer will coordinate.
| assert self._trainer_delta is not None | ||
| return self._trainer_delta.compress_records() | ||
|
|
||
| def connect_generator( |
There was a problem hiding this comment.
This method is used by "gpu-fetch" in #6237, so it seems delta transport support both "cpu_prefetch" and "gpu_fetch" right? The diagram in PR summary seems only showing the "cpu_prefetch" path.
It's a bit hard for me to understand the details from the code. Maybe a system diagram using @felipemello1 's skill could help? https://artifacts.internalmeta.com/?source=favorites&cards=1481387240597243&full=0
In general I have some high level questions for both paths
- where does the compression / decompression happen?
- where do we store the generator base checkpoint -- if storing on CPU (as the torchstore path does right now), we will OOM on large models like Kimi K3. Miles / humans& puts it on shared disk storage, which could also help with [rl] Weight sync fan-out to many generators #6072? Sorry that I'm bringing up two other issues (CPU memory limit, scaling to many generators)
- overall a comparison between this solution and https://humansand.ai/blog/gpu-accelerated-weight-teleportation, or Miles' current options
There was a problem hiding this comment.
Did you check out torchtitan/rl/MODEL_STATE_DICT_DELTA_TRANSPORT.md? it has a walkthrough with diagrams
where does the compression / decompression happen?
on the cpu in this pr - that's why the xor delta is sparse. a full xor was too slow on cpu
where do we store the generator base checkpoint
this is only for the path where we transfer from trainer gpu to generator cpu - so we're just using the buffer that already exists
the new buffers added in this pr are both bounded to the size of the largest fsdp group - that should be smaller relative to model size?
maybe we can add disk storage separately as a follow up? seems independent of delta i.e. we probably need to stream the existing cpu buffer to disk
overall a comparison
there's a table in the pr description though I can add more details
There was a problem hiding this comment.
Did you check out torchtitan/rl/MODEL_STATE_DICT_DELTA_TRANSPORT.md? it has a walkthrough with diagrams
Sorry I couldn't follow the .md -- could you make it more accessible? Aside from the .md, I'm interested in learning justifications of the design choices you made.
there's a table in the pr description though I can add more details
I did see some table, but I didn't see the comparison with Humans& or Miles. Related to above point, I would love to understand where we are different from them.
Maybe we should also have an interactive session?
There was a problem hiding this comment.
Hi, quick question adding to the discussion above: does current delta transport leave room for an accelerator option later, where the trainer encodes on the GPU/accelerator and the generator decodes and applies the changes in place into its live weights? Not for this PR, just a seam to plug it in.
| self._windows = [] | ||
| for (lo, hi), window_piece_list in zip(bounds, window_pieces): | ||
| capacity = _delta_capacity(hi - lo, capacity_divisor) | ||
| positions = pinned_buffer(capacity * torch.int32.itemsize) |
There was a problem hiding this comment.
the original tensors' finalizers unpin these buffers while their int32 and int16 views are still alive, so the GPU-to-CPU copies block during staging. could we keep the original positions, XOR, and count buffers alive alongside their views?
| (`old`), assemble this push's window (`new`), stage the changes, then write | ||
| `new` back. | ||
|
|
||
| Comparing one window at a time bounds the trainer's GPU memory: the temporaries |
There was a problem hiding this comment.
locally a 64MB window peaked at about 400MB of GPU scratch, including a 256MB int64 temporary from changed.sum(). could we avoid widening the mask and update the 180MB estimate here?
| """Each 64 MiB window of the staging buffer sends at most 1 / | ||
| ``capacity_divisor`` of its words; a push with more changes in a window is | ||
| read whole. It sizes the trainer's pinned buffers of changes and the | ||
| registered delta and receive buffers (1 / (2 x ``capacity_divisor``) of the |
There was a problem hiding this comment.
the buffers reserve 4 bytes per changed 2-byte word they allow, so a 64MB window needs 8MB at the default divisor of 16 rather than the 2MB the docstring implies. could we update the docstring to match?
| | | ||
| | load_groups = [["wq", "wk"], ...] -> both in group 0 | ||
| v | ||
| _Group.pack (pinned buffers, one per group) |
There was a problem hiding this comment.
the packing example should start with wk because _Group.pack sorts by key, and _pending is keyed by load group index. could we update the example and show that the last load group contains model buffers in their original dtypes?
Summary (human-written)
Compared various approaches. Given these constraints
This seems like a decent approach
torchtitan/rl/MODEL_STATE_DICT_DELTA_TRANSPORT.mdworks through an example to illustrate the design.Why
Every pull reads the whole model state dict, though an RL optimizer step changes
about 2% of bf16 words. On Qwen3.5-27B each generator reads 53.8 GB per pull;
with delta sync it reads 0.75-1.00 GB, and generator weights stay bitwise
identical to full sync.
What changed
A new
ModelStateDictDeltaTransport(model_state_dict_delta_transport.py, docMODEL_STATE_DICT_DELTA_TRANSPORT.md), selected by placingModelStateDictDeltaTransport.ConfigwhereModelStateDictTransport.Configgoes. Its
Configaddscapacity_divisor(default 16: the most changed words a64 MiB window sends, as a fraction of its words) and
codec_threads(default 32:compression and decompression threads per process). Mechanical:
prepare_transferreturns per-push metadata that the controller forwards toeach generator's
read;connect_generatortakes the generator's FSDP loadgroups; three transport helpers become public.
Read whole, as full sync: the first push, a missed push, more than
1 /
capacity_divisorof a 64 MiB window changed, records over the trainer'sdelta buffer, or a generator rank's records over its share of the receive buffer.
Alternatives considered
nonzeroload_groups)connect_generatorUser-facing changes
ModelStateDictTransport.Config(backend=...): every pull reads the whole stateModelStateDictDeltaTransport.Config(backend=...): after the first pull, only changes;ModelStateDictTransport.Configstays full syncNumerics
Bitwise exact: generator weights match full sync bit for bit (unit tests with
rtol=0, atol=0, and a local check on the 27B layout).Performance
Qwen3.5-27B DAPO-Math, 4 generators, GB300, at 8994728.
ModelStateDictTransport)ModelStateDictDeltaTransport)forward_backwardincl. overlapped staging (steps 2-6)Memory
_Groupbuffers (power-of-two rounding); ~4.9 GiB heap, mostly the write-back's int64 positions (~4.4 GiB at peak)The receive-buffer and pinned-allocator figures are measured (RSS and
torch.cuda.host_memory_stats()logged before and after each phase); the heapfigures are inferred from RSS growth and buffer sizes.
CPU threads
Each process uses
Config.codec_threadscodec threads (default 32). A GB300 hosthas 144 CPUs and runs 4 ranks, each with a 72-CPU affinity, so 64 codec threads
per 72-CPU set.
Testing
pytest -q tests/rl/unit_tests/cpu/test_model_state_dict_transport.pyplus the generator, engine-loop, trainer and router tests.
test_model_state_dict_transport.py)Known issues / follow-ups
_Groupbuffers at exact size would recover ~3 GiB (est.) but could slow the pullprevious write-back competes with the next decompress (one 1.72 s pull out of 6).
replicated over trainer TP are read from alternating ranks, which breaks up runs.
Pull time isn't affected (RDMA wait 12-166 ms).