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
Fix optimizer state offload crash with Q-GaLore weight quantization (#13979)
Daniel Hanee8465458379
diff --git a/tests/test_optimizer_state_offload.py b/tests/test_optimizer_state_offload.pyindex c881b331563..5688df879a7 100644--- a/tests/test_optimizer_state_offload.py+++ b/tests/test_optimizer_state_offload.py@@ -19,6 +19,7 @@import importlib.utilimport ioimport os+import sysimport typesimport pytest@@ -546,3 +547,86 @@ def test_mps_synchronize_takes_no_device(monkeypatch):)module._synchronize(torch.device("mps"))assert calls == [()]+++def _q_galore(monkeypatch):+ # Loaded by path under its real module name (so _chunk_safe sees unsloth.optimizers.*),+ # without importing the full unsloth package.+ pytest.importorskip("bitsandbytes")+ for name, path in (+ ("unsloth", [os.path.join(_ROOT, "unsloth")]),+ ("unsloth.optimizers", [os.path.join(_ROOT, "unsloth", "optimizers")]),+ ):+ package = types.ModuleType(name)+ package.__path__ = path+ monkeypatch.setitem(sys.modules, name, package)+ device_type = types.ModuleType("unsloth_zoo.device_type")+ device_type.device_synchronize = torch.cuda.synchronize+ monkeypatch.setitem(sys.modules, "unsloth_zoo", types.ModuleType("unsloth_zoo"))+ monkeypatch.setitem(sys.modules, "unsloth_zoo.device_type", device_type)+ for name in ("q_galore_projector", "q_galore_adamw"):+ full = "unsloth.optimizers." + name+ spec = importlib.util.spec_from_file_location(+ full, os.path.join(_ROOT, "unsloth", "optimizers", name + ".py")+ )+ loaded = importlib.util.module_from_spec(spec)+ monkeypatch.setitem(sys.modules, full, loaded)+ spec.loader.exec_module(loaded)+ return loaded+++def test_weight_quant_q_galore_steps_unchunked():+ module = _module()+ p = [torch.nn.Parameter(torch.randn(2))]++ class QGaLoreAdamW8bit(torch.optim.AdamW):+ pass++ QGaLoreAdamW8bit.__module__ = "unsloth.optimizers.q_galore_adamw"+ assert module._chunk_safe(QGaLoreAdamW8bit([{"params": p, "weight_quant": False}]))+ assert not module._chunk_safe(QGaLoreAdamW8bit([{"params": p, "weight_quant": True}]))++[email protected](not torch.cuda.is_available(), reason = "needs CUDA")[email protected]("weight_quant", [False, True])+def test_q_galore_multi_chunk_offload(monkeypatch, weight_quant):+ module = _module()+ q_galore = _q_galore(monkeypatch)++ def run(offload):+ torch.manual_seed(17)+ params = [torch.nn.Parameter(torch.randn(256, 256, device = "cuda")) for _ in range(2)]+ groups = [+ {+ "params": params,+ "rank": 16,+ "weight_quant": weight_quant,+ "stochastic_round": False,+ }+ ]+ optimizer = q_galore.QGaLoreAdamW8bit(groups, lr = 1e-3)+ if weight_quant:+ q_galore.QGaLoreAdamW8bit.init_weight_quantization(+ torch.nn.ParameterList(params), groups+ )+ if offload:+ module.offload_optimizer_state(optimizer, chunk_bytes = 256 << 10)+ for step in range(2):+ for p in params:+ if weight_quant and step:+ q_galore._materialize_weight(p)+ p.grad = torch.full_like(p, 0.01 * (step + 1))+ optimizer.step()+ return params, optimizer++ base, _ = run(False)+ params, optimizer = run(True)+ for p, q in zip(params, base):+ if weight_quant:+ # p itself is a one element placeholder; the INT8 copy holds the weight.+ assert torch.equal(p._q_data, q._q_data)+ assert torch.equal(p._q_scales, q._q_scales)+ else:+ assert torch.equal(p, q)+ assert torch.equal(p.grad, q.grad)+ assert _state_devices(optimizer) == {"cpu"}diff --git a/unsloth/optimizers/state_offload.py b/unsloth/optimizers/state_offload.pyindex d3c04d458de..69eb96bea73 100644--- a/unsloth/optimizers/state_offload.py+++ b/unsloth/optimizers/state_offload.py@@ -58,6 +58,10 @@ _CHUNK_SAFE_MODULES = (def _chunk_safe(optimizer):+ # Q-GaLore weight_quant swaps p.data for a one element placeholder inside step, so the full+ # size gradients hidden between chunks can no longer be put back on it.+ if any(group.get("weight_quant", False) for group in optimizer.param_groups):+ return Falsefor cls in type(optimizer).__mro__:if "step" in vars(cls):return cls.__module__.startswith(_CHUNK_SAFE_MODULES)