Repository navigation
MoE grouped GEMM: accumulate expert dW into an existing param.grad - #14480
Conversation
When an expert weight already holds a gradient (gradient accumulation micro-steps after the first, zero_grad(set_to_none=False)), the Triton dW kernel now reads the existing grad tile, adds in fp32 and rounds once, and backward returns None for W. This drops the (E, N, K) dW temporary and the AccumulateGrad add kernel. Falls back to the returned-gradient path under torch.compile, autograd.grad, backward(inputs=) without W, create_graph, tensor or post-accumulate hooks, non-leaf or subclass weights, autotune, and UNSLOTH_MOE_DW_ACCUMULATE=0. The fresh path also writes the weight dtype directly when activations are wider (bf16 experts on fp32 hidden states), which rounds identically to the old cast.
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1b37e2cbf6
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| buffer, so there is nothing to save), tensor hooks, layout or dtype mismatch, autotune. | ||
| The grad may be narrower than X (bf16 weights, fp32 activations): the add still runs in fp32. | ||
| """ | ||
| if torch.compiler.is_compiling() or _is_tracing(X) or torch.is_grad_enabled(): |
There was a problem hiding this comment.
Disable in-place accumulation under anomaly detection
When torch.autograd.detect_anomaly() is active and the parameter already has an eligible .grad, this predicate still selects the in-place path. If the dW kernel produces NaNs (especially with dW_only=True), backward returns None for W, so autograd has no gradient output on which to perform its anomaly check and training continues with a corrupted gradient instead of raising. Include torch.is_anomaly_enabled() among the fallback conditions.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 40e1fae: torch.is_anomaly_enabled() now takes the returned-gradient path, so anomaly mode sees W's gradient. Covered in test_hooks_create_graph_kill_switch_and_non_leaf_fall_back (fails without the check).
| # Already in param.grad: returning it as well would add it twice. | ||
| dW = None |
There was a problem hiding this comment.
Preserve hooks registered directly on autograd nodes
When an eligible parameter already has a gradient, a caller may still have registered a hook or pre-hook directly on Y.grad_fn or W's AccumulateGrad node via the public Node.register_hook/register_prehook APIs. Those hooks are not represented by the parameter's _backward_hooks dictionaries checked above, so the kernel mutates .grad before they run and returning None here prevents them from observing or replacing the W gradient; hooks that transform the gradient are silently ignored and hooks expecting a tensor may fail. This path must fall back whenever either relevant autograd node has such hooks, or otherwise preserve their processing before modifying .grad.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing this one. Hooks registered with Node.register_hook / register_prehook live in the C++ node and cannot be enumerated from Python, so there is nothing to test against short of patching those methods globally. Tensor hooks and post-accumulate hooks on the parameter (what FSDP2, compiled DDP and optimizer-in-backward use) are detected and fall back; AccumulateGrad post-hooks that read param.grad (the DDP reducer, tested with 2 ranks) still run and see the accumulated gradient. A node hook that rewrites W's gradient on these internal MoE nodes would need graph walking; for that case UNSLOTH_MOE_DW_ACCUMULATE=0 restores the old path, and the docstring now says so.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 40e1faede5
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| grouped_gemm_dW_accumulate( | ||
| X = X, | ||
| dY = dY, | ||
| m_sizes = m_sizes, | ||
| gather_indices = gather_indices, | ||
| dW = target.grad, |
There was a problem hiding this comment.
Avoid racing tied-weight accumulation across CUDA streams
When the same expert weight is used by grouped GEMMs whose forwards were recorded on different CUDA streams, autograd may run their backward functions on those respective streams before the shared AccumulateGrad join. Each call here then launches an unsynchronized read-modify-write into the same target.grad, so concurrent kernels can overwrite one another and silently drop a tied-weight contribution. The returned-gradient path avoids this by writing separate buffers and joining them at AccumulateGrad; this optimization needs equivalent stream serialization or must fall back for multi-stream graphs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6b1bd9e: the forward marks a weight used on a non-default CUDA stream, and every backward of that weight (and any backward running on a non-default stream) takes the returned-gradient path, so tied uses on different streams join at AccumulateGrad as before. Covered by test_side_stream_use_keeps_the_returned_gradient_path (fails on the previous commit).
| mask = nk_mask, | ||
| other = 0.0, | ||
| ) | ||
| accumulator = prev.to(acc_dtype) |
There was a problem hiding this comment.
Add the existing gradient after reducing the new dW
For bf16/fp16 gradients, seeding the fp32 dot-product accumulator with the existing gradient changes more than the final low-precision rounding: cancellation within the current microbatch can erase an earlier accumulated gradient. For example, an existing value of 1 followed by fp32 tile contributions near +1e8 and -1e8 produces 0 here because the 1 is lost in the first addition, whereas computing the new dW first and then adding the existing value produces 1. Keep the existing gradient separate until the dot-product reduction is complete, as is already done for fp32.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6b1bd9e: the existing gradient is no longer used to seed the accumulator; it is loaded after the dot-product reduction and added in fp32, then rounded once, for every dtype. test_existing_gradient_survives_in_microbatch_cancellation builds your +1e8 / -1e8 case across two M tiles with an existing 1 (fails on the previous commit, passes now).
…p side-stream weights on the returned path [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
unslothai#14759) Follow-up to unslothai#14480. The in-place dW path adds the expert weight gradient straight into `param.grad` and returns `None` for W. Tensor hooks and post-accumulate-grad hooks on W were already detected, but hooks registered on autograd Nodes were not: - `register_prehook` on the weight's `AccumulateGrad` node - `register_hook` on the `GroupedGemmBackward` node Both received `None` instead of dW, so a hook that scales or replaces the gradient was silently ignored. `UNSLOTH_MOE_DW_ACCUMULATE=0` was the only workaround. Nodes cannot list their hooks, but every Python hook of one kind on a Node lives in one shared dict, and the handle of a new registration points at it. `_dW_accumulate_target` now registers a no-op on both nodes, checks whether anything else is in the dict, and removes the no-op. If a hook is present, that weight uses the returned-gradient path. The probe runs last, only for weights that are otherwise eligible, and never under `torch.compile`. No-hook behaviour is unchanged: same kernel call, same `param.grad` bytes, in-place path still taken. Host overhead is a few microseconds per eligible dW call. Tests: `tests/test_moe_dw_accumulate_node_hooks.py` runs the real autograd wrapper on CPU with the Triton GEMMs replaced by dense matmuls. It checks that hooked weights match `UNSLOTH_MOE_DW_ACCUMULATE=0` bitwise, and that unhooked or unhooked-after-removal weights still accumulate in place. The two Node hook cases fail before this change.
Summary
In the MoE Triton grouped GEMM backward, the expert weight gradient dW is computed into a fresh buffer and autograd then adds it into
param.grad. With gradient accumulation (micro-steps 2..GA) that is an extra[E, N, K]temporary plus an add kernel per layer, and with fp32 activations and bf16 experts (Unsloth full finetuning) also an fp32 buffer and a cast.This lets the dW kernel accumulate straight into an existing
param.grad:unsloth::grouped_gemm_dW_accumulate(mutates_args=("dW",), fake impl).torch.compile,autograd.gradorbackward(inputs=)without W,create_graph, anomaly mode, a weight used on a non-default CUDA stream, tensor or post-accumulate hooks, non-leaf or subclass weights, a gradient of another layout or dtype, autotune on, or no gradient yet (autograd already reuses the fresh buffer there).UNSLOTH_MOE_DW_ACCUMULATE=0restores exactly today's backward.Results
One MoE layer, E=128, H=2048, I=768, top-k 8, T=4096 (B200, A/A per number):
bf16-activation timing is neutral. The memory saving is one layer's temporary at the global peak.
Tests
tests/test_moe_dw_accumulate.py: 124 passed on torch 2.13 (the revision before the review fixes also on 2.14). Each of 8 safeguards, when removed, makes its test fail.test_matches_returned_gradient_path_and_is_closer_to_fp64); an existing gradient survives in-microbatch cancellation.no_sync, bothgradient_as_bucket_viewsettings) and FSDP2 (1 NCCL rank, sync off for 3 micro-steps): in-place path engages, gradients match the kill switch within bf16 rounding.torch.compile(fullgraph=True): 0 graph breaks (compiled backward takes today's path).Not covered
Multi-rank NCCL DDP / FSDP2, torch below 2.13, ROCm, a real 30B finetune.