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.

PPO / RLOO fused log-probs: fall back under torch global module hooks (#17043)

Daniel Han0148e62926d5
diff --git a/tests/test_ppo_fused_logprobs.py b/tests/test_ppo_fused_logprobs.py
index 3e36a636d79..c19d2ba5c92 100644
--- a/tests/test_ppo_fused_logprobs.py
+++ b/tests/test_ppo_fused_logprobs.py
@@ -497,3 +497,29 @@ def test_ppo_hooked_head_keeps_trl():
route, trainer = _route(model)
assert route is None
assert "output head has hooks or a patched forward" in trainer._unsloth_ppo_fused_fallbacks
+
+
+ "register",
+ [
+ "register_module_forward_hook",
+ "register_module_forward_pre_hook",
+ "register_module_full_backward_hook",
+ "register_module_full_backward_pre_hook",
+ ],
+)
+def test_ppo_global_module_hooks_keep_trl(register):
+ """torch's global module hooks would never see a head the fused kernel reads directly."""
+ from torch.nn.modules import module as module_hooks
+
+ module = _ppo_module()
+ model = _wrapper(module, _Policy())
+ assert _route(model)[0] is not None
+ handle = getattr(module_hooks, register)(lambda *a: None)
+ try:
+ route, trainer = _route(model)
+ finally:
+ handle.remove()
+ assert route is None
+ assert "output head has hooks or a patched forward" in trainer._unsloth_ppo_fused_fallbacks
+ assert _route(model)[0] is not None
diff --git a/unsloth/models/_fused_rl_logprobs.py b/unsloth/models/_fused_rl_logprobs.py
index d5ac2bafa2a..7b1e4155bab 100644
--- a/unsloth/models/_fused_rl_logprobs.py
+++ b/unsloth/models/_fused_rl_logprobs.py
@@ -70,9 +70,13 @@ def fused_head(model):
head = _unsloth_gkd_dense_head(model)
if head is None:
return None, None, "output head is not a dense nn.Linear"
- # The kernel reads weight / bias directly: a hooked head is not F.linear(h, W, b).
+ # The kernel reads weight / bias directly: a hooked head (its own or torch's global module hooks) is not
+ # F.linear(h, W, b).
+ from .dpo import _global_module_hooks
+
if (
- hasattr(head, "_hf_hook")
+ _global_module_hooks()
+ or hasattr(head, "_hf_hook")
or "forward" in vars(head)
or head._forward_hooks
or head._forward_pre_hooks