Repository navigation
Native FSDP2: keep accelerate FSDP2 for custom Accelerator loops, support unsharded generation on torch 2.6 / 2.7 - #14882
Conversation
… 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.
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
|
|
||
| @functools.wraps(original_init) | ||
| def __init__(self, *args, **kwargs): | ||
| if _raw_accelerator_wants_fsdp2(kwargs) and not _built_by_trainer(sys._getframe(1)): |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| if any( | ||
| kwargs.get(name) is not None | ||
| for name in ("fsdp_plugin", "deepspeed_plugin", "deepspeed_plugins", "megatron_lm_plugin") |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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].
…s count as explicit [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
pre-commit.ci autofix |
…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).
Since #14273,
UNSLOTH_FSDP2=1shards natively inside the Trainer and no longer exports accelerate's FSDP env. A custom loop that builds its ownAcceleratorand callsaccelerator.prepare(model, optimizer)therefore gets a plain DDP wrap, with no parameter or optimizer sharding, where it used to get accelerate's FSDP2 wrap.Acceleratorbuilt outside a Trainer gets the accelerate FSDP2 launch env again, the same asUNSLOTH_FSDP2_BACKEND=accelerate, with a rank-0 message. It is left alone whenUNSLOTH_FSDP2_BACKENDis set explicitly, when a distributed plugin is passed, on a CPU run, when anAcceleratorStatealready exists, or whenshard_modelalready sharded a model. The Trainer path is unchanged.Accelerator()only foris_main_processand 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=nativekeeps native.native_fsdp2_unsharded(generation and merges) calledFSDPModule.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) andtest_unsharded_context_without_reshard_setterfail 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 preparesFSDPSequentialwith DTensor weights where main preparedDistributedDataParallel, 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.