Repository navigation
FSDP2 bitsandbytes: no per-parameter device sync, bounded GPU memory in the optimizer save - #15384
Conversation
…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.
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. |
|
@codex review |
There was a problem hiding this comment.
💡 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".
| if paged: | ||
| _sync_device(p) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…off the default stream [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". |
…e local-shard step [skip ci]
|
Follow-up in 6dfc2d5: an LR scheduler built before the optimizer is localized ( @codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! 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". |
…#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.
|
The |
`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 |
Since #15008, native FSDP2 (
UNSLOTH_FSDP2=1) keeps bitsandbytes foradamw_8bitand steps each rank's local shard. That optimizer inherits bitsandbytes'Optimizer8bit.step, which callssync_gpu(p), i.e.torch.cuda.synchronize(), after every parameter. Before #15008 this path usedadamw_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_optimizercallsget_optimizer_state_dict(full_state_dict = True, cpu_offload = True). torch callsoptimizer.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.stepruns the same loop as bitsandbytes (closure,check_overrides/to_gpuon 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_adamw_8bit,paged_adamw_32bit) keep bitsandbytes' fences: one after every parameter plus the final one, as before.stepis wrapped withtorch.optim.Optimizer.profile_hook_step, so step pre / post hooks and the profiler label run exactly once per step.Save (second commit):
native_save_optimizerentersfull_cpu_state_export(optimizer)aroundget_optimizer_state_dictwhen it asks for the full, CPU-offloaded state (writer rank 0, the default Traineroptimizer.ptsave).state_dict()gathers each parameter's exported state and moves it to the CPU right away, the same way torch's_gather_state_dictdoes (redistribute toReplicate,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.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:
B200, torch 2.13.0 (two separate runs):
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_optimizeron 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.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_dictoutput, and a resume into a fresh optimizer restoresstate1,state2,absmax1andabsmax2bitwise.Tests
tests/test_fsdp2_bnb_optim_sync.py(CPU, bitsandbytes' CPU kernels,sync_gpucounted):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:PagedAdamW8bitmakes 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.pyandtests/test_fsdp2_save_gloo.pystill pass. The two-rank Traineradamw_8bitsave and resume test now goes through the new export. All together: 57 passed, 3 skipped (nopercentile_clippingin 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_gpufalls back totorch.cuda.synchronizewhen 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.