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
Routing replay: score named PEFT reference adapters with their own routing (#15387)
Daniel Han0993cc111688
diff --git a/tests/test_grpo_routing_replay_trainer_hooks.py b/tests/test_grpo_routing_replay_trainer_hooks.pyindex bdd632e8e2d..c4327fd755a 100644--- a/tests/test_grpo_routing_replay_trainer_hooks.py+++ b/tests/test_grpo_routing_replay_trainer_hooks.py@@ -330,3 +330,77 @@ def test_router_that_cannot_be_primed_loses_its_hook_with_a_warning(replay):assert not model.model.layers[0].mlp.gate._forward_hooksassert model.model.layers[1].mlp.gate._forward_hooksassert getattr(model.model.layers[1].mlp.gate, "_unsloth_replay_formula", None) is not None+++def _use_adapter(model, adapter_name):+ try:+ from trl.trainer.utils import use_adapter+ except Exception:+ use_adapter = None+ if use_adapter is not None:+ return use_adapter(model, adapter_name)+ import contextlib++ @contextlib.contextmanager+ def fallback():+ previous = model.active_adapter+ model.set_adapter(adapter_name)+ try:+ yield+ finally:+ model.set_adapter(previous)++ return fallback()+++def test_named_reference_adapter_routes_naturally(replay):+ peft = pytest.importorskip("peft")+ base = _moe()+ ids = [5, 6, 7, 30, 31, 32]+ natural_logits, natural_ids = _natural(base, ids)+ config = peft.LoraConfig(r = 4, target_modules = ["q_proj", "v_proj"])+ model = peft.get_peft_model(base, config)+ model.add_adapter("ref", config)+ for name, param in model.named_parameters():+ if ".default." in name:+ model.get_parameter(name.replace(".default.", ".ref.")).data.copy_(param.data)+ model.set_adapter("default")+ model.vllm_engine = None+ _run_post_init(model)+ decoder = model.base_model.model.model+ routers = [layer.mlp.gate for layer in decoder.layers]+ tables = lambda: [+ (dict(m._forward_hooks), dict(m._forward_pre_hooks), dict(m._forward_pre_hooks_with_kwargs))+ for m in [decoder, *decoder.layers, *routers]+ ]+ hooks_before = tables()+ assert all(r._forward_hooks for r in routers)++ forced = ((natural_ids + 3) % EXPERTS).numpy().astype(np.int16)+ rr.record_routed_experts(+ [+ SimpleNamespace(+ prompt_token_ids = ids[:3],+ outputs = [SimpleNamespace(token_ids = ids[3:], routed_experts = forced[:-1])],+ )+ ],+ pad_token_id = PAD,+ )+ x = torch.tensor([ids])+ with torch.no_grad():+ policy = model(input_ids = x).logits+ assert not torch.allclose(policy, natural_logits, atol = 1e-4)+ model.set_adapter("default")+ torch.testing.assert_close(model(input_ids = x).logits, policy, rtol = 0, atol = 0)+ with _use_adapter(model, "ref"):+ reference = model(input_ids = x).logits+ assert all(not r._forward_hooks for r in routers)+ with model.disable_adapter():+ disabled = model(input_ids = x).logits+ assert all(not r._forward_hooks for r in routers)+ # "ref" is a copy of "default" (LoRA B at zero): its own routing is the natural one.+ torch.testing.assert_close(reference, natural_logits, rtol = 1e-5, atol = 1e-6)+ torch.testing.assert_close(disabled, natural_logits, rtol = 1e-5, atol = 1e-6)+ again = model(input_ids = x).logits+ torch.testing.assert_close(again, policy, rtol = 0, atol = 0)+ assert tables() == hooks_beforediff --git a/unsloth/models/_routing_replay.py b/unsloth/models/_routing_replay.pyindex 1d4030ffbc2..5a3b013bc85 100644--- a/unsloth/models/_routing_replay.py+++ b/unsloth/models/_routing_replay.py@@ -18,8 +18,9 @@ Only used when routing replay is requested. Two things the zoo hooks need from t- their routing weight formula is picked from the first replayed router call, which reads tensorvalues; done inside a compiled region that is a graph break (fullgraph fails), so it is pickedhere once, eagerly, right after the hooks are installed;-- PEFT reference scoring (`disable_adapter()`) must see the base model's own routing, as a separate- reference model does, so the hooks are detached inside that context.+- PEFT reference scoring (`disable_adapter()`, or a named reference adapter made active with+ `set_adapter()`) must see the reference's own routing, as a separate reference model does, so the+ hooks are detached while it scores."""import contextlib@@ -55,10 +56,8 @@ def _new_hooks(model, before):return hooks-def _detached(hooks):- # Hook order is call order, and ids do not give it (register_*_hook(prepend = True) puts a newer- # id first): keep each table's own key order and put it back exactly.+def _detach(hooks):+ # Keep each table's key order: ids do not give call order (prepend = True).orders = {}removed = []for module, name, extras, hook_id in hooks:@@ -67,19 +66,55 @@ def _detached(hooks):continueorders.setdefault(id(table), (table, list(table.keys())))removed.append((table, hook_id, table.pop(hook_id)))+ return orders, removed+++def _reattach(detached):+ orders, removed = detached+ for table, hook_id, value in removed:+ table[hook_id] = value+ for table, order in orders.values():+ known = set(order)+ added = [k for k in table if k not in known] # registered while detached: keep last+ items = dict(table)+ table.clear()+ for k in order + added:+ if k in items:+ table[k] = items[k]+++class _ReplayDetacher:+ """Replay hooks stay off while any reason holds (disabled adapter or non-policy set_adapter)."""++ def __init__(self, hooks):+ self.hooks = hooks+ self.reasons = []+ self.detached = None++ def push(self, reason):+ self.reasons.append(reason)+ if self.detached is None:+ self.detached = _detach(self.hooks)++ def pop(self, reason):+ if reason in self.reasons:+ self.reasons.remove(reason)+ if not self.reasons and self.detached is not None:+ detached, self.detached = self.detached, None+ _reattach(detached)+++def _active_adapters(model):try:- yield- finally:- for table, hook_id, value in removed:- table[hook_id] = value- for table, order in orders.values():- known = set(order)- added = [k for k in table if k not in known] # registered inside the context: keep last- items = dict(table)- table.clear()- for k in order + added:- if k in items:- table[k] = items[k]+ active = model.active_adapter+ except Exception:+ return None+ if isinstance(active, str):+ return frozenset((active,))+ try:+ return frozenset(active)+ except TypeError:+ return Nonedef _router_extra_args(module, parent):@@ -202,7 +237,8 @@ def _remove_hook(module, name, extras, hook_id):def prepare_routing_replay(model, before):"""After install_routing_replay(model, ...): prime the router formulas outside compilation and- detach the replay hooks during `model.disable_adapter()` (PEFT reference scoring). A router that+ detach the replay hooks during `model.disable_adapter()` and while `model.set_adapter()` leaves a+ non-policy adapter active (PEFT reference scoring). A router thatcannot be primed loses its replay hook (it keeps its natural routing) with a warning, ratherthan reaching the data dependent formula pick inside a compiled graph. Returns the number ofreplay hooks left (0 when routing replay installed nothing)."""@@ -249,14 +285,48 @@ def prepare_routing_replay(model, before):stacklevel = 2,)+ detacher = getattr(model, "_unsloth_routing_replay_detacher", None)+ if detacher is None:+ detacher = _ReplayDetacher(hooks)+ try:+ model._unsloth_routing_replay_detacher = detacher+ except Exception:+ pass+disable_adapter = getattr(model, "disable_adapter", None)if callable(disable_adapter) and not getattr(disable_adapter, "_unsloth_routing_replay", False):@contextlib.contextmanagerdef disable_adapter_without_replay(*args, **kwargs):- with disable_adapter(*args, **kwargs), _detached(hooks):- yield+ with disable_adapter(*args, **kwargs):+ detacher.push("disable_adapter")+ try:+ yield+ finally:+ detacher.pop("disable_adapter")disable_adapter_without_replay._unsloth_routing_replay = Truemodel.disable_adapter = disable_adapter_without_replay++ # TRL use_adapter(model, "ref") calls set_adapter: score it with natural routing like disable_adapter().+ policy = _active_adapters(model)+ set_adapter = getattr(model, "set_adapter", None)+ if (+ policy+ and callable(set_adapter)+ and not getattr(set_adapter, "_unsloth_routing_replay", False)+ ):++ def set_adapter_without_replay(*args, **kwargs):+ out = set_adapter(*args, **kwargs)+ active = _active_adapters(model)+ if active is not None and active != policy:+ if "set_adapter" not in detacher.reasons:+ detacher.push("set_adapter")+ else:+ detacher.pop("set_adapter")+ return out++ set_adapter_without_replay._unsloth_routing_replay = True+ model.set_adapter = set_adapter_without_replayreturn len(hooks)