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.

Fix Q-GaLore checkpoint weights and stacked MoE grouping (#13276)

cherry77-cloud041787066035
diff --git a/tests/utils/test_q_galore.py b/tests/utils/test_q_galore.py
index 7e6ae81fc8a..5067f91472e 100644
--- a/tests/utils/test_q_galore.py
+++ b/tests/utils/test_q_galore.py
@@ -741,3 +741,124 @@ class TestQGaLoreIntegration:
for h in handles:
h.remove()
+
+
+class _TinyBlock(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.q_proj = nn.Linear(32, 32, bias = False)
+ self.down_proj = nn.Parameter(torch.randn(4, 32, 16) * 0.02)
+
+ def forward(self, x):
+ return torch.einsum("bh,eho->bo", self.q_proj(x), self.down_proj)
+
+
+def _q_galore_step(model, device, weight_quant, targets):
+ groups = make_q_galore_param_groups(
+ model,
+ rank = 4,
+ proj_quant = False,
+ weight_quant = weight_quant,
+ stochastic_round = False,
+ weight_group_size = 32,
+ target_modules = targets,
+ )
+ if weight_quant:
+ _adamw_mod.QGaLoreAdamW8bit.init_weight_quantization(model, groups, group_size = 32)
+ _adamw_mod.install_weight_quant_hooks(model)
+ optimizer = _adamw_mod.QGaLoreAdamW8bit(groups, lr = 1e-2)
+ model(torch.randn(2, 32, device = device)).square().sum().backward()
+ optimizer.step()
+ return groups
+
+
[email protected](not _adamw_mod._HAS_BNB, reason = "bitsandbytes is required")
+def test_stacked_expert_weights_use_plain_adamw_not_galore():
+ device = "cuda" if torch.cuda.is_available() else "cpu"
+ requires_bnb_optimizer(device)
+ torch.manual_seed(0)
+ model = _TinyBlock().to(device)
+ before = model.down_proj.detach().clone()
+ groups = _q_galore_step(model, device, weight_quant = False, targets = ["q_proj", "down_proj"])
+ galore = next(g for g in groups if "rank" in g)["params"]
+ assert [p.dim() for p in galore] == [2]
+ assert not torch.equal(model.down_proj.detach(), before)
+
+
[email protected](not _adamw_mod._HAS_BNB, reason = "bitsandbytes is required")
+def test_weight_quant_state_dict_after_step_holds_full_weights():
+ device = "cuda" if torch.cuda.is_available() else "cpu"
+ requires_bnb_optimizer(device)
+ torch.manual_seed(0)
+ model = _TinyBlock().to(device)
+ _q_galore_step(model, device, weight_quant = True, targets = ["q_proj"])
+ weight = model.q_proj.weight
+ assert weight.shape == (1,)
+
+ state_dict = {k: v.detach().clone() for k, v in model.state_dict().items()}
+ expected = _dequantize(weight._q_data, weight._q_scales, weight._q_zeros, weight._q_shape)
+ torch.testing.assert_close(state_dict["q_proj.weight"], expected)
+ assert weight.shape == (1,)
+
+ fresh = _TinyBlock().to(device)
+ fresh.load_state_dict(state_dict)
+ x = torch.randn(2, 32, device = device)
+ torch.testing.assert_close(model(x), fresh(x))
+
+ # Loading into the live quantized model must not be overwritten by the stale INT8 copy.
+ target = {k: torch.randn_like(v) for k, v in state_dict.items()}
+ model.load_state_dict(target)
+ fresh.load_state_dict(target)
+ torch.testing.assert_close(model(x), fresh(x))
+
+
+class _HookBypassingBlock(_TinyBlock):
+ # Calls forward directly, like a torch.compile'd parent that never runs submodule pre-hooks.
+ def forward(self, x):
+ return torch.einsum("bh,eho->bo", self.q_proj.forward(x), self.down_proj)
+
+
[email protected](not _adamw_mod._HAS_BNB, reason = "bitsandbytes is required")
+def test_weight_quant_root_hook_restores_weights_for_bypassed_submodules():
+ device = "cuda" if torch.cuda.is_available() else "cpu"
+ requires_bnb_optimizer(device)
+ torch.manual_seed(0)
+ model = _HookBypassingBlock().to(device)
+ _q_galore_step(model, device, weight_quant = True, targets = ["q_proj"])
+ weight = model.q_proj.weight
+ expected = _dequantize(weight._q_data, weight._q_scales, weight._q_zeros, weight._q_shape)
+ model(torch.randn(2, 32, device = device))
+ torch.testing.assert_close(weight.data, expected)
+ # Already materialized: checkpointing reuses the live tensor instead of a second dense copy.
+ assert model.state_dict()["q_proj.weight"].data_ptr() == weight.data_ptr()
+
+
+class _TwoBranchBlock(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.q_proj = nn.Linear(32, 32, bias = False)
+ self.k_proj = nn.Linear(32, 32, bias = False)
+ self.use_k = True
+
+ def forward(self, x):
+ return (self.k_proj if self.use_k else self.q_proj)(x)
+
+
[email protected](not _adamw_mod._HAS_BNB, reason = "bitsandbytes is required")
+def test_weight_quant_unrouted_weights_return_to_placeholders():
+ device = "cuda" if torch.cuda.is_available() else "cpu"
+ requires_bnb_optimizer(device)
+ torch.manual_seed(0)
+ model = _TwoBranchBlock().to(device)
+ groups = _q_galore_step(model, device, weight_quant = True, targets = ["q_proj", "k_proj"])
+ weight = model.k_proj.weight
+ assert weight.shape == (1,)
+ optimizer = _adamw_mod.QGaLoreAdamW8bit(groups, lr = 1e-2)
+ weight.grad = None
+ model.use_k = False
+ model(torch.randn(2, 32, device = device)).square().sum().backward()
+ assert weight.shape == (32, 32)
+ q_data = weight._q_data.clone()
+ optimizer.step()
+ assert weight.shape == (1,)
+ assert torch.equal(weight._q_data, q_data)
diff --git a/unsloth/optimizers/q_galore_adamw.py b/unsloth/optimizers/q_galore_adamw.py
index ef804033f96..a8575440e0b 100644
--- a/unsloth/optimizers/q_galore_adamw.py
+++ b/unsloth/optimizers/q_galore_adamw.py
@@ -167,6 +167,9 @@ class QGaLoreAdamW8bit(Optimizer2State):
for gindex, group in enumerate(self.param_groups):
for pindex, p in enumerate(group["params"]):
if p.grad is None:
+ # Unrouted weights were densified by the model pre-hook; the INT8 copy is still current.
+ if self._has_weight_quant(p, group) and _is_materialized(p):
+ p.data = torch.empty(1, dtype = p.data.dtype, device = p.data.device)
continue
state = self.state[p]
@@ -176,14 +179,7 @@ class QGaLoreAdamW8bit(Optimizer2State):
has_weight_quant = self._has_weight_quant(p, group)
if has_weight_quant:
- if p._q_scales is not None:
- float_weight = _dequantize(
- p._q_data,
- p._q_scales,
- p._q_zeros,
- p._q_shape,
- )
- p.data = float_weight
+ _materialize_weight(p)
if "rank" in group:
if "projector" not in state:
@@ -293,30 +289,70 @@ class QGaLoreAdamW8bit(Optimizer2State):
p._weight_group_size = group_size
+def _is_placeholder(p):
+ return getattr(p, "_q_scales", None) is not None and p.shape != p._q_shape
+
+
+def _is_materialized(p):
+ return getattr(p, "_q_scales", None) is not None and p.shape == p._q_shape
+
+
+def _dequantized(p):
+ return _dequantize(p._q_data, p._q_scales, p._q_zeros, p._q_shape).to(p.device)
+
+
+def _materialize_weight(p):
+ if _is_placeholder(p):
+ p.data = _dequantized(p)
+
+
def _weight_quant_pre_hook(module, args):
"""Forward pre-hook: dequantize INT8 weights to float before forward."""
for p in module.parameters(recurse = False):
- if hasattr(p, "_q_scales") and p._q_scales is not None:
- float_weight = _dequantize(
- p._q_data,
- p._q_scales,
- p._q_zeros,
- p._q_shape,
- )
- p.data = float_weight.to(p.data.device)
+ _materialize_weight(p)
+
+
+def _weight_quant_model_pre_hook(module, args, kwargs):
+ # Runs outside torch.compile'd submodules, whose own pre-hooks never see the placeholder.
+ for p in module.parameters():
+ _materialize_weight(p)
+
+
+def _weight_quant_state_dict_hook(module, state_dict, prefix, local_metadata):
+ """Serialize full weights without materializing the live placeholders."""
+ for name, p in module.named_parameters(recurse = False, remove_duplicate = False):
+ if _is_placeholder(p):
+ state_dict[prefix + name] = _dequantized(p)
+
+
+def _weight_quant_load_state_dict_hook(module, state_dict, prefix, *args):
+ # Loaded values must win over the INT8 copy, so drop it.
+ for name, p in module.named_parameters(recurse = False, remove_duplicate = False):
+ if prefix + name in state_dict and getattr(p, "_q_scales", None) is not None:
+ _materialize_weight(p)
+ p._q_scales = None
+ p._q_zeros = None
+ del p._q_data
def install_weight_quant_hooks(model: torch.nn.Module) -> list:
- """Register forward pre-hooks on modules whose weights are INT8-quantized.
+ """Register forward and checkpoint hooks for INT8-quantized weights.
Returns a list of hook handles so the caller can remove them if needed.
"""
- handles = []
+ handles = [
+ model.register_forward_pre_hook(
+ _weight_quant_model_pre_hook, prepend = True, with_kwargs = True
+ )
+ ]
for module in model.modules():
has_quant_param = any(hasattr(p, "_q_scales") for p in module.parameters(recurse = False))
if has_quant_param:
- h = module.register_forward_pre_hook(_weight_quant_pre_hook)
- handles.append(h)
+ handles.append(module.register_forward_pre_hook(_weight_quant_pre_hook))
+ handles.append(module.register_state_dict_post_hook(_weight_quant_state_dict_hook))
+ handles.append(
+ module.register_load_state_dict_pre_hook(_weight_quant_load_state_dict_hook)
+ )
return handles
@@ -352,7 +388,7 @@ def make_q_galore_param_groups(
) -> list:
"""Build param groups suitable for :class:`QGaLoreAdamW8bit`.
- Parameters matching ``target_modules`` (or the default set of attention
+ Two-dimensional parameters matching ``target_modules`` (or the default set of attention
and MLP projection names) are placed in the GaLore group. All other
trainable parameters go into the non-GaLore group.
@@ -387,10 +423,9 @@ def make_q_galore_param_groups(
if not param.requires_grad:
continue
- # Match target module names and exclude 1-D params (biases, norms), since GaLoreProjector.project
- # requires 2-D gradients.
+ # GaLoreProjector requires matrices; biases, norms, and stacked experts use ordinary AdamW.
name_parts = name.split(".")
- is_galore = param.dim() >= 2 and any(t in name_parts for t in targets)
+ is_galore = param.dim() == 2 and any(t in name_parts for t in targets)
if is_galore:
galore_params.append(param)
diff --git a/unsloth/trainer.py b/unsloth/trainer.py
index c5dd49445d1..6fa5e4e927d 100644
--- a/unsloth/trainer.py
+++ b/unsloth/trainer.py
@@ -1191,7 +1191,7 @@ class UnslothTrainer(SFTTrainer):
)
if not any("rank" in group for group in param_groups):
- # make_q_galore_param_groups selects on param.dim() >= 2, and FSDP1 hands us 1-D
+ # make_q_galore_param_groups selects on param.dim() == 2, and FSDP1 hands us 1-D
# views: FlatParameter with use_orig_params=False, and a 1-D sharded view even
# with use_orig_params=True. Nothing matches, so a requested Q-GaLore run would
# quietly become ordinary 8-bit AdamW. Say so instead.