Skip to content

FSDP2 block CUDA graphs: free the gathered weights of MoE blocks - #15720

Merged
danielhanchen merged 3 commits into
mainfrom
dh/recheck-fsdp2-moe-keep
Oct 28, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
dh/recheck-fsdp2-moe-keep

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

UNSLOTH_BLOCK_CUDAGRAPHS=1 under native FSDP2 keeps the all-gathered weights of every parameter inside a compiled decoder block allocated (_keep_unsharded_for_block_cudagraphs, #15215), so the block CUDA graphs see one address per weight and replay instead of re-recording.

Since #15553, _block_compile runs MoE blocks compiled without CUDA graphs (_graphs_unsafe_moe: routing outputs are overwritten across replays and the grouped GEMM copies offsets to the host during capture). FSDP2 still kept the gathered weights of those blocks. Those graphs never record, so nothing reads the fixed addresses. The cost is that every rank holds every expert of every MoE block unsharded after the first forward. For MoE models, the experts are most of the weights, so most of what FSDP2 shards stays fully gathered on every rank.

Fix

_compiled_block_modules skips blocks that _block_compile._graphs_unsafe_moe marks as MoE. It uses the same check that routes them to the graphs-off path, so the two cannot disagree. Their gathered weights are freed at reshard as usual. Dense blocks keep theirs, and nothing changes without UNSLOTH_BLOCK_CUDAGRAPHS=1 or without block compile, because the check only runs on blocks _block_compile wrapped.

Tests

tests/test_fsdp2_native_block_cudagraphs_moe_gloo.py (CPU, gloo, world size 2). It uses a tiny random Qwen3-MoE whose layer 0 is dense (mlp_only_layers=[0]) and layer 1 is MoE, UNSLOTH_BLOCK_CUDAGRAPHS=1, full finetune, 2 steps, _block_compile.py loaded by file path:

test main this branch
test_moe_block_weights_are_freed_under_block_cudagraphs FAIL (MoE block storages kept, size > 0) PASS (size 0)
test_dense_block_weights_stay_kept_under_block_cudagraphs PASS PASS

The existing tests/test_fsdp2_native_block_cudagraphs_gloo.py and tests/test_block_cudagraphs_clone.py still pass (61 passed with the new file, main at d21d016). tests/test_fsdp2_native_units.py passes too (40 passed, before the rebase onto #15352). All runs used torch 2.13 and transformers 5.17 on CPU.

Not covered

_block_compile runs MoE blocks compiled without CUDA graphs (#15553), but
_keep_unsharded_for_block_cudagraphs still kept their all-gathered weights
allocated, so every rank held every expert unsharded for graphs that never
record. Skip blocks _graphs_unsafe_moe marks; dense blocks are unchanged.
@danielhanchen danielhanchen self-assigned this Oct 28, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-28T08:40:34.322707Z 0cf072f Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 0cf072f6fe

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 2e516f8 into main Oct 28, 2026
@danielhanchen
danielhanchen deleted the dh/recheck-fsdp2-moe-keep branch October 28, 2026 13:02
danielhanchen added a commit that referenced this pull request Oct 28, 2026
…blocks (#15756)

## Summary

Follow-up to #15553 and #15720. With `UNSLOTH_BLOCK_CUDAGRAPHS=1` under
native FSDP2, decoder blocks called with a flex attention `BlockMask`
run compiled without CUDA graphs (`_flex_block_mask_call`), but
`_keep_unsharded_for_block_cudagraphs` still kept their gathered weights
allocated. That wastes the memory FSDP2 would free at reshard, and those
bytes count against the `UNSLOTH_BLOCK_CUDAGRAPHS_FSDP2_KEEP_GB` budget,
so in a model where only some blocks take a `BlockMask` the dense blocks
could lose their graphs.

There is no reliable module-level signal for "this block is flex": the
`BlockMask` check is per call, and `attn_implementation ==
"flex_attention"` on the config does not say which layers actually
receive a `BlockMask`. So the keep set is now updated from what the
blocks are observed doing.

## Changes

- `_block_compile.py`: `_note_block_mask_call(layer, args, kwargs)`
wraps `_flex_block_mask_call` and records `_unsloth_block_flex_only` on
the layer: `True` while every call so far took a `BlockMask`, `False`
(sticky) after the first call without one. An observer on the layer runs
on the first `BlockMask` call and on the `True -> False` change. A block
whose first call had no `BlockMask` never calls it. `run()` calls it
before reading `_unsloth_block_graphs_off`, so a change applies to the
same call.
- `fsdp2_native.py`: the keep decision moves into `_BlockWeightKeep`.
Candidates are grouped per block, and `apply()` keeps the weights of
every block that is not flex-only when their total fits the budget.
Flex-only blocks drop the `free_unsharded_param` override, so FSDP2
frees them at the next reshard and the next all-gather allocates again.
They also leave the budget, so dense blocks that were over it with them
get their weights kept and their graphs back. Setup behaves as before.
The observer re-runs `apply()`.
- A block that sometimes takes a `BlockMask` and sometimes not stays
kept once it has run a graphed call, because its graphs need one weight
address.

## Tests

- `tests/test_fsdp2_native_block_cudagraphs_flex_gloo.py` (CPU gloo, 2
ranks, tiny Gemma3 with `attn_implementation="flex_attention"`, so the
blocks get real transformers `BlockMask`s; CPU flex has no backward, so
attention goes through SDPA with the mask the `BlockMask` describes):
- flex blocks: gathered storage 0 bytes after every step (main: all
kept, e.g. 4096 / 8192 bytes per tensor)
  - SDPA blocks: still kept
  - flex for two steps, then SDPA: freed, then kept again
- mixed model with a budget of 1.5 blocks (layer 0 without a
`BlockMask`, layer 1 flex): layer 0 kept with graphs on, layer 1 freed
(main: over budget, nothing kept, both blocks without graphs)
- losses: with and without graphs bitwise equal, and bitwise equal to
main for every arm
- `tests/test_block_cudagraphs_clone.py`: the real `_wrap` / `run()`
path records the flag and calls the observer exactly on `None -> True`
and `True -> False`.

| test | main | this PR |
| --- | --- | --- |
| `test_fsdp2_native_block_cudagraphs_flex_gloo.py` | 3 failed, 2 passed
| 5 passed |
| `test_block_cudagraphs_clone.py` | 1 failed, 48 passed | 49 passed |
| `test_fsdp2_native_block_cudagraphs_gloo.py`, `test_block_compile.py`,
`test_flex_mask_graph_breaks.py` | unchanged | unchanged |

`test_block_compile.py::test_sm_count_is_read_outside_the_trace` fails
on main as well.

This applies cleanly on top of #15720 (the MoE block change). With both
applied, the MoE, flex and existing block CUDA graph gloo tests pass (18
passed).

## Not covered

- No GPU memory measurement. The CPU tests check FSDP2's all-gather
storage sizes directly, but the actual CUDA graph recording under FSDP2
was not run here.
- A block whose `_unsloth_block_mode` falls to off after setup (compile
failure) still keeps its weights. That was already the case before this
change.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Oct 28, 2026
`Repo tests (CPU, fsdp2)` on #15833's staging run passed every test and
still went red:

```
364 passed, 28 skipped, 80 warnings in 2092.29s (0:34:52)
##[error]Process completed with exit code 124.
```

The shard's pytest step runs under `timeout --signal=INT --kill-after=60
2100`. pytest finished 8 s under that cap, and the cap then fired while
it was exiting.

## Cause

#15291 moved the FSDP2 gloo tests into their own shard at about ten
minutes of runner time. They have grown since, with most of a dozen
FSDP2 PRs merged today adding tests there (#15756, #15748, #15720,
#15709, #15708, #15352, ...). Over the last twenty-odd staging runs this
job took 21 to 38 minutes, so it now sits at its cap on an ordinary
runner. Nothing failed; the shard is simply too big for its timeout.

## Fix

Split the shard in two by file name, balanced on measured time. Per-test
durations on main, summed per file across all 76 files:

| shard | selection | files | tests | measured time |
|---|---|---|---|---|
| `fsdp2` | `tests/test_fsdp2_[!n]*.py tests/test_fsdp2_n[!a]*.py
tests/test_fsdp2_native_[abc]*.py` | 34 | 237 | 1156 s (45%) |
| `fsdp2-native` (new) | `tests/test_fsdp2_native_[!abc]*.py` | 42 | 276
| 1406 s (55%) |
| both together, unchanged total | `tests/test_fsdp2*.py` | 76 | 513 |
2562 s |

`fsdp2` keeps its name, so its check name is unchanged. The step timeout
and job cap are left alone, so each half gets the whole budget.

## Guards

- `tests/test_ci_repo_cpu_shards.py` already fails when a file lands in
no shard or in two. It caught my first draft, which dropped
`test_fsdp2_non_cuda_accelerate_route.py`; hence the `n[!a]` glob.
- A new check, `TestEveryGlobRootMatchesAFile`, fails if a shard glob
matches no test file. bash passes an unmatched glob through literally
and pytest then fails the whole shard on a missing path. Sabotage:
adding `tests/test_fsdp2_zz*.py` to a selection fails it with
`[('fsdp2', 'tests/test_fsdp2_zz*.py')]`.
- `tests/studio/test_backend_ci_parallel_isolation.py` pins the number
of parallel runs, now nine (six repo-root shards).

## Verification

- `tests/test_ci_repo_cpu_shards.py` and
`tests/studio/test_backend_ci_parallel_isolation.py`: 56 passed.
- With `tests/studio/test_cache_budget_discipline.py` added: everything
passes except the guard on my first draft, fixed above.
- `--collect-only` on the two selections gives 237 + 276 = 513, the same
as the old single glob.

The per-file times are from a local `-n 8` run, so the split ratio is
approximate. The first runs of the two new shards will show the actual
runner times.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant