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 accumulate test: compare in-place against grad + dW, check the exact 1 on CUDA only (#15254)

Daniel Hanb8e8cd7a078e
diff --git a/tests/test_moe_dw_accumulate.py b/tests/test_moe_dw_accumulate.py
index e9096fbe872..2a754ca64ca 100644
--- a/tests/test_moe_dw_accumulate.py
+++ b/tests/test_moe_dw_accumulate.py
@@ -566,7 +566,6 @@ def test_fsdp2_no_sync_gradient_accumulation(tmp_path):
def test_existing_gradient_survives_in_microbatch_cancellation(monkeypatch):
- monkeypatch.setenv("UNSLOTH_MOE_DW_ACCUMULATE", "1")
E, N, K, T = 1, 64, 64, 128
dtype, big = torch.bfloat16, 1e4
X = torch.zeros(T, K, device = DEV, dtype = dtype)
@@ -576,11 +575,20 @@ def test_existing_gradient_survives_in_microbatch_cancellation(monkeypatch):
m_sizes = torch.tensor([T], device = DEV, dtype = torch.int32)
gather = torch.arange(T, device = DEV, dtype = torch.int32)
W = _param(E, N, K, dtype)
- W.grad = torch.ones_like(W)
- before = gg.DW_ACCUMULATE_STATS["inplace"]
- _gemm(X, W, m_sizes, gather, 1, "none", _cfgs()).backward(G)
- assert gg.DW_ACCUMULATE_STATS["inplace"] == before + 1
- assert torch.equal(W.grad, torch.ones_like(W))
+ grads = {}
+ for inplace in ("1", "0"):
+ monkeypatch.setenv("UNSLOTH_MOE_DW_ACCUMULATE", inplace)
+ W.grad = torch.ones_like(W)
+ before = gg.DW_ACCUMULATE_STATS["inplace"]
+ _gemm(X, W, m_sizes, gather, 1, "none", _cfgs()).backward(G)
+ assert gg.DW_ACCUMULATE_STATS["inplace"] == before + (inplace == "1")
+ grads[inplace] = W.grad.clone()
+ # The existing gradient is added after the reduction, exactly as grad + dW: folded in before it,
+ # the 1 would be lost against the 1e8 partial sum. gfx1151's MFMA leaves the cancelled dW at -4
+ # rather than 0 (4e-8 of the partials) in both arms, so only CUDA checks the absolute value.
+ assert torch.equal(grads["1"], grads["0"])
+ if torch.version.hip is None:
+ assert torch.equal(grads["1"], torch.ones_like(W))
def test_side_stream_use_keeps_the_returned_gradient_path(monkeypatch):