Skip to content

[rl] Model state dict deltas on public TorchStore APIs - #5872

Closed
d4l3k wants to merge 1 commit into
mainfrom
d4l3k/titan-delta-lib
Closed

d4l3k wants to merge 1 commit into
mainfrom
d4l3k/titan-delta-lib

Conversation

@d4l3k

@d4l3k d4l3k commented Nov 5, 2026

Copy link
Copy Markdown
Member

Summary (human-written)

Why

Comparison for #5751 + meta-pytorch/torchstore#279, which implement model state dict delta sync inside torchstore. This PR implements the same behavior in torchtitan on public torchstore APIs, plus one new query (ts.get_state_dict_layout, meta-pytorch/torchstore#298), to show what the general APIs can express and where they fall short.

Between consecutive RL versions only ~0.5-2% of model state dict elements change in the wire dtype, but generators pull the full model state dict every version.

Example.

# before: every version, every generator reads the full model state dict
# after:
controller.model_state_dict_delta_max_fraction = 0.05
# trainer: put full model state dict + "model_state_dict_delta" rows
#   row per local shard = [count, version, epoch, wire dtype] | values | int32 indices
# generator holding (epoch, version - 1): read rows, scatter into its shards;
#   read in full only overflowed (count == -1) or untrusted tensors

What changed

Depends on meta-pytorch/torchstore#298 (ts.get_state_dict_layout); unit tests fail against torchstore main until it lands.

  • torchtitan/rl/model_state_dict_delta.py (new): ModelStateDictDeltaPublisher (trainer; previous version in pinned host memory, chunked GPU compare, fixed-capacity rows) and ModelStateDictDeltaReader (generator; plans with ts.get_state_dict_layout for both keys, maps publisher shards to its own shards, falls back to ts.get_state_dict(..., strict=False) per tensor).
  • Controller: model_state_dict_delta_max_fraction: float | None (None = full pulls). Requires cpu_prefetch; ValueError otherwise.
  • Trainer / generator: call the publisher / reader when enabled. Small, skimmable.

Gaps vs. the in-torchstore version (#279)

  • Rows must be a second state dict of fixed capacity; overflow granularity is a whole shard.
  • No versioned / conditional get: version and epoch checks live in the row header, fallback is reimplemented here.
  • Row reads and full reads can't be pinned to the same replica; the per-rank epoch is only safe because torchstore reads a key from a deterministic replica.
  • torchtitan replicates torchstore's offset, fully-local and wire-dtype rules and uses private DTensor helpers (_compute_local_shape_and_global_offset; TODO in code). _StridedShard correctness is inherited from torchstore's box assumption.
  • Plan is cached for the reader's lifetime; no layout change notification.
  • No precomputed per-destination transfer plan: apply is ~2x slower than Use stateful dataloader to checkpoint data iteration order and token buffer #279.
  • Design question (core principle 3): ~450 lines of transfer logic in torchtitan arguably belong in torchstore.

Alternatives considered

Numerics

Generator weights are bitwise equal to a full torchstore get after every delta pull (Qwen3-0.6B, generator TP2, 6 steps, lr 2e-6, max_fraction 0.05): 28/28 pulls exact across trainer FSDP1 and FSDP2. Trainer numerics unchanged (feature off by default).

Performance

Qwen3-0.6B, 0.5-1.9% elements changed per version:

Path Generator pull (s) Trainer encode (s)
Full get 0.12-0.18 -
This PR 0.27-0.74 0.05-0.76
#279 0.18-0.50 -

Trainer encode adds a host-to-device and device-to-host copy of each shard per push (memory: one extra pinned copy in the transfer dtype). At 0.6B the full get is faster; the delta pays off when pull bandwidth, not latency, dominates (larger models / more generators).

Testing

  • pytest tests/rl/unit_tests/cpu : 552 passed; 2 dapo_math failures also fail on main.
  • test_model_state_dict_delta.py (multi-chunk encode): bitwise tracking across sparse deltas, sub-precision changes, overflow fallback, trainer restart (new epoch), failed full read not trusted as delta base (fails before the held-version fix); shard-to-destination mapping across shardings.
  • E2E above (manual harness, not in CI).

Lines: impl +503/-2, tests +175/-11.

Trainer publishes changed elements per shard as a second TorchStore state dict; generators apply them to their prefetch buffers and read tensors in full on overflow or version mismatch.
@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 5, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 5, 2026
@d4l3k d4l3k closed this Nov 13, 2026
d4l3k added a commit that referenced this pull request Nov 13, 2026
…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).
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.

1 participant