Skip to content

MoE grouped GEMM: accumulate expert dW into an existing param.grad - #14480

Merged
danielhanchen merged 8 commits into
mainfrom
dh/s2-w19b-dw-accumulate
Oct 21, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
dh/s2-w19b-dw-accumulate

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

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:

  • Each dW output tile belongs to exactly one program, so the read-modify-write needs no atomics. The existing tile is loaded after the dot-product reduction, added in fp32 and rounded once (fp32 gradients: bitwise identical to today). Experts with no tokens are skipped, so their gradient is untouched.
  • New opaque op unsloth::grouped_gemm_dW_accumulate (mutates_args=("dW",), fake impl).
  • Taken only when safe; otherwise today's path: under torch.compile, autograd.grad or backward(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).
  • On the fresh path, when the weight dtype differs from the activation dtype, dW is written in the weight dtype directly; this rounds identically to autograd's cast (asserted in a test) and drops the fp32 buffer and cast kernel.
  • UNSLOTH_MOE_DW_ACCUMULATE=0 restores exactly today's backward.

Results

One MoE layer, E=128, H=2048, I=768, top-k 8, T=4096 (B200, A/A per number):

before after
peak extra backward memory, bf16 activations, micro-steps 2..GA 816 MiB 96 MiB
same, fp32 activations, micro-steps 2..GA 1952 MiB 192 MiB
same, fp32 activations, micro-step 1 2336 MiB 1248 MiB
layer backward, fp32 activations, micro-steps 2..4 13.65 ms 13.03 ms

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.
  • Accuracy vs fp64: at least as close as today in every dtype; bitwise identical for fp32 gradients and when the gradient starts as None or zeros. bf16 on an existing gradient: one rounding instead of two (test_matches_returned_gradient_path_and_is_closer_to_fp64); an existing gradient survives in-microbatch cancellation.
  • Tiny Qwen3-MoE full finetune, GA=4, deterministic: 36 of 48 backward calls in place (the other 12 are first micro-steps), A/A bitwise; expert gradients closer to fp64 than today (2.65e-3 vs 3.15e-3 relative); losses identical through the first optimizer step.
  • DDP (2 gloo ranks, no_sync, both gradient_as_bucket_view settings) 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.

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-21T10:27:30.753500Z
We couldn’t complete this review. Comment @codex review to try again.
ef9b2fd New commits
🔒 Security Review 🔄 Running since 2026-10-21T09:32:16.911747Z 1b37e2c PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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():

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment on lines +971 to +972
# Already in param.grad: returning it as well would add it twice.
dW = None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@danielhanchen danielhanchen Oct 21, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +966 to +971
grouped_gemm_dW_accumulate(
X = X,
dY = dY,
m_sizes = m_sizes,
gather_indices = gather_indices,
dW = target.grad,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 6b1bd9eb08

ℹ️ 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".

@danielhanchen
danielhanchen merged commit d2f83d5 into main Oct 21, 2026
@danielhanchen
danielhanchen deleted the dh/s2-w19b-dw-accumulate branch October 21, 2026 11:02
NilayYadav pushed a commit to NilayYadav/unsloth that referenced this pull request Oct 22, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant