Skip to content

Native FSDP2: keep accelerate FSDP2 for custom Accelerator loops, support unsharded generation on torch 2.6 / 2.7 - #14882

Merged
danielhanchen merged 2 commits into
mainfrom
dh/s3-fsdp2-launch-raw-accelerate
Oct 23, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
dh/s3-fsdp2-launch-raw-accelerate

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Since #14273, UNSLOTH_FSDP2=1 shards natively inside the Trainer and no longer exports accelerate's FSDP env. A custom loop that builds its own Accelerator and calls accelerator.prepare(model, optimizer) therefore gets a plain DDP wrap, with no parameter or optimizer sharding, where it used to get accelerate's FSDP2 wrap.

  • The first Accelerator built outside a Trainer gets the accelerate FSDP2 launch env again, the same as UNSLOTH_FSDP2_BACKEND=accelerate, with a rank-0 message. It is left alone when UNSLOTH_FSDP2_BACKEND is set explicitly, when a distributed plugin is passed, on a CPU run, when an AcceleratorState already exists, or when shard_model already sharded a model. The Trainer path is unchanged.
  • One behaviour change: a script that builds Accelerator() only for is_main_process and then a Trainer now runs accelerate's FSDP2 again, as before Native FSDP2: fully_shard per block and root for every model, LoRA, QLoRA and full finetuning (UNSLOTH_FSDP2=1) #14273. UNSLOTH_FSDP2_BACKEND=native keeps native.
  • native_fsdp2_unsharded (generation and merges) called FSDPModule.set_reshard_after_forward, which only exists from torch 2.8 (absent at the v2.6.0 and v2.7.0 tags). On torch 2.6 / 2.7 it now sets the param group's post-forward mesh directly and restores the saved value on exit; 2.8+ keeps the public setter.

Tests: tests/test_fsdp2_native_raw_accelerator.py (10 cases) and test_unsharded_context_without_reshard_setter fail on main and pass here, on torch 2.10, 2.13 and 2.14. The FSDP2 suites keep the same failing test ids as main on every venv (one pre-existing failure on 2.14). In a 2-rank check on one GPU, the raw loop now prepares FSDPSequential with DTensor weights where main prepared DistributedDataParallel, and a native Trainer run is identical to main (native sharding, same loss).

Not run: a real 2-GPU NCCL job, torch 2.6 / 2.7 installs, native Windows, and the memory difference itself.

… unsharded generation on torch 2.6 / 2.7

UNSLOTH_FSDP2=1 now shards natively inside the Trainer only, so a custom loop that builds its own
Accelerator and calls accelerator.prepare(model, optimizer) got a plain DDP wrap instead of the
accelerate FSDP2 wrap it had before. The first Accelerator built outside a Trainer (no explicit
UNSLOTH_FSDP2_BACKEND, plugin or CPU run, nothing sharded natively yet) now gets the accelerate FSDP2
launch env, the same as UNSLOTH_FSDP2_BACKEND=accelerate. The Trainer path is unchanged.

native_fsdp2_unsharded called FSDPModule.set_reshard_after_forward, which only exists from torch
2.8. On 2.6 / 2.7 it now switches the param group's post-forward mesh directly and restores it.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 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-23T03:50:27.897933Z 53820e4 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 chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 230911aaa5

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

Comment thread unsloth/fsdp2_launch.py Outdated

@functools.wraps(original_init)
def __init__(self, *args, **kwargs):
if _raw_accelerator_wants_fsdp2(kwargs) and not _built_by_trainer(sys._getframe(1)):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Bind positional Accelerator options before choosing FSDP2

When callers pass supported options positionally, kwargs does not contain them, so this wrapper can misclassify an explicitly configured Accelerator as an ordinary custom loop. For example, Accelerator(True, False, None, 1, True) explicitly selects CPU, while positional deepspeed_plugin or fsdp_plugin values are also allowed; all are missed here, causing the wrapper to export the FSDP2 environment despite the stated leave-alone behavior. Bind args and kwargs against the original constructor signature before evaluating _raw_accelerator_wants_fsdp2.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 53820e4: positional arguments are bound against the original constructor's signature before the check, so Accelerator(True, False, None, 1, True) (CPU) or a positional plugin is left alone. Test test_positional_options_count_as_explicit.

Comment thread unsloth/fsdp2_launch.py Outdated
Comment on lines +384 to +386
if any(
kwargs.get(name) is not None
for name in ("fsdp_plugin", "deepspeed_plugin", "deepspeed_plugins", "megatron_lm_plugin")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Exclude explicit tensor-parallel configurations from fallback

When a custom loop supplies torch_tp_plugin= or parallelism_config= as a keyword, this check still treats the Accelerator as unconfigured and exports the FSDP2 environment. A valid pure-TP configuration such as ParallelismConfig(tp_size=WORLD_SIZE) is then combined with an auto-created FSDP2 plugin; current Accelerate rejects that combination because its mesh has neither a data-parallel shard nor context-parallel dimension. Treat these arguments as explicit distributed configurations just like the plugins already listed here.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 53820e4: torch_tp_plugin and parallelism_config (both in accelerate 1.15's constructor) now count as an explicit distributed configuration like the plugins. Tests test_left_alone[tp_plugin] and test_left_alone[parallelism_config].

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 53820e4de8

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

Copy link
Copy Markdown
Member Author

pre-commit.ci autofix

@danielhanchen
danielhanchen merged commit 482058c into main Oct 23, 2026
@danielhanchen
danielhanchen deleted the dh/s3-fsdp2-launch-raw-accelerate branch October 23, 2026 07:45
danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Oct 25, 2026
…enerate (unslothai#14762)

## 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 unslothai#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).
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