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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
FSDP2: restore the checkpoint's 4-bit QuantState on a full DCP load (#14747)
Daniel Hanc06680485675
diff --git a/tests/test_fsdp2_save_gloo.py b/tests/test_fsdp2_save_gloo.pyindex bacd9a93f97..af93a6fe891 100644--- a/tests/test_fsdp2_save_gloo.py+++ b/tests/test_fsdp2_save_gloo.py@@ -610,6 +610,193 @@ def _case_dcp_bnb(rank, world_size, m):return out+def _case_dcp_restore(rank, world_size, m):+ """A full DCP checkpoint loaded into a 4-bit model whose QuantState differs from the one it was+ saved from: the packed bytes come from the checkpoint, so their scales must too."""+ bnb = pytest.importorskip("bitsandbytes")+ q = _load("fsdp2_qlora")+ from torch.distributed.checkpoint.state_dict import StateDictOptions+ from torch.distributed.device_mesh import init_device_mesh+ from torch.distributed.fsdp import fully_shard+ import torch.distributed.checkpoint.state_dict as dcp++ def model(+ scale,+ nested,+ blocksize = 64,+ ):+ torch.manual_seed(0)+ layer = bnb.nn.Linear4bit(+ 128,+ 64,+ bias = False,+ compute_dtype = torch.bfloat16,+ quant_type = "nf4",+ quant_storage = torch.bfloat16,+ )+ layer.weight = bnb.nn.Params4bit(+ torch.randn(64, 128) * scale,+ requires_grad = False,+ quant_type = "nf4",+ quant_storage = torch.bfloat16,+ blocksize = blocksize,+ compress_statistics = nested,+ module = layer,+ )+ net = torch.nn.Sequential(layer.to("cpu"), torch.nn.Linear(64, 8))+ reference = bnb.functional.dequantize_4bit(net[0].weight.data, net[0].weight.quant_state)+ q.prepare_fsdp2_qlora(net)+ fully_shard(net, mesh = init_device_mesh("cpu", (world_size,)))+ return net, reference++ def scales(quant_state):+ tensors = [quant_state.absmax, quant_state.code]+ if quant_state.state2 is not None:+ tensors += [quant_state.state2.absmax, quant_state.state2.code, quant_state.offset]+ return [t.detach().cpu().clone() for t in tensors]++ def restored(net, reference):+ out = {}+ with m.fsdp2_gathered(net) as writer:+ if writer:+ weight = net[0].weight+ actual = bnb.functional.dequantize_4bit(weight.data, weight.quant_state)+ out["dequant_equal"] = torch.equal(actual, reference)+ return out++ m.install_dcp_bnb_state_dict()+ out = {}+ full = StateDictOptions(full_state_dict = True, cpu_offload = True)+ for nested in (False, True):+ src, reference = model(0.1, nested)+ expected = scales(src[0].weight.quant_state)+ sd = dcp.get_model_state_dict(src, options = full)+ dst, _ = model(0.05, nested)+ dcp.set_model_state_dict(+ dst,+ sd if rank == 0 else {},+ options = StateDictOptions(full_state_dict = True, broadcast_from_rank0 = True),+ )+ live = scales(dst[0].weight.quant_state)+ out[f"broadcast_{nested}"] = dict(+ restored(dst, reference),+ scales = all(torch.equal(a, b) for a, b in zip(live, expected)),+ )+ sharded = dcp.get_model_state_dict(src)+ dst, _ = model(0.05, nested)+ dcp.set_model_state_dict(dst, sharded)+ live = scales(dst[0].weight.quant_state)+ out[f"sharded_{nested}"] = dict(+ restored(dst, reference),+ scales = all(torch.equal(a, b) for a, b in zip(live, expected)),+ )+ src, _ = model(0.1, False, blocksize = 128)+ sd = dcp.get_model_state_dict(src, options = full)+ dst, _ = model(0.05, False)+ try:+ dcp.set_model_state_dict(+ dst,+ sd if rank == 0 else {},+ options = StateDictOptions(full_state_dict = True, broadcast_from_rank0 = True, strict = False),+ )+ out["mismatch"] = "loaded"+ except ValueError as error:+ out["mismatch"] = "ValueError" if "4-bit quantization state" in str(error) else str(error)+ except Exception as error:+ out["mismatch"] = f"{type(error).__name__}: {error}"+ return out+++def _case_dcp_restore_guard(rank, world_size, m):+ """Checkpoint quantization metadata that cannot be applied: entries without their packed weight+ (a partial state dict under strict=False) and a nested checkpoint loaded into a non-nested model."""+ bnb = pytest.importorskip("bitsandbytes")+ q = _load("fsdp2_qlora")+ from torch.distributed.checkpoint.state_dict import StateDictOptions+ from torch.distributed.device_mesh import init_device_mesh+ from torch.distributed.fsdp import fully_shard+ import torch.distributed.checkpoint.state_dict as dcp++ def model(scale, nested):+ torch.manual_seed(0)+ layer = bnb.nn.Linear4bit(+ 128,+ 64,+ bias = False,+ compute_dtype = torch.bfloat16,+ quant_type = "nf4",+ quant_storage = torch.bfloat16,+ )+ layer.weight = bnb.nn.Params4bit(+ torch.randn(64, 128) * scale,+ requires_grad = False,+ quant_type = "nf4",+ quant_storage = torch.bfloat16,+ blocksize = 64,+ compress_statistics = nested,+ module = layer,+ )+ net = torch.nn.Sequential(layer.to("cpu"), torch.nn.Linear(64, 8))+ reference = bnb.functional.dequantize_4bit(net[0].weight.data, net[0].weight.quant_state)+ q.prepare_fsdp2_qlora(net)+ fully_shard(net, mesh = init_device_mesh("cpu", (world_size,)))+ return net, reference++ def scales(quant_state):+ tensors = [quant_state.absmax, quant_state.code]+ if quant_state.state2 is not None:+ tensors += [quant_state.state2.absmax, quant_state.state2.code, quant_state.offset]+ return [t.detach().cpu().clone() for t in tensors]++ def dequant_equal(net, reference):+ out = None+ with m.fsdp2_gathered(net) as writer:+ if writer:+ weight = net[0].weight+ actual = bnb.functional.dequantize_4bit(weight.data, weight.quant_state)+ out = torch.equal(actual, reference)+ return out++ m.install_dcp_bnb_state_dict()+ out = {}+ full = StateDictOptions(full_state_dict = True, cpu_offload = True)+ loose = StateDictOptions(full_state_dict = True, broadcast_from_rank0 = True, strict = False)+ src, _ = model(0.1, False)+ for mode in ("broadcast", "sharded"):+ if mode == "broadcast":+ sd = dcp.get_model_state_dict(src, options = full)+ else:+ sd = dcp.get_model_state_dict(src)+ sd = {k: v for k, v in sd.items() if k != "0.weight"}+ dst, reference = model(0.05, False)+ expected = scales(dst[0].weight.quant_state)+ if mode == "broadcast":+ dcp.set_model_state_dict(dst, sd if rank == 0 else {}, options = loose)+ else:+ dcp.set_model_state_dict(dst, sd, options = StateDictOptions(strict = False))+ live = scales(dst[0].weight.quant_state)+ out[f"partial_{mode}"] = dict(+ scales = all(torch.equal(a, b) for a, b in zip(live, expected)),+ dequant_equal = dequant_equal(dst, reference),+ )+ src, _ = model(0.1, True)+ for mode in ("broadcast", "sharded"):+ dst, _ = model(0.05, False)+ try:+ if mode == "broadcast":+ sd = dcp.get_model_state_dict(src, options = full)+ dcp.set_model_state_dict(dst, sd if rank == 0 else {}, options = loose)+ else:+ sd = dcp.get_model_state_dict(src)+ dcp.set_model_state_dict(dst, sd, options = StateDictOptions(strict = False))+ out[f"nested_{mode}"] = "loaded"+ except ValueError as error:+ out[f"nested_{mode}"] = str(error)+ except Exception as error:+ out[f"nested_{mode}"] = f"{type(error).__name__}: {error}"+ return out++def _nf4_model(nested = False, device = "cpu"):bnb = pytest.importorskip("bitsandbytes")@@ -925,7 +1112,9 @@ def _worker(rank, world_size, port, case, queue):import datetime- timeout = datetime.timedelta(seconds = 4) if case == "slow_writer" else None+ # dcp_restore_guard: a rank left waiting on a collective fails in 60 s instead of hanging.+ timeout = {"slow_writer": 4, "dcp_restore_guard": 60}.get(case)+ timeout = datetime.timedelta(seconds = timeout) if timeout else Nonedist.init_process_group("nccl" if nccl else "gloo",rank = rank,@@ -943,6 +1132,10 @@ def _worker(rank, world_size, port, case, queue):result = _case_merge_offload(rank, world_size, m)elif case == "gather_4bit":result = _case_gather_4bit(rank, world_size, m)+ elif case == "dcp_restore":+ result = _case_dcp_restore(rank, world_size, m)+ elif case == "dcp_restore_guard":+ result = _case_dcp_restore_guard(rank, world_size, m)elif case == "merged_4bit_streamed":result = _case_merged_4bit_streamed(rank, world_size, m)elif case == "gather_4bit_offload":@@ -991,11 +1184,15 @@ def _run(else:os.environ["CUDA_VISIBLE_DEVICES"] = savedresults = {}- for _ in procs:- rank, result = queue.get(timeout = 240)- results[rank] = result- for p in procs:- p.join(timeout = 60)+ try:+ for _ in procs:+ rank, result = queue.get(timeout = 240)+ results[rank] = result+ finally:+ for p in procs:+ p.join(timeout = 60)+ if p.is_alive():+ p.terminate()for r in results.values():assert "error" not in r, r.get("error")return results@@ -1071,6 +1268,35 @@ def test_dcp_state_dict_of_bitsandbytes_4bit():]+def test_full_dcp_load_restores_the_checkpoint_quant_state():+ """Full and sharded DCP loads take the checkpoint's QuantState with its packed bytes."""+ pytest.importorskip("bitsandbytes")+ results = _run("dcp_restore")+ for rank, r in results.items():+ for nested in (False, True):+ for mode in ("broadcast", "sharded"):+ got = r[f"{mode}_{nested}"]+ assert got["scales"], (rank, mode, nested, r)+ if rank == 0:+ assert got["dequant_equal"], (mode, nested, r)+ assert r["mismatch"] == "ValueError", (rank, r)+++def test_full_dcp_load_skips_or_rejects_quant_state_it_cannot_apply():+ """QuantState without its packed weight keeps the live scales (it used to apply the checkpoint's),+ and a nested checkpoint into a non-nested model raises on every rank."""+ pytest.importorskip("bitsandbytes")+ results = _run("dcp_restore_guard")+ for rank, r in results.items():+ for mode in ("broadcast", "sharded"):+ assert r[f"partial_{mode}"]["scales"], (rank, mode, r)+ if rank == 0:+ assert r[f"partial_{mode}"]["dequant_equal"], (mode, r)+ message = r[f"nested_{mode}"]+ assert "nested" in message and "does not match" in message, (rank, mode, r)+ assert r["nested_broadcast"] == results[0]["nested_broadcast"], results++def test_a_slow_writer_does_not_time_out_the_other_ranks():results = _run("slow_writer")assert all(r["ok"] for r in results.values()), resultsdiff --git a/unsloth/models/fsdp2_save.py b/unsloth/models/fsdp2_save.pyindex f8445de8c10..794adc303f5 100644--- a/unsloth/models/fsdp2_save.py+++ b/unsloth/models/fsdp2_save.py@@ -632,7 +632,8 @@ def _restore_quant_state(model, state_dict, options):"""Loading a full DCP state dict: the saved QuantState entries (`_add_quant_state_entries`) arecopied into each live QuantState in place, so the packed bytes DCP loads are dequantized with thescales they were saved with. A saved QuantState that does not fit the live one (other shape,- blocksize, quant type or nesting) raises instead of pairing the bytes with the wrong scales. With+ blocksize, quant type or nesting) raises instead of pairing the bytes with the wrong scales, as+ does one without its packed weight unless strict=False (DCP keeps the live bytes then). With`broadcast_from_rank0` only rank 0 holds the entries and sends them to the others."""entries = _linear4bit_entries(model)if not entries:@@ -656,6 +657,8 @@ def _restore_quant_state(model, state_dict, options):returnfrom bitsandbytes.functional import QuantState+ strict = bool(getattr(options, "strict", True)) if options is not None else True+ orphans = []for prefix, module in entries:live = module.weight.quant_statehead = prefix + "weight."@@ -693,7 +696,24 @@ def _restore_quant_state(model, state_dict, options):"quantization state is kept.")continue+ if not loads_weight:+ if strict:+ raise ValueError(+ f"Unsloth: the state dict has the 4-bit quantization state of `{head[:-1]}` but "+ "not its packed weight. Load the weight with it, or pass strict=False to keep "+ "the model's own weight and quantization state."+ )+ orphans.append(head[:-1])+ continueexpected = set(live.as_dict(packed = True))+ saved_nested = any(k.startswith("nested_") for k in saved)+ if saved_nested != bool(live.nested):+ raise ValueError(+ f"Unsloth: the checkpoint's 4-bit quantization state for `{head[:-1]}` (nested "+ f"{saved_nested}) does not match the model's (nested {bool(live.nested)}). Load it "+ "into a model quantized with the same bitsandbytes settings "+ "(bnb_4bit_use_double_quant)."+ )if set(saved) != expected:raise ValueError(f"Unsloth: the checkpoint's 4-bit quantization state for `{head[:-1]}` has entries "@@ -727,6 +747,27 @@ def _restore_quant_state(model, state_dict, options):with torch.no_grad():for _, a, b in pairs:b.copy_(a.to(b.device))+ if orphans and (not broadcast or dist.get_rank() == 0):+ import warnings+ warnings.warn(+ f"Unsloth: skipped the 4-bit quantization state of {', '.join(orphans)}: the state dict "+ "does not have the packed weight, so the model keeps its own weight and quantization "+ "state.",+ stacklevel = 3,+ )+++# Every key `QuantState.as_dict(packed = True)` can write, so skipped metadata never reaches DCP.+_QUANT_STATE_KEYS = frozenset(+ (+ "absmax",+ "quant_map",+ "nested_absmax",+ "nested_quant_map",+ "quant_state.bitsandbytes__nf4",+ "quant_state.bitsandbytes__fp4",+ )+)def _without_quant_state_entries(name, args, kwargs):@@ -738,7 +779,8 @@ def _without_quant_state_entries(name, args, kwargs):drop = set()for prefix, module in _linear4bit_entries(model):drop.update(- prefix + "weight." + key for key in module.weight.quant_state.as_dict(packed = True)+ prefix + "weight." + key+ for key in _QUANT_STATE_KEYS.union(module.weight.quant_state.as_dict(packed = True)))if not drop:return args, kwargs