Skip to content

Make the TorchFT quorum mode configurable - #4754

Merged
tianyu-l merged 1 commit into
pytorch:mainfrom
jojoinfra:fix-async-quorum
Sep 28, 2026
Merged

tianyu-l merged 1 commit into
pytorch:mainfrom
jojoinfra:fix-async-quorum

Conversation

@jojoinfra

Copy link
Copy Markdown
Contributor

Motivation

When the quorum runs asynchronously, the healing export (model.state_dict()) is issued from the
quorum worker thread and nothing waits for it before the step starts. FSDP2's state-dict pre-save
hook reshards every parameter group that is currently unsharded for compute, so an export that lands
inside a forward hands that forward a sharded DTensor and the step dies:

RuntimeError: aten.bmm.default got mixed torch.Tensor and DTensor,
need to convert all torch.Tensor to DTensor before calling distributed operators!

It is a race, so the same setup sometimes finishes without crashing.

There is no way to ask for a synchronous quorum today without switching algorithms: the quorum mode
is not a config option, it is derived from semi_sync_method (use_async_quorum = semi_sync_method is None), and setting that switches to LocalSGD or DiLoCo, which replace the replicated
data-parallel synchronization with their own hooks. This PR adds a field that controls the quorum
mode on its own, so the standard replicated data-parallel path can wait for the quorum without
changing the algorithm. The default keeps the asynchronous behavior.

A synchronous quorum is an acceptable trade-off: the only thing given up is overlapping the quorum
with the step, and in return the forward always starts after any healing export or load has already
finished. For runs that value that over the overlap, the extra latency is worth paying -- which is
why this is a new knob rather than a change to the default.

Relates to: <4753>

Usage

  • --fault_tolerance.no-use_async_quorum, or config.fault_tolerance.use_async_quorum = False in a
    recipe. The step then waits for the quorum -- including any state export or load it performs for
    healing -- before the forward and backward passes run.
  • The default stays True, and the option is ignored when semi_sync_method is set, since semi-sync
    training always requires a synchronous quorum.
  • Cost: the quorum no longer overlaps the step, so its latency (and any export) is on the critical
    path. This is an escape hatch for the race, not a fix for it.

@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Sep 16, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 16, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

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

@tianyu-l

Copy link
Copy Markdown
Contributor

@d4l3k could you help review

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 test should be moved to experiments/torchft/tests/ folder

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved the test to torchtitan/experiments/torchft/tests/test_torchft_optimizer.py. While doing that I noticed the TorchFT CPU unit test lane only ran test_torchft_checkpoint.py by name, so nothing else in that folder was covered; I changed it to run the whole tests folder.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review this PR -- in particular, evaluate the necessity of the added flag use_async_quorum

@claude

claude Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 6m 23s —— View job


Review: Make the TorchFT quorum mode configurable

  • Read changed files (manager, optimizer, checkpoint wiring, trainer)
  • Understand use_async_quorum vs semi_sync_method interaction
  • Evaluate necessity of the flag
  • Review tests and CI change

On the necessity of use_async_quorum

Verdict: the flag exposes a genuinely new capability, and the refactor around it fixes a latent conflation bug -- but it is an escape hatch, not a fix for the race it targets.

Two things are bundled here, and it's worth separating them:

1. The decoupling is the valuable part (and is correct). Before this PR, self.use_async_quorum = config.semi_sync_method is None was doing double duty: it both configured torchft.Manager(use_async_quorum=...) and gated the replicate PG, the FSDP all-reduce hook, loss_sync_pg, and the per-step _quorum_manager. Those latter four have nothing to do with whether the quorum overlaps the step -- they are about whether this is the replicated-DP path at all. So if someone had naively flipped the old boolean to force a sync quorum, they would have silently dropped all cross-replica gradient and loss synchronization. The PR correctly splits this into:

  • use_async_quorum = config.use_async_quorum and semi_sync_method is None -> only feeds torchft.Manager
  • replicate_pg_enabled = semi_sync_method is None -> gates replicate PG / hook / loss sync / quorum driver

manager.py:127-133, optimizer.py:46-47, and the loss_sync_pg/maybe_set_all_reduce_hook sites are all keyed on replicate_pg_enabled now, which is the right axis. The three reachable states (semi-sync; replicated+async; replicated+sync) map exactly to what's intended. This decoupling is worth landing on its own merits -- it removes a booby-trap.

2. The flag itself is defensible but does not fix the root cause. The PR is explicit that this is "an escape hatch for the race, not a fix for it," and the default stays True, so the default path still races. Per the repo's own principle #2 (investigate root cause before patching; don't land band-aid fixes), I'd push back on framing this as the resolution to #4753. The actual bug is that FSDP2's state-dict pre-save hook reshards live parameter groups, and the async healing export can land mid-forward. A synchronous quorum avoids it by serializing the export before forward, but the underlying "export must not reshard params that a concurrent forward is using" problem is untouched -- any other async export path would hit the same wall. It would be good to (a) keep #4753 open for the real fix and (b) say plainly in the PR body that this changes what users can configure, not the default behavior.

That said, a synchronous quorum is a legitimate torchft mode with a real cost/benefit (loses step overlap, gains determinism), so exposing it as a knob is reasonable regardless of the race. The capability did not previously exist on the replicated-DP path, so the flag is not redundant.

Actionable findings

1. Silent no-op when use_async_quorum=False is combined with semi_sync_method (config.md violation). The docstring says the option "is ignored when semi_sync_method is set," but the code silently drops it. The repo config rule is explicit: "When a config option silently doesn't take effect in certain code paths, emit a warning to the user." A user who sets use_async_quorum=False and a semi-sync method gets async-off honored (semi-sync is already sync) but with no signal that their knob was subsumed. Recommend a logger.warning in __init__ when config.use_async_quorum is False and config.semi_sync_method is not None. manager.py:127
Fix this →

2. Cross-module test import couples experiments tests to a core test file. tests/test_torchft_optimizer.py:41 imports FakeMoEModel, FakeParallelDims from tests.unit_tests.cpu.test_optimizer_param_groups. The test was moved into experiments (good, per @tianyu-l), but it now depends on a core unit-test module being importable. This works today only because the repo root is on sys.path; it's fragile coupling in the opposite direction of the move. Consider promoting those fakes to a shared test helper (e.g. torchtitan/experiments/torchft/tests/_fakes.py or a common testing util) rather than reaching back into tests/unit_tests/cpu/.

3. CI lane change is a good catch, minor note. Switching unit_test_cpu_torchft.yaml from a single named file to torchtitan/experiments/torchft/tests/ is a real coverage improvement -- previously only test_torchft_checkpoint.py ran. Note integration_tests.py in that folder is not test_*-prefixed so pytest won't collect it, and test_torchft_optimizer.py needs Gloo (guarded with skipUnless) -- both fine. (I can't edit files under .github/workflows/ due to app permissions, so this is informational only.)

Nits

  • test_torchft_manager.py monkeypatches the optional torchft surface with doubles -- clean approach for the CPU lane. test_semi_sync_training_always_uses_synchronous_quorum asserts not hasattr(ft_manager, "replicate_pg"), which correctly pins the "no replicate PG in semi-sync" behavior.
  • Docstrings/README are clear and ASCII-clean, consistent with the style guide.

Summary

The decoupling of replicate_pg_enabled from use_async_quorum is the right change and removes a latent silent-correctness trap; the tests pin it well. The flag is a reasonable escape hatch but should be described as such -- it does not fix the resharding race, and the default still exhibits it, so #4753 warrants a follow-up root-cause fix. Please add the missing warning for the ignored-config case (finding #1) to satisfy the repo's config rules, and consider decoupling the test-fake import (finding #2).
· branch fix-async-quorum

@tianyu-l tianyu-l 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.

I didn't read the issue, but from claude's response, it sounds a workaround rather than fix.

@jojoinfra

Copy link
Copy Markdown
Contributor Author

I didn't read the issue, but from claude's response, it sounds a workaround rather than fix.

Thanks @tianyu-l — I agree this doesn't fix the underlying race.

My concern is that the background Python thread running quorum may race with FSDP operations on the main training thread. Preventing these races may require additional locking or coordination between the two threads, adding complexity to the design and implementation. Running quorum synchronously avoids this particular cross-thread interaction.

@d4l3k d4l3k left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generally sync quorum should be pretty safe though this PR seems much more invasive than I was expecting from the title. I'm also curious if you've run into issues with async quorum causing problems. Generally the biggest risk area is around live p2p recovery

# Semi-sync methods synchronize replicas through their own hooks instead
# of the replicate process group, which every other mode relies on for
# cross-replica gradient and loss synchronization.
self.replicate_pg_enabled = config.semi_sync_method is None

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do we need this new parameters? why not just expose use_async_quorum manual override?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use_async_quorum is currently also used to gate creation of the cross-replica process group and the FSDP gradient synchronization hooks. So if we simply override it to False, it would also change the replicated-DP training semantics, rather than only the quorum execution mode.

The intention of replicate_pg_enabled is just to separate these two concerns, so we can use synchronous quorum while preserving the existing cross-replica synchronization behavior.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A cleaner fix for #4753 may be to avoid running FSDP model.state_dict() on the TorchFT worker thread.

Instead, we could materialize the FSDP state on the training thread at a safe point, and keep the rest of the quorum/recovery work asynchronous.

This should avoid the FSDP forward/backward race without forcing the whole quorum path to be synchronous. Would appreciate your thoughts on whether this direction makes sense.

@jojoinfra

Copy link
Copy Markdown
Contributor Author

Generally sync quorum should be pretty safe though this PR seems much more invasive than I was expecting from the title. I'm also curious if you've run into issues with async quorum causing problems. Generally the biggest risk area is around live p2p recovery

Yes, i did run into an issue with async quorum. I filed #4753 with the repro and root-cause analysis.

@d4l3k

d4l3k commented Sep 22, 2026

Copy link
Copy Markdown
Member

@jojoinfra thanks for filing the issue! Happy to accept fixes if you have time to take a stab at it. For this pr specifically, it seems reasonable but let's simplify it

@jojoinfra
jojoinfra force-pushed the fix-async-quorum branch 2 times, most recently from 067a184 to 2922cd9 Compare September 22, 2026 11:44
@jojoinfra

Copy link
Copy Markdown
Contributor Author

@d4l3k Thanks, I’ve simplified the implementation. Does this look better? The remaining diff is mostly test updates and related CI changes.

@tianyu-l
tianyu-l requested a review from d4l3k September 22, 2026 23:02

@d4l3k d4l3k left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@d4l3k
d4l3k requested a review from tianyu-l September 28, 2026 11:19
1. Allow synchronous quorum without changing replica synchronization.
2. Update tests and CPU CI coverage.
@tianyu-l
tianyu-l merged commit 60e4ac6 into pytorch:main Sep 28, 2026
19 checks passed
tianyu-l added a commit that referenced this pull request Oct 29, 2026
… route PRs to area experts (#5667)

## Why

PR volume has outgrown review capacity. Of the 1,429 PRs merged since
April, one maintainer approved 1,066 (75%), and October alone had 351
merged PRs. Many PRs are agent-generated, and the agents (and `@claude`)
follow `.claude/CLAUDE.md`, which in several places contradicts how PRs
are actually reviewed:

- Principle 5 says to flag BC breakage. The maintainers deliberately
don't promise BC.
- config.md says "emit a warning" when config is silently skipped.
Review comments almost always say "just error out".
- PR expectations say "new features need CPU unit tests at minimum". In
~1,000 reviews the maintainer almost never asked for a new unit test,
and often asked for tests to be removed or folded into existing ones.

The result: across 130 PRs, the current `@claude` cited CLAUDE.md at
least 38 times, mostly to escalate. That produced 16+ BC concerns, 9+
"add a warning" suggestions and 23+ test requests. It also missed the
most common real review question: should this change exist in this form
at all?

This PR rewrites the rules from what reviewers actually say. The source
data:
- 3,391 inline comments, 289 review bodies and 383 PR comments from
Jul-Oct 2026.
- 48 refactor PRs, used to extract structural preferences.
- A comparison of 196 `@claude` runs against the human review on the
same PRs.

It then adds a torchtitan review skill, builds on PyTorch's `pr-review`
skill, and routes PRs to area experts without making them blocking
owners.

**Example: one past PR, as reviewed by the new skill** (#5546, at the
commit that was originally reviewed; blind, with no access to the real
comments):

```
Verdict: Request changes -- The problem is real, but the fix swaps a hard error for a
warn-and-continue fallback to FA2 ... It also adds a head-dim hook to 9 call sites,
7 of which can never fire.
Must fix
1. torchtitan/tools/utils.py:95-104 -- a missing wheel on Hopper/Blackwell now means a
   warning plus a silent switch to a slower kernel with different numerics ...
   Smallest fix (~15 lines): ... raise a clear error that names the module to install.
```
The human review of that PR: "450 LoC PR for a safety check sounds
insane" and "can we error out -- we don't want people to implicitly get
bad perf".

## What changed

**1. Rules** (`.claude/CLAUDE.md`, `.claude/rules/`):
- Core principles rewritten:
  - start from the problem, not the patch;
  - minimal by default;
  - PyTorch-native and upstream first;
  - reuse, but don't bend shared code for one consumer;
  - keep core oblivious to features;
- no BC promises, but protect numerics, HF loading, metric keys and
main-path perf;
  - raise instead of warn;
  - hardware-agnostic.
- Naming additions: overloaded terms, one name per concept, `_private`.
- PR expectations: descriptions must convince a human; tests must earn
their cost; one concern per PR.
- `config.md` rewritten:
  - each component owns its `X.Config`;
  - select implementations by config type;
  - `X.Config | None` instead of `enable_*`;
  - no post-hoc config mutation;
  - few knobs;
  - validate in `__post_init__`.
- `distributed.md`: spmd_types first, parallelism combinations, hidden
D2H syncs, hardware.
- New rules files:
  - `design.md`: structural rules distilled from past refactors.
- `tests.md`: when to add tests, preferring extensions of existing
coverage, placement, golden files.
- `direction.md`: current migrations. This needs maintainers to keep it
current.

**2. `pr-review` skill** (`.claude/skills/pr-review/`):

| Step | What it does |
| --- | --- |
| Context | Applicable rules, maintainer comments addressed or not,
earlier bot findings, overlapping open PRs. |
| Necessity/design gate | Is the problem real on main? Root cause vs
symptom? Right layer, or upstream? Should torchtitan own this?
Superseded? Smallest alternative? Value evidence? |
| Deep review | A quick sweep of every hunk (scope, placement, new knobs
and tests), then the checklist, split by lens for large PRs. |
| Consolidate and fact-check | Dedupe by root cause and fix; drop BC,
"add a warning", generic "add tests", lint and praise; verify must-fix
items. |
| Output | Verdict first, plain-words summary, a concrete before/after
example, at most a few must-fix items, details collapsed, unverified
claims labeled. |
| Modes | Full review, "review again" (only the delta), "review my
review", or answer a specific question first. |
| Posting | Line-anchored findings as inline comments (with `suggestion`
blocks for small fixes, at most ~10, posted only by the main agent after
fact-check), then one formal review via `gh pr review` (`--approve` /
`--request-changes` / `--comment`) with the verdict and one-line
pointers. |

**3. PR descriptions:**
- `pr-description` skill and `.github/pull_request_template.md`: Why
(with a simple example) -> What changed -> user-facing before/after ->
numerics -> testing.
- CONTRIBUTING.md updated to match.

**4. `@claude` workflow** (`claude-code.yml`):
- Always uses the skill.
- Allows read-only `gh issue view` / `gh pr view` / `gh pr diff` / `gh
pr list`, plus `gh pr review` and the action's inline-comment tool (it
cannot approve). `gh api` stays blocked.
- `effort=low|max` and `fable` comment keywords; default effort `high`.
- 55-minute timeout.

**5. Review routing:**
- `CODEOWNERS`:
- `*`: `tianyu-l` `fegin` `wwwjn` `shuhuayu` `acisseJZhong`
`felipemello1`.
- graph_trainer paths: core plus `SherlockNoMad` `aditvenk`
`sanketpurandare`.
  - torchft paths: core plus `d4l3k`.
- Every path has an owner, so a bot approval can never satisfy branch
protection on its own.
- `.github/area_reviewers.yml` and `workflows/area_reviewers.yml`
request at most 3 area experts as non-blocking reviewers, based on which
areas the changed files touch. The workflow runs on
`pull_request_target`, reads only the file list through the API, and
never checks out PR code.

## Alternatives considered

- **Copy PyTorch's skill as-is.** Its "missing tests -> Request Changes"
and BC section are exactly what produced noise here.
- **PyTorch-style per-directory `REVIEW.md` files.** The existing
glob-scoped `.claude/rules/` already do this, without more `.md` sprawl.
- **Deterministic lint hooks** for `torch.cuda.*`, `isinstance(..,
DTensor)` and `enable_*` fields. Every pattern already has hits on main
(12, 15 and 7 files), so they would need allowlists. The skill checks
them on the diff instead.
- **Making area experts code owners.** That makes them blocking;
auto-requesting reviews routes PRs without adding gates.

## Testing

**Backtest.** The new skill reviewed 7 past PRs blind, each at the
commit that was originally reviewed, and the output was compared with
the real human review. The skill was then fixed for the misses, and the
affected cases were re-run.

| PR | Human review's main point | New skill |
| --- | --- | --- |
| #5546 | too big for a safety check; error out | Hit both |
| #5153 | does this happen on main? don't violate the `nn.Module`
contract | Hit; proposed the fix that eventually landed |
| #4754 | workaround, not a fix; move the test | Hit the root cause (the
same fix the author later proposed); missed the test move, now covered
by the sweep |
| #5463 | motivation first; `LocalCompileConfig` design | Hit the design
and unused kwargs; motivation is a must-fix after the re-run |
| #5183 | NCCL-specific knob in core; TODO; `<0` semantics | Hit |
| #4474 | approve; DSv4 should fix the model/loss | Approve; partly
raised the model point |
| #4421 | approve; "how much e2e?" | Originally requested changes;
approves with items after the re-run |

None of the 10 reviews raised BC or asked for a warning.

**Other checks:**
- **Reviewer routing:** the area-reviewer logic was replayed on 1,429
merged PRs. Peak load is about 50 requests/month per person (graph
trainer, PP, MoE).
- **Workflow script:** dry-run with mocked GitHub objects on a real PR's
file list. The author is excluded, existing reviewers are skipped, and a
non-collaborator failure doesn't fail the run.
- **YAML and lint:** all YAML parses, the inline JS passes `node
--check`, and `pre-commit` passes.

## Known issues / follow-ups

- Comment-triggered workflows run from `main`, so `claude-code.yml` and
the skill only take effect after merge. Try `@claude review` on a real
PR right after.
- Not verified: whether the Claude GitHub App has write access. If it
does, its approvals count toward the 1 required approval (but never as a
code-owner approval), and its REQUEST_CHANGES blocks merging until it
re-approves or someone dismisses it. If it doesn't, its reviews are
advisory. The first real review will show which.
- `direction.md` and `area_reviewers.yml` are only useful if they are
kept current.
- Not included:
- PyTorch's time-budget hook (reviews that hit the 55-minute limit are
lost);
- auto-review on every push, which needs the PyTorch CI owners' hardened
setup.
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 CLA Signed This label is managed by the Meta Open Source bot.

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants