Skip to content

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

Merged
danielhanchen merged 1 commit into
mainfrom
dh/s3-dw-accum-hooks
Oct 22, 2026
Merged

danielhanchen merged 1 commit into
mainfrom
dh/s3-dw-accum-hooks

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Follow-up to #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.

The in-place dW path wrote straight into param.grad and returned None for W,
so a prehook on the weight's AccumulateGrad node or a post hook on the
GroupedGemmBackward node saw None and could not scale or replace dW.
Detect such hooks by probing the node's shared hook dict and return dW
through autograd for that weight. The no-hook path is unchanged.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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 ✅ Completed 2026-10-22T18:45:41.458625Z 7422b0f Manual request
ℹ️ 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: 7422b0f462

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

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)

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 Avoid installing a persistent empty prehook during detection

For every otherwise eligible weight, calling acc.register_prehook creates a Python prehook adapter and hook dictionary on the long-lived AccumulateGrad node. handle.remove() only deletes the probe from that dictionary; it does not unregister the adapter itself. Consequently, even weights that never had a user hook permanently acquire an empty Python prehook after their first backward, forcing subsequent AccumulateGrad executions through Python and the GIL. This adds ongoing overhead to the default fast path and to unrelated later uses of the parameter, rather than only the stated probe-time cost.

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.

Measured this on torch 2.10, 2.13 and 2.14. You are right that handle.remove() leaves the empty hook dict and its Python adapter on the AccumulateGrad node. The cost is about 0.9 us per AccumulateGrad execution on that node (CPU microbench, 256 parameters, A/A noise 40 to 200 ns).

It is not permanent in practice: the AccumulateGrad node is owned by the graph and freed after each backward, so in a normal training loop the adapter costs one extra Python call in the backward that probed it. It carries over only while something else keeps that node alive. The probe runs once per eligible expert weight per backward, next to a grouped GEMM over all routed tokens, so the overhead is far below run-to-run noise.

The alternatives I tried either have no public read-only way to list a node's hooks, or need a process-wide patch of a private torch API (Function._register_hook), which I would rather not ship for a sub-microsecond cost. Keeping the probe as is.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 7422b0f462

ℹ️ 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 7de9c3b into main Oct 22, 2026
@danielhanchen
danielhanchen deleted the dh/s3-dw-accum-hooks branch October 22, 2026 21:13
danielhanchen added a commit that referenced this pull request Oct 22, 2026
pre-commit.ci fails `ruff-format-with-kwargs` on every open PR (#14806,
#14805, #14803, #14790, #14785, #14781, #14780, #14777, #14776, #14775,
#14774, #14773, #14772, #14770, #14769, #14768, and others): "files were
modified by this hook". pre-commit.ci runs the hooks on all files, and
20 files on main (26 by the time this lands) are not in the formatter's
output, so every PR is reformatted outside its own diff. Where
pre-commit.ci can push, its autofix commit drags those unrelated files
into the PR (for example #14790's touches `tests/test_block_compile.py`,
`tests/test_bnb_integration_compile.py` and `unsloth/models/_utils.py`).

The drift came in with PRs merged today, among them #14702, #14751,
#14759, #14784, #14786, #14787, #14788, #14791 and the FP8 block decode,
GRPO routing replay, 4-bit decode, compiled blocks and MoE LoRA target
changes.

### Change

`python scripts/run_ruff_format.py` (the hook's own entry point,
`ruff==0.6.9` as pinned in `.pre-commit-config.yaml`) applied to those
20 files, plus 6 more from #14739, #14779 and #14806, which merged while
this was open. Formatting only.

### Verification

- Every changed file parses to an identical AST before and after.
- A second run of the hook over the same files changes nothing (fixed
point), and over all tracked Python files on this branch it changes
nothing.
- `ruff check` passes on the changed files;
`tests/test_formatter_fixed_point.py` passes (16).

Open PRs pick this up on their next pre-commit.ci run after merging
main.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant