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
Make Q-GaLore optimizer state resumable from checkpoints (#13051)
Daniel Han6be12621e70c
diff --git a/tests/utils/test_q_galore.py b/tests/utils/test_q_galore.pyindex 9f1ba174bdc..7e6ae81fc8a 100644--- a/tests/utils/test_q_galore.py+++ b/tests/utils/test_q_galore.py@@ -202,6 +202,55 @@ def test_projected_step_preserves_full_rank_gradients(out_features, in_features)torch.testing.assert_close(model.weight.grad, expected_grad)[email protected](not _adamw_mod._HAS_BNB, reason = "bitsandbytes is required")[email protected]("quant", [True, False])+def test_resume_from_weights_only_checkpoint_matches_uninterrupted(quant):+ """unslothai/unsloth#729: transformers resumes with torch.load(weights_only=True, map_location="cpu")."""+ import io++ device = "cuda" if torch.cuda.is_available() else "cpu"+ requires_bnb_optimizer(device)++ def make(weight, bias):+ weight = nn.Parameter(weight.clone())+ bias = nn.Parameter(bias.clone())+ projected = {"params": [weight], "rank": 4, "update_proj_gap": 2, "quant": quant}+ projected.update(queue_size = 2, cos_threshold = 0.0)+ optimizer = _adamw_mod.QGaLoreAdamW8bit([projected, {"params": [bias]}], lr = 1e-2)+ return weight, bias, optimizer++ def step(weight, bias, optimizer, i):+ # svd_lowrank draws from the global RNG, so each step reseeds it.+ torch.manual_seed(i)+ weight.grad = torch.randn(weight.shape, device = device)+ bias.grad = torch.randn(bias.shape, device = device)+ optimizer.step()++ torch.manual_seed(0)+ weight, bias, optimizer = make(+ torch.randn(128, 64, device = device), torch.randn(64, device = device)+ )+ for i in range(3):+ step(weight, bias, optimizer, i)+ buffer = io.BytesIO()+ torch.save(optimizer.state_dict(), buffer)+ assert isinstance(optimizer.state[weight]["projector"], GaLoreProjector)+ buffer.seek(0)+ saved = torch.load(buffer, map_location = "cpu", weights_only = True)++ weight2, bias2, resumed = make(weight.detach(), bias.detach())+ resumed.load_state_dict(saved)+ projector = resumed.state[weight2]["projector"]+ assert projector.ortho_matrix.device == weight2.device+ for i in range(3, 7):+ step(weight, bias, optimizer, i)+ step(weight2, bias2, resumed, i)+ assert torch.equal(weight, weight2)+ assert torch.equal(bias, bias2)+ # The adaptive schedule widened the gap after resume, so its saved queue was used.+ assert projector.update_proj_gap == optimizer.state[weight]["projector"].update_proj_gap == 4++# ======================================================================# Projector tests# ======================================================================diff --git a/unsloth/optimizers/q_galore_adamw.py b/unsloth/optimizers/q_galore_adamw.pyindex fe085db3a3e..ef804033f96 100644--- a/unsloth/optimizers/q_galore_adamw.py+++ b/unsloth/optimizers/q_galore_adamw.py@@ -108,6 +108,39 @@ class QGaLoreAdamW8bit(Optimizer2State):**legacy_kwargs,)+ def state_dict(self):+ # A raw GaLoreProjector fails transformers' weights_only resume load and keeps its tensors on CPU.+ state_dict = super().state_dict()+ for key, param_state in state_dict["state"].items():+ if isinstance(param_state, dict) and isinstance(+ param_state.get("projector"), GaLoreProjector+ ):+ state_dict["state"][key] = {+ **param_state,+ "projector": param_state["projector"].state_dict(),+ }+ return state_dict++ def load_state_dict(self, state_dict, *args, **kwargs):+ # Projectors bypass the base cast, which would downcast float32 bases to the param dtype.+ projectors, state = {}, {}+ for key, param_state in state_dict["state"].items():+ projector = param_state.get("projector") if isinstance(param_state, dict) else None+ if isinstance(projector, GaLoreProjector):+ projector = projector.state_dict()+ if isinstance(projector, dict):+ param_state = {k: v for k, v in param_state.items() if k != "projector"}+ projectors[key] = projector+ state[key] = param_state+ super().load_state_dict({**state_dict, "state": state}, *args, **kwargs)+ saved_ids = (i for g in state_dict["param_groups"] for i in g["params"])+ params = (p for g in self.param_groups for p in g["params"])+ for key, p in zip(saved_ids, params):+ if key in projectors:+ self.state[p]["projector"] = GaLoreProjector.from_state_dict(+ projectors[key], device = p.device+ )+@torch.no_grad()def step(self, closure = None):"""Perform a single optimization step.diff --git a/unsloth/optimizers/q_galore_projector.py b/unsloth/optimizers/q_galore_projector.pyindex f7aaf39714f..d3cfa629823 100644--- a/unsloth/optimizers/q_galore_projector.py+++ b/unsloth/optimizers/q_galore_projector.py@@ -106,6 +106,33 @@ class GaLoreProjector:self.ortho_matrix_zeros = Noneself.ortho_matrix_shape = None+ def state_dict(self) -> dict:+ """Plain dict of tensors and primitives, loadable with ``torch.load(weights_only = True)``."""+ state = {+ name: getattr(self, name) for name in self.__slots__ if name != "_ortho_float_cache"+ }+ state["queue"] = list(self.queue)+ if self.ortho_matrix_shape is not None:+ state["ortho_matrix_shape"] = tuple(self.ortho_matrix_shape)+ return state++ @classmethod+ def from_state_dict(+ cls,+ state: dict,+ device = None,+ ) -> "GaLoreProjector":+ # Checkpoints load on CPU; tensors go back to the parameter's device with their dtype kept.+ projector = cls.__new__(cls)+ for name in cls.__slots__:+ value = state.get(name)+ if device is not None and isinstance(value, torch.Tensor):+ value = value.to(device)+ setattr(projector, name, value)+ projector.queue = deque(state.get("queue") or (), maxlen = projector.queue_size)+ projector._ortho_float_cache = None+ return projector+def project(self, full_rank_grad: torch.Tensor, step: int) -> torch.Tensor:"""Project a full-rank gradient into the low-rank subspace.