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.

Review follow-ups: fused LoRA dropout/bias under compile and 4-bit, Q-GaLore offload, GRPO truncated support, CP save on transformers 4.x (#14226)

Daniel Han103ba5267172
diff --git a/tests/test_context_parallel_fsdp2_save_gloo.py b/tests/test_context_parallel_fsdp2_save_gloo.py
index 6f7a1b3bd55..d45a7c844f5 100644
--- a/tests/test_context_parallel_fsdp2_save_gloo.py
+++ b/tests/test_context_parallel_fsdp2_save_gloo.py
@@ -45,7 +45,13 @@ def _accelerator_less_import():
spec.loader.exec_module(importlib.util.module_from_spec(spec))
-def _worker(rank, port, out_dir, user_config):
+def _worker(
+ rank,
+ port,
+ out_dir,
+ user_config,
+ state_dict_type = "FULL_STATE_DICT",
+):
_accelerator_less_import()
os.environ.update(
RANK = str(rank),
@@ -73,7 +79,7 @@ def _worker(rank, port, out_dir, user_config):
state = types.SimpleNamespace(
device_mesh = manager.device_mesh,
parallelism_config = None,
- fsdp_plugin = types.SimpleNamespace(state_dict_type = "FULL_STATE_DICT"),
+ fsdp_plugin = types.SimpleNamespace(state_dict_type = state_dict_type),
)
if user_config:
# A dp_shard only ParallelismConfig the user passed: still non-None for transformers 4.x.
@@ -126,6 +132,14 @@ def _worker(rank, port, out_dir, user_config):
trainer.accelerator = Acc()
trainer.accelerator.state = state
trainer._context_parallel_manager = manager
+ full_state_dicts = []
+
+ def get_state_dict(model, *args, **kwargs):
+ # Accelerator.get_state_dict gathers the whole model, frozen base weights included.
+ full_state_dicts.append(1)
+ return Accelerator.get_state_dict(trainer.accelerator, model, *args, **kwargs)
+
+ trainer.accelerator.get_state_dict = get_state_dict
result = {}
try:
@@ -134,11 +148,14 @@ def _worker(rank, port, out_dir, user_config):
except Exception as e:
result["error"] = f"{type(e).__name__}: {e}"
result["config_kept"] = state.parallelism_config is installed
+ result["full_state_dicts"] = len(full_state_dicts)
dist.barrier()
if rank == 0 and result["error"] is None:
from safetensors.torch import load_file
- saved = load_file(os.path.join(out_dir, "adapter_model.safetensors"))
+ path = os.path.join(out_dir, "adapter_model.safetensors")
+ # A save that silently writes nothing must fail the count, not crash the rank.
+ saved = load_file(path) if os.path.exists(path) else {}
equal = 0
for name, ref in reference.items():
got = saved.get(name.replace(".default", ""))
@@ -154,17 +171,48 @@ def _worker(rank, port, out_dir, user_config):
dist.destroy_process_group()
[email protected]("user_config", [False, True])
-def test_save_model_gathers_fsdp2_lora_under_context_parallel(tmp_path, user_config):
+def _run(
+ tmp_path,
+ user_config,
+ state_dict_type = "FULL_STATE_DICT",
+):
import json
import torch.multiprocessing as mp
- mp.spawn(_worker, args = (_free_port(), str(tmp_path), user_config), nprocs = 2, join = True)
+ args = (_free_port(), str(tmp_path), user_config, state_dict_type)
+ mp.spawn(_worker, args = args, nprocs = 2, join = True)
with open(tmp_path / "result.json") as f:
results = json.load(f)
for r in results:
assert r["error"] is None, r["error"]
assert r["config_kept"]
+ return results
+
+
[email protected]("user_config", [False, True])
+def test_save_model_gathers_fsdp2_lora_under_context_parallel(tmp_path, user_config):
+ results = _run(tmp_path, user_config)
+ assert results[0]["lora_tensors"] == 4
+ assert results[0]["saved_whole_and_equal"] == 4
+
+
+def _parallelism_config_dispatched_first():
+ import transformers
+ from packaging.version import Version
+ return Version(transformers.__version__).major < 5
+
+
+ not _parallelism_config_dispatched_first(),
+ reason = "transformers >= 5 dispatches save_model on FSDP first, as without CP",
+)
[email protected]("state_dict_type", ["FULL_STATE_DICT", "SHARDED_STATE_DICT"])
+def test_save_model_adapter_export_gathers_only_adapter(tmp_path, state_dict_type):
+ # transformers < 5 exported the adapter for either plugin setting through the parallelism_config
+ # branch; clearing the config sent it to the FSDP branch, which writes nothing for a sharded
+ # setting and otherwise gathers the frozen base model to rank 0 before PEFT drops it.
+ results = _run(tmp_path, False, state_dict_type)
assert results[0]["lora_tensors"] == 4
assert results[0]["saved_whole_and_equal"] == 4
+ assert [r["full_state_dicts"] for r in results] == [0, 0]
diff --git a/tests/test_fused_lora_dropout_bias.py b/tests/test_fused_lora_dropout_bias.py
index 060ef09a1f2..bde9a1305bc 100644
--- a/tests/test_fused_lora_dropout_bias.py
+++ b/tests/test_fused_lora_dropout_bias.py
@@ -231,7 +231,8 @@ def test_eval_mode_skips_dropout_like_peft(monkeypatch, device):
for g, e in zip(got, expected):
torch.testing.assert_close(g, e)
name, args = spy.calls[0]
- assert name == "LoRA_QKV" and args[-4:] == (None, None, None, None)
+ # p = 0 in eval, but the dropout route is kept so the plain path's global dequant scratch is not.
+ assert name == "LoRA_QKV" and args[-4:] == ((0.0, 0.0, 0.0), None, None, None)
@pytest.mark.parametrize("device", DEVICES)
diff --git a/tests/test_fused_lora_dropout_bias_compile_memory.py b/tests/test_fused_lora_dropout_bias_compile_memory.py
new file mode 100644
index 00000000000..f22989e5aa7
--- /dev/null
+++ b/tests/test_fused_lora_dropout_bias_compile_memory.py
@@ -0,0 +1,146 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Dropout / lora_B bias fusion must not cost graph breaks or resident memory versus PEFT.
+
+Before torch 2.11 the fused LoRA Functions run behind torch._dynamo.disable (fast_lora._apply), so a
+dropout or bias projection routed into them while compiling turns a PEFT forward Dynamo traced into a
+graph break (fullgraph=True raises). Those configurations stay on PEFT while compiling there; plain
+LoRA keeps its existing routing. Eagerly, the dropout / bias path dequantizes 4-bit weights into a
+fresh tensor rather than the per-device global scratch, which PEFT never kept resident.
+"""
+
+from __future__ import annotations
+
+import pytest
+import torch
+import unsloth # noqa: F401
+
+from real_accelerator import has_real_cuda
+from unsloth.kernels import fast_lora
+from unsloth.kernels import utils as kernel_utils
+
+H, I = 32, 64
+TARGETS = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
+
+
+class _Block(torch.nn.Module):
+ def __init__(self, linear):
+ super().__init__()
+ for name in TARGETS:
+ shape = (
+ (I, H)
+ if name == "down_proj"
+ else ((H, I) if name in ("gate_proj", "up_proj") else (H, H))
+ )
+ setattr(self, name, linear(*shape))
+ self.act_fn = torch.nn.SiLU()
+
+
+def _peft_block(
+ dropout,
+ lora_bias,
+ linear = None,
+ device = "cpu",
+ dtype = torch.float32,
+):
+ from peft import LoraConfig, get_peft_model
+
+ torch.manual_seed(3407)
+ block = _Block(linear or (lambda i, o: torch.nn.Linear(i, o, bias = False)))
+ block = block.to(dtype = dtype).to(device = device)
+ if linear is not None:
+ block.is_loaded_in_4bit = True
+ cfg = LoraConfig(
+ r = 4,
+ lora_alpha = 8,
+ lora_dropout = dropout,
+ target_modules = TARGETS,
+ init_lora_weights = False,
+ lora_bias = lora_bias,
+ )
+ model = get_peft_model(block, cfg)
+ for name, p in model.named_parameters():
+ p.requires_grad_("lora_" in name)
+ model.train()
+ return model, model.base_model.model
+
+
+def _emulate_torch_before_2_11(monkeypatch):
+ # What importing fast_lora does on torch < 2.11.
+ def _apply(function, *args):
+ return function.apply(*args)
+
+ monkeypatch.setattr(fast_lora, "TRACE_LORA_FUNCTIONS", False)
+ monkeypatch.setattr(fast_lora, "_apply", torch._dynamo.disable(_apply))
+
+
+CASES = [(0.1, False), (0.0, True), (0.1, True)]
+
+
[email protected]("dropout,lora_bias", CASES)
[email protected]("path", ["o", "qkv"])
+def test_fullgraph_compiles_before_torch_2_11(monkeypatch, dropout, lora_bias, path):
+ _emulate_torch_before_2_11(monkeypatch)
+ model, block = _peft_block(dropout, lora_bias)
+ if path == "o":
+ fn = lambda X: fast_lora.apply_lora_o(block, X)
+ else:
+ fn = lambda X: sum(fast_lora.apply_lora_qkv(block, X, inplace = False))
+ torch._dynamo.reset()
+ compiled = torch.compile(fn, backend = "eager", fullgraph = True)
+ X = torch.randn(2, 3, H, requires_grad = True)
+ compiled(X * 1).sum().backward()
+ assert X.grad is not None and torch.isfinite(X.grad).all()
+
+ # Eagerly the same configuration still runs fused.
+ calls = []
+ real = fast_lora._apply
+ monkeypatch.setattr(fast_lora, "_apply", lambda f, *a: calls.append(f) or real(f, *a))
+ fn(torch.randn(2, 3, H))
+ assert len(calls) == 1
+ torch._dynamo.reset()
+
+
[email protected]("dropout,lora_bias", CASES)
+def test_no_new_graph_breaks_before_torch_2_11(monkeypatch, dropout, lora_bias):
+ from torch._dynamo.utils import counters
+
+ _emulate_torch_before_2_11(monkeypatch)
+ model, block = _peft_block(dropout, lora_bias)
+ torch._dynamo.reset()
+ counters.clear()
+ compiled = torch.compile(lambda X: fast_lora.apply_lora_o(block, X), backend = "eager")
+ compiled(torch.randn(2, 3, H))
+ assert sum(counters["graph_break"].values()) == 0, dict(counters["graph_break"])
+ torch._dynamo.reset()
+
+
[email protected]("dropout,lora_bias", CASES)
[email protected]("path", ["o", "qkv", "mlp"])
+def test_dropout_and_bias_paths_keep_no_global_dequant_scratch(
+ monkeypatch, dropout, lora_bias, path
+):
+ if not has_real_cuda():
+ pytest.skip("needs a CUDA GPU for bitsandbytes 4-bit weights")
+ bnb = pytest.importorskip("bitsandbytes")
+ linear = lambda i, o: bnb.nn.Linear4bit(
+ i, o, bias = False, compute_dtype = torch.float16, quant_type = "nf4"
+ )
+ model, block = _peft_block(dropout, lora_bias, linear, "cuda", torch.float16)
+ calls = []
+ real = fast_lora._apply
+ monkeypatch.setattr(fast_lora, "_apply", lambda f, *a: calls.append(f) or real(f, *a))
+ monkeypatch.setattr(kernel_utils, "_SCRATCH", {})
+ X = torch.randn(2, 3, H, device = "cuda", dtype = torch.float16, requires_grad = True)
+ fn = {
+ "o": lambda X: fast_lora.apply_lora_o(block, X),
+ "qkv": lambda X: sum(fast_lora.apply_lora_qkv(block, X, inplace = False)),
+ "mlp": lambda X: fast_lora.apply_lora_mlp_swiglu(block, X, inplace = False),
+ }[path]
+ with torch.autocast("cuda", dtype = torch.float16):
+ out = fn(X * 1)
+ out.float().sum().backward()
+ assert len(calls) == 1, "the fused kernel did not run"
+ assert X.grad is not None
+ assert not any(key[0] == "weight" for key in kernel_utils._SCRATCH), list(kernel_utils._SCRATCH)
diff --git a/tests/test_grpo_efficient_autocast_latch.py b/tests/test_grpo_efficient_autocast_latch.py
index 47ab379f601..362ced2af34 100644
--- a/tests/test_grpo_efficient_autocast_latch.py
+++ b/tests/test_grpo_efficient_autocast_latch.py
@@ -46,6 +46,8 @@ def _namespace():
exec(_function("_unsloth_grpo_autocast_forced_float32"), ns)
exec(_function("_unsloth_grpo_autocast"), ns)
exec(_function("_unsloth_grpo_autocast_unscored"), ns)
+ exec(_function("_unsloth_grpo_support_mismatch"), ns)
+ exec(_function("_unsloth_grpo_refuse_unscored_support"), ns)
exec(
_function(
"_get_per_token_logps_and_entropies", "grpo_trainer__get_per_token_logps_and_entropies"
diff --git a/tests/test_grpo_truncated_support_policy_gate.py b/tests/test_grpo_truncated_support_policy_gate.py
new file mode 100644
index 00000000000..717915385cd
--- /dev/null
+++ b/tests/test_grpo_truncated_support_policy_gate.py
@@ -0,0 +1,235 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""UNSLOTH_GRPO_TRUNCATED_SUPPORT=1 must only score over truncated sets while every scored policy is the sampler.
+
+Each scoring call rebuilds its own top_k / top_p / min_p kept set from the logits it sees and always keeps the
+scored token. That set is the sampler's only while the scored weights are the rollout weights. A reference model
+(beta != 0) or a stale old policy (TRL computes old logps when gradient_accumulation_steps is not a multiple of
+steps_per_generation * num_iterations) keeps a different set, so an excluded token gets a denominator that
+depends on which token is scored: the implied probabilities no longer sum to 1 and the PPO ratio / KL are wrong.
+Runs the shipped binding block of ``_get_per_token_logps_and_entropies`` on a stub trainer.
+"""
+
+from __future__ import annotations
+
+import ast
+import sys
+import textwrap
+import types
+import warnings
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+torch = pytest.importorskip("torch")
+
+_SOURCE_PATH = Path(__file__).resolve().parents[1] / "unsloth" / "models" / "rl_replacements.py"
+_SUPPORT = {"support_top_k": 2, "support_top_p": 1.0, "support_min_p": 0.0}
+
+
+def _sources():
+ text = _SOURCE_PATH.read_text(encoding = "utf-8")
+ tree = ast.parse(text)
+ helpers = [
+ ast.get_source_segment(text, node)
+ for node in tree.body
+ if isinstance(node, ast.FunctionDef) and node.name == "_unsloth_grpo_support_mismatch"
+ ]
+ (function,) = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.FunctionDef) and node.name == "_get_per_token_logps_and_entropies"
+ ]
+ for node, field in ((n, f) for n in ast.walk(function) for f in ("body", "orelse")):
+ stmts = getattr(node, field, None)
+ if not isinstance(stmts, list):
+ continue
+ starts = [
+ i
+ for i, s in enumerate(stmts)
+ if isinstance(s, ast.Try) and "grpo_truncated_support_kwargs" in ast.unparse(s)
+ ]
+ if not starts:
+ continue
+ block = []
+ for s in stmts[starts[0] :]:
+ if "_support_kwargs" not in ast.unparse(s):
+ break
+ block.append(textwrap.dedent(ast.get_source_segment(text, s, padded = True)))
+ return "\n".join(helpers), "\n".join(block)
+ raise AssertionError("truncated-support block not found")
+
+
+def _bind(monkeypatch, trainer):
+ helpers, block = _sources()
+ zoo = types.ModuleType("unsloth_zoo")
+ zoo_rl = types.ModuleType("unsloth_zoo.rl_replacements")
+ zoo_rl.grpo_truncated_support_kwargs = lambda t: dict(_SUPPORT)
+ zoo.rl_replacements = zoo_rl
+ monkeypatch.setitem(sys.modules, "unsloth_zoo", zoo)
+ monkeypatch.setitem(sys.modules, "unsloth_zoo.rl_replacements", zoo_rl)
+
+ def chunked_hidden_states_selective_log_softmax(*args, **kwargs):
+ return kwargs
+
+ def chunked_selective_log_softmax(*args, **kwargs):
+ return kwargs
+
+ ns = {
+ "self": trainer,
+ "chunked_hidden_states_selective_log_softmax": chunked_hidden_states_selective_log_softmax,
+ "chunked_selective_log_softmax": chunked_selective_log_softmax,
+ }
+ exec(compile(helpers, str(_SOURCE_PATH), "exec"), ns)
+ with warnings.catch_warnings(record = True) as caught:
+ warnings.simplefilter("always")
+ exec(compile(block, str(_SOURCE_PATH), "exec"), ns)
+ return ns, [str(w.message) for w in caught]
+
+
+def _trainer(
+ beta = 0.0,
+ num_iterations = 1,
+ steps_per_generation = 4,
+ gradient_accumulation_steps = 4,
+):
+ return SimpleNamespace(
+ beta = beta,
+ num_iterations = num_iterations,
+ use_vllm = True,
+ args = SimpleNamespace(
+ steps_per_generation = steps_per_generation,
+ gradient_accumulation_steps = gradient_accumulation_steps,
+ ),
+ )
+
+
+ "trainer",
+ [
+ _trainer(),
+ _trainer(steps_per_generation = 2, gradient_accumulation_steps = 4),
+ _trainer(steps_per_generation = None),
+ ],
+ ids = ["on_policy", "generation_divides_accumulation", "default_steps_per_generation"],
+)
+def test_on_policy_without_reference_scores_over_the_kept_set(monkeypatch, trainer):
+ ns, messages = _bind(monkeypatch, trainer)
+ assert ns["chunked_selective_log_softmax"]() == _SUPPORT
+ assert ns["chunked_hidden_states_selective_log_softmax"]() == _SUPPORT
+ assert getattr(trainer, "_unsloth_truncated_support_scored", False) is True
+ assert not messages
+
+
+ "trainer, reason",
+ [
+ (_trainer(beta = 0.04), "beta"),
+ (_trainer(num_iterations = 2), "num_iterations"),
+ (_trainer(steps_per_generation = 8, gradient_accumulation_steps = 4), "steps_per_generation"),
+ ],
+ ids = ["reference_model", "multiple_iterations", "buffered_generation"],
+)
+def test_policies_with_their_own_kept_set_score_the_full_vocabulary(monkeypatch, trainer, reason):
+ ns, messages = _bind(monkeypatch, trainer)
+ # Left unbound: the zoo loss then refuses the support kwargs too, since old / ref logps exist and
+ # the trainer is not marked, so every policy is normalised over the full vocabulary.
+ assert ns["chunked_selective_log_softmax"]() == {}
+ assert ns["chunked_hidden_states_selective_log_softmax"]() == {}
+ assert not getattr(trainer, "_unsloth_truncated_support_scored", False)
+ assert len(messages) == 1 and reason in messages[0]
+ # The zoo's own refusal ("needs an unsloth build ...") would be misleading here: already explained.
+ assert trainer._unsloth_truncated_support_refused is True
+ _, messages = _bind(monkeypatch, trainer)
+ assert not messages
+
+
+def _own_support_logps(logits, index, top_k):
+ """The per-policy rule: each policy's own top-k set, plus the scored token."""
+ kth = torch.topk(logits, top_k, dim = -1).values[:, -1:]
+ keep = logits >= kth
+ keep = keep.scatter(-1, index.unsqueeze(-1), True)
+ kept = logits.masked_fill(~keep, float("-inf"))
+ return torch.gather(logits, -1, index.unsqueeze(-1)).squeeze(-1) - torch.logsumexp(kept, dim = -1)
+
+
+def test_own_support_scoring_is_not_a_distribution_when_supports_differ():
+ """Why the gate exists: with a policy whose top-2 set excludes a sampled token, scoring every token
+ under the per-policy rule implies probabilities summing to more than 1."""
+ new = torch.tensor([[0.0, 1.0, 2.0]])
+ implied = torch.cat([_own_support_logps(new, torch.tensor([i]), 2) for i in range(3)]).exp()
+ assert implied.sum().item() > 1.08
+ # Same policy as the sampler: the scored token is always inside the set, so it is a distribution.
+ sampler = torch.tensor([[2.0, 1.0, 0.0]])
+ on_policy = torch.cat(
+ [_own_support_logps(sampler, torch.tensor([i]), 2) for i in range(2)]
+ ).exp()
+ assert on_policy.sum().item() == pytest.approx(1.0)
+
+
+def test_skipped_vllm_sync_rejects_truncated_support():
+ # LoRA / quantized without fast_inference: the sampler keeps the initial weights.
+ text = _SOURCE_PATH.read_text(encoding = "utf-8")
+ (node,) = [
+ n
+ for n in ast.parse(text).body
+ if isinstance(n, ast.FunctionDef) and n.name == "_unsloth_grpo_support_mismatch"
+ ]
+ ns = {}
+ exec(compile(ast.get_source_segment(text, node), str(_SOURCE_PATH), "exec"), ns)
+ _unsloth_grpo_support_mismatch = ns["_unsloth_grpo_support_mismatch"]
+ trainer = types.SimpleNamespace(
+ beta = 0.0,
+ num_iterations = 1,
+ args = types.SimpleNamespace(gradient_accumulation_steps = 1, steps_per_generation = 1),
+ _unsloth_vllm_sync_skip = True,
+ )
+ assert any("sync" in reason for reason in _unsloth_grpo_support_mismatch(trainer))
+ trainer._unsloth_vllm_sync_skip = False
+ assert _unsloth_grpo_support_mismatch(trainer) == []
+
+
+def _refuse_helper(monkeypatch, support):
+ text = _SOURCE_PATH.read_text(encoding = "utf-8")
+ nodes = [
+ n
+ for n in ast.parse(text).body
+ if isinstance(n, ast.FunctionDef)
+ and n.name in ("_unsloth_grpo_support_mismatch", "_unsloth_grpo_refuse_unscored_support")
+ ]
+ zoo = types.ModuleType("unsloth_zoo")
+ zoo_rl = types.ModuleType("unsloth_zoo.rl_replacements")
+ zoo_rl.grpo_truncated_support_kwargs = lambda t: dict(support)
+ zoo.rl_replacements = zoo_rl
+ monkeypatch.setitem(sys.modules, "unsloth_zoo", zoo)
+ monkeypatch.setitem(sys.modules, "unsloth_zoo.rl_replacements", zoo_rl)
+ ns = {}
+ for node in nodes:
+ exec(compile(ast.get_source_segment(text, node), str(_SOURCE_PATH), "exec"), ns)
+ return ns["_unsloth_grpo_refuse_unscored_support"]
+
+
+def test_efficient_path_refuses_the_kept_set_for_an_unsynced_sampler(monkeypatch):
+ # compute_efficient (beta = 0, vLLM) never reaches the scoring gate: the zoo loss scores the
+ # current policy, so the refusal has to be recorded on the trainer before returning.
+ refuse = _refuse_helper(monkeypatch, _SUPPORT)
+ trainer = _trainer()
+ trainer._unsloth_vllm_sync_skip = True
+ with warnings.catch_warnings(record = True) as caught:
+ warnings.simplefilter("always")
+ refuse(trainer)
+ refuse(trainer)
+ assert trainer._unsloth_truncated_support_refused is True
+ assert len(caught) == 1 and "sync" in str(caught[0].message)
+ # Synced sampler: the kept set is the sampler's, nothing is refused.
+ trainer = _trainer()
+ refuse(trainer)
+ assert not getattr(trainer, "_unsloth_truncated_support_refused", False)
+ # Opt-in off (no support kwargs): nothing to refuse.
+ refuse = _refuse_helper(monkeypatch, {})
+ trainer = _trainer()
+ trainer._unsloth_vllm_sync_skip = True
+ refuse(trainer)
+ assert not getattr(trainer, "_unsloth_truncated_support_refused", False)
diff --git a/tests/test_optimizer_state_offload.py b/tests/test_optimizer_state_offload.py
index 10f36b9bce6..48d63f11e18 100644
--- a/tests/test_optimizer_state_offload.py
+++ b/tests/test_optimizer_state_offload.py
@@ -614,6 +614,29 @@ def test_weight_quant_q_galore_restores_only_active_state(monkeypatch):
assert restored == [[active], None, None]
+def test_weight_quant_q_galore_restores_state_a_later_pre_hook_activates(monkeypatch):
+ module = _module()
+
+ class QGaLoreAdamW8bit(torch.optim.AdamW):
+ pass
+
+ QGaLoreAdamW8bit.__module__ = "unsloth.optimizers.q_galore_adamw"
+ active, idle = torch.nn.Parameter(torch.randn(16)), torch.nn.Parameter(torch.randn(16))
+ optimizer = QGaLoreAdamW8bit([{"params": [active, idle], "weight_quant": True}])
+ offloader = _hooked(module, optimizer, chunk_bytes = None)
+ restored = []
+ monkeypatch.setattr(offloader, "restore", lambda params = None: restored.append(params))
+
+ def fill_missing(optimizer, args, kwargs):
+ # A hook registered after the offloader creates the gradient the step then uses.
+ idle.grad = torch.ones_like(idle)
+
+ optimizer.register_step_pre_hook(fill_missing)
+ active.grad = torch.ones_like(active)
+ assert optimizer.step() is None
+ assert restored == [[active, idle]]
+
+
@pytest.mark.skipif(not has_real_cuda(), reason = "needs CUDA")
def test_q_galore_weight_quant_inactive_state_stays_on_host(monkeypatch):
module = _module()
@@ -706,6 +729,44 @@ def test_q_galore_multi_chunk_offload(monkeypatch, weight_quant):
assert _state_devices(optimizer) == {"cpu"}
[email protected](not has_real_cuda(), reason = "needs CUDA")
+def test_q_galore_weight_quant_later_pre_hook_gradient(monkeypatch):
+ 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": True, "stochastic_round": False}]
+ optimizer = q_galore.QGaLoreAdamW8bit(groups, lr = 1e-3)
+ q_galore.QGaLoreAdamW8bit.init_weight_quantization(torch.nn.ParameterList(params), groups)
+ if offload:
+ module.offload_optimizer_state(optimizer)
+ for _ in range(2):
+ for p in params:
+ q_galore._materialize_weight(p)
+ p.grad = torch.full_like(p, 0.01)
+ optimizer.step()
+ optimizer.zero_grad(set_to_none = True)
+
+ def fill_missing(optimizer, args, kwargs):
+ q_galore._materialize_weight(params[1])
+ params[1].grad = torch.full_like(params[1], 0.01)
+
+ optimizer.register_step_pre_hook(fill_missing)
+ q_galore._materialize_weight(params[0])
+ params[0].grad = torch.full_like(params[0], 0.01)
+ optimizer.step()
+ return params, optimizer
+
+ base, _ = run(False)
+ params, optimizer = run(True)
+ for p, q in zip(params, base):
+ assert torch.equal(p._q_data, q._q_data)
+ assert torch.equal(p._q_scales, q._q_scales)
+ assert _state_devices(optimizer) == {"cpu"}
+
+
@pytest.mark.skipif(not has_real_cuda(), reason = "needs CUDA")
def test_load_state_dict_tracks_dtensor_state_on_host():
import copy
diff --git a/unsloth/context_parallel.py b/unsloth/context_parallel.py
index b44fc969a6f..8185f2b4f43 100644
--- a/unsloth/context_parallel.py
+++ b/unsloth/context_parallel.py
@@ -537,6 +537,53 @@ def _install_fsdp2_parallelism_config(state, manager) -> None:
_INSTALLED_PARALLELISM_CONFIG[:] = [previous, pc]
+def _save_model_checks_parallelism_config_first() -> bool:
+ # transformers < 5 Trainer.save_model takes any non-None parallelism_config before FSDP.
+ try:
+ import transformers
+ from packaging.version import Version
+ return Version(transformers.__version__).major < 5
+ except Exception:
+ return False
+
+
+def _fsdp2_units_of(trainer):
+ from .models.fsdp2_save import fsdp2_units
+ return fsdp2_units(getattr(trainer, "model", None))
+
+
+def _gathered_save_model(trainer, original_save_model, args, kwargs):
+ """save_model under Unsloth's CP config on transformers < 5, which hands every rank to `_save`
+ without a state dict. Gather like Unsloth's FSDP2 save: an adapter save gathers only trainable and
+ still-saved frozen parameters, never the frozen base model (Accelerator.get_state_dict would), and a
+ SHARDED_STATE_DICT plugin still exports (clearing the config made the FSDP branch skip it)."""
+ from .models.fsdp2_save import fsdp2_gathered
+ from .save import _fsdp2_peft_saved_frozen
+
+ try:
+ from peft import PeftModel
+ except ImportError:
+ PeftModel = None
+ model = trainer.model
+ adapter = PeftModel is not None and isinstance(getattr(model, "_orig_mod", model), PeftModel)
+ include = _fsdp2_peft_saved_frozen(model, {}) if adapter else None
+ with fsdp2_gathered(model, trainable_only = adapter, include = include) as writer:
+ if writer is not False:
+ return original_save_model(trainer, *args, **kwargs)
+ # Rank 0 writes the gathered weights; the others still run save_model (a push_to_hub save is
+ # collective again) but must not write their shards.
+ missing = object()
+ previous = trainer.__dict__.get("_save", missing)
+ trainer._save = lambda *a, **k: None
+ try:
+ return original_save_model(trainer, *args, **kwargs)
+ finally:
+ if previous is missing:
+ trainer.__dict__.pop("_save", None)
+ else:
+ trainer._save = previous
+
+
def _restore_parallelism_config(state) -> None:
if _INSTALLED_PARALLELISM_CONFIG and (
getattr(state, "parallelism_config", None) is _INSTALLED_PARALLELISM_CONFIG[1]
@@ -814,8 +861,10 @@ def patch_sft_trainer(install_cp_methods: bool = False) -> None:
installed = _INSTALLED_PARALLELISM_CONFIG[1] if _INSTALLED_PARALLELISM_CONFIG else None
if installed is None or getattr(state, "parallelism_config", None) is not installed:
return original_save_model(self, *args, **kwargs)
- # transformers < 5 takes any non-None parallelism_config before FSDP and skips the FSDP2 state
- # dict gather, so save without one; even a user dp_shard config would take that branch.
+ if _save_model_checks_parallelism_config_first() and _fsdp2_units_of(self):
+ return _gathered_save_model(self, original_save_model, args, kwargs)
+ # Otherwise (transformers >= 5 checks FSDP first, or nothing FSDP2-sharded) save without the
+ # config; on transformers < 5 even a user dp_shard config would skip the FSDP branch.
state.parallelism_config = None
try:
return original_save_model(self, *args, **kwargs)
diff --git a/unsloth/kernels/fast_lora.py b/unsloth/kernels/fast_lora.py
index f4d995cf80b..daa2fb5839e 100644
--- a/unsloth/kernels/fast_lora.py
+++ b/unsloth/kernels/fast_lora.py
@@ -162,7 +162,13 @@ def _lora_dropout_and_bias(projs, X):
else:
return None, (None,) * len(projs)
dropout_p, biases = [], []
+ # Before torch 2.11 the fused Functions run Dynamo-disabled (see _apply): while compiling, a dropout
+ # module or lora_B bias keeps PEFT's traceable forward, as before they were fused, not a graph break.
+ peft_when_unplain = not TRACE_LORA_FUNCTIONS and _is_compiling()
+ has_dropout_module = False
for proj in projs:
+ if peft_when_unplain and not _is_plain_lora(proj):
+ return None
adapter = _active_lora_adapter(proj)
if adapter is None:
# Enabled adapter missing from this projection: PEFT runs the base layer alone.
@@ -171,6 +177,12 @@ def _lora_dropout_and_bias(projs, X):
dropout_p.append(0.0)
biases.append(None)
continue
+ dropout = getattr(proj, "lora_dropout", None)
+ has_dropout_module |= (
+ dropout is not None
+ and adapter in dropout
+ and type(dropout[adapter]) is not torch.nn.Identity
+ )
p = _lora_dropout_p(proj, X, adapter)
if p is None:
return None
@@ -178,7 +190,10 @@ def _lora_dropout_and_bias(projs, X):
biases.append(proj.lora_B[adapter].bias)
if any(lora_bias_blocks_fused(proj) for proj in projs):
return None
- return (tuple(dropout_p) if any(dropout_p) else None), tuple(biases)
+ # A dropout module in eval (p = 0) keeps the dropout route, so it still skips the global
+ # dequantization scratch the plain path keeps resident.
+ keep = any(dropout_p) or has_dropout_module
+ return (tuple(dropout_p) if keep else None), tuple(biases)
def _dropout_forward(X, p):
@@ -208,9 +223,10 @@ def _dropout_replay(
def _matmul_lora_ext(X, X_lora, W, W_quant, A, B, S, bias):
# matmul_lora with the LoRA branch reading X_lora (X after dropout, or X itself) plus lora_B's bias.
+ # No global dequantization scratch: these configurations ran PEFT, which keeps no dense weight resident.
if A is None or (X_lora is X and bias is None):
- return matmul_lora(X, W, W_quant, A, B, S)
- out = matmul_lora(X, W, W_quant, None, None, None)
+ return matmul_lora(X, W, W_quant, A, B, S, use_global_buffer = False)
+ out = matmul_lora(X, W, W_quant, None, None, None, use_global_buffer = False)
dtype = X.dtype
XA = torch.matmul(X_lora.reshape(-1, X_lora.shape[-1]), A.to(dtype).t())
out2d = out.view(-1, out.shape[-1])
@@ -317,7 +333,8 @@ class LoRA_MLP(torch.autograd.Function):
):
dtype = X.dtype
- if dropout_p is None and gateBias is None and upBias is None and downBias is None:
+ plain = dropout_p is None and gateBias is None and upBias is None and downBias is None
+ if plain:
e = matmul_lora(X, gateW, gateW_quant, gateA, gateB, gateS)
g = matmul_lora(X, upW, upW_quant, upA, upB, upS)
h = _forward_function(e, g)
@@ -354,6 +371,7 @@ class LoRA_MLP(torch.autograd.Function):
ctx.inplace = inplace and (not _rms_layernorm._SAVE_OUTPUT or _may_overwrite_input(X))
ctx.dropout_p = dropout_p or (0.0, 0.0, 0.0)
ctx.biases = (gateBias is not None, upBias is not None, downBias is not None)
+ ctx.global_buffer = plain
return i
@staticmethod
@@ -407,10 +425,18 @@ class LoRA_MLP(torch.autograd.Function):
else:
downW = downW.t()
if down_mask is None:
- DW = matmul_lora(dY, downW, downW_quant, downB, downA, downS)
+ DW = matmul_lora(
+ dY,
+ downW,
+ downW_quant,
+ downB,
+ downA,
+ downS,
+ use_global_buffer = getattr(ctx, "global_buffer", True),
+ )
else:
# Only the LoRA branch saw the dropped out h, so only its gradient goes through the mask.
- DW = matmul_lora(dY, downW, downW_quant, None, None, None)
+ DW = matmul_lora(dY, downW, downW_quant, None, None, None, use_global_buffer = False)
down_mask = down_mask.view(-1, down_mask.shape[-1])
DW.add_(_dropout_replay((dY @ downB.t()) @ downA.t(), down_mask, down_p, downS))
del downW
diff --git a/unsloth/kernels/utils.py b/unsloth/kernels/utils.py
index 625a067fa38..b78385f5efd 100644
--- a/unsloth/kernels/utils.py
+++ b/unsloth/kernels/utils.py
@@ -1696,6 +1696,7 @@ def matmul_lora(
B,
s,
out = None,
+ use_global_buffer = True,
):
dtype = X.dtype
@@ -1722,7 +1723,7 @@ def matmul_lora(
elif _is_packed_state(W_quant):
out = W_quant.matmul(X, W, out = out)
else:
- W = fast_dequantize(W, W_quant, use_global_buffer = True)
+ W = fast_dequantize(W, W_quant, use_global_buffer = use_global_buffer)
out = torch_matmul(X, W.t(), out = out)
if W_quant is not None:
del W
diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py
index c37c301c547..1709cd1243c 100644
--- a/unsloth/models/rl_replacements.py
+++ b/unsloth/models/rl_replacements.py
@@ -1218,6 +1218,64 @@ def _unsloth_grpo_autocast_kwargs(self, device_type = DEVICE_TYPE_TORCH):
return {"enabled": enabled, "dtype": dtype}
+def _unsloth_grpo_refuse_unscored_support(self):
+ """With compute_efficient no old / ref logps are scored here, so the gate below in
+ _get_per_token_logps_and_entropies never runs, and the zoo loss scores the current policy over
+ its own kept set against vLLM's logprobs. When that set cannot be the sampler's (an unsynced
+ vLLM sampler, a reference model, reused rollouts), mark the trainer refused, which the zoo loss
+ honours by scoring the full vocabulary."""
+ if getattr(self, "_unsloth_truncated_support_refused", False):
+ return
+ try:
+ from unsloth_zoo.rl_replacements import grpo_truncated_support_kwargs
+ if not grpo_truncated_support_kwargs(self):
+ return
+ except Exception:
+ return
+ mismatch = _unsloth_grpo_support_mismatch(self)
+ if mismatch:
+ import warnings
+ warnings.warn(
+ "Unsloth: ignoring UNSLOTH_GRPO_TRUNCATED_SUPPORT=1 because "
+ f"{', '.join(mismatch)}: the scored policy is not the sampler, so its top_k / top_p / "
+ "min_p kept set differs from vLLM's and the PPO ratio would be unnormalised. "
+ "Scoring over the full vocabulary instead.",
+ stacklevel = 2,
+ )
+ self._unsloth_truncated_support_refused = True
+
+
+def _unsloth_grpo_support_mismatch(self):
+ """Why UNSLOTH_GRPO_TRUNCATED_SUPPORT=1 cannot score this trainer, or [] when it can.
+
+ Each scoring call rebuilds the top_k / top_p / min_p kept set from its own logits and always keeps the
+ scored token. That is the sampler's set only while the scored weights are the rollout's. A reference
+ model (beta != 0), or old logps TRL keeps because generation is not aligned to the optimizer step
+ (gradient_accumulation_steps % (steps_per_generation * num_iterations) != 0), keeps another set: a
+ token outside it gets a denominator that depends on the scored token, so the implied probabilities do
+ not sum to 1 and the PPO ratio / KL inputs are wrong. A shared set would need the sampler's kept ids.
+ """
+ reasons = []
+ if getattr(self, "_unsloth_vllm_sync_skip", False):
+ reasons.append("vLLM weight sync is skipped, so rollouts use the initial weights")
+ beta = getattr(self, "beta", 0.0)
+ if beta is not None and float(beta) != 0.0:
+ reasons.append(f"beta={beta} scores a reference model")
+ args = getattr(self, "args", None)
+ accumulation = int(getattr(args, "gradient_accumulation_steps", 1) or 1)
+ steps_per_generation = int(getattr(args, "steps_per_generation", None) or accumulation)
+ num_iterations = getattr(self, "num_iterations", None)
+ if num_iterations is None:
+ num_iterations = getattr(args, "num_iterations", 1)
+ num_iterations = int(num_iterations or 1)
+ if accumulation % (steps_per_generation * num_iterations) != 0:
+ reasons.append(
+ f"num_iterations={num_iterations} / steps_per_generation={steps_per_generation} "
+ f"reuse rollouts across optimizer steps"
+ )
+ return reasons
+
+
def _unsloth_grpo_accumulation_steps(trainer):
"""Gradient accumulation divisor for the GRPO loss. 1 whenever the model is not training.
@@ -2498,6 +2556,8 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function):
if compute_efficient:
# No scoring forward may run (vLLM, beta = 0): latch precision here, not from the shared env.
_unsloth_grpo_autocast_unscored(self)
+ # The current policy is then scored only in the zoo loss: refuse the kept set there too.
+ _unsloth_grpo_refuse_unscored_support(self)
return None, None
else:
_unsloth_grpo_autocast(self)
@@ -2582,6 +2642,22 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function):
_support_kwargs = grpo_truncated_support_kwargs(self)
except Exception:
_support_kwargs = {}
+ _support_mismatch = _unsloth_grpo_support_mismatch(self) if _support_kwargs else []
+ if _support_mismatch:
+ # Left unmarked, the zoo loss drops the kept set for the current policy as well.
+ if not getattr(self, "_unsloth_truncated_support_refused", False):
+ import warnings
+ warnings.warn(
+ "Unsloth: ignoring UNSLOTH_GRPO_TRUNCATED_SUPPORT=1 because "
+ f"{', '.join(_support_mismatch)}: those logprobs come from weights other "
+ "than the rollout's, whose top_k / top_p / min_p kept set differs from the "
+ "sampler's, so per-policy kept sets give unnormalised PPO ratios and KL. "
+ "Scoring over the full vocabulary instead.",
+ stacklevel = 2,
+ )
+ # Also silences the zoo's refusal, which would blame the unsloth version.
+ self._unsloth_truncated_support_refused = True
+ _support_kwargs = {}
if _support_kwargs:
from functools import partial
@@ -3592,6 +3668,8 @@ RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_autocast_for
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_autocast))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_autocast_unscored))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_autocast_kwargs))
+RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_support_mismatch))
+RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_refuse_unscored_support))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_get_model_config))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_text_configs))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_get_final_logit_softcapping))
diff --git a/unsloth/optimizers/state_offload.py b/unsloth/optimizers/state_offload.py
index 0711dd0f5b0..087a1c76902 100644
--- a/unsloth/optimizers/state_offload.py
+++ b/unsloth/optimizers/state_offload.py
@@ -294,17 +294,28 @@ class _StateOffloader:
closure = rest[0] if rest else kwargs.get("closure")
# A closure recomputes the loss on every call, so it must run once over all parameters.
if closure is not None or not _chunk_safe(optimizer):
- params = None
- if closure is None and _grad_only_step(optimizer):
- # Unchunked weight_quant Q-GaLore still skips parameters without a gradient.
- params = [
- p
- for group in optimizer.param_groups
- for p in group["params"]
- if p.grad is not None
- ]
- self.restore(params)
- return
+ if closure is not None or not _grad_only_step(optimizer):
+ self.restore()
+ return
+
+ # Unchunked weight_quant Q-GaLore still skips parameters without a gradient. Select
+ # them from the step's closure, after later pre hooks that may create gradients.
+ def _restore_active():
+ self.restore(
+ [
+ p
+ for group in optimizer.param_groups
+ for p in group["params"]
+ if p.grad is not None
+ ]
+ )
+ return None
+
+ if rest:
+ rest = (_restore_active,) + tuple(rest[1:])
+ else:
+ kwargs = dict(kwargs, closure = _restore_active)
+ return ((optimizer,) + tuple(rest) if has_self else tuple(rest)), kwargs
# Chunk-safe steps call a closure first, before any update, so the chunked updates run
# after every step pre hook (registered later ones too), as a plain step would.