Skip to content

Native FSDP2: restore the exact reshard-after-forward setting after generate - #14762

Merged
danielhanchen merged 4 commits into
mainfrom
fsdp2-unsharded-restore-older-torch
Oct 25, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
fsdp2-unsharded-restore-older-torch

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Problem

native_fsdp2_unsharded wraps generate by default (FSDP2Config.wrap_generate = True). It keeps every unit gathered for the call, then restores each unit's reshard-after-forward setting on exit. On torch 2.8 and newer the restore goes through FSDPModule.set_reshard_after_forward(unit._unsloth_reshard_after_forward). That setter only accepts a bool, but FSDP2Config.reshard_after_forward (and unit_reshard_after_forward) may be an int (reshard to a smaller world). With an int setting, every model.generate on a natively sharded model raises ValueError: reshard_after_forward should be a bool, got <class 'int'> from the finally block, and the units after the failing one are never restored.

The torch 2.6 / 2.7 half of the original report (no set_reshard_after_forward before 2.8) was fixed on main by #14882; this branch has been merged with main.

Change

_reshard_after_forward_off / _reshard_after_forward_restore now save each param group's post_forward_mesh_info (and the state's _auto_reshard_after_forward), set it to None (what the setter writes for False), and put back exactly what was there. One path for torch 2.6 through current; int settings come back unchanged; torch >= 2.13 states with several param groups (_fsdp_param_groups) are covered. The finally block reshards every unit, restores every unit, then re-raises the first reshard error.

Tests

New tests/test_fsdp2_native_unsharded_restore.py (one-rank gloo group on the CPU, real fully_shard): exact setting restored and weights gathered inside the context; int setting restored; set_reshard_after_forward removed (torch 2.6 / 2.7 API).

torch (CPU, gloo) main this branch
2.8.0 1 failed (int: ValueError), 2 passed 3 passed
2.13.0 1 failed (int: ValueError), 2 passed 3 passed

CUDA + NCCL on a T4 (one rank, bool and int settings, then a training forward + backward after the context):

torch main bool / int this branch bool / int
2.6.0 ok / ok ok / ok
2.7.1 ok / ok ok / ok
2.14.1 ok / ValueError ok / ok

Not covered

  • No multi-GPU generate run (one rank only).

…enerate

native_fsdp2_unsharded called FSDPModule.set_reshard_after_forward, which torch 2.6 / 2.7 do not have
(the declared floor is 2.6), and restored an int reshard_after_forward through it, which raises
'should be a bool'. Save and restore each unit's post-forward mesh info instead.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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-25T05:57:01.978211Z f9f8055 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: ae8579bd82

ℹ️ 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".

# Conflicts:
#	unsloth/models/fsdp2_native.py

[skip ci]
@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. Swish!

Reviewed commit: f9f8055b5f

ℹ️ 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 5c1e04e into main Oct 25, 2026
26 of 30 checks passed
@danielhanchen
danielhanchen deleted the fsdp2-unsharded-restore-older-torch branch October 25, 2026 09:41
danielhanchen added a commit that referenced this pull request Oct 26, 2026
…nsharded (#15426)

## Problem

`native_fsdp2_unsharded` (the context that wraps `generate`, merges and
the sentence-transformer encode path under native FSDP2) cleared each
unit's `post_forward_mesh_info` and only then called `unshard()`.

With an int `reshard_after_forward` (for example `shard_model(model,
FSDP2Config(reshard_after_forward = 2))` on a 4-rank mesh), a forward
outside backward, such as an evaluation step, leaves the unit in
`SHARDED_POST_FORWARD` on its 2-rank sub-mesh. FSDP2 picks the
all-gather group for that state from `post_forward_mesh_info`, so
entering the context after an evaluation forward failed on every rank:

```
AssertionError: Expected mesh_info to be FSDPMeshInfo, got <class 'NoneType'>
```

Entering the context cold worked, and so did bool settings. #14762 added
int restore support, but its test ran on one rank, so the units never
resharded onto a sub-mesh.

The env and Trainer paths only produce bool settings
(`UNSLOTH_FSDP2_RESHARD_AFTER_FORWARD` is 1 / 0 / auto). An int only
reaches this code through an explicit `FSDP2Config(reshard_after_forward
= N)` or `unit_reshard_after_forward`.

## Fix

Unshard every unit first, while the post-forward mesh is still set, and
then turn post-forward resharding off for the forwards inside the
context. Exit is unchanged: reshard fully, then restore the saved
setting.

## Before / after

New test `tests/test_fsdp2_native_unsharded_int_mesh_gloo.py`, 4 gloo
CPU ranks, `FSDP2Config(reshard_after_forward = 2)`. It checks outputs
inside the context against one process, the restored setting, the
resharded weights on exit, and a training step afterwards.

| Test | torch 2.10 base | torch 2.10 head | torch 2.13 base | torch
2.13 head | torch 2.14 base | torch 2.14 head |
|---|---|---|---|---|---|---|
| `test_int_mesh_unsharded_context[cold]` | pass | pass | pass | pass |
pass | pass |
| `test_int_mesh_unsharded_context[after_eval_forward]` | fail | pass |
fail | pass | fail | pass |

On torch 2.13 the existing native FSDP2 tests that use the context
(`unsharded_restore`, `qat_convert_generate`, `infer_embed_audio`,
`vision`, `optim_reentry`, `units`) pass with this change: 68 passed.

## Not covered

- torch 2.6: FSDP2 does not run on a CPU gloo mesh there
(`Stream.record_event` is missing), so this test and the existing
restore tests cannot run on that version. The change only reorders two
existing steps (`unshard()` and the post-forward mesh write), both
present on 2.6.
- No CUDA / NCCL run of the new test in this change.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant