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: keep bitsandbytes 8-bit AdamW state by stepping the local shards (#15008)

Daniel Hanf674295fc4cf
diff --git a/tests/test_fsdp2_native_bnb_8bit_gloo.py b/tests/test_fsdp2_native_bnb_8bit_gloo.py
new file mode 100644
index 00000000000..10af9553394
--- /dev/null
+++ b/tests/test_fsdp2_native_bnb_8bit_gloo.py
@@ -0,0 +1,626 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""bitsandbytes 8-bit AdamW under native FSDP2, stepped on the local shards (gloo world of 2, CPU,
+bitsandbytes' CPU kernels):
+
+* the local-shard optimizer equals bitsandbytes stepping each rank's plain shard (bitwise), keeps 8-bit
+ state where one GPU would (min_8bit_size on the full size), handles an empty shard, a replicated
+ parameter, two groups and an LR change;
+* the full optimizer state (get / set_optimizer_state_dict, full_state_dict) round-trips the 8-bit
+ state exactly, and a step after the reload equals a step without it;
+* a Trainer with optim = 'adamw_8bit' keeps bitsandbytes (it was switched to torch's AdamW before), with
+ 8-bit state on lm_head, 32-bit on the embedding (transformers' override), and a checkpoint resume
+ that ends on the same weights as the uninterrupted run."""
+
+import multiprocessing
+import os
+
+if multiprocessing.parent_process() is not None or getattr(
+ multiprocessing.current_process(), "_inheriting", False
+):
+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts
+
+import datetime # noqa: E402
+import sys # noqa: E402
+import time # noqa: E402
+
+import pytest # noqa: E402
+import torch # noqa: E402
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from test_fsdp2_native_units import _load_native # noqa: E402
+from test_fsdp2_native_trainer_ckpt_gloo import _free_port, _model, _stub_unsloth_save # noqa: E402
+from test_fsdp2_native_trainer_args_gloo import _install_wrapped_trainer_init # noqa: E402
+
+_SHAPES = {"w": (96, 64), "b": (96,), "row": (1, 5000), "odd": (3, 1000), "mis": (5, 1000)}
+_REPLICATED = {"rep": (4096,)}
+
+
+class _Toy(torch.nn.Module):
+ def __init__(self, mesh, seed):
+ device = mesh.device_type
+ super().__init__()
+ from torch.distributed.tensor import Shard, distribute_tensor
+
+ g = torch.Generator().manual_seed(seed)
+ for name, shape in _SHAPES.items():
+ full = torch.randn(shape, generator = g).to(device)
+ self.register_parameter(
+ name, torch.nn.Parameter(distribute_tensor(full, mesh, [Shard(0)]))
+ )
+ for name, shape in _REPLICATED.items():
+ self.register_parameter(
+ name, torch.nn.Parameter(torch.randn(shape, generator = g).to(device))
+ )
+
+
+def _groups(model):
+ return [
+ {"params": [model.w, model.b, model.row]},
+ {"params": [model.odd, model.mis, model.rep], "lr": 5e-3},
+ ]
+
+
+def _grads(step, device = "cpu"):
+ g = torch.Generator().manual_seed(100 + step)
+ shapes = {**_SHAPES, **_REPLICATED}
+ return {
+ name: (torch.randn(shape, generator = g) * (0.1 + step)).to(device)
+ for name, shape in shapes.items()
+ }
+
+
+def _set_grads(model, grads):
+ from torch.distributed.tensor import DTensor, distribute_tensor
+ for name, p in model.named_parameters():
+ full = grads[name]
+ p.grad = (
+ distribute_tensor(full, p.device_mesh, p.placements) if isinstance(p, DTensor) else full
+ )
+
+
+def _locals(model):
+ from torch.distributed.tensor import DTensor
+ return {
+ n: (p._local_tensor if isinstance(p, DTensor) else p).detach().clone()
+ for n, p in model.named_parameters()
+ }
+
+
+def _raw(optimizer, model):
+ out = {}
+ for name, p in model.named_parameters():
+ state = optimizer.state.get(p, {})
+ out[name] = {k: v.clone() if torch.is_tensor(v) else v for k, v in state.items()}
+ return out
+
+
+def _case_unit(
+ rank,
+ tmp,
+ device = "cpu",
+):
+ import bitsandbytes as bnb
+ from torch.distributed.device_mesh import init_device_mesh
+
+ from unsloth.models.fsdp2_bnb_optim import (
+ is_local_shard_bnb_optimizer,
+ localize_bnb_optimizer,
+ rename_optimizer_state_for,
+ )
+
+ mesh = init_device_mesh(device, (2,))
+ model = _Toy(mesh, 0)
+ optimizer = bnb.optim.AdamW8bit(_groups(model), lr = 1e-2, weight_decay = 0.01)
+ assert localize_bnb_optimizer(optimizer) and is_local_shard_bnb_optimizer(optimizer)
+
+ # Reference: bitsandbytes over this rank's plain shards, with one GPU's 8-bit choice per parameter
+ # (full numel >= min_8bit_size) forced through bitsandbytes' own per-parameter override.
+ manager = bnb.optim.GlobalOptimManager.get_instance()
+ local0 = _locals(model)
+ ref = {n: torch.nn.Parameter(t.clone()) for n, t in local0.items() if t.numel() > 0}
+ for name, p in ref.items():
+ full = getattr(model, name).numel()
+ manager.override_config(p, "min_8bit_size", 0 if full >= 4096 else 10**9)
+ ref_groups = [
+ {"params": [ref[n] for n in ("w", "b", "row") if n in ref]},
+ {"params": [ref[n] for n in ("odd", "mis", "rep") if n in ref], "lr": 5e-3},
+ ]
+ ref_opt = bnb.optim.AdamW8bit(ref_groups, lr = 1e-2, weight_decay = 0.01)
+
+ # One GPU: bitsandbytes over the full tensors (different quantization blocks).
+ single = {
+ n: torch.nn.Parameter(getattr(model, n).full_tensor().clone())
+ if n in _SHAPES
+ else torch.nn.Parameter(getattr(model, n).detach().clone())
+ for n in local0
+ }
+ single_opt = bnb.optim.AdamW8bit(
+ [
+ {"params": [single[n] for n in ("w", "b", "row")]},
+ {"params": [single[n] for n in ("odd", "mis", "rep")], "lr": 5e-3},
+ ],
+ lr = 1e-2,
+ weight_decay = 0.01,
+ )
+
+ def _step(step):
+ grads = _grads(step, device)
+ _set_grads(model, grads)
+ local_grads = {
+ n: (p.grad._local_tensor if hasattr(p.grad, "_local_tensor") else p.grad)
+ for n, p in model.named_parameters()
+ }
+ for n, p in ref.items():
+ p.grad = local_grads[n].clone()
+ for n, p in single.items():
+ p.grad = grads[n].clone()
+ optimizer.step()
+ ref_opt.step()
+ single_opt.step()
+ optimizer.zero_grad(set_to_none = True)
+
+ res = {}
+ for step in range(3):
+ if step == 2: # an LR scheduler writes the groups' lr
+ for opt in (optimizer, ref_opt, single_opt):
+ opt.param_groups[0]["lr"] = 2e-3
+ _step(step)
+ now = _locals(model)
+ res["vs_shard_bnb"] = max((now[n] - ref[n].detach()).abs().max().item() for n in ref)
+ res["moved"] = min((now[n] - local0[n]).abs().max().item() for n in ref)
+ res["dtypes"] = {
+ n: str(optimizer.state[getattr(model, n)].get("state1", torch.empty(0)).dtype)
+ if "state1" in optimizer.state[getattr(model, n)]
+ else "none"
+ for n in local0
+ }
+ res["steps"] = {n: optimizer.state[getattr(model, n)]["step"] for n in local0}
+ for n in local0: # one GPU vs FSDP2 (blocks differ): reported, not asserted
+ got = getattr(model, n)
+ got = got.full_tensor() if n in _SHAPES else got.detach()
+ res.setdefault("vs_single_rel", {})[n] = (
+ (got - single[n].detach()).norm() / (single[n].detach().norm() + 1e-12)
+ ).item()
+
+ # Full optimizer state round trip and a step after the reload.
+ native = sys.modules["unsloth.models.fsdp2_native"]
+ path = os.path.join(tmp, "optimizer.pt")
+ native.native_save_optimizer(model, optimizer, path) # collective, written by rank 0
+ full = torch.load(path, map_location = "cpu", weights_only = True)
+ res["full_keys"] = sorted(full["state"]["w"])
+ res["full_shapes"] = {n: list(full["state"][n]["state1"].shape) for n in local0}
+ res["full_dtype"] = str(full["state"]["w"]["state1"].dtype)
+ model2 = _Toy(mesh, 0)
+ with torch.no_grad():
+ for (n, p), (_, q) in zip(model.named_parameters(), model2.named_parameters()):
+ target = q._local_tensor if hasattr(q, "_local_tensor") else q
+ target.copy_(p._local_tensor if hasattr(p, "_local_tensor") else p)
+ optimizer2 = bnb.optim.AdamW8bit(_groups(model2), lr = 1e-2, weight_decay = 0.01)
+ localize_bnb_optimizer(optimizer2)
+ native.native_load_optimizer(model2, optimizer2, path)
+ raw1, raw2 = _raw(optimizer, model), _raw(optimizer2, model2)
+ mismatch = []
+ for n in raw1:
+ if sorted(raw1[n]) != sorted(raw2[n]):
+ mismatch.append((n, sorted(raw1[n]), sorted(raw2[n])))
+ continue
+ for k, v in raw1[n].items():
+ w = raw2[n][k]
+ same = torch.equal(v, w) if torch.is_tensor(v) else v == w
+ if not same:
+ mismatch.append((n, k))
+ res["reload_mismatch"] = mismatch
+ res["lr_after_reload"] = [g["lr"] for g in optimizer2.param_groups]
+ grads = _grads(7, device)
+ _set_grads(model, grads)
+ _set_grads(model2, grads)
+ optimizer.step()
+ optimizer2.step()
+ a, b = _locals(model), _locals(model2)
+ res["after_reload_step_diff"] = max((a[n] - b[n]).abs().max().item() for n in a if a[n].numel())
+
+ # A torch AdamW checkpoint (exp_avg / exp_avg_sq, tensor step) maps onto the bitsandbytes keys.
+ as_torch = {
+ "state": {
+ n: {"exp_avg": torch.zeros(2), "exp_avg_sq": torch.ones(2), "step": torch.tensor(3.0)}
+ for n in ("w",)
+ },
+ "param_groups": [],
+ }
+ rename_optimizer_state_for(optimizer, as_torch)
+ res["renamed"] = sorted(as_torch["state"]["w"]) + [
+ type(as_torch["state"]["w"]["step"]).__name__
+ ]
+ return res
+
+
+def _cpu_percentile_clipping(functional):
+ """bitsandbytes' percentile_clipping (CUDA only) in torch for the CPU ranks: the squared gradient
+ norm goes to gnorm_vec[step % 100], and the clip value is the given percentile of the history."""
+ original = functional.percentile_clipping
+
+ def percentile_clipping(
+ grad,
+ gnorm_vec,
+ step,
+ percentile = 5,
+ ):
+ if grad.is_cuda:
+ return original(grad, gnorm_vec, step, percentile)
+ gnorm_vec[step % 100] = grad.float().pow(2).sum()
+ current = torch.sqrt(gnorm_vec[step % 100])
+ vals, _ = torch.sort(gnorm_vec)
+ clip = torch.sqrt(vals[percentile])
+ return current, clip, (clip / current if current > clip else 1.0)
+
+ functional.percentile_clipping = percentile_clipping
+
+
+def _case_pclip(
+ rank,
+ tmp,
+ device = "cpu",
+):
+ """percentile_clipping = 5: bitsandbytes keeps the last 100 squared gradient norms per parameter
+ (gnorm_vec) and clips at their 5th percentile, so a resume must restore that history."""
+ import bitsandbytes as bnb
+ import bitsandbytes.optim.optimizer as bnb_optimizer
+ from torch.distributed.device_mesh import init_device_mesh
+
+ from unsloth.models.fsdp2_bnb_optim import localize_bnb_optimizer
+
+ _cpu_percentile_clipping(bnb_optimizer.F)
+ native = sys.modules["unsloth.models.fsdp2_native"]
+ mesh = init_device_mesh(device, (2,))
+
+ def grads(step):
+ g = torch.Generator().manual_seed(1000 + step)
+ scale = 1.0 + (step % 7)
+ shapes = {**_SHAPES, **_REPLICATED}
+ return {n: (torch.randn(s, generator = g) * scale).to(device) for n, s in shapes.items()}
+
+ def build(model):
+ opt = bnb.optim.AdamW8bit(_groups(model), lr = 1e-3, percentile_clipping = 5)
+ localize_bnb_optimizer(opt)
+ return opt
+
+ def run(model, opt, steps):
+ for step in steps:
+ _set_grads(model, grads(step))
+ opt.step()
+ opt.zero_grad(set_to_none = True)
+
+ model = _Toy(mesh, 0)
+ optimizer = build(model)
+ run(model, optimizer, range(100))
+ path = os.path.join(tmp, "optimizer_pclip.pt")
+ native.native_save_optimizer(model, optimizer, path)
+ at_save = _locals(model)
+ run(model, optimizer, range(100, 104))
+
+ model2 = _Toy(mesh, 0)
+ with torch.no_grad():
+ for n, q in model2.named_parameters():
+ (q._local_tensor if hasattr(q, "_local_tensor") else q).copy_(at_save[n])
+ optimizer2 = build(model2)
+ native.native_load_optimizer(model2, optimizer2, path)
+ run(model2, optimizer2, range(100, 104))
+ a, b = _locals(model), _locals(model2)
+ res = {
+ "resume_diff": max((a[n] - b[n]).abs().max().item() for n in a if a[n].numel()),
+ "has_gnorm": sorted(
+ n for n, p in model.named_parameters() if "gnorm_vec" in optimizer.state[p]
+ ),
+ "gnorm_diff": max(
+ (optimizer.state[p]["gnorm_vec"] - optimizer2.state[q]["gnorm_vec"]).abs().max().item()
+ for (n, p), (_, q) in zip(model.named_parameters(), model2.named_parameters())
+ if "gnorm_vec" in optimizer.state[p]
+ ),
+ }
+ return res
+
+
+def _case_refuse(rank, tmp):
+ """A bitsandbytes optimizer that cannot step local shards, built by Trainer.create_optimizer (here
+ through get_optimizer_cls_and_kwargs, as a non-blockwise Adam) or by a subclass create_optimizer
+ (LAMB): refused when it is built, not inside the first step."""
+ import bitsandbytes as bnb
+ from transformers import Trainer, TrainingArguments
+
+ from test_fsdp2_native_trainer_ckpt_gloo import _non_blockwise_adamw8bit
+
+ _load_native()
+ _stub_unsloth_save()
+ _install_wrapped_trainer_init()
+ res = {}
+
+ def args():
+ return TrainingArguments(
+ output_dir = os.path.join(tmp, "out"),
+ report_to = [],
+ use_cpu = True,
+ optim = "adamw_8bit",
+ max_steps = 2,
+ )
+
+ trainer = Trainer(model = _model(False, 1, tmp), args = args())
+ non_blockwise = _non_blockwise_adamw8bit()
+ trainer.get_optimizer_cls_and_kwargs = lambda *a, **k: (non_blockwise, {"lr": 1e-3})
+ try:
+ trainer.create_optimizer()
+ res["base_hook"] = "built " + type(trainer.optimizer).__name__
+ except ValueError as exc:
+ res["base_hook"] = "refused" if "cannot" in str(exc) else f"other: {exc}"
+
+ class LambTrainer(Trainer):
+ def create_optimizer(self, *a, **k):
+ self.optimizer = bnb.optim.LAMB8bit(self.model.parameters(), lr = 1e-3)
+ return self.optimizer
+
+ trainer = LambTrainer(model = _model(False, 1, tmp), args = args())
+ try:
+ trainer.create_optimizer_and_scheduler(num_training_steps = 2)
+ res["subclass_hook"] = "built " + type(trainer.optimizer).__name__
+ except ValueError as exc:
+ res["subclass_hook"] = "refused" if "cannot" in str(exc) else f"other: {exc}"
+ return res
+
+
+def _trainer_case(
+ native,
+ tmp,
+ resume_from = None,
+ max_steps = 4,
+):
+ from datasets import Dataset
+ from transformers import Trainer, TrainingArguments
+
+ _install_wrapped_trainer_init()
+ model = _model(False, 1, tmp)
+ rows = [{"input_ids": list(range(5, 37)), "labels": list(range(5, 37))}] * 8
+ args = TrainingArguments(
+ output_dir = os.path.join(tmp, "out"),
+ report_to = [],
+ use_cpu = True,
+ optim = "adamw_8bit",
+ max_steps = max_steps,
+ learning_rate = 1e-3,
+ per_device_train_batch_size = 1,
+ lr_scheduler_type = "linear",
+ save_strategy = "steps",
+ save_steps = 2,
+ logging_steps = 1,
+ seed = 0,
+ data_seed = 0,
+ )
+ trainer = Trainer(model = model, args = args, train_dataset = Dataset.from_list(rows))
+ trainer.train(resume_from_checkpoint = resume_from)
+ return trainer
+
+
+def _case_trainer(rank, tmp):
+ import torch.distributed as dist
+ from torch.distributed.tensor import DTensor
+
+ native = _load_native()
+ _stub_unsloth_save()
+ trainer = _trainer_case(native, tmp)
+ inner = native._inner_optimizer(trainer.optimizer)
+ res = {
+ "optim": str(getattr(trainer.args.optim, "value", trainer.args.optim)),
+ "cls": f"{type(inner).__module__}.{type(inner).__name__}",
+ "local_shards": getattr(type(inner), "_unsloth_fsdp2_local_shards", False),
+ "native": native.is_native_fsdp2(trainer.model),
+ "losses": [h["loss"] for h in trainer.state.log_history if "loss" in h],
+ }
+ model = native._native_root(trainer.model)
+ dtypes = {}
+ for name, p in model.named_parameters():
+ state = inner.state.get(p, {})
+ if "state1" in state and ("lm_head" in name or "embed_tokens" in name):
+ dtypes[name] = str(state["state1"].dtype)
+ res["dtypes"] = dtypes
+ final = {
+ n: (p.full_tensor() if isinstance(p, DTensor) else p).detach().clone()
+ for n, p in model.named_parameters()
+ }
+ ckpt = os.path.join(tmp, "out", "checkpoint-2")
+ res["ckpt"] = os.path.isfile(os.path.join(ckpt, "optimizer.pt"))
+ if rank == 0 and res["ckpt"]:
+ saved = torch.load(
+ os.path.join(ckpt, "optimizer.pt"), map_location = "cpu", weights_only = True
+ )
+ any_state = next(iter(saved["state"].values()))
+ res["saved_keys"] = sorted(any_state)
+ step = any_state["step"]
+ res["saved_step"] = float(step) if torch.is_tensor(step) else step # plain, for the queue
+ dist.barrier()
+ resumed = _trainer_case(native, tmp, resume_from = ckpt)
+ rmodel = native._native_root(resumed.model)
+ again = {
+ n: (p.full_tensor() if isinstance(p, DTensor) else p).detach().clone()
+ for n, p in rmodel.named_parameters()
+ }
+ res["resume_diff"] = max((again[n] - final[n]).abs().max().item() for n in final)
+ res["resume_steps"] = resumed.state.global_step
+ return res
+
+
+def _worker(rank, world, port, out, case, tmp):
+ os.environ.update(
+ MASTER_ADDR = "127.0.0.1",
+ MASTER_PORT = str(port),
+ RANK = str(rank),
+ WORLD_SIZE = str(world),
+ LOCAL_RANK = str(rank),
+ LOCAL_WORLD_SIZE = str(world),
+ UNSLOTH_FSDP2 = "1",
+ )
+ import torch.distributed as dist
+
+ dist.init_process_group(
+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 120)
+ )
+ try:
+ _load_native()
+ cases = {
+ "unit": _case_unit,
+ "trainer": _case_trainer,
+ "pclip": _case_pclip,
+ "refuse": _case_refuse,
+ }
+ res = cases[case](rank, tmp)
+ out.put((rank, res))
+ except Exception as exc:
+ import traceback
+ out.put((rank, {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}))
+ finally:
+ try:
+ dist.destroy_process_group()
+ except Exception:
+ pass
+
+
+def _run(
+ case,
+ tmp_path,
+ timeout = 300,
+):
+ import torch.multiprocessing as mp
+
+ ctx = mp.get_context("spawn")
+ out = ctx.Queue()
+ procs = mp.start_processes(
+ _worker,
+ args = (2, _free_port(), out, case, str(tmp_path)),
+ nprocs = 2,
+ join = False,
+ start_method = "spawn",
+ )
+ deadline = time.time() + timeout
+ try:
+ while not procs.join(timeout = 5):
+ if time.time() > deadline:
+ for p in procs.processes:
+ p.kill()
+ pytest.fail(
+ f"{case}: the ranks did not finish within {timeout} s (hung collective)"
+ )
+ except mp.ProcessExitedException as exc:
+ pytest.fail(f"{case}: a rank died ({exc})")
+ results = {}
+ while not out.empty():
+ rank, r = out.get(timeout = 5)
+ results[rank] = r
+ assert sorted(results) == [0, 1], results
+ for rank, r in results.items():
+ print("BNB8_RESULT", case, rank, r)
+ assert "crash" not in r, r["crash"]
+ return results
+
+
+def test_local_shard_bnb_matches_shard_bnb_and_reloads_exactly(tmp_path):
+ pytest.importorskip("bitsandbytes")
+ results = _run("unit", tmp_path)
+ for rank, r in results.items():
+ assert r["vs_shard_bnb"] == 0.0, (rank, r)
+ assert r["moved"] > 0, (rank, r)
+ # 8-bit where one GPU picks it (full numel >= 4096), even for a 3072-element shard.
+ assert r["dtypes"]["w"] == "torch.uint8" and r["dtypes"]["rep"] == "torch.uint8", r
+ assert r["dtypes"]["mis"] == "torch.uint8", r
+ assert r["dtypes"]["b"] == "torch.float32" and r["dtypes"]["odd"] == "torch.float32", r
+ assert r["steps"] == {n: 3 for n in r["steps"]}, r
+ assert r["full_keys"] == ["state1", "state2", "step"], r
+ assert r["full_dtype"] == "torch.float32", r
+ assert r["full_shapes"] == {
+ "w": [96, 64],
+ "b": [96],
+ "row": [1, 5000],
+ "odd": [3, 1000],
+ "mis": [5, 1000],
+ "rep": [4096],
+ }, r
+ assert r["reload_mismatch"] == [], (rank, r["reload_mismatch"])
+ assert r["lr_after_reload"] == [2e-3, 5e-3], r
+ assert r["after_reload_step_diff"] == 0.0, (rank, r)
+ assert r["renamed"] == ["state1", "state2", "step", "int"], r
+ # Shards that are whole 256-element blocks of the full tensor quantize exactly as one GPU does;
+ # (5, 1000) splits into 3000 / 2000 elements, so its blocks differ from one GPU's.
+ for rank, r in results.items():
+ assert r["vs_single_rel"]["w"] == 0.0 and r["vs_single_rel"]["row"] == 0.0, r
+ assert r["vs_single_rel"]["odd"] == 0.0 and r["vs_single_rel"]["b"] == 0.0, r
+ assert 0.0 < r["vs_single_rel"]["mis"] < 1e-2, r
+ # The (1, 5000) parameter: rank 0 holds the whole row in 8-bit, rank 1 an empty shard.
+ assert results[0]["dtypes"]["row"] == "torch.uint8", results[0]
+ assert results[1]["dtypes"]["row"] == "none", results[1]
+
+
+def test_trainer_adamw_8bit_keeps_bnb_state_and_resumes(tmp_path):
+ pytest.importorskip("bitsandbytes")
+ pytest.importorskip("datasets")
+ results = _run("trainer", tmp_path, timeout = 600)
+ for rank, r in results.items():
+ assert r["native"] and r["optim"] == "adamw_8bit", (rank, r)
+ assert r["local_shards"] and r["cls"].startswith("bitsandbytes."), (rank, r)
+ assert any("lm_head" in n and d == "torch.uint8" for n, d in r["dtypes"].items()), r
+ assert any("embed_tokens" in n and d == "torch.float32" for n, d in r["dtypes"].items()), r
+ assert all(x == x and abs(x) < 1e4 for x in r["losses"]) and len(r["losses"]) == 4, r
+ assert r["ckpt"] and r["resume_steps"] == 4, r
+ assert r["resume_diff"] == 0.0, (rank, r)
+ assert results[0]["saved_keys"] == ["state1", "state2", "step"], results[0]
+
+
+def test_percentile_clipping_history_survives_resume(tmp_path):
+ bnb = pytest.importorskip("bitsandbytes")
+ import inspect
+
+ if "percentile_clipping" not in inspect.signature(bnb.optim.AdamW8bit.__init__).parameters:
+ pytest.skip("this bitsandbytes has no percentile_clipping")
+ probe = torch.nn.Parameter(torch.zeros(8))
+ probe.grad = torch.ones(8)
+ try:
+ bnb.optim.AdamW8bit([probe], percentile_clipping = 5, min_8bit_size = 0).step()
+ except RuntimeError as exc: # bitsandbytes <= 0.48: 8-bit kernels are CUDA only
+ pytest.skip(f"this bitsandbytes cannot step 8-bit state on the CPU ({str(exc)[:60]})")
+ for rank, r in _run("pclip", tmp_path).items():
+ assert r["has_gnorm"], (rank, r)
+ assert r["gnorm_diff"] == 0.0, (rank, r)
+ assert r["resume_diff"] == 0.0, (rank, r)
+
+
+def test_bnb_optimizer_that_cannot_step_shards_is_refused_when_built(tmp_path):
+ pytest.importorskip("bitsandbytes")
+ for rank, r in _run("refuse", tmp_path).items():
+ assert r["base_hook"] == "refused", (rank, r)
+ assert r["subclass_hook"] == "refused", (rank, r)
+
+
+def test_chunked_requantization_is_bitwise_equal_to_one_pass():
+ """The checkpoint (de)quantization runs a bounded number of blocks per pass; a state spanning
+ several chunks with a ragged tail block gives the same codes, absmax and float32 values as one
+ pass, and inverts bitsandbytes' own state exactly."""
+ bnb = pytest.importorskip("bitsandbytes")
+ _load_native()
+ from unsloth.models.fsdp2_bnb_optim import _dequantize, _quantize_into
+
+ torch.manual_seed(0)
+ n = 256 * 10 + 77 # 11 blocks, the last one 77 elements
+ p = torch.nn.Parameter(torch.randn(n))
+ opt = bnb.optim.AdamW8bit([p], lr = 1e-2, min_8bit_size = 0)
+ for step in range(3):
+ p.grad = torch.randn(n) * (10.0 ** (step - 1))
+ opt.step()
+ raw = opt.state[p]
+ for key in ("state1", "state2"):
+ i = key[-1]
+ whole = _dequantize(raw, key, raw[key].device, chunk_blocks = 10**6)
+ for chunk_blocks in (1, 3, 4, 10**6):
+ values = _dequantize(raw, key, raw[key].device, chunk_blocks = chunk_blocks)
+ assert torch.equal(values, whole), (key, chunk_blocks)
+ codes = torch.empty_like(raw[key])
+ absmax = torch.empty_like(raw[f"absmax{i}"])
+ _quantize_into(values, raw[f"qmap{i}"], codes, absmax, chunk_blocks = chunk_blocks)
+ assert torch.equal(codes, raw[key]), (key, chunk_blocks)
+ assert torch.equal(absmax, raw[f"absmax{i}"]), (key, chunk_blocks)
diff --git a/tests/test_fsdp2_native_trainer_ckpt_gloo.py b/tests/test_fsdp2_native_trainer_ckpt_gloo.py
index edc8fb2663a..b434ad13999 100644
--- a/tests/test_fsdp2_native_trainer_ckpt_gloo.py
+++ b/tests/test_fsdp2_native_trainer_ckpt_gloo.py
@@ -325,7 +325,9 @@ def test_bnb_optimizers_without_torch_equivalent_are_refused(optim):
("adamw_torch", "adamw_torch"),
],
)
-def test_bnb_optimizers_switch_to_torch(optim, target):
+def test_bnb_optimizers_switch_to_torch(optim, target, monkeypatch):
+ # bitsandbytes Adam / AdamW step local shards by default; UNSLOTH_FSDP2_BNB_LOCAL=0 switches them.
+ monkeypatch.setenv("UNSLOTH_FSDP2_BNB_LOCAL", "0")
native = _load_native()
args = types.SimpleNamespace(optim = optim)
native._swap_bnb_optimizer(args)
@@ -338,3 +340,128 @@ def test_bnb_optimizers_switch_to_torch(optim, target):
return
known = set(native._BNB_OPTIMS) | set(native._BNB_UNSUPPORTED)
assert {str(o.value) for o in _BITSANDBYTES_OPTIMIZERS} <= known
+
+
+ "optim", ["adamw_8bit", "adamw_bnb_8bit", "paged_adamw_8bit", "paged_adamw_32bit"]
+)
+def test_bnb_adam_is_kept_for_local_shards(optim):
+ pytest.importorskip("bitsandbytes")
+ native = _load_native()
+ args = types.SimpleNamespace(optim = optim)
+ assert native._swap_bnb_optimizer(args) is False
+ assert args.optim == optim
+ assert set(native._BNB_LOCAL_SHARD_OPTIMS) <= set(native._BNB_OPTIMS)
+
+
+def _non_blockwise_adamw8bit():
+ """bitsandbytes Adam with per-tensor 8-bit state (block_wise = False, the kwarg older bitsandbytes
+ takes): an Optimizer2State 'adam' subclass the class check alone accepts."""
+ import bitsandbytes as bnb
+
+ class NonBlockwiseAdamW8bit(bnb.optim.AdamW8bit):
+ def __init__(self, params, **kwargs):
+ super().__init__(params, **kwargs)
+ self.args.block_wise = False
+
+ return NonBlockwiseAdamW8bit
+
+
[email protected]("which", ["lamb", "non_blockwise", "adamw8bit", "paged_adamw8bit"])
+def test_bnb_optimizer_cls_preflight_uses_the_localization_predicate(which):
+ bnb = pytest.importorskip("bitsandbytes")
+ native = _load_native()
+ cls = {
+ "lamb": bnb.optim.LAMB8bit,
+ "non_blockwise": _non_blockwise_adamw8bit(),
+ "adamw8bit": bnb.optim.AdamW8bit,
+ "paged_adamw8bit": bnb.optim.PagedAdamW8bit,
+ }[which]
+ if which in ("lamb", "non_blockwise"):
+ with pytest.raises(ValueError, match = "cannot"):
+ native._refuse_bnb_optimizer_cls((cls, {"lr": 1e-3}))
+ else:
+ native._refuse_bnb_optimizer_cls((cls, {"lr": 1e-3}))
+
+
+def test_cpu_shards_keep_the_torch_adamw_switch_when_bnb_cannot_step_cpu(monkeypatch):
+ """CPU-offloaded / CPU-mesh shards are CPU tensors; bitsandbytes releases before 0.50 refuse CPU
+ inputs in the 8-bit Adam step, so adamw_8bit falls back to torch's AdamW there."""
+ pytest.importorskip("bitsandbytes")
+ native = _load_native()
+ import unsloth.models.fsdp2_bnb_optim as local_shards
+
+ for cpu_shards, can_step_cpu, kept in (
+ (False, False, True),
+ (True, True, True),
+ (True, False, False),
+ ):
+ monkeypatch.setattr(local_shards, "bnb_steps_cpu_tensors", lambda: can_step_cpu)
+ args = types.SimpleNamespace(optim = "adamw_8bit")
+ native._swap_bnb_optimizer(args, cpu_shards)
+ value = str(getattr(args.optim, "value", args.optim))
+ assert (value == "adamw_8bit") == kept, (cpu_shards, can_step_cpu, value)
+ if not kept:
+ assert value in ("adamw_torch", "adamw_torch_fused"), value
+ # A prebuilt bitsandbytes optimizer over CPU tensors is then not localized (and refused).
+ import bitsandbytes as bnb
+
+ opt = bnb.optim.AdamW8bit([torch.nn.Parameter(torch.zeros(4))])
+ assert native._localize_bnb_optimizer(opt) is False
+ with pytest.raises(ValueError, match = "cannot"):
+ native._refuse_bnb_optimizer_instance(opt)
+ # Where the shards will live: UNSLOTH_FSDP2_CPU_OFFLOAD, a CPU Trainer, or no CUDA device.
+ monkeypatch.setattr(native.torch.cuda, "is_available", lambda: True)
+ args = types.SimpleNamespace(use_cpu = False, no_cuda = False)
+ monkeypatch.delenv("ACCELERATE_USE_CPU", raising = False)
+ monkeypatch.delenv("UNSLOTH_FSDP2_CPU_OFFLOAD", raising = False)
+ assert native._native_shards_on_cpu(None, args) is False
+ monkeypatch.setenv("UNSLOTH_FSDP2_CPU_OFFLOAD", "1")
+ assert native._native_shards_on_cpu(None, args) is True
+ monkeypatch.delenv("UNSLOTH_FSDP2_CPU_OFFLOAD")
+ assert native._native_shards_on_cpu(None, types.SimpleNamespace(use_cpu = True)) is True
+
+
+def _q_galore_class():
+ """unsloth/optimizers/q_galore_adamw.py loaded on its own (unsloth_zoo's device helper stubbed)."""
+ import importlib.util
+
+ zoo = types.ModuleType("unsloth_zoo.device_type")
+ zoo.device_synchronize = lambda *a, **k: None
+ sys.modules.setdefault("unsloth_zoo", types.ModuleType("unsloth_zoo"))
+ sys.modules["unsloth_zoo.device_type"] = zoo
+ optimizers = types.ModuleType("unsloth.optimizers")
+ optimizers.__path__ = [os.path.join(REPO, "unsloth", "optimizers")]
+ sys.modules["unsloth.optimizers"] = optimizers
+ name = "unsloth.optimizers.q_galore_adamw"
+ spec = importlib.util.spec_from_file_location(
+ name, os.path.join(REPO, "unsloth", "optimizers", "q_galore_adamw.py")
+ )
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[name] = module
+ spec.loader.exec_module(module)
+ return module.QGaLoreAdamW8bit
+
+
+def test_q_galore_is_refused_not_localized():
+ bnb = pytest.importorskip("bitsandbytes")
+ native = _load_native()
+ from unsloth.models.fsdp2_bnb_optim import supports_local_shards
+
+ QGaLoreAdamW8bit = _q_galore_class()
+ opt = QGaLoreAdamW8bit([torch.nn.Parameter(torch.zeros(64, 64))], lr = 1e-3)
+ assert opt.optimizer_name == "adam" # what the old predicate keyed on
+ assert supports_local_shards(opt) is False and supports_local_shards(QGaLoreAdamW8bit) is False
+ assert native._localize_bnb_optimizer(opt) is False
+ with pytest.raises(ValueError, match = "Q-GaLore"):
+ native._refuse_bnb_optimizer_instance(opt)
+ with pytest.raises(ValueError, match = "cannot"):
+ native._refuse_bnb_optimizer_cls((QGaLoreAdamW8bit, {"lr": 1e-3}))
+ # bitsandbytes' own Adam classes still step local shards.
+ for cls in (
+ bnb.optim.AdamW8bit,
+ bnb.optim.Adam8bit,
+ bnb.optim.PagedAdamW8bit,
+ bnb.optim.PagedAdamW32bit,
+ ):
+ assert supports_local_shards(cls([torch.nn.Parameter(torch.zeros(4))])), cls
diff --git a/unsloth/models/fsdp2_bnb_optim.py b/unsloth/models/fsdp2_bnb_optim.py
new file mode 100644
index 00000000000..cea78485838
--- /dev/null
+++ b/unsloth/models/fsdp2_bnb_optim.py
@@ -0,0 +1,487 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""bitsandbytes 8-bit (and 32-bit) Adam / AdamW under native FSDP2, stepped on the local shards.
+
+bitsandbytes' kernels take plain tensors, and native FSDP2 parameters are DTensors. Each DTensor
+parameter's local shard is an ordinary tensor sharing the parameter's storage, and its gradient's local
+shard is the matching ordinary tensor, so bitsandbytes can step the shard in place. The optimizer
+keeps the DTensor parameters in its param_groups and its state keyed by them (the LR scheduler, the
+Trainer, gradient clipping, GradScaler and torch.distributed.checkpoint all see the same objects); only
+init_state / update_step hand bitsandbytes the local shards.
+
+The 8-bit state is quantized per 256-element block of each LOCAL shard, so it is not bitwise equal to
+one GPU, where the blocks run over the whole tensor. Which parameters get 8-bit state follows one GPU:
+bitsandbytes' `min_8bit_size` rule is applied to the full parameter size, not the shard size.
+
+state_dict() returns the state dequantized to float32, wrapped as DTensors laid out like each parameter,
+so the collective full-state save (get_optimizer_state_dict(full_state_dict = True)) gathers a
+world-size-independent checkpoint. load_state_dict() re-quantizes it: the inverse is exact when the
+blocks are unchanged (same world size), so a resume restores the same 8-bit state.
+"""
+
+import functools
+import os
+
+import torch
+
+__all__ = [
+ "bnb_local_shards_enabled",
+ "is_local_shard_bnb_optimizer",
+ "localize_bnb_optimizer",
+ "supports_local_shards",
+ "rename_optimizer_state_for",
+]
+
+_BLOCKSIZE = 256 # bitsandbytes Optimizer2State 8-bit blockwise state block size
+_FLAG = "_unsloth_fsdp2_local_shards"
+_STATE_KEYS = ("state1", "state2")
+# Per-parameter history vectors bitsandbytes keeps next to the moments: gnorm_vec (percentile_clipping
+# < 100: the last 100 squared gradient norms, of this rank's shard) and unorm_vec (max_unorm > 0).
+_AUX_KEYS = {"gnorm_vec": 100, "unorm_vec": 1}
+_TORCH_ADAM_KEYS = {"state1": "exp_avg", "state2": "exp_avg_sq"}
+
+
+def bnb_local_shards_enabled():
+ """UNSLOTH_FSDP2_BNB_LOCAL=0 restores the old behaviour (bitsandbytes Adam switched to torch's)."""
+ value = os.environ.get("UNSLOTH_FSDP2_BNB_LOCAL", "1").strip().lower()
+ return value not in ("0", "false", "no", "off")
+
+
+def _dtensor_class():
+ try:
+ from torch.distributed.tensor import DTensor
+ except ImportError:
+ return None
+ return DTensor
+
+
+def _bnb_base_classes():
+ try:
+ from bitsandbytes.optim.optimizer import Optimizer2State
+ except Exception:
+ return None
+ return Optimizer2State
+
+
+def supports_local_shards(optimizer_or_cls):
+ """bitsandbytes Adam / AdamW (8-bit blockwise, paged or not, or 32-bit): Optimizer2State with
+ optimizer_name 'adam' (AdEMAMix keeps two first moments in one state and is not covered). The class
+ check alone when given a class."""
+ base = _bnb_base_classes()
+ if base is None:
+ return False
+ cls = optimizer_or_cls if isinstance(optimizer_or_cls, type) else type(optimizer_or_cls)
+ if not issubclass(cls, base):
+ return False
+ if "ademamix" in cls.__name__.lower():
+ return False
+ if not _plain_bnb_class(cls, base):
+ return False
+ if isinstance(optimizer_or_cls, type):
+ return True
+ if getattr(optimizer_or_cls, "optimizer_name", None) != "adam":
+ return False
+ args = getattr(optimizer_or_cls, "args", None)
+ if args is not None and int(getattr(args, "optim_bits", 32)) == 8:
+ # 8-bit non-blockwise state (max1 / new_max1) is per tensor: not covered.
+ return bool(getattr(args, "block_wise", True))
+ return True
+
+
+def _plain_bnb_class(cls, base):
+ """Only bitsandbytes' own Adam / AdamW / PagedAdam(W) classes: every class above Optimizer2State
+ comes from bitsandbytes and none replaces step / init_state / update_step. A subclass elsewhere
+ (Unsloth's QGaLoreAdamW8bit: optimizer_name 'adam', its own step() projecting whole 2-D weights)
+ cannot be stepped shard by shard."""
+
+ def unwrapped(fn):
+ while hasattr(fn, "__wrapped__"):
+ fn = fn.__wrapped__
+ return fn
+
+ for klass in cls.__mro__:
+ if klass is base:
+ return True
+ module = str(getattr(klass, "__module__", "") or "")
+ if module != "bitsandbytes" and not module.startswith("bitsandbytes."):
+ return False
+ for name in ("step", "init_state", "update_step"):
+ # torch.optim.Optimizer.__init__ rewraps the class's inherited step for profiling
+ # (`step.hooked`), so compare the unwrapped function with the base's.
+ if name in vars(klass) and unwrapped(vars(klass)[name]) is not unwrapped(
+ getattr(base, name)
+ ):
+ return False
+ return False
+
+
[email protected]_cache(maxsize = None)
+def bnb_steps_cpu_tensors():
+ """Whether this bitsandbytes steps 8-bit blockwise and 32-bit Adam on CPU tensors (0.50 does; older
+ releases require GPU inputs). Probed once with one step on a tiny CPU parameter of each."""
+ try:
+ import bitsandbytes as bnb
+ for kwargs in ({"optim_bits": 8, "min_8bit_size": 0}, {"optim_bits": 32}):
+ p = torch.nn.Parameter(torch.zeros(256))
+ p.grad = torch.ones(256)
+ bnb.optim.AdamW([p], lr = 1e-3, **kwargs).step()
+ if not torch.isfinite(p).all():
+ return False
+ except Exception:
+ return False
+ return True
+
+
+def is_local_shard_bnb_optimizer(optimizer):
+ return getattr(type(optimizer), _FLAG, False) is True
+
+
+def _local(p, DTensor):
+ """The plain local tensor of a DTensor parameter (shares its storage), else None."""
+ if DTensor is not None and isinstance(p, DTensor):
+ return p._local_tensor
+ return None
+
+
+def _local_grad(grad, DTensor):
+ if DTensor is not None and isinstance(grad, DTensor):
+ return grad._local_tensor
+ return grad
+
+
+# Blocks per pass when (de)quantizing a checkpointed state: 16384 blocks = 4M elements, so the
+# temporaries (a float table and int64 indices per candidate scale) stay a few hundred MB however large
+# the shard is. Every block is independent, so the result does not depend on the chunking.
+_CHUNK_BLOCKS = 16384
+
+
+def _dequantize(
+ raw,
+ key,
+ device,
+ chunk_blocks = None,
+):
+ """float32 copy of state `key` on `device`, built chunk by chunk into the one output tensor. Paged
+ state reports the CPU device (unified memory)."""
+ value = raw[key]
+ if value.dtype != torch.uint8:
+ return value.to(device = device, dtype = torch.float32)
+ index = key[-1]
+ code = raw[f"qmap{index}"].to(device = device, dtype = torch.float32)
+ absmax = raw[f"absmax{index}"]
+ flat_codes = value.reshape(-1)
+ n = flat_codes.numel()
+ out = torch.empty(n, dtype = torch.float32, device = device)
+ step = (chunk_blocks or _CHUNK_BLOCKS) * _BLOCKSIZE
+ for start in range(0, n, step):
+ end = min(start + step, n)
+ codes = flat_codes[start:end].to(device).long()
+ scale = absmax[start // _BLOCKSIZE : (end + _BLOCKSIZE - 1) // _BLOCKSIZE]
+ scale = scale.to(device = device, dtype = torch.float32).repeat_interleave(_BLOCKSIZE)
+ torch.mul(code[codes], scale[: end - start], out = out[start:end])
+ return out.reshape(value.shape)
+
+
+def _nearest_codes(padded, sorted_code, scale):
+ """Per block: index into sorted_code of the nearest code * scale for each element, and the block's
+ total absolute reconstruction error."""
+ table = sorted_code.unsqueeze(0) * scale.unsqueeze(1) # (blocks, 256), ascending per row
+ hi = torch.searchsorted(table, padded.contiguous()).clamp_(max = table.shape[1] - 1)
+ lo = (hi - 1).clamp_(min = 0)
+ err_lo = (padded - table.gather(1, lo)).abs()
+ err_hi = (table.gather(1, hi) - padded).abs()
+ pick_lo = err_lo < err_hi
+ return torch.where(pick_lo, lo, hi), torch.where(pick_lo, err_lo, err_hi).sum(dim = 1)
+
+
+def _quantize_into(
+ values,
+ code,
+ out_codes,
+ out_absmax,
+ chunk_blocks = None,
+):
+ """bitsandbytes' blockwise quantization of `values` (float32) into `out_codes` (uint8, same shape)
+ and `out_absmax` (one float32 per 256 elements), inverting a dequantization exactly. bitsandbytes
+ scales a block by its largest magnitude A, and the signed map has no -1.0: when that element is
+ negative it is stored as min_code * A. The scale is therefore the largest positive value, or the
+ largest |negative| / |min code| (with its float32 neighbours, since that division can round), and
+ each element maps to the nearest code * scale; per block the candidate with the smallest
+ reconstruction error wins (zero for the original scale). Runs `chunk_blocks` blocks at a time."""
+ device = out_codes.device
+ code = code.to(device = device, dtype = torch.float32)
+ flat = values.reshape(-1)
+ n = flat.numel()
+ if n == 0:
+ return
+ sorted_code, order = torch.sort(code)
+ min_code = float(sorted_code[0].item())
+ codes_out = out_codes.view(-1)
+ step = (chunk_blocks or _CHUNK_BLOCKS) * _BLOCKSIZE
+ for start in range(0, n, step):
+ end = min(start + step, n)
+ chunk = flat[start:end].to(device = device, dtype = torch.float32)
+ blocks = (end - start + _BLOCKSIZE - 1) // _BLOCKSIZE
+ if chunk.numel() != blocks * _BLOCKSIZE: # the ragged tail block, zero padded
+ chunk = torch.nn.functional.pad(chunk, (0, blocks * _BLOCKSIZE - chunk.numel()))
+ index, scale = _quantize_blocks(chunk.view(blocks, _BLOCKSIZE), sorted_code, min_code)
+ codes_out[start:end].copy_(order[index].reshape(-1)[: end - start].to(torch.uint8))
+ out_absmax[start // _BLOCKSIZE : start // _BLOCKSIZE + blocks].copy_(
+ scale.to(out_absmax.dtype)
+ )
+
+
+def _quantize_blocks(padded, sorted_code, min_code):
+ """(blocks, 256) float32 -> (index into sorted_code per element, scale per block)."""
+ positive = padded.clamp(min = 0).amax(dim = 1)
+ candidates = [positive]
+ negative = None
+ if min_code < 0:
+ negative = (-padded).clamp(min = 0).amax(dim = 1)
+ guess = negative / (-min_code)
+ candidates += [
+ guess,
+ torch.nextafter(guess, torch.full_like(guess, float("inf"))),
+ torch.nextafter(guess, torch.zeros_like(guess)),
+ ]
+ best_scale = best_index = best_err = None
+ for scale in candidates:
+ index, err = _nearest_codes(padded, sorted_code, scale)
+ valid = scale >= positive
+ if negative is not None:
+ valid = valid & (scale * (-min_code) >= negative)
+ err = torch.where(valid, err, torch.full_like(err, float("inf")))
+ if best_err is None:
+ best_scale, best_index, best_err = scale, index, err
+ continue
+ better = err < best_err
+ best_scale = torch.where(better, scale, best_scale)
+ best_index = torch.where(better.unsqueeze(1), index, best_index)
+ best_err = torch.where(better, err, best_err)
+ return best_index, best_scale
+
+
+class _LocalShardMixin:
+ """Overrides for a bitsandbytes Optimizer2State whose parameters may be DTensors."""
+
+ _unsloth_fsdp2_local_shards = True
+
+ def get_config(self, gindex, pindex, group):
+ config = super().get_config(gindex, pindex, group)
+ local = _local(group["params"][pindex], _dtensor_class())
+ if local is not None:
+ full = group["params"][pindex].numel()
+ # One GPU picks 8-bit state for numel >= min_8bit_size: decide on the full size.
+ config["min_8bit_size"] = 0 if full >= config["min_8bit_size"] else local.numel() + 1
+ return config
+
+ def _shard_call(self, method, group, p, gindex, pindex, with_grad):
+ DTensor = _dtensor_class()
+ local = _local(p, DTensor)
+ if local is None:
+ return getattr(super(), method)(group, p, gindex, pindex)
+ state = self.state.pop(p, {})
+ if local.numel() == 0:
+ state.setdefault("step", 0)
+ if method == "update_step":
+ state["step"] += 1
+ self.state[p] = state
+ return None
+ work = local if local.is_contiguous() else local.contiguous()
+ alias = work.detach()
+ if with_grad:
+ alias.grad = _local_grad(p.grad, DTensor).detach()
+ self.state[alias] = state
+ try:
+ return getattr(super(), method)(group, alias, gindex, pindex)
+ finally:
+ self.state[p] = self.state.pop(alias)
+ alias.grad = None
+ if work is not local:
+ local.copy_(work)
+
+ def init_state(self, group, p, gindex, pindex):
+ return self._shard_call("init_state", group, p, gindex, pindex, with_grad = False)
+
+ @torch.no_grad()
+ def update_step(self, group, p, gindex, pindex):
+ return self._shard_call("update_step", group, p, gindex, pindex, with_grad = True)
+
+ def prefetch_state(self, p):
+ if "state1" not in self.state.get(p, {}):
+ return None
+ return super().prefetch_state(p)
+
+ def _aux_keys(self, group, gindex, pindex):
+ """The history vectors bitsandbytes allocates for this parameter (the same on every rank)."""
+ config = self.get_config(gindex, pindex, group)
+ keys = []
+ if config.get("percentile_clipping", 100) < 100:
+ keys.append("gnorm_vec")
+ if config.get("max_unorm", 0.0) > 0.0:
+ keys.append("unorm_vec")
+ return keys
+
+ def _export_aux(self, p, raw, keys, out):
+ """Each rank's history vectors for a DTensor parameter, as one Shard(0) DTensor of shape
+ (world * n,) over the parameter's mesh, so the full checkpoint holds every rank's vector and a
+ same-world-size resume gets its own back; a replicated parameter's vector is plain."""
+ DTensor = _dtensor_class()
+ local = _local(p, DTensor)
+ for key in keys:
+ n = _AUX_KEYS[key]
+ device = (local if local is not None else p).device
+ value = raw.get(key)
+ if value is None: # an empty shard never ran init_state
+ value = torch.zeros((n,), dtype = torch.float32, device = device)
+ value = value.detach().to(device = device, dtype = torch.float32).reshape(n).clone()
+ if local is not None:
+ mesh = p.device_mesh
+ if mesh.ndim != 1:
+ continue # not produced by native FSDP2 (1-D mesh); resumes from zeros
+ from torch.distributed.tensor import Shard
+
+ value = DTensor.from_local(
+ value, mesh, [Shard(0)], run_check = False, shape = (mesh.size() * n,), stride = (1,)
+ )
+ out[key] = value
+
+ def _export_state(
+ self,
+ p,
+ raw,
+ slot = None,
+ ):
+ DTensor = _dtensor_class()
+ local = _local(p, DTensor)
+ out = {"step": int(raw.get("step", 0))}
+ if slot is not None:
+ group, gindex, pindex = slot
+ self._export_aux(p, raw, self._aux_keys(group, gindex, pindex), out)
+ for key in _STATE_KEYS:
+ if key in raw:
+ value = _dequantize(raw, key, (local if local is not None else p).device)
+ elif local is not None and local.numel() == 0:
+ value = torch.zeros(local.shape, dtype = torch.float32, device = local.device)
+ else:
+ continue
+ if local is not None:
+ value = DTensor.from_local(
+ value,
+ p.device_mesh,
+ p.placements,
+ run_check = False,
+ shape = p.shape,
+ stride = p.stride(),
+ )
+ out[key] = value
+ return out
+
+ def state_dict(self):
+ """float32 state1 / state2 (DTensors for DTensor parameters) and an int step per parameter."""
+ state_dict = torch.optim.Optimizer.state_dict(self)
+ slots = [
+ (p, (group, gindex, pindex))
+ 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()
+ }
+ return state_dict
+
+ def _import_state(self, group, p, gindex, pindex, saved):
+ DTensor = _dtensor_class()
+ self.state[p] = {}
+ self.init_state(group, p, gindex, pindex)
+ raw = self.state[p]
+ step = saved.get("step", 0)
+ raw["step"] = int(step.item() if torch.is_tensor(step) else step)
+ for key in _STATE_KEYS:
+ value = saved.get(key, saved.get(_TORCH_ADAM_KEYS[key]))
+ if value is None or key not in raw:
+ continue
+ value = _local_grad(value, DTensor)
+ target = raw[key]
+ if value.shape != target.shape:
+ raise ValueError(
+ f"Unsloth: optimizer state '{key}' has shape {tuple(value.shape)}, but this rank's "
+ f"shard of the parameter has shape {tuple(target.shape)}."
+ )
+ if target.dtype == torch.uint8:
+ index = key[-1]
+ _quantize_into(value, raw[f"qmap{index}"], target, raw[f"absmax{index}"])
+ else:
+ target.copy_(value.to(device = target.device, dtype = target.dtype))
+ for key in _AUX_KEYS:
+ value = saved.get(key)
+ if value is None or key not in raw:
+ continue
+ value = _local_grad(value, DTensor)
+ if value.numel() == raw[key].numel(): # another world size: the vector starts fresh
+ raw[key].copy_(value.reshape(raw[key].shape).to(raw[key].device, raw[key].dtype))
+
+ def load_state_dict(self, state_dict, *args, **kwargs):
+ """Inverse of state_dict(); also reads exp_avg / exp_avg_sq (a torch Adam checkpoint)."""
+ saved_groups = state_dict["param_groups"]
+ torch.optim.Optimizer.load_state_dict(self, {"state": {}, "param_groups": saved_groups})
+ slots = [
+ (group, p, gindex, pindex)
+ for gindex, group in enumerate(self.param_groups)
+ for pindex, p in enumerate(group["params"])
+ ]
+ flat_saved = [saved_id for g in saved_groups for saved_id in g["params"]]
+ slot_of = dict(zip(flat_saved, slots))
+ with torch.no_grad():
+ for saved_id, saved in state_dict["state"].items():
+ if saved_id in slot_of:
+ self._import_state(*slot_of[saved_id], saved)
+
+
[email protected]_cache(maxsize = None)
+def _local_shard_class(cls):
+ return type(cls.__name__, (_LocalShardMixin, cls), {"__module__": cls.__module__})
+
+
+def localize_bnb_optimizer(optimizer):
+ """Make a bitsandbytes Adam / AdamW step DTensor parameters on their local shards (class swap,
+ in place). Returns True when converted (or already converted)."""
+ if is_local_shard_bnb_optimizer(optimizer):
+ return True
+ if not supports_local_shards(optimizer):
+ return False
+ if any(len(s) for s in optimizer.state.values()):
+ raise RuntimeError(
+ "Unsloth: native FSDP2 got a bitsandbytes optimizer that already holds state for DTensor "
+ "parameters; build it after `shard_model(model)` and before training."
+ )
+ optimizer.__class__ = _local_shard_class(type(optimizer))
+ return True
+
+
+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."""
+ states = full_state.get("state") if isinstance(full_state, dict) else None
+ if not isinstance(states, dict):
+ return full_state
+ to_bnb = is_local_shard_bnb_optimizer(optimizer)
+ to_torch = isinstance(optimizer, (torch.optim.Adam, torch.optim.AdamW))
+ if not (to_bnb or to_torch):
+ return full_state
+ for entry in states.values():
+ if not isinstance(entry, dict):
+ continue
+ for bnb_key, torch_key in _TORCH_ADAM_KEYS.items():
+ if to_bnb and torch_key in entry and bnb_key not in entry:
+ entry[bnb_key] = entry.pop(torch_key).float()
+ elif to_torch and bnb_key in entry and torch_key not in entry:
+ entry[torch_key] = entry.pop(bnb_key)
+ step = entry.get("step")
+ if to_bnb and torch.is_tensor(step):
+ entry["step"] = int(step.item())
+ elif to_torch and step is not None and not torch.is_tensor(step):
+ entry["step"] = torch.tensor(float(step))
+ return full_state
diff --git a/unsloth/models/fsdp2_native.py b/unsloth/models/fsdp2_native.py
index b2055663bec..9f65570c38b 100644
--- a/unsloth/models/fsdp2_native.py
+++ b/unsloth/models/fsdp2_native.py
@@ -2037,6 +2037,10 @@ def native_load_optimizer(model, optimizer, path_or_state):
state = path_or_state
if not isinstance(state, dict):
state = torch.load(state, map_location = "cpu", weights_only = True)
+ from .fsdp2_bnb_optim import rename_optimizer_state_for
+
+ # A checkpoint from torch's AdamW resumed into a local-shard bitsandbytes Adam, or back.
+ rename_optimizer_state_for(_inner_optimizer(optimizer), state)
set_optimizer_state_dict(
_native_root(model),
_inner_optimizer(optimizer),
@@ -2354,6 +2358,9 @@ def _install_trainer_hooks():
if is_native_fsdp2(getattr(self, "model", None)):
# Before the LR scheduler records one base LR per group.
_split_mixed_param_groups(getattr(optimizer, "optimizer", optimizer))
+ # Localized, or refused here (a bitsandbytes optimizer that cannot step local shards
+ # would otherwise fail inside the first step).
+ _refuse_bnb_optimizer_instance(optimizer)
return optimizer
original_create_scheduler = Trainer.create_scheduler
@@ -2371,6 +2378,8 @@ def _install_trainer_hooks():
# above, and transformers 4.x builds the scheduler before Accelerator.prepare splits the
# groups. Split here, before the scheduler records one base LR (and lambda) per group.
target = optimizer if optimizer is not None else getattr(self, "optimizer", None)
+ if is_native_fsdp2(getattr(self, "model", None)):
+ _refuse_bnb_optimizer_instance(target) # a subclass create_optimizer's bitsandbytes one
if (
target is not None
and getattr(self, "lr_scheduler", None) is None
@@ -2537,7 +2546,10 @@ def _native_optimizer(optimizer):
# bitsandbytes optimizers (transformers' OptimizerNames) step plain tensors through custom ops with no
-# DTensor sharding strategy. Those with a torch equivalent are switched to it; the others are refused.
+# DTensor sharding strategy. Adam / AdamW step each DTensor's local shard (fsdp2_bnb_optim), keeping
+# their 8-bit state as on one GPU; the others with a torch equivalent are switched to it (as are Adam /
+# AdamW with UNSLOTH_FSDP2_BNB_LOCAL=0); the rest are refused.
+_BNB_LOCAL_SHARD_OPTIMS = ("adamw_8bit", "adamw_bnb_8bit", "paged_adamw_8bit", "paged_adamw_32bit")
_BNB_OPTIMS = {
"adamw_8bit": "adamw_torch_fused",
"adamw_bnb_8bit": "adamw_torch_fused",
@@ -2559,8 +2571,10 @@ _BNB_UNSUPPORTED = (
)
-def _swap_bnb_optimizer(training_args):
- """bitsandbytes' optimizers step plain CUDA tensors; native FSDP2 parameters are DTensors."""
+def _swap_bnb_optimizer(training_args, cpu_shards = False):
+ """bitsandbytes' optimizers step plain CUDA tensors; native FSDP2 parameters are DTensors. Adam /
+ AdamW step the local shards instead, unless the shards sit on the CPU (CPU offload, a CPU mesh)
+ and this bitsandbytes cannot step CPU tensors: then the switch to torch's AdamW stays."""
optim = getattr(training_args, "optim", None)
if optim is None:
return False
@@ -2575,6 +2589,13 @@ def _swap_bnb_optimizer(training_args):
target = _BNB_OPTIMS.get(name)
if target is None:
return False
+ if name in _BNB_LOCAL_SHARD_OPTIMS and _bnb_local_shards_available(cpu_shards):
+ _print_rank0(
+ f"Unsloth: native FSDP2 keeps optim = '{name}': bitsandbytes steps each rank's local shard "
+ "of the DTensor parameters (8-bit state per shard; UNSLOTH_FSDP2_BNB_LOCAL=0 switches to "
+ "torch's AdamW)."
+ )
+ return False
if target == "adamw_torch_fused" and not torch.cuda.is_available():
target = "adamw_torch"
_print_rank0(
@@ -2589,6 +2610,66 @@ def _swap_bnb_optimizer(training_args):
return True
+def _bnb_local_shards_available(cpu_shards = False):
+ from .fsdp2_bnb_optim import (
+ bnb_local_shards_enabled,
+ bnb_steps_cpu_tensors,
+ supports_local_shards,
+ )
+
+ if not bnb_local_shards_enabled():
+ return False
+ if cpu_shards and not bnb_steps_cpu_tensors():
+ return False
+ try:
+ from bitsandbytes.optim import AdamW8bit
+ except Exception:
+ return False
+ return supports_local_shards(AdamW8bit)
+
+
+def _optimizer_on_cpu(optimizer):
+ """Whether any parameter's local shard (or the parameter itself) is a CPU tensor."""
+ for group in getattr(optimizer, "param_groups", None) or []:
+ for p in group["params"]:
+ local = getattr(p, "_local_tensor", p)
+ if getattr(local, "device", None) is not None and local.device.type == "cpu":
+ return True
+ return False
+
+
+def _native_shards_on_cpu(model, training_args):
+ """Where native FSDP2 keeps (or will keep) the trainable shards: on the CPU with
+ UNSLOTH_FSDP2_CPU_OFFLOAD, a CPU Trainer (use_cpu) or no CUDA device."""
+ if model is not None and is_native_fsdp2(model):
+ return any(
+ getattr(p, "_local_tensor", p).device.type == "cpu"
+ for p in model.parameters()
+ if p.requires_grad
+ )
+ if _trainer_uses_cpu(training_args) or not torch.cuda.is_available():
+ return True
+ try:
+ return bool(FSDP2Config.from_env().cpu_offload)
+ except Exception:
+ return False
+
+
+def _localize_bnb_optimizer(optimizer):
+ """A bitsandbytes Adam / AdamW (built by the Trainer from args.optim, or passed in) steps the local
+ shards of its DTensor parameters (fsdp2_bnb_optim). True when it now does."""
+ if optimizer is None:
+ return False
+ inner = _inner_optimizer(optimizer)
+ if not _is_bnb_optimizer_class(type(inner)):
+ return False
+ if not _bnb_local_shards_available(_optimizer_on_cpu(inner)):
+ return False
+ from .fsdp2_bnb_optim import localize_bnb_optimizer
+
+ return localize_bnb_optimizer(inner)
+
+
# Trainer.__init__'s positional order (the same in transformers 4.57 and 5.x), for an __init__ whose
# signature cannot be read (a wrapper without functools.wraps).
_TRAINER_INIT_ORDER = (
@@ -2699,18 +2780,34 @@ def _refuse_bnb_optimizer_instance(optimizer):
"""A prebuilt optimizer passed as Trainer(optimizers = (opt, ...)) or to accelerator.prepare:
_swap_bnb_optimizer only edits args.optim, so a bitsandbytes instance would be kept and step
DTensor shards it cannot handle. Torch optimizers pass."""
- if optimizer is None:
+ if optimizer is None or _localize_bnb_optimizer(optimizer):
return
inner = _inner_optimizer(optimizer)
+ if "galore" in type(inner).__name__.lower():
+ raise ValueError(_Q_GALORE_REFUSAL)
if _is_bnb_optimizer_class(type(inner)):
raise ValueError(
f"Unsloth: native FSDP2 shards parameters as DTensors, which bitsandbytes' optimizers cannot "
- f"step (got a {type(inner).__name__}). Build a torch optimizer (torch.optim.AdamW over "
+ f"step (got a {type(inner).__name__}; only bitsandbytes Adam / AdamW step local shards). "
+ "Build a torch optimizer (torch.optim.AdamW over "
"`unsloth.models.fsdp2_native.split_param_groups(...)`), or let the Trainer build it with "
- "optim = 'adamw_8bit', which native FSDP2 switches to torch's AdamW."
+ "optim = 'adamw_8bit'."
)
+def _bnb_probe_supports_local_shards(cls, kwargs):
+ """The localization predicate on the optimizer the Trainer would build: the class alone cannot tell
+ (the optimizer name and block_wise / optim_bits come from __init__ and its kwargs), so build it over
+ one CPU placeholder parameter (bitsandbytes allocates state lazily) and ask the instance."""
+ from .fsdp2_bnb_optim import supports_local_shards
+
+ try:
+ probe = cls([nn.Parameter(torch.zeros(1))], **dict(kwargs))
+ except Exception:
+ return False
+ return supports_local_shards(probe)
+
+
def _refuse_bnb_optimizer_cls(optimizer_cls_and_kwargs):
"""Trainer(optimizer_cls_and_kwargs = (cls, kwargs)) overrides args.optim, so the bitsandbytes
switch in _swap_bnb_optimizer never sees it; bitsandbytes' optimizers step plain CUDA tensors, not
@@ -2718,12 +2815,16 @@ def _refuse_bnb_optimizer_cls(optimizer_cls_and_kwargs):
if not isinstance(optimizer_cls_and_kwargs, (tuple, list)) or not optimizer_cls_and_kwargs:
return
cls = optimizer_cls_and_kwargs[0]
+ kwargs = optimizer_cls_and_kwargs[1] if len(optimizer_cls_and_kwargs) > 1 else None
+ if _is_bnb_optimizer_class(cls) and _bnb_local_shards_available():
+ if _bnb_probe_supports_local_shards(cls, kwargs or {}):
+ return # Trainer.create_optimizer builds it; the native hook makes it step local shards
if _is_bnb_optimizer_class(cls):
raise ValueError(
f"Unsloth: native FSDP2 shards parameters as DTensors, which bitsandbytes' optimizers cannot "
f"step (optimizer_cls_and_kwargs = ({getattr(cls, '__name__', cls)}, ...)). Pass a torch "
- "optimizer class (torch.optim.AdamW), or drop optimizer_cls_and_kwargs and set optim = "
- "'adamw_8bit' / 'paged_adamw_8bit', which native FSDP2 switches to torch's AdamW."
+ "optimizer class (torch.optim.AdamW) or a bitsandbytes Adam / AdamW, or drop "
+ "optimizer_cls_and_kwargs and set optim = 'adamw_8bit' / 'paged_adamw_8bit'."
)
@@ -2812,16 +2913,19 @@ def _refuse_clef(model):
)
+_Q_GALORE_REFUSAL = (
+ "Unsloth: native FSDP2 (UNSLOTH_FSDP2=1) cannot train with q_galore_config: Q-GaLore's "
+ "8-bit optimizer projects whole 2-D weights, and native FSDP2 hands it DTensor shards. Set "
+ "q_galore_config = None, or launch without UNSLOTH_FSDP2."
+)
+
+
def _refuse_q_galore(training_args):
"""UnslothTrainer builds QGaLoreAdamW8bit in its own create_optimizer when q_galore_config is set,
bypassing args.optim (so _swap_bnb_optimizer never sees it). Its 8-bit states and 2-D projections
expect plain tensors, not DTensor shards."""
if getattr(training_args, "q_galore_config", None) is not None:
- raise ValueError(
- "Unsloth: native FSDP2 (UNSLOTH_FSDP2=1) cannot train with q_galore_config: Q-GaLore's "
- "8-bit optimizer projects whole 2-D weights, and native FSDP2 hands it DTensor shards. Set "
- "q_galore_config = None, or launch without UNSLOTH_FSDP2."
- )
+ raise ValueError(_Q_GALORE_REFUSAL)
def _refuse_projection_optim(training_args):
@@ -2940,7 +3044,7 @@ def native_fsdp2_trainer_setup(
raise RuntimeError(_MIXED_GROUPS_REFUSAL)
if is_native_fsdp2(model):
_swap_bnb_optimizer(
- training_args
+ training_args, _native_shards_on_cpu(model, training_args)
) # the Trainer still builds the optimizer from args.optim
if model is None or not isinstance(model, nn.Module) or is_native_fsdp2(model):
return model
@@ -2951,7 +3055,7 @@ def native_fsdp2_trainer_setup(
"`unsloth.models.fsdp2_native.shard_model(model)` before building the optimizer, or "
"let the Trainer build it (optimizers = (None, None))."
)
- _swap_bnb_optimizer(training_args)
+ _swap_bnb_optimizer(training_args, _native_shards_on_cpu(model, training_args))
config = FSDP2Config.from_env()
if _trainer_uses_cpu(training_args):
config.device = "cpu" # the Trainer will run on the CPU: no GPU mesh