Repository navigation
Conversation
|
@claude please review |
|
Claude finished @felipemello1's task in 4m 10s —— View job Needs discussion: the new knob has no in-repo consumer, the only measurement shows it slower, and the delta path may drop |
There was a problem hiding this comment.
Verdict: Needs discussion -- the code is small and well placed, but the new knob has no in-repo consumer, and the only measurement shows it slower. Maintainers need to decide whether it lands before a bandwidth-bound run shows a win.
What this PR does. It adds Controller.Config.model_state_dict_delta_max_fraction. When the field is set, the trainer builds a ts.StateDictDelta after loading the checkpoint, and each push calls ts.put_state_dict_delta: a full put plus one row per shard of up to f changed (value, index) pairs, diffed against a pinned-host copy of the previous version. Generators call ts.get_state_dict_delta into their persistent pinned prefetch buffers. Tensors whose rows overflowed, or that missed a version, are read in full.
Example.
config.model_state_dict_delta_max_fraction = 0.05
v1: trainer full put + rows (count=-1, overflow) -> generator reads every tensor in full
v2: 1.5% of bf16 elements changed -> rows hold them; generator reads 225 MB of rows,
scatters them into prefetch buffers, reads nothing in full
before (None): every version, every generator reads the full 1.5 GB
Must fix
torchtitan/rl/trainer/trainer.py:474-- the delta path dropsdirect_rdma=False. The pull of version N overlapsoptim_stepN+1 (controller.py:1230), so full reads must come from a StorageVolume snapshot, not from live GPU tensors. The delta put needs to forwarddirect_rdma(torchstore#279) and passFalsehere. Unverified whether torchstore's default already makes this safe.torchtitan/rl/controller/controller.py:305-- no recipe or test turns on this knob, the measured result is a regression on loopback, and users have no metric to tunefwith. Before landing, it needs either a measured win (cross-host or many-generator egress) plus a recipe that enables it, or an explicit maintainer decision to land it ahead of that evidence.- Merge order: the new trainer test patches
ts.put_state_dict_delta, which doesn't exist ontorchstore@main, and that is what CI installs. This PR can only land after torchstore#279.
Should consider
tests/rl/unit_tests/cpu/test_trainer.py:125-- fold the new test into the existing full-path test by parametrizing over the delta.torchtitan/rl/trainer/trainer.py:458-- with the delta set,_model_buffer_names(...)is still computed on every push and then ignored, becauseStateDictDeltaholdspreserve_dtype_keysfrom construction. Skip it on the delta path, or don't pass it at all.- The "Summary (human-written)" section only has the stacking and dependency links. The author should add a sentence or two in their own words.
Questions
- Does the delta path work with the colocated SharedMemory transport that
push_model_state_dict's docstring describes? If it isn't supported, or isn't useful there (the full put is already a local copy), it should raise in__post_init__rather than silently run the slower path.
Details
- Placement: putting the field on
Controller.Configmakes sense, because it configures both the trainer and the generators, which only the controller spawns. Validation is in__post_init__. The generator takes aboolderived from it and doesn't need the fraction. - Ordering invariant:
generator.py:449documents that a pull overlapping a push leaves the buffers permanently stale._trainer_loopkeeps that ordering (each pull waits for its push, and the next push waits for the previous pull). Nothing else enforces it, but torchstore's per-row (epoch, version) catches restarts and missed versions. - PP: each PP rank publishes a partial state dict under the same key with its own epoch. torchstore#279 tests rows from several publishers at different versions, so this should compose. Not exercised in this repo.
- Memory: the description puts GPU compare temporaries at per-tensor size. They are allocated in the push worker while forward/backward N+1 is running, so they add to peak activation memory when the knob is on. Default-off, so the main path is unaffected.
- Smallest alternative if maintainers want this in now: same diff minus the duplicated test, plus
direct_rdmaforwarded. About +40 lines.
Not verified: torchstore's direct_rdma default; behavior with the SharedMemory transport; GPU runs.
| delta = self._model_state_dict_delta | ||
| if delta is not None: | ||
| asyncio.run( | ||
| ts.put_state_dict_delta(delta, model_state_dict, "model_state_dict") | ||
| ) | ||
| return |
There was a problem hiding this comment.
The delta path loses the explicit direct_rdma=False that the full path passes. In torchstore#279, routing.delta.put_state_dict_delta calls state_dict_utils.put_state_dict(store, state_dict, key, transfer_dtype=..., preserve_dtype_keys=...) with no direct_rdma, and ts.put_state_dict_delta has no way to pass it.
This matters because of how the controller orders things: the pull of version N is awaited only after optim_step N+1 (controller.py:1230). If the full put registers live GPU tensors, a generator whose row overflowed and does a full read (always the case for version 1) can read weights while the optimizer is changing them. That corrupts the weights silently, and every later delta builds on top of the bad copy. The generator comment at generator.py:447 ("StorageVolume snapshot so generators do not read live trainer GPU tensors") relies on this snapshot.
Unverified: I couldn't check the default of direct_rdma in state_dict_utils.put_state_dict. If the default is False, this is fine today, but the invariant then depends on a torchstore default. Smallest fix: forward direct_rdma through put_state_dict_delta in torchstore#279 and pass direct_rdma=False here, the same as the full path.
| asyncio.run(run()) | ||
|
|
||
|
|
||
| def test_push_model_state_dict_puts_delta_on_push_stream_in_worker() -> None: |
There was a problem hiding this comment.
This test copies the full-path test above it almost line for line (worker thread, stream.synchronize before the put, __exit__ after it). The only difference is which ts function gets awaited. A smaller option is to parametrize the existing test over delta in (None, MagicMock()) and assert which put was awaited.
Also, patch("...ts.put_state_dict_delta") raises AttributeError until torchstore#279 is merged. CI installs torchstore@main (scripts/install_rl_env.sh:79), so this test fails until then.
| model_state_dict_delta_max_fraction: float | None = None | ||
| """Send generators only the elements of the model state dict that changed | ||
| since the previous version; None pulls the full state dict every version. | ||
|
|
||
| The trainer still publishes the full model state dict every version, plus | ||
| one fixed-size row per tensor shard holding up to this fraction, in (0, 1], | ||
| of the shard's elements. A generator that holds the previous version | ||
| scatters those rows and reads in full only the tensors whose rows | ||
| overflowed. Rows cost ``fraction * (wire dtype size + 4)`` bytes per | ||
| element on every pull, so set it just above the typical changed fraction | ||
| of a step. The trainer keeps one more CPU copy of its model state dict | ||
| shards, in the transfer dtype, to diff against.""" |
There was a problem hiding this comment.
This adds a knob that no recipe or test in the repo sets, and the only measurement given shows a regression: prefetch takes 0.18-0.50 s vs 0.12-0.18 s, and the trainer push gets 0.13-0.24 s slower. Under rules/config.md ("Expose only options a verified recipe uses"; "how would a user decide how to set this?"), it needs a run where the knob wins, such as cross-host generators or N generators sharing trainer egress, with numbers for that setup. Then it needs a recipe that turns it on.
"Set it just above the typical changed fraction of a step" doesn't help anyone yet: there is no metric for the changed fraction (listed as a follow-up). So the user has no way to pick a value. Either land the metric in this PR or note this as a TODO in the docstring.
Adds Controller.Config.model_state_dict_delta_max_fraction. When set, the push worker publishes the model state dict with ts.put_state_dict_delta: it compares the live GPU tensors against the previous version kept in pinned host memory, then puts the full state dict and one fixed-size row of changed elements per shard. Generators pull with ts.get_state_dict_delta into their persistent prefetch buffers, falling back to a full read per tensor on overflow or a missed version.
3ad6d49 to
ec48935
Compare
…5996) Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.18.0) (oldest at bottom): * #6097 * #5997 * __->__ #5996 ## 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 RL syncs the trainer's model state dict to the generators through TorchStore, which adds a store, controller and extra copies around the transfer. With 14B on one 8xB200 host (trainer FSDP 4, generator TP 2, NIXL) a TorchStore pull takes 10-13 s (2.3-3.0 GB/s); with this transport the same pull takes 0.6-0.9 s (RDMA read at ~60 GB/s per generator rank). `torch.distributed._transport` now provides one-sided RDMA reads over Mooncake/NIXL, so the generators can read the trainer's shards directly. ## What changed - `torchtitan/rl/model_state_dict_transport.py` (new): - `shard_layout` / `_staged_pieces`: each trainer rank stages, per generator rank, the intersection of its FSDP box with the generator rank's box, cast to the generator dtype and 16 B aligned, in one registered pinned CPU buffer (pinned with cudaHostRegister, since `pin_memory=True` rounds up to a power of two). Generator ranks that need the same piece (e.g. a TP-replicated tensor) share one staged copy, so the buffer is about the trainer shard size at the transfer dtype. - `_staged_placements`: where a trainer shard cuts a generator shard on a dim after the first sharded dim, the trainer stages that DTensor with its later-dim shards moved to the first sharded dim, via one `redistribute` (an all-to-all within its mesh) in `stage`; e.g. a row-parallel weight (FSDP `Shard(0)`, TP `Shard(1)`) read by a generator split on dim 0 is staged as `(Shard(0), Shard(0))`: one read per piece instead of one per row. A generator TP on dim 1 matching the trainer's needs no restage. The decision uses every trainer rank's box, so all trainer ranks agree (the redistribute is a collective). - `_plan_reads`: each generator rank plans reads from every trainer rank straight into its prefetch buffers, one contiguous read per piece per index of the dims before its sharded dim (1 for a 2-D weight, 2 for a stacked `[2, F, D]` w13 sharded on F). HSDP replicas are spread round-robin across generator ranks. Raises if the trainer does not cover a shard exactly, and on `Partial` or uneven `_StridedShard` placements. - `shared_rank_layouts`: checks every generator reports the same per-rank layout. - `ModelStateDictTransport`: `register_trainer_source` + `stage` (trainer; a collective when restaging), `connect_generator` + `read` (generator). `read` fails after `Config.read_timeout_s` (default 600 s) instead of hanging on a stuck transfer; the job must then restart. - Every generator key must be fully covered by the trainer, or init raises (TorchStore loads with `strict=False`). Trainer keys no generator has (e.g. ones the generator drops) are not staged. - `Config.backend` selects the `torch.distributed._transport` backend: `"mooncake"` (default) or `"nixl"`. - Unused until the next PR wires it in behind a config flag. - Mooncake needs a PyTorch nightly from 2026-11-10 or later (Mooncake transport pytorch/pytorch#202780, multi-peer pytorch/pytorch#202536 and pytorch/pytorch#203461, poller fix pytorch/pytorch#203623). The staging buffer is laid out per staged piece, so a later delta sync can stage and read a subset of pieces without changing the plan. ## Alternatives considered - Keep TorchStore: its extra hop and copies are the bottleneck measured above. - Read directly from trainer GPU memory: a pull would then race the next optimizer step, and dtype casts would still need a staging copy. - Monarch RDMA (as `rdma_microbatch.py` uses for microbatches): ties the trainer and generator cores to Monarch and offers no Mooncake backend; `torch.distributed._transport` is PyTorch-native and backend-selectable. ## Related drafts - #5751, #5872 (delta sync), #5778 (TorchStore control plane), #5484 (pinned prefetch buffers), #5844 and #5846 (LoRA syncs) change the TorchStore path. They are independent of this PR; delta and LoRA syncs can move onto this transport by staging and reading a subset of pieces. ## Size Implementation +544, tests +451. ## Testing - `pytest tests/rl/unit_tests/cpu/test_model_state_dict_transport.py` (19 pass): checks `Config.backend` reaches `new_transport`, and runs `register_trainer_source`/`stage`/`connect_generator`/`read` over an in-process fake transport and checks every element lands in the right place and every read targets a connected trainer rank, with a bf16 cast, for HSDP 3x4 -> TP 1/2 on either dim (replica assignment across two generators), a stacked `[2, F, D]` weight sharded on F -> TP 1/2 on F or D (multi-run reads), mixed dtypes with `preserve_dtype_keys` and an odd-sized key (alignment), generator ranks sharing a replicated piece (one staged copy), a generator rank with an empty shard, incomplete or overlapping coverage and dtype mismatches (raise), mismatched generator layouts, and rejecting `Partial`/uneven `_StridedShard`. A 4-rank gloo test stages real FSDP 2 x TP 2 DTensors (row-parallel `(Shard(0), Shard(1))`, colwise FSDP over TP `(_StridedShard(0), Shard(0))`, stacked w13 `(_StridedShard(1), Shard(1))`, and a small `(Shard(0), Shard(1))` key on which 2 ranks have no pieces but must still join the restage) and reads them into generator TP 2 shards on two layouts, asserting the restage decision per layout (none when generator TP matches trainer TP on dim 1; `(Shard(0), Shard(0))` for row-parallel and the small key when the generator splits dim 0). This catches layout/offset bugs that would otherwise silently corrupt weights. - End-to-end numbers are in the next PR. AI-assisted (Claude).
Summary (human-written)
Stacked on #5659. Depends on meta-pytorch/torchstore#279 (
StateDictDelta,put_state_dict_delta,get_state_dict_delta).Why
Each generator pulls the full model state dict every version, even though an RL step with a small LR changes only a small fraction of the elements in the transfer dtype. In the Qwen3-0.6B run below, 1.1-1.8% of the bf16 elements change per step, yet every pull reads all 1.5 GB.
Example.
What changed
Controller.Config.model_state_dict_delta_max_fraction: float | None = None, validated in__post_init__. None keeps today's behavior.ts.StateDictDeltaafter loading the checkpoint. The push worker thread from [rl] Put GPU weights directly into TorchStore, drop trainer staging buffers #5659 callsts.put_state_dict_deltainstead ofts.put_state_dict. It compares the live GPU tensors on the push stream against the previous version kept in pinned host memory, then puts the full state dict and the rows.prefetch_model_state_dictcallsts.get_state_dict_deltainto the existing prefetch buffers, which keep the previous version between pulls.Alternatives considered
put_state_dict: a generator that starts late or misses a version would have nothing to fall back to.User-facing changes
model_state_dict_delta_max_fraction=fpulls only changed elements (up tofper shard)Numerics
Generator weights are bitwise identical to a full pull. In the e2e run, the generator also did a full pull into a copy on every step and compared the bytes; no tensor mismatched on any step.
Performance
Qwen3-0.6B (751.6M elements, bf16) on a single host over loopback. The trainer runs on 1 GPU, 2 generators,
max_fraction=0.05:f=0.05:Testing
pytest tests/rl/unit_tests/cpuagainst the torchstore PR: 488 passed, 9 skipped, 1 failed. The failure,test_rl_recipes_get_model_defaults[dapo_math], also fails without this change (environment).Known issues / follow-ups
ts.put_state_dict_deltawithcreate=Trueuntil then).Lines: impl +58/-12, tests +36/-15.