Skip to content

FSDP2 bitsandbytes: no per-parameter device sync, bounded GPU memory in the optimizer save - #15384

Merged
danielhanchen merged 7 commits into
mainfrom
dh/s7-rc-bnbsync
Oct 26, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
dh/s7-rc-bnbsync

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Since #15008, native FSDP2 (UNSLOTH_FSDP2=1) keeps bitsandbytes for adamw_8bit and steps each rank's local shard. That optimizer inherits bitsandbytes' Optimizer8bit.step, which calls sync_gpu(p), i.e. torch.cuda.synchronize(), after every parameter. Before #15008 this path used adamw_torch_fused, which does not synchronize at all. With a few hundred LoRA tensors, the host now waits for the device once per tensor on every step.

The same optimizer's checkpoint export also has a memory problem. native_save_optimizer calls get_optimizer_state_dict(full_state_dict = True, cpu_offload = True). torch calls optimizer.state_dict() first and only gathers and offloads afterwards, and the local-shard optimizer exports float32 moments. So every moment of every parameter, 8 bytes per element against the 2 bytes of the 8-bit state, sat on the GPU until the whole state dict existed.

This PR fixes both, in two commits.

Change

Step (first commit):

  • _LocalShardMixin.step runs the same loop as bitsandbytes (closure, check_overrides / to_gpu on the first step, init_state, prefetch_state, update_step) without the per-parameter synchronize for non-paged optimizers. Their state is on the device and every update is queued on the current stream, so the host does not need to wait.
  • Paged optimizers (paged_adamw_8bit, paged_adamw_32bit) keep bitsandbytes' fences: one after every parameter plus the final one, as before.
  • The new step is wrapped with torch.optim.Optimizer.profile_hook_step, so step pre / post hooks and the profiler label run exactly once per step.
  • Plain bitsandbytes outside native FSDP2 (single GPU, DDP) is not touched.

Save (second commit):

  • native_save_optimizer enters full_cpu_state_export(optimizer) around get_optimizer_state_dict when it asks for the full, CPU-offloaded state (writer rank 0, the default Trainer optimizer.pt save).
  • Inside it, the local-shard optimizer's state_dict() gathers each parameter's exported state and moves it to the CPU right away, the same way torch's _gather_state_dict does (redistribute to Replicate, to_local, copy to the CPU on rank 0, nothing kept on other ranks). The tensors equal torch's own export, so the saved file and resume are unchanged.
  • Other optimizers, the sharded DCP save (UNSLOTH_FSDP2_DCP_OPTIM=1) and the sub-mesh writer path are unchanged.

Measurements

Step

Optimizer step only, Llama-3.1-8B LoRA r=16 on q, k, v, o, gate, up, down: 448 fp32 tensors, 41.9M parameters, one-rank DTensor mesh. bitsandbytes 0.50.2. 9 interleaved rounds of 20 steps per arm, median per step with the min and max round. main (A/A) is a second, independent optimizer on main, to show run-to-run noise.

L4, torch 2.14.1:

Arm syncs / step median ms min to max ms
torch fused AdamW (native FSDP2 before #15008) 0 10.46 10.30 to 10.63
bitsandbytes AdamW8bit, plain tensors (no FSDP) 448 36.80 36.47 to 37.24
local-shard AdamW8bit, main 448 49.17 48.72 to 49.38
local-shard AdamW8bit, main (A/A) 448 48.97 48.38 to 49.22
local-shard AdamW8bit, this PR 0 35.16 34.96 to 35.58

B200, torch 2.13.0 (two separate runs):

Arm run 1 median ms run 2 median ms
torch fused AdamW 12.22 6.17
bitsandbytes plain 33.07 18.44
local-shard main 44.21 24.26
local-shard main (A/A) 44.96 25.31
local-shard, this PR 33.47 18.30

The A/A gap is 0.4% on L4 and under 5% on B200; the change is 28% on L4 (14.0 ms per step) and 24% to 25% on B200. Parameters after the same steps are bitwise equal to main (max abs difference 0.0 on both GPUs). This is the optimizer step alone; a full training step was not timed, so the end-to-end share depends on how long the forward and backward take.

The local-shard optimizer is still slower than fused torch AdamW. The rest of the gap is the per-tensor Python and DTensor overhead, which this PR does not change.

Save

native_save_optimizer on one NCCL rank, 16 DTensor parameters of 1M elements (16.8M elements), after two steps. Peak and retained GPU memory are measured above the allocation before the save.

Arm allocated before the save save peak above it retained after
torch fused AdamW (native FSDP2 before #15008) 192.0 MiB 0 MiB 0 MiB
local-shard AdamW8bit, main 96.5 MiB 144.0 MiB 0 MiB
local-shard AdamW8bit, this PR 96.5 MiB 32.0 MiB 0 MiB

On main the save peak (240.5 MiB in total) was above even the torch AdamW run (192.0 MiB). With this PR it is 128.5 MiB and no longer grows with the number of parameters: it is about one parameter's export. On both, the exported tensors equal torch's own get_optimizer_state_dict output, and a resume into a fresh optimizer restores state1, state2, absmax1 and absmax2 bitwise.

Tests

tests/test_fsdp2_bnb_optim_sync.py (CPU, bitsandbytes' CPU kernels, sync_gpu counted):

  • test_local_shard_step_does_not_sync_per_parameter[AdamW8bit], [Adam8bit], [AdamW]: no sync during a step, same parameters as bitsandbytes' own step, step post hook called once per step. Fail on main (4 syncs for 4 parameters), pass here.
  • test_paged_local_shard_step_keeps_bitsandbytes_fences: PagedAdamW8bit makes the same number of fences as bitsandbytes (parameters + 1), with equal parameters. Passes on both.

tests/test_fsdp2_bnb_optim_save_memory_cuda.py::test_local_shard_bnb_save_keeps_one_parameter_on_the_gpu (one NCCL rank, skipped without CUDA): the save peak stays within 5 parameters' float32 moments, nothing is retained on the GPU, the state equals torch's export and resumes bitwise. Fails on main (144 MiB peak), passes here.

tests/test_fsdp2_native_bnb_8bit_gloo.py, tests/test_fsdp2_native_dcp_bnb_8bit_gloo.py, tests/test_fsdp2_native_trainer_ckpt_gloo.py and tests/test_fsdp2_save_gloo.py still pass. The two-rank Trainer adamw_8bit save and resume test now goes through the new export. All together: 57 passed, 3 skipped (no percentile_clipping in this bitsandbytes; two-GPU NCCL; the CUDA test on a CPU run).

Not covered: multi-rank GPU training end to end, XPU, ROCm, bitsandbytes 0.45.5 (the floor; the loop only calls methods that exist there, and sync_gpu falls back to torch.cuda.synchronize when the import fails), paged optimizers on a real GPU, a two-rank NCCL save, and the save memory of the sharded DCP path, which still exports every float32 moment on the GPU.

…update

bitsandbytes' Optimizer8bit.step calls sync_gpu(p) (torch.cuda.synchronize) after
every parameter. The local-shard optimizer native FSDP2 uses for adamw_8bit now runs
the same loop without it for non-paged optimizers; paged optimizers keep the
per-parameter and final fences. The step stays wrapped by torch's profile hook, so
step pre / post hooks run once.
…e optimizer save

get_optimizer_state_dict(full_state_dict, cpu_offload) calls optimizer.state_dict()
before it gathers and offloads, and the local-shard bitsandbytes optimizer exports
float32 moments, so every moment (8 bytes per element) sat on the GPU until the state
dict was complete. native_save_optimizer now has the optimizer gather and move each
parameter's state to the CPU as it exports it, with the same tensors torch produces.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 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-26T16:25:03.527030Z 6dfc2d5 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

@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: 5efc054566

ℹ️ 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/models/fsdp2_bnb_optim.py Outdated
Comment on lines +330 to +331
if paged:
_sync_device(p)

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 Preserve synchronization when stepping on a non-default stream

When a non-paged local-shard optimizer is stepped inside a non-default CUDA stream, this removes every fence even though bitsandbytes' CUDA optimizer kernels launch on the legacy default stream. Subsequent work on the caller's stream can therefore read parameters before their updates finish, silently changing training results. The existing guard in unsloth/import_fixes.py::_on_default_streams explicitly preserves synchronization for this case, and tests/test_bnb_optimizer_step_sync.py::test_step_on_a_side_stream_keeps_every_sync covers that behavior, but this replacement bypasses both. Retain the synchronization outside the default stream, or explicitly establish the required cross-stream dependencies.

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.

Confirmed and fixed in 211753b. The local-shard step now keeps bitsandbytes' per-parameter fences whenever a parameter's CUDA device is not on its default stream (and on devices other than CUDA / CPU), the same rule as _on_default_streams in import_fixes.py; on the default stream it still takes none. New test_local_shard_step_on_a_side_stream_keeps_every_fence (CUDA): no fences on the default stream, one per parameter plus a final one under torch.cuda.stream(side). test_fsdp2_bnb_optim_sync.py, test_bnb_optimizer_step_sync.py and test_fsdp2_bnb_optim_save_memory_cuda.py: 13 passed on B200.

@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: 211753be87

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

Follow-up in 6dfc2d5: an LR scheduler built before the optimizer is localized (Trainer(optimizers = (opt, scheduler))) had already wrapped the old class's step on the instance (torch's _wrapped_by_lr_sched wrapper), so the local-shard step never ran and every parameter still synced. Localization now points that wrapper at the new class step and keeps the scheduler's step-called tracking (same contract on torch 2.6, 2.13 and 2.14). New test_local_shard_step_runs_when_the_scheduler_was_built_first: 4 syncs on the previous head, 0 now, parameters equal to bitsandbytes' own step, no scheduler-order warning.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 6dfc2d5e97

ℹ️ 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 added a commit that referenced this pull request Oct 26, 2026
…#15407)

## Problem

`(Python 3.13, g-r)` failed on #15384 (job 121698439734), which only
touches FSDP2 code:

```
studio/backend/tests/test_mcp_http_sessions.py::test_unscoped_http_stays_one_shot
E   AssertionError: assert {('http://127...7fe68c1ef0e0>} == {}
```

The test asserts `mcp_client._mcp_sessions == {}` after two unscoped
calls. Whether it passes depends on what ran before it on the same xdist
worker.

## Cause


`test_mcp_http_read_timeout.py::test_tool_call_outlives_sdk_read_timeout[chat-1]`
makes a scoped call, which caches a session in `_mcp_sessions`, and
never closes it. I found it by checking `_mcp_sessions` after each of
the 41 backend test files that touch the MCP client. It was the only
test that left an entry behind (`('http://127.0.0.1:.../mcp', (),
'chat-1', 'owner')`).

The same pattern as #15287 (cached tools and probe cool-offs leaking
between tests): module state one test leaves behind decides a later
test.

Reproduced on main by running the two in that order:

```
pytest -p no:randomly 'tests/test_mcp_http_read_timeout.py::test_tool_call_outlives_sdk_read_timeout[chat-1]' \
    tests/test_mcp_http_sessions.py::test_unscoped_http_stays_one_shot
main:        1 failed, 1 passed
this branch: 2 passed
```

## Fix

- **The leaker:** `test_tool_call_outlives_sdk_read_timeout` closes its
sessions in a `finally`.
- **For the next one:** the autouse `_forget_mcp_discovery_state`
fixture in `studio/backend/tests/conftest.py`, from #15287, also closes
any session left in `_mcp_sessions`, before and after each test
(`close_mcp_sessions(all_accounts = True)`).
- Stand-in sessions are tolerated. Tests that monkeypatch
`_mcp_sessions` with `SimpleNamespace` objects
(`test_account_tool_isolation.py`) have no `close()`, and their own
monkeypatch restores the real dict, so that `AttributeError` is skipped.
- **The guard:** `test_mcp_session_cache_reset_between_tests.py`, an
ordered pair in one xdist group. The first test leaves a session cached
the way a scoped call does. The second fails unless the cache is empty
and that session was closed.

## Verification

- The ordering above: fails on main, passes here.
- The guard pair: 2 passed, both serially and under `-n 2 --dist
loadgroup`.
- Sabotage: with the conftest close removed, the pair's second test
fails.
- All backend test files that touch the MCP client: 5781 passed under
`-n 8`. `test_blender_managed.py` is left out because it fails on this
host on main too.
- ruff format and check are clean.
@danielhanchen

Copy link
Copy Markdown
Member Author

Repo tests (CPU, studio) fails on this PR's new test (job 121698440083):

tests/studio test_no_skip_guard_reads_a_spoofable_accelerator_probe
  test_fsdp2_bnb_optim_sync.py:99: torch.cuda.is_available()

tests/_zoo_aggressive_cuda_spoof.py patches torch.cuda.is_available to True for the whole pytest process on the CPU runners, so a skip guard on it un-skips there whenever this file shares a session with the spoofed suites. The repo's guards use from real_accelerator import has_real_cuda and skipif(not has_real_cuda(), ...) instead, which asks the driver rather than the patched probe.

The Repo tests (CPU, gloo) failures on this run came from the TP parity tests on the old base (be64e0d); they are fixed on main by #15397 and #15400, so a merge of main or a re-run clears them.

@danielhanchen
danielhanchen merged commit 8abe47a into main Oct 26, 2026
@danielhanchen
danielhanchen deleted the dh/s7-rc-bnbsync branch October 26, 2026 20:32
danielhanchen added a commit that referenced this pull request Oct 27, 2026
`Repo tests (CPU, studio)` fails on main in
`tests/python/test_accelerator_skip_guards.py`, which keeps tests from
reading a probe that `tests/_zoo_aggressive_cuda_spoof.py` patches to
True for the whole session:

- `test_no_skip_guard_reads_a_spoofable_accelerator_probe`:
`test_fsdp2_bnb_optim_sync.py:95: torch.cuda.is_available()` (from
#15384). The skip guard now uses `has_real_cuda()` from
`tests/_shared/real_accelerator.py`, like the other root tests.
- `test_no_test_lets_a_loader_infer_the_device_from_a_spoofed_probe`:
`test_tp_replica_gloo.py:257: PeftModel.from_pretrained() with no
torch_device=` (from #15368). This is a gloo CPU test, so the reload
passes `torch_device = "cpu"`.

Test-only change.

| check | main | this PR |
|---|---|---|
| `tests/python/test_accelerator_skip_guards.py` | 2 failed | passed |
| `test_accelerator_skip_guards.py` + `test_fsdp2_bnb_optim_sync.py` +
`test_tp_replica_gloo.py` (CPU) | | 44 passed, 1 skipped |
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