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.

MoE dW accumulation: fall back when autograd Node hooks can rewrite dW (#14759)

Daniel Han7de9c3bc096b
diff --git a/tests/test_moe_dw_accumulate_node_hooks.py b/tests/test_moe_dw_accumulate_node_hooks.py
new file mode 100644
index 00000000000..a566235e679
--- /dev/null
+++ b/tests/test_moe_dw_accumulate_node_hooks.py
@@ -0,0 +1,133 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""In-place dW accumulation must not bypass hooks registered on autograd Nodes.
+
+A prehook on the weight's AccumulateGrad node, or a post hook on the GroupedGemmBackward node, may
+rewrite dW before it reaches param.grad. Both must see the same gradient as the returned-gradient
+path (UNSLOTH_MOE_DW_ACCUMULATE=0). Runs on CPU: the Triton GEMMs are swapped for dense matmuls and
+the stream queries are mocked, so the autograd wrapper and the selector are the real code."""
+
+import importlib
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+
+torch = pytest.importorskip("torch")
+pytest.importorskip("triton")
+
+
+def gg(monkeypatch):
+ stubs = {
+ "unsloth": ROOT / "unsloth",
+ "unsloth.kernels": ROOT / "unsloth" / "kernels",
+ "unsloth.kernels.moe": ROOT / "unsloth" / "kernels" / "moe",
+ }
+ for name, path in stubs.items():
+ pkg = types.ModuleType(name)
+ pkg.__path__ = [str(path)]
+ monkeypatch.setitem(sys.modules, name, pkg)
+ sys.modules["unsloth"].DEVICE_TYPE = "cuda"
+ device_type = types.ModuleType("unsloth.device_type")
+ device_type.cuda_visible_capabilities = lambda: ()
+ monkeypatch.setitem(sys.modules, device_type.__name__, device_type)
+ utils = types.ModuleType("unsloth.kernels.utils")
+ utils.torch_gpu_device = lambda device: torch.cuda.device(device)
+ monkeypatch.setitem(sys.modules, utils.__name__, utils)
+ for name in list(sys.modules):
+ if name.startswith("unsloth.kernels.moe."):
+ monkeypatch.delitem(sys.modules, name)
+ try:
+ module = importlib.import_module("unsloth.kernels.moe.grouped_gemm.interface")
+ except Exception as e: # pragma: no cover - depends on the installed Triton
+ pytest.skip(f"grouped_gemm interface is unimportable here: {type(e).__name__}: {e}")
+
+ # Single expert, dense CPU arithmetic in place of the Triton launches.
+ def fwd(X, W, **kw):
+ return X @ W[0].T
+
+ def dX(dY, W, **kw):
+ return dY @ W[0]
+
+ def dense_dW(X, dY, dW_dtype = None, **kw):
+ return (dY.T @ X).unsqueeze(0).to(dW_dtype or X.dtype)
+
+ def dW_accumulate(dW, **kw):
+ dW.add_(dense_dW(**kw).to(dW.dtype))
+
+ monkeypatch.setattr(module, "grouped_gemm_forward", fwd)
+ monkeypatch.setattr(module, "grouped_gemm_dX", dX)
+ monkeypatch.setattr(module, "grouped_gemm_dW", dense_dW)
+ monkeypatch.setattr(module, "grouped_gemm_dW_accumulate", dW_accumulate)
+ monkeypatch.setattr(torch.cuda, "current_stream", lambda *a, **k: 0)
+ monkeypatch.setattr(torch.cuda, "default_stream", lambda *a, **k: 0)
+ yield module
+ for name in list(sys.modules):
+ if name.startswith("unsloth.kernels.moe."):
+ sys.modules.pop(name, None)
+
+
+def _cfg():
+ return types.SimpleNamespace(
+ use_tma_load_x = False, use_tma_load_w = False, use_tma_load_dy = False,
+ use_tma_store = False, BLOCK_SIZE_M = 32, BLOCK_SIZE_N = 32, BLOCK_SIZE_K = 32,
+ num_warps = 4, num_stages = 2,
+ ) # fmt: skip
+
+
+def _scale(g, k):
+ return None if g is None else g * k
+
+
+def _run(gg, monkeypatch, enabled, hook = None):
+ monkeypatch.setenv("UNSLOTH_MOE_DW_ACCUMULATE", "1" if enabled else "0")
+ gen = torch.Generator().manual_seed(0)
+ X = torch.randn(4, 3, generator = gen, requires_grad = True)
+ W = torch.nn.Parameter(torch.randn(1, 2, 3, generator = gen))
+ W.grad = torch.randn(1, 2, 3, generator = gen)
+ G = torch.randn(4, 2, generator = gen)
+ cfg = _cfg()
+ Y = gg.GroupedGemm.apply(
+ X, W, torch.tensor([4]), 1, None, False, False, None, False, cfg, cfg, cfg, False, False, False
+ )
+ handle = None
+ if hook == "acc_prehook":
+ handle = Y.grad_fn.next_functions[1][0].register_prehook(lambda gs: (_scale(gs[0], 2),))
+ elif hook == "node_posthook":
+ handle = Y.grad_fn.register_hook(lambda gi, go: (gi[0], _scale(gi[1], 3)) + tuple(gi[2:]))
+ elif hook == "tensor_hook":
+ handle = W.register_hook(lambda g: g * 5)
+ elif hook == "removed":
+ Y.grad_fn.next_functions[1][0].register_prehook(lambda gs: (gs[0] * 2,)).remove()
+ Y.grad_fn.register_hook(lambda gi, go: None).remove()
+ before = dict(gg.DW_ACCUMULATE_STATS)
+ Y.backward(G)
+ after = gg.DW_ACCUMULATE_STATS
+ path = "inplace" if after["inplace"] > before["inplace"] else "fallback"
+ if handle is not None:
+ handle.remove()
+ return W.grad.clone(), X.grad.clone(), path
+
+
[email protected]("hook", ["acc_prehook", "node_posthook", "tensor_hook"])
+def test_hooked_weight_matches_returned_gradient_path(gg, monkeypatch, hook):
+ ref_w, ref_x, ref_path = _run(gg, monkeypatch, enabled = False, hook = hook)
+ out_w, out_x, path = _run(gg, monkeypatch, enabled = True, hook = hook)
+ assert ref_path == "fallback"
+ torch.testing.assert_close(out_w, ref_w, rtol = 0, atol = 0)
+ torch.testing.assert_close(out_x, ref_x, rtol = 0, atol = 0)
+ assert path == "fallback"
+
+
[email protected]("hook", [None, "removed"])
+def test_unhooked_weight_still_accumulates_in_place(gg, monkeypatch, hook):
+ ref_w, ref_x, _ = _run(gg, monkeypatch, enabled = False, hook = hook)
+ out_w, out_x, path = _run(gg, monkeypatch, enabled = True, hook = hook)
+ assert path == "inplace"
+ torch.testing.assert_close(out_w, ref_w)
+ torch.testing.assert_close(out_x, ref_x, rtol = 0, atol = 0)
diff --git a/unsloth/kernels/moe/grouped_gemm/interface.py b/unsloth/kernels/moe/grouped_gemm/interface.py
index 7dd35b673dc..372304c0bbd 100644
--- a/unsloth/kernels/moe/grouped_gemm/interface.py
+++ b/unsloth/kernels/moe/grouped_gemm/interface.py
@@ -988,10 +988,9 @@ def _dW_accumulate_enabled():
def _dW_accumulate_target(ctx, X, autotune):
"""The leaf parameter whose existing .grad the dW kernel may add into, else None.
- Any case where AccumulateGrad would do more than `param.grad += dW` falls back to returning dW.
- Hooks registered directly on autograd Nodes (Node.register_hook / register_prehook) cannot be
- enumerated from Python and see None for W here; UNSLOTH_MOE_DW_ACCUMULATE=0 restores the
- returned-gradient path."""
+ Any case where AccumulateGrad would do more than `param.grad += dW` falls back to returning dW,
+ including Node hooks that can rewrite dW: prehooks on W's AccumulateGrad and post hooks on this
+ GroupedGemmBackward. Post hooks on AccumulateGrad only observe (they see None for this dW)."""
if torch.compiler.is_compiling() or _is_tracing(X) or torch.is_grad_enabled():
return None
# Anomaly mode checks the returned gradients for NaN; an in-place add returns None for W.
@@ -1032,9 +1031,34 @@ def _dW_accumulate_target(ctx, X, autotune):
return None
except RuntimeError:
return None # autograd.grad(): W's gradient is captured, never accumulated
+ # Last: the only checks that cost Python work, so they run only for an otherwise eligible weight.
+ if _node_has_python_hooks(acc.register_prehook) or _node_has_python_hooks(ctx.register_hook):
+ return None
return param
+def _node_hook_probe(*args):
+ return None
+
+
+def _node_has_python_hooks(register):
+ """True if the Node behind `register` (register_hook / register_prehook) already holds a Python hook.
+
+ Nodes cannot list their hooks, but every Python hook of one kind shares a single dict, and the
+ handle of a new registration points at it: register a no-op, count, remove it again."""
+ try:
+ handle = register(_node_hook_probe)
+ except Exception:
+ return True
+ try:
+ hooks = handle.hooks_dict_ref()
+ return hooks is None or len(hooks) > 1
+ except Exception:
+ return True
+ finally:
+ handle.remove()
+
+
class GroupedGemm(torch.autograd.Function):
@staticmethod
def forward(