Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

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

Daniel Han8abe47a8f781
diff --git a/tests/test_fsdp2_bnb_optim_save_memory_cuda.py b/tests/test_fsdp2_bnb_optim_save_memory_cuda.py
new file mode 100644
index 00000000000..470e4f9cde2
--- /dev/null
+++ b/tests/test_fsdp2_bnb_optim_save_memory_cuda.py
@@ -0,0 +1,160 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""GPU memory of the native FSDP2 optimizer.pt export with a local-shard bitsandbytes optimizer:
+the peak stays about one parameter, tensors equal torch's export, and a resume restores the 8-bit
+state bitwise. `python tests/test_fsdp2_bnb_optim_save_memory_cuda.py --out result.json [--arm torch]`
+runs a worker."""
+
+import argparse
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+import torch
+
+_HERE = Path(__file__).resolve().parent
+N_PARAMS = 16
+NUMEL = 1 << 20
+
+if __name__ != "__main__":
+ if not torch.cuda.is_available() or not torch.distributed.is_nccl_available():
+ pytest.skip("needs a CUDA GPU with NCCL", allow_module_level = True)
+ pytest.importorskip("bitsandbytes")
+
+
+def _worker(out, arm, rdzv):
+ sys.path.insert(0, str(_HERE))
+ from test_fsdp2_native_units import _load_native
+
+ native = _load_native()
+ import bitsandbytes as bnb
+ import torch.distributed as dist
+ from torch.distributed.checkpoint.state_dict import StateDictOptions, get_optimizer_state_dict
+ from torch.distributed.device_mesh import init_device_mesh
+ from torch.distributed.tensor import Shard, distribute_tensor
+
+ torch.cuda.set_device(0)
+ dist.init_process_group("nccl", init_method = f"file://{rdzv}", rank = 0, world_size = 1)
+ mesh = init_device_mesh("cuda", (1,))
+
+ def build(seed):
+ model = torch.nn.Module()
+ g = torch.Generator(device = "cuda").manual_seed(seed)
+ for i in range(N_PARAMS):
+ full = torch.randn(NUMEL // 256, 256, device = "cuda", generator = g)
+ model.register_parameter(
+ f"w{i}", torch.nn.Parameter(distribute_tensor(full, mesh, [Shard(0)]))
+ )
+ setattr(model, native._NATIVE_FLAG, True)
+ if arm == "torch":
+ opt = torch.optim.AdamW(model.parameters(), lr = 1e-3, fused = True)
+ else:
+ opt = bnb.optim.AdamW8bit(model.parameters(), lr = 1e-3)
+ from unsloth.models.fsdp2_bnb_optim import localize_bnb_optimizer
+ assert localize_bnb_optimizer(opt)
+ return model, opt
+
+ model, opt = build(0)
+ for step in range(2):
+ g = torch.Generator(device = "cuda").manual_seed(10 + step)
+ for p in model.parameters():
+ p.grad = distribute_tensor(
+ torch.randn(p.shape, device = "cuda", generator = g), mesh, [Shard(0)]
+ )
+ opt.step()
+ opt.zero_grad(set_to_none = True)
+ torch.cuda.synchronize()
+ before = torch.cuda.memory_allocated()
+ torch.cuda.reset_peak_memory_stats()
+ state = native.native_save_optimizer(model, opt)
+ torch.cuda.synchronize()
+ peak = torch.cuda.max_memory_allocated() - before
+ retained = torch.cuda.memory_allocated() - before
+ on_cpu = all(
+ v.device.type == "cpu"
+ for s in state["state"].values()
+ for v in s.values()
+ if torch.is_tensor(v)
+ )
+ ref = get_optimizer_state_dict(
+ model, opt, options = StateDictOptions(full_state_dict = True, cpu_offload = True)
+ )
+ equal = state["state"].keys() == ref["state"].keys() and all(
+ state["state"][k].keys() == ref["state"][k].keys()
+ and all(
+ torch.equal(v, ref["state"][k][key])
+ if torch.is_tensor(v)
+ else v == ref["state"][k][key]
+ for key, v in state["state"][k].items()
+ )
+ for k in state["state"]
+ )
+ resumed = None
+ if arm != "torch":
+ model2, opt2 = build(1)
+ native.native_load_optimizer(model2, opt2, state)
+ raw = {n: opt.state[p] for n, p in model.named_parameters()}
+ raw2 = {n: opt2.state[p] for n, p in model2.named_parameters()}
+ resumed = all(
+ all(
+ torch.equal(raw[n][key], raw2[n][key])
+ for key in ("state1", "state2", "absmax1", "absmax2")
+ )
+ for n in raw
+ )
+ result = {
+ "arm": arm,
+ "elements": N_PARAMS * NUMEL,
+ "one_param_fp32_moments_bytes": 2 * 4 * NUMEL,
+ "train_allocated_bytes": before,
+ "save_extra_peak_bytes": peak,
+ "save_extra_retained_bytes": retained,
+ "state_on_cpu": on_cpu,
+ "equal_to_torch_export": bool(equal),
+ "resume_bitwise": resumed,
+ }
+ Path(out).write_text(json.dumps(result))
+ dist.destroy_process_group()
+
+
+def _run(tmp_path, arm = "bnb"):
+ out = tmp_path / f"{arm}.json"
+ env = dict(os.environ)
+ env["CUDA_VISIBLE_DEVICES"] = env.get("CUDA_VISIBLE_DEVICES", "0").split(",")[0] or "0"
+ subprocess.run(
+ [
+ sys.executable,
+ __file__,
+ "--out",
+ str(out),
+ "--arm",
+ arm,
+ "--rdzv",
+ str(tmp_path / "rdzv"),
+ ],
+ check = True,
+ env = env,
+ timeout = 600,
+ )
+ return json.loads(out.read_text())
+
+
+def test_local_shard_bnb_save_keeps_one_parameter_on_the_gpu(tmp_path):
+ r = _run(tmp_path)
+ assert r["state_on_cpu"] and r["equal_to_torch_export"] and r["resume_bitwise"], r
+ # Unbounded export peaked at 144 MiB here; one parameter with scratch is about 32 MiB.
+ assert r["save_extra_peak_bytes"] <= 5 * r["one_param_fp32_moments_bytes"], r
+ assert r["save_extra_retained_bytes"] <= 1 << 20, r
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--out", required = True)
+ parser.add_argument("--arm", default = "bnb", choices = ["bnb", "torch"])
+ parser.add_argument("--rdzv", default = None)
+ args = parser.parse_args()
+ _worker(args.out, args.arm, args.rdzv or (args.out + ".rdzv"))
diff --git a/tests/test_fsdp2_bnb_optim_sync.py b/tests/test_fsdp2_bnb_optim_sync.py
new file mode 100644
index 00000000000..e3e3ecdf7ff
--- /dev/null
+++ b/tests/test_fsdp2_bnb_optim_sync.py
@@ -0,0 +1,147 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""The local-shard bitsandbytes optimizer skips bitsandbytes' per-parameter sync_gpu unless paged.
+Runs on the CPU: sync_gpu is counted, not executed."""
+
+import os
+import sys
+import warnings
+
+import pytest
+import torch
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from test_fsdp2_native_units import _load_native # noqa: E402
+
+_SHAPES = ((300, 16), (16, 300), (5000,), (40,))
+
+
+def _params(seed):
+ g = torch.Generator().manual_seed(seed)
+ return [torch.nn.Parameter(torch.randn(s, generator = g)) for s in _SHAPES]
+
+
+def _set_grads(params, step):
+ g = torch.Generator().manual_seed(100 + step)
+ for p in params:
+ p.grad = torch.randn(p.shape, generator = g) * 1e-2
+
+
+def sync_calls(monkeypatch):
+ bnb = pytest.importorskip("bitsandbytes")
+ _load_native()
+ from unsloth.models.fsdp2_bnb_optim import bnb_steps_cpu_tensors
+
+ if not bnb_steps_cpu_tensors():
+ pytest.skip("this bitsandbytes cannot step CPU tensors")
+ import bitsandbytes.optim.optimizer as bnb_optimizer
+ import bitsandbytes.utils as bnb_utils
+
+ calls = []
+ for module in (bnb_optimizer, bnb_utils):
+ if hasattr(module, "sync_gpu"):
+ monkeypatch.setattr(module, "sync_gpu", lambda t: calls.append(t.device.type))
+ return bnb, calls
+
+
[email protected]("name", ["AdamW8bit", "Adam8bit", "AdamW"])
+def test_local_shard_step_does_not_sync_per_parameter(sync_calls, name):
+ bnb, calls = sync_calls
+ from unsloth.models.fsdp2_bnb_optim import localize_bnb_optimizer
+
+ cls = getattr(bnb.optim, name)
+ local, ref = _params(0), _params(0)
+ opt = cls(local, lr = 1e-2, min_8bit_size = 0)
+ ref_opt = cls(ref, lr = 1e-2, min_8bit_size = 0)
+ assert localize_bnb_optimizer(opt)
+ hooks = []
+ opt.register_step_post_hook(lambda *a: hooks.append(1))
+ for step in range(3):
+ _set_grads(local, step)
+ _set_grads(ref, step)
+ ref_opt.step()
+ calls.clear()
+ opt.step()
+ assert calls == [], (name, step, calls)
+ for a, b in zip(local, ref):
+ assert torch.equal(a, b)
+ assert len(hooks) == 3
+
+
+def test_paged_local_shard_step_keeps_bitsandbytes_fences(sync_calls):
+ bnb, calls = sync_calls
+ from unsloth.models.fsdp2_bnb_optim import localize_bnb_optimizer
+
+ local, ref = _params(1), _params(1)
+ opt = bnb.optim.PagedAdamW8bit(local, lr = 1e-2, min_8bit_size = 0)
+ ref_opt = bnb.optim.PagedAdamW8bit(ref, lr = 1e-2, min_8bit_size = 0)
+ assert localize_bnb_optimizer(opt)
+ for step in range(2):
+ _set_grads(local, step)
+ _set_grads(ref, step)
+ calls.clear()
+ ref_opt.step()
+ expected = len(calls)
+ calls.clear()
+ opt.step()
+ assert expected == len(_SHAPES) + 1
+ assert len(calls) == expected, (step, calls)
+ for a, b in zip(local, ref):
+ assert torch.equal(a, b)
+
+
[email protected](not torch.cuda.is_available(), reason = "needs a CUDA side stream")
+def test_local_shard_step_on_a_side_stream_keeps_every_fence(monkeypatch):
+ """Off the default stream the per-parameter fences stay; on it none are taken."""
+ bnb = pytest.importorskip("bitsandbytes")
+ _load_native()
+ import bitsandbytes.optim.optimizer as bnb_optimizer
+ import bitsandbytes.utils as bnb_utils
+ from unsloth.models.fsdp2_bnb_optim import localize_bnb_optimizer
+
+ calls = []
+ for module in (bnb_optimizer, bnb_utils):
+ if hasattr(module, "sync_gpu"):
+ monkeypatch.setattr(module, "sync_gpu", lambda t: calls.append(t.device.type))
+ params = [torch.nn.Parameter(p.detach().cuda()) for p in _params(2)]
+ opt = bnb.optim.AdamW8bit(params, lr = 1e-2, min_8bit_size = 0)
+ assert localize_bnb_optimizer(opt)
+ for p in params:
+ p.grad = torch.full_like(p, 1e-2)
+ opt.step()
+ assert calls == []
+ side = torch.cuda.Stream()
+ with torch.cuda.stream(side):
+ opt.step()
+ assert len(calls) == len(_SHAPES) + 1, calls
+
+
+def test_local_shard_step_runs_when_the_scheduler_was_built_first(sync_calls):
+ """Trainer(optimizers = (opt, scheduler)): the scheduler wraps opt.step before localization."""
+ bnb, calls = sync_calls
+ from unsloth.models.fsdp2_bnb_optim import localize_bnb_optimizer
+
+ local, ref = _params(0), _params(0)
+ opt = bnb.optim.AdamW8bit(local, lr = 1e-2, min_8bit_size = 0)
+ ref_opt = bnb.optim.AdamW8bit(ref, lr = 1e-2, min_8bit_size = 0)
+ sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: 1.0)
+ assert localize_bnb_optimizer(opt)
+ hooks = []
+ opt.register_step_post_hook(lambda *a: hooks.append(1))
+ for step in range(2):
+ _set_grads(local, step)
+ _set_grads(ref, step)
+ ref_opt.step()
+ calls.clear()
+ opt.step()
+ assert calls == [], calls
+ with warnings.catch_warnings():
+ warnings.simplefilter(
+ "error"
+ ) # "lr_scheduler.step() before optimizer.step()" would raise
+ sched.step()
+ for a, b in zip(local, ref):
+ assert torch.equal(a, b)
+ assert len(hooks) == 2
diff --git a/unsloth/models/fsdp2_bnb_optim.py b/unsloth/models/fsdp2_bnb_optim.py
index 30400a19de8..bb0bf193200 100644
--- a/unsloth/models/fsdp2_bnb_optim.py
+++ b/unsloth/models/fsdp2_bnb_optim.py
@@ -20,6 +20,7 @@ world-size-independent checkpoint. load_state_dict() re-quantizes it: the invers
blocks are unchanged (same world size), so a resume restores the same 8-bit state.
"""
+import contextlib
import functools
import os
@@ -27,6 +28,7 @@ import torch
__all__ = [
"bnb_local_shards_enabled",
+ "full_cpu_state_export",
"is_local_shard_bnb_optimizer",
"localize_bnb_optimizer",
"supports_local_shards",
@@ -301,6 +303,35 @@ class _LocalShardMixin:
if work is not local:
local.copy_(work)
+ @torch.no_grad()
+ def step(self, closure = None):
+ """bitsandbytes' Optimizer8bit.step, but per-parameter device syncs only for paged optimizers
+ (async prefetches) or off the default stream."""
+ loss = None
+ if closure is not None:
+ with torch.enable_grad():
+ loss = closure()
+ if not self.initialized:
+ self.check_overrides()
+ self.to_gpu()
+ self.initialized = True
+ paged = bool(getattr(self, "is_paged", False))
+ fence = paged or _off_default_stream(self)
+ p = None
+ for gindex, group in enumerate(self.param_groups):
+ for pindex, p in enumerate(group["params"]):
+ if p.grad is None:
+ continue
+ if len(self.state[p]) == 0:
+ self.init_state(group, p, gindex, pindex)
+ self.prefetch_state(p)
+ self.update_step(group, p, gindex, pindex)
+ if fence:
+ _sync_device(p)
+ if fence and p is not None:
+ _sync_device(p)
+ return loss
+
def init_state(self, group, p, gindex, pindex):
return self._shard_call("init_state", group, p, gindex, pindex, with_grad = False)
@@ -386,10 +417,12 @@ class _LocalShardMixin:
for gindex, group in enumerate(self.param_groups)
for pindex, p in enumerate(group["params"])
]
- state_dict["state"] = {
- index: self._export_state(slots[index][0], raw, slots[index][1])
- for index, raw in state_dict["state"].items()
- }
+ to_cpu = getattr(self, "_unsloth_full_cpu_export", False)
+ exported = {}
+ for index, raw in state_dict["state"].items():
+ out = self._export_state(slots[index][0], raw, slots[index][1])
+ exported[index] = _gather_to_cpu(out) if to_cpu else out
+ state_dict["state"] = exported
return state_dict
def _import_state(self, group, p, gindex, pindex, saved):
@@ -440,9 +473,83 @@ class _LocalShardMixin:
self._import_state(*slot_of[saved_id], saved)
+def _gather_to_cpu(entry):
+ """Mirrors torch _gather_state_dict + cpu_offload for one parameter: CPU on rank 0, None elsewhere."""
+ DTensor = _dtensor_class()
+ dist = torch.distributed
+ keep = not (dist.is_available() and dist.is_initialized()) or dist.get_rank() == 0
+ out = {}
+ for key, value in entry.items():
+ if DTensor is not None and isinstance(value, DTensor):
+ from torch.distributed.tensor import Replicate
+
+ mesh = value.device_mesh
+ if value.device.type != mesh.device_type:
+ value = value.to(mesh.device_type)
+ value = value.redistribute(
+ device_mesh = mesh, placements = [Replicate() for _ in value.placements]
+ ).to_local()
+ try:
+ from torch.distributed._functional_collectives import AsyncCollectiveTensor
+ except ImportError:
+ AsyncCollectiveTensor = None
+ if AsyncCollectiveTensor is not None and isinstance(value, AsyncCollectiveTensor):
+ value = value.wait()
+ if torch.is_tensor(value):
+ value = value.to("cpu") if keep else None
+ out[key] = value
+ return out
+
+
+def full_cpu_state_export(optimizer):
+ """Gather + offload each parameter's dequantized state as it is exported, instead of holding all
+ float32 moments on the device until torch gathers. Every rank must enter it (collectives)."""
+ if not is_local_shard_bnb_optimizer(optimizer):
+ yield
+ return
+ optimizer._unsloth_full_cpu_export = True
+ try:
+ yield
+ finally:
+ optimizer._unsloth_full_cpu_export = False
+
+
+def _off_default_stream(optimizer):
+ devices = {p.device for group in optimizer.param_groups for p in group["params"]}
+ for device in devices:
+ if device.type == "cpu":
+ continue
+ if device.type != "cuda":
+ return True
+ if torch.cuda.current_stream(device) != torch.cuda.default_stream(device):
+ return True
+ return False
+
+
+def _sync_device(p):
+ try:
+ from bitsandbytes.utils import sync_gpu
+ except ImportError:
+ sync_gpu = None
+ if sync_gpu is not None:
+ return sync_gpu(p)
+ if p.device.type == "cuda":
+ torch.cuda.synchronize()
+ elif p.device.type == "xpu":
+ torch.xpu.synchronize()
+
+
@functools.lru_cache(maxsize = None)
def _local_shard_class(cls):
- return type(cls.__name__, (_LocalShardMixin, cls), {"__module__": cls.__module__})
+ namespace = {"__module__": cls.__module__}
+ hook_step = getattr(torch.optim.Optimizer, "profile_hook_step", None)
+ if hook_step is not None:
+ # The mixin's step shadows torch's hooked step: re-wrap so step hooks still run once.
+ step = hook_step(_LocalShardMixin.step)
+ step.hooked = True
+ namespace["step"] = step
+ return type(cls.__name__, (_LocalShardMixin, cls), namespace)
def localize_bnb_optimizer(optimizer):
@@ -458,9 +565,30 @@ def localize_bnb_optimizer(optimizer):
"parameters; build it after `shard_model(model)` and before training."
)
optimizer.__class__ = _local_shard_class(type(optimizer))
+ _rebind_scheduler_step(optimizer)
return True
+def _rebind_scheduler_step(optimizer):
+ """A scheduler built before localization wrapped the old class step on the instance; repoint it."""
+ wrapped = vars(optimizer).get("step")
+ if wrapped is None or not getattr(wrapped, "_wrapped_by_lr_sched", False):
+ return
+ import weakref
+
+ opt_ref = weakref.ref(optimizer)
+ func = type(optimizer).step
+
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ opt = opt_ref()
+ opt._opt_called = True
+ return func.__get__(opt, opt.__class__)(*args, **kwargs)
+
+ wrapper._wrapped_by_lr_sched = True
+ optimizer.step = wrapper
+
+
def rename_optimizer_state_for(optimizer, full_state):
"""Full (FQN-keyed) optimizer state: map torch Adam keys (exp_avg / exp_avg_sq) to the local-shard
bitsandbytes keys (state1 / state2) or back, to resume across the two optimizers."""
diff --git a/unsloth/models/fsdp2_native.py b/unsloth/models/fsdp2_native.py
index 6f5b8763058..af3949e263d 100644
--- a/unsloth/models/fsdp2_native.py
+++ b/unsloth/models/fsdp2_native.py
@@ -2357,11 +2357,18 @@ def native_save_optimizer(
from .fsdp2_save import _dist, _wait_for_writer, mesh_writer_rank
writer_rank = mesh_writer_rank(model)
- state = get_optimizer_state_dict(
- model,
- optimizer,
- options = StateDictOptions(full_state_dict = writer_rank == 0, cpu_offload = writer_rank == 0),
- )
+ export = contextlib.nullcontext()
+ if writer_rank == 0:
+ from .fsdp2_bnb_optim import full_cpu_state_export
+ export = full_cpu_state_export(optimizer)
+ with export:
+ state = get_optimizer_state_dict(
+ model,
+ optimizer,
+ options = StateDictOptions(
+ full_state_dict = writer_rank == 0, cpu_offload = writer_rank == 0
+ ),
+ )
if writer_rank != 0:
state = _gather_to_writer(state, writer_rank)
dist = _dist()