Skip to content

[rl] Push model state dicts as compressed XOR deltas - #6176

Open
wolfcomos wants to merge 1 commit into
pytorch:mainfrom
wolfcomos:rl-xor-delta-weight-sync
Open

wolfcomos wants to merge 1 commit into
pytorch:mainfrom
wolfcomos:rl-xor-delta-weight-sync

Conversation

@wolfcomos

@wolfcomos wolfcomos commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Why

Every push sends the whole model (Qwen3-30B-A3B: 61 GB in BF16, 15.3 GB per generator rank), and each generator reads it again. An optimizer step changes few bits: 2.6% of BF16 elements at lr 5e-6 and 0.4% at 1e-6, in every tensor. The XOR of two pushes compresses 27-53x and 64-100x with zstd.

This follows humans&' lossless XOR-delta weight sync (GPU-accelerated weight teleportation, radixark/miles#3894), applied to ModelStateDictTransport's staged bytes, which are already in each generator rank's layout. Design discussion: RFC #6178.

config.model_state_dict_transport = ModelStateDictTransport.Config(xor_delta_codec="zstd")  # default None

What changed

  • ModelStateDictTransport.Config.xor_delta_codec: Literal["zstd"] | None = None.
  • Trainer: a pinned baseline (the last push) and a registered delta buffer (a header, then the compressed windows; at most 1/4 of the staging buffer). finish_stage() XORs and compresses each 256 MiB window on the GPU, pipelined over H2D, compress and D2H streams.
  • Generator: read() reads every trainer rank's header, then only the compressed windows covering its pieces, and decompresses and XORs them into its prefetch buffers on the GPU. The first push, a missed push, or a delta that does not fit is read whole, as before. The load path is unchanged.
  • trainer.py: push_model_state_dict awaits finish_stage() (one line). install_rl_env.sh installs nvCOMP 6.0.0.12. MODEL_STATE_DICT_TRANSPORT.md documents the format.
  • Cost: trainer host memory +1.25x the staging buffer, trainer GPU +~3 GiB while encoding, generator host memory +0.25x of its pieces.

Numerics

Lossless: the prefetch buffers end up bitwise equal to a whole read.

Testing

  • Unit (test_model_state_dict_transport_xor_delta.py, 1 GPU, fake transport): trainer FSDP and HSDP, generator TP with packed pieces; every load bitwise, the bytes read, and the three fallbacks. The existing CPU transport and trainer tests pass.
  • End to end, bitwise (re-read pulls whole and compare): every pull over 12 steps, every 10th pull over 140 pushes, and a run that forces the overflow fallback. All equal.
  • Qwen3-30B-A3B DAPO, trainer FSDP4/EP4, generator DP4/EP4, NIXL, 20 steps, means over steps 3+:
generator pull whole XOR delta
1 node 1.24 s 1.20 s
2 nodes, InfiniBand, 1 generator 1.27 s 1.36 s
2 nodes, InfiniBand, 2 generators 2.15 s 1.66 s
2 nodes, TCP (UCX_TLS=tcp,self,cuda_copy), 1 generator 6.26 s 1.66 s

Bytes per generator rank per push: 15.3 GB -> 0.47-0.58 GB. The trainer waits 0.04-0.17 s per step on the push. The delta is neutral with one generator on a fast link, and faster with more generators or a slower link.

Not verified: Mooncake, SGLang, PP trainers, LoRA.

Notes

🤖 Generated with Claude Code

With ModelStateDictTransport.Config.xor_delta_codec="zstd" (default None), each
trainer rank sends every push after the first as the XOR of its staged bytes
with the previous push's, compressed with nvCOMP zstd on its GPU per 256 MiB
window. Generator ranks read only the compressed windows covering their pieces,
decompress them on their GPU and XOR them into their prefetch buffers, which end
up bitwise equal to a whole read. The first push, a missed push and a delta that
does not fit its buffer fall back to whole reads.

On Qwen3-30B-A3B (FP32 master, BF16 sent) a push shrinks 27-53x at lr 5e-6,
from 15.3 GB to ~0.5 GB per generator rank. With one generator on InfiniBand the
pull time is unchanged; with two generators it drops from 2.15 to 1.66 s, and
over TCP from 6.26 to 1.66 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 18, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@d4l3k

d4l3k commented Nov 19, 2026

Copy link
Copy Markdown
Member

@claude review this

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @d4l3k's task in 4m 18s —— View job


Needs discussion: RFC #6178's questions are still open (whether to add the nvCOMP dependency, and how this relates to #6142 and #6147), and the PR doesn't yet show the change shortens training steps. 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: Needs discussion -- maintainers have not yet answered RFC #6178's questions: whether nvCOMP is an acceptable dependency, and which of #6142, #6147 and this PR the transport should build on. The evidence also doesn't yet show an end-to-end step-time win.

What this PR does. With ModelStateDictTransport.Config(xor_delta_codec="zstd"), each trainer rank keeps a pinned copy of the previous push (the baseline). After stage(), it XORs the new staging buffer against that baseline in 256 MiB windows on its GPU and compresses the result with nvCOMP zstd into a registered delta buffer that starts with a header. A generator rank reads every trainer rank's header first. If it holds the previous push and every trainer rank has a delta, it reads only the compressed windows covering its pieces, then decompresses them and XORs them into its pinned prefetch buffers on its GPU. Otherwise it reads the push whole, as before.

Example. Qwen3-30B-A3B, one generator rank, push N:

before: generator rank reads 15.3 GB of staged BF16 bytes over RDMA
after:  trainer rank:   xor = staged(N) ^ staged(N-1) -> zstd -> ~0.5 GB delta buffer
        generator rank: read headers (push N, has delta), read ~0.5 GB of windows,
                        H2D prefetch bytes + compressed, decode, XOR, D2H back into prefetch
fallback (whole read): first push, generator missed push N-1, or a delta over 1/4 of the covered bytes

I checked the ordering in Controller._trainer_loop: push N (including finish_stage) completes before pull N starts, and pull N completes before push N+1. So the header-then-windows reads can't race a re-encode.

Must fix

  1. PR description -- the "Summary (human-written)" section is empty. The author needs to write it (see CLAUDE.md, PR expectations).
  2. Proof of value -- the table reports generator pull wall time. The controller runs that pull in the background, overlapped with forward/backward N+1, so a faster pull only matters if it was on the critical path. The one critical-path number reported is a cost: the trainer now waits 0.04-0.17 s per step on the push. On top of that, encoding runs on the trainer GPU during forward/backward, holding ~3 GiB near the activation peak and competing for SMs. Please report, whole vs delta: timing/step/blocking_trainer_push_model_state_dict, timing/step/blocking_generator_pull_model_state_dict, forward/backward time, step time or tok/s, and trainer peak GPU memory. If blocking pull time is ~0 with whole reads on 1 node and on IB with 1 generator, the delta only adds cost there. The case for the feature then rests on the 2-generator and TCP rows, and those should show the step-time win.
  3. Overlap with #6142 / #6147 / #6177 -- #6142 and this PR each add a second trainer baseline buffer and a post-stage hook to the same transport. #6147 makes generators read straight into GPU memory, which would remove the generator-side H2D -> XOR -> D2H round trip in _apply_deltas, roughly half of this PR's generator code. Maintainers should pick one delta mechanism and decide the order before this lands. Otherwise two sync_mode-style knobs end up on one transport.

Should consider

  • model_state_dict_transport.py:215 -- _CachingAllocation ignores nvCOMP's stream argument. Its stream-ordering safety argument relies on the current stream instead.
  • model_state_dict_transport.py:606 -- the trainer codec device comes from the first state dict entry. Use the accelerator's current device, as the generator does.
  • model_state_dict_transport.py:730, :922 -- per-push INFO logs on every trainer and generator rank. Use debug level, or log on rank 0 only.
  • model_state_dict_transport.py:920 -- generator decode memory (~1 GiB+) is outside vLLM's gpu_memory_utilization budget and stays cached after the pull.
  • test_model_state_dict_transport_xor_delta.py:17 -- importorskip can only hide a broken nvCOMP install in RL GPU CI. Drop it.

Questions

  • Is an optional, lazily imported nvCOMP dependency acceptable in torchtitan/rl/ (RFC Q1)? NIXL and Mooncake set a precedent for transport backends, but this is a compute library, and the PR routes its allocator process-wide.
  • Is zstd over XOR deltas a candidate for upstream (TorchStore, a meta-pytorch repo, or torch.distributed._transport) rather than torchtitan?
Details
  • Correctness: I traced the trainer pipeline (slot reuse guarded by done and computed, a baseline window stored only after its H2D loads complete, overflow switching to baseline-only updates with header[1] = 0) and the generator pipeline. I found no ordering bugs. The version check (version == _version + 1) plus the induction "prefetch == staging(N-1)" holds because only read() writes the prefetch buffers and copy_prefetched_ only reads them. If _apply_deltas raises partway, _version stays put, so the next pull reads whole.
  • Size: +537 lines in the transport. Most of that is the two 3-stream pipelines, which also need perf numbers (item 2). If #6147 lands, the generator half shrinks to a decode and XOR into GPU memory.
  • torch.cuda.Stream / torch.cuda.Event are used throughout. That's acceptable only because nvCOMP is CUDA-only. Elsewhere trainer.py uses torch.Stream.

Not verified: GPU runs, nvCOMP allocator stream semantics, generator memory headroom under vLLM. A maintainer still needs to review.

so work queued on it before the free still runs before any reuse.
"""

def __init__(self, nbytes: int, stream: Any) -> 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.

stream is ignored. The allocation goes onto whatever torch stream is current on the calling thread. The docstring's safety argument (freed blocks go back to the codec stream's pool, so queued work runs before reuse) only holds if nvCOMP always allocates from a thread inside on_stream() and on the same stream it was given. Nothing enforces either. Honoring the argument makes this hold by construction:

with torch.cuda.stream(torch.cuda.ExternalStream(stream)):
    self.tensor = torch.empty(nbytes, dtype=torch.uint8, device="cuda")

(unverified: I didn't check which stream nvCOMP passes here.)

delta = None
if self._xor_delta_codec is not None:
# The device the shards live on, which encodes the deltas.
device = next(iter(model_state_dict.values())).device

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.

The codec device comes from whichever tensor happens to be first in the state dict. If that entry is a CPU buffer, torch.cuda.Stream(cpu) fails with an unclear error. The generator side uses torch.accelerator.current_device_index(). Doing the same here (or passing the trainer's engine.device) keeps the two sides symmetric and stops depending on key order.

header[1] = int(encode)
if table:
header[2 : 2 + 2 * len(table)] = torch.tensor(table).view(-1)
logger.info(

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.

This logs one INFO line per push on every trainer rank, and line 922 logs one per pull on every generator rank. With trainer FSDP4/EP4 and generator DP4/EP4 that's dozens of lines per step. Use logger.debug here, or log only on rank 0. If the compressed size matters for tuning, report it as a metric instead.

import pytest
import torch

pytest.importorskip("nvidia.nvcomp")

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.

unit_test_gpu_rl.yaml runs scripts/install_rl_env.sh, which this PR makes install nvCOMP. So the skip can only fire when that install is broken, and then the test silently skips instead of failing. Drop the importorskip so CI can't quietly lose this coverage.

if not whole and planned:
deltas = [(plan, decodes) for plan, _, decodes in planned]
delta_nbytes = sum(n for _, decodes in deltas for _, _, n in decodes)
await asyncio.to_thread(self._apply_deltas, deltas)

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.

This decode runs inside the generator process while the engine keeps serving. It needs about 3 windows (~768 MiB), plus 2x the largest compressed window, plus nvCOMP's decode scratch, all through PyTorch's caching allocator. None of that is in the engine's gpu_memory_utilization budget, which was sized at startup. The blocks also stay cached on the codec stream's pool after the pull. On GPUs with less headroom than B200 (e.g. H100 at util 0.9) this can OOM, and decoding also competes with generation for SMs. Please state the headroom this needs (or check it), and report generation throughput during a pull. Unverified: I couldn't run it.

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.

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/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

Status: Todo

Development

Successfully merging this pull request may close these issues.

2 participants