Skip to content

MoE grouped GEMM: per-expert dW kernel - #14550

Merged
danielhanchen merged 2 commits into
mainfrom
moe-dw-per-expert
Oct 21, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
moe-dw-per-expert

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

The grouped GEMM weight gradient (dW) in unsloth/kernels/moe/grouped_gemm was 1.5 to 3.3x slower than torch._grouped_mm even at its best tile. Each output tile looped over every expert and reduced over masked token tiles.

It runs for MoE full finetuning (expert weights trainable; LoRA never computes it) on the unsloth_triton backend, through zoo's forward_triton_grouped_gemm:

  • that is the default backend on torch builds where the torch._grouped_mm probe fails (torch 2.8 and some ROCm builds);
  • elsewhere it is reached with UNSLOTH_MOE_BACKEND=unsloth_triton.

Change

  • New dW kernel (kernels/backward.py): one program per (expert, N tile, K tile), in expert-major order. Each program reads its expert's row range from the counts and loops only over that expert's tokens.
    • fp32 accumulation and one rounding.
    • Each program owns its output tile: no atomics, deterministic.
    • Empty experts store zeros, or leave an accumulated gradient untouched.
  • fp32 activations (the bf16 full finetune case: fp32 RMSNorm weights feed fp32 activations into bf16 experts) run single stage at the default tile. Two stages doubled shared memory there and lost.
  • An autotuned variant. autotune_cache.py reads the chosen config from whichever kernel ran.
  • Unchanged: the interface, the accumulate path, TMA load / store, bf16 / fp16.
  • UNSLOTH_MOE_DW_KERNEL=legacy restores the previous kernel.

Validation

Parity: the output is bit-identical to the previous kernel in every cell, and against fp64:

  • bf16 1.66e-3 (the same as torch._grouped_mm), fp16 2.07e-4, bf16 input with an fp32 dW 1.7e-7 to 3.4e-7, fp32 activations 1.83e-3;
  • empty experts exactly zero or exactly unchanged.

Cells: real Qwen3-30B-A3B, gpt-oss-20b, Mixtral-8x7B and Qwen1.5-MoE expert dims, balanced, skewed and empty-expert routing, permute_x / permute_y / none, accumulate, and TMA where supported. 0 failures on B200, RTX PRO 6000, A100 and L4, torch 2.10.0 and 2.14.1.

Kernel time, new / previous kernel at the same tile (interleaved arms, 3 fresh-process repeats, torch 2.10.0 and 2.14.1, T = 512 and 4096):

GPU bf16, default tile bf16, tuned tile fp32 activations, default tile new kernel vs torch._grouped_mm (median)
B200 0.16 to 0.63 0.18 to 0.54 0.53 to 0.98 1.52x
RTX PRO 6000 0.32 to 0.84 0.25 to 0.55 0.51 to 0.91 0.86x
A100 0.42 to 0.79 0.39 to 0.61 0.57 to 0.94 1.10x
L4 0.40 to 0.94 0.38 to 0.95 0.52 to 0.92 1.00x
  • Faster in 317 of 320 cells. The same kernel run twice in one process (A/A) differs by 1 to 2% on B200, RTX PRO 6000 and A100.
  • L4's A/A is noisier (up to 1.34), so its 0.94 to 0.95 Mixtral cells are inside noise.
  • One real loss: A100, fp32 activations, the UNSLOTH_MOE_DISABLE_AUTOTUNE=1 heuristic tile, Mixtral gate_up at T = 4096: 3 to 4% slower, tight repeats on both torch versions. Not routed separately.

End to end on B200, full finetune on unsloth_triton, 2 layers with real Qwen3-30B-A3B expert dims, sequence 4096, 3 repeats each, step ms:

activations main this PR main again this PR with legacy
fp32 (default full finetune) 71.85 67.25 (-6.7%) 72.35 72.13
bf16 57.9 53.3 (-8%) 58.9 58.0
  • 4 dW launches per step in every arm, all through the new kernel on this PR.
  • Graph breaks (24 / 24 fp32, 35 / 35 bf16), unique graphs, peak memory and losses are the same on both sides.

Tests:

  • New tests/test_moe_dw_per_expert.py: bit-equality with the previous kernel and fp64 checks, incl. empty experts, accumulate and fp32 activations.
  • test_grouped_gemm_mixed_tma_device.py: its stub list gains the two new kernel names.
  • dW accumulate / grouped_gemm / fallback tile tests: main 219 passed, this PR 259 passed, no failures on either side.
  • unsloth/kernels/moe/tests: 41 failures on both sides with identical IDs. These are forward autotune / autograd cases at hidden 5120 / intermediate 8192, and they already fail on main.

Found on main, not changed here:

  • the on-disk autotune cache never hits: load_cached_config compares a JSON list to a tuple;
  • autotuning inside compiled blocks fails, so real runs use the default tile on both sides.

Not covered:

  • H100 and ROCm were not run.
  • torch 2.8, where this kernel is the default backend, was not benchmarked (2.10.0 and 2.14.1 were).
  • Eager-mode autotuning end to end was not tested.
  • End to end only on B200 with Qwen3 dims. gpt-oss does not reach this kernel: its interleaved gate_up goes to grouped_mm or the loop.

The dW kernel launched one persistent program per (n, k) output tile and walked
every expert inside it, so a launch had only N * K / (BN * BK) programs and each
restarted its pipeline once per expert. The new kernel launches one program per
(expert, n tile, k tile), reduces over that expert's own rows from the counts,
accumulates in fp32 and owns its output tile: no atomics, deterministic, and
bit-identical to the old kernel for the same tile config (same reduction order).
Empty experts store zeros (the output is no longer pre-zeroed) or, when adding
into an existing gradient, leave it untouched. The TMA load / store paths and
the interface are unchanged.

fp32 activations (fp32 RMSNorm outputs in a bf16 full finetune) run the tile
with one stage: two stages double shared memory for the tf32 dot and were slower
than the old kernel at the default 128x128x64 tile.

Autotuning reads the selected config from the tuner of the kernel it ran.
UNSLOTH_MOE_DW_KERNEL=legacy restores the old kernel.
@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-21T18:56:40.741708Z
We couldn’t complete this review. Comment @codex review to try again.
9f99ee7 PR opened
🔒 Security Review ⚠️ Failed 2026-10-21T18:56:29.604309Z
We couldn’t complete this review. Comment @codex security review to try again.
9f99ee7 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

Copy link
Copy Markdown

The account paying for this security review has reached its Codex usage limits. The payer can check the Codex usage dashboard. For personal accounts, using credits requires enabling “Use credits for security reviews” in Code review settings. If you do not manage the paying account, contact this repository's admins.

@danielhanchen
danielhanchen merged commit 4a5a3e5 into main Oct 21, 2026
@danielhanchen
danielhanchen deleted the moe-dw-per-expert branch October 21, 2026 19:11
Lyxot pushed a commit to NilayYadav/unsloth that referenced this pull request Oct 22, 2026
…slothai#14617)

## What broke

unslothai#14578 made disk cache hits in `unsloth/kernels/moe/autotune_cache.py`
live: `get_or_autotune_moe_kernels` rebuilds the cached `KernelConfig*`
objects and returns them straight away. Two things were missing on that
path:

1. The cache key has no schema or Triton identity, so a file written by
the pre-unslothai#14578 code (whose loader always returned `None` and deleted it,
so the file was dormant) now loads unchanged.
2. The loaded configs never go through `_fit_configs_to_dims` /
`_fit_configs_to_smem`, which every other config source (heuristic,
default) already uses.

Concrete failure: bf16, E=128, hidden 2048, intermediate 768, top-k 8, a
cached dW tile (BM, BN, BK, warps, stages) = (128, 256, 256, 8, 4). That
tile was valid for the legacy dW kernel (69,632 B shared memory on
sm86), but the per-expert dW kernel from unslothai#14550 needs 132,096 B on sm86
(limit 101,376 B) and 263,168 B on sm90 (limit 232,448 B), so the launch
raises `OutOfResources`. A cached entry with N=128, K=64 and
`BLOCK_SIZE_K=128` also loads unchanged and fails `tl.static_assert(K %
BLOCK_SIZE_K == 0)`.

## Change

- `_CACHE_SCHEMA_VERSION = 2` plus `triton.__version__` go into the
cache key and into the saved JSON. `load_cached_config` treats an entry
without them, or with different values, as a miss (returns `None`
without deleting; the next save overwrites it). Legacy files sit under
the old key and are never opened.
- On a disk hit, the reconstructed configs run through
`_fit_configs_to_dims(configs, 2 * intermediate_dim, hidden_dim)` and
`_fit_configs_to_smem(configs, dtype, weight_dtype)` before they go into
the in-memory cache. The example dW tile becomes (64, 256, 256, 8, 3),
66,048 B compiled on sm86.

The warm path is still a single dict lookup: fitting runs once per key
per process, on the first disk load. `get_or_autotune_moe_kernels` stays
`@torch.compiler.disable`, so compile behaviour does not change. A
one-time re-tune per model shape happens after upgrading, since old
entries are misses.

## Validation

New `tests/test_moe_autotune_cache_validate.py` (CPU, CUDA capability
and shared memory mocked):

- a legacy unversioned file is ignored and autotuning runs once; the
legacy-key file is left on disk
- an oversized dW tile from disk is fitted to (64, 256, 256, 8, 3) with
zero autotune calls
- a `BLOCK_SIZE_K` larger than K from disk is fitted to divide K and N
- a valid current entry hits unchanged with zero autotune calls, and the
warm call returns the same tuple without reading disk

`tests/test_moe_autotune_cache_hit.py` now pins the mocked shared memory
so its tuned tiles stay as saved.

Flip on main: 3 of the 4 new tests fail (legacy file reused, dW tile
unchanged, BLOCK_SIZE_K unchanged); the valid-hit guard passes on both.
With the fix, the new tests plus the existing MoE cache / fallback /
compile tests (`test_moe_autotune_cache_hit.py`,
`test_moe_fallback_smem.py`, `test_moe_fallback_tile_dims.py`,
`test_grouped_gemm_mixed_tma_device.py`,
`test_moe_autotune_under_compile.py`) give 230 passed on torch 2.10 and
torch 2.14 venvs.

## Not covered

- No GPU launch of a refitted disk config was run in this change; the
shared memory numbers come from the existing estimator and a CPU
cross-compile.
- Device selection is unchanged: lookup and tuning still use the current
CUDA device, and unsloth_zoo passes no operand device. On a mixed-GPU
host where the current device differs from the operand device,
capability and shared memory can be read from the wrong card. Fixing
that needs a device argument threaded from zoo, left for a follow-up.
oobabooga pushed a commit to oobabooga/unsloth that referenced this pull request Oct 22, 2026
…rflows per-expert shared memory (unslothai#14723)

Follow-up to unslothai#14550: keep the legacy dW kernel when an explicit tile
overflows per-expert shared memory.

The per-expert dW kernel double buffers both operand tiles, so a tile
the legacy kernel launched can now raise `OutOfResources`. CPU
cross-compile (Triton 3.8, 16 B aligned pointers), bf16, tile
128x256x256, 4 stages:

| Card | Legacy | Per-expert | Limit |
|---|---:|---:|---:|
| A100 (sm_80) | 69,632 | 131,584 | 166,912 |
| A10 / L4 (sm_86 / sm_89) | 69,632 | 131,584 | 101,376 |
| H100 (sm_90) | 131,072 | 262,656 | 232,448 |
| RTX 5090 (sm_120) | 69,632 | 131,584 | 101,376 |

The automatic config sources are already fitted. A sweep of 2,220 fitted
configs found 0 over the limit. It covered heuristic, default, and every
autotune candidate tile refit as a stale disk entry, on
sm_80/86/89/90/120, bf16 and fp32, two GEMM shapes. The autotuner also
skips `OutOfResources` configs. Two cases are not covered: a
caller-supplied tile (`grouped_gemm(kernel_config_bwd_dW=...)` or
`_grouped_gemm_dW_impl`), and a config fitted against another card.
Fitting reads `torch.cuda.current_device()`, not the operand's device.

Change: before a non-autotuned per-expert dW launch,
`_launch_grouped_gemm_dW` estimates shared memory on the operand's card,
cached per card and tile. It uses the same `_estimate_smem` the fitting
uses. If the tile does not fit, it falls back to the legacy kernel. The
two kernels are bitwise equal, so results do not change. ROCm and an
unreadable device keep the per-expert kernel.

## Tests

- GPU kernel suite on B200: main 164 passed / 8 failed (all 8 are the
new tests), this branch 172 passed.
- New `tests/test_moe_dw_explicit_tile_smem.py`. CPU routing per card
(A100, A10, L4, H100, B200, RTX 5090) plus a GPU test: the explicit tile
launches, is bitwise equal to legacy, and the accumulate path matches.
Base: 7 failed. Fix: 7 passed plus the GPU case. Related MoE kernel
tests, CPU, torch 2.14: base 233 passed / 7 failed (all new), fix 240
passed, 43 skipped on both.

## Not covered

- Fitting configs to the operand's card instead of the current one (the
other half of the mixed-host gap) is unslothai#14719; this PR checks explicit
tiles on `X.device` independently of it.
- unslothai#14550's reported 3 to 4% A100 slowdown was not re-timed: fp32
activations, heuristic tile, Mixtral gate_up, T = 4096. No A100 on this
host. It is a single kernel-time cell on a non-default fp32 path, and it
is not routed here.
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 24, 2026
…flow the card (unslothai#15070)

The per-expert MoE dW kernel (the default since unslothai#14550) can raise
`OutOfResources` on cards with less shared memory than an H100. unslothai#14723
added a fallback to the legacy kernel for oversized tiles, but its
shared memory estimate is wrong in one case: when neither operand is
gathered (`permute_x = False` and `permute_y = False`).

### Cause
Shared memory was checked with offline `triton.compile` runs (Triton 3.6
and 3.8, sm75 / 80 / 89 / 90), reading `metadata.shared`.
- **Gathered launches:** the legacy kernel, and any launch where one
operand is gathered, never pipeline. Their shared memory does not depend
on `num_stages`, which is what `_estimate_smem("dW")` models.
- **Unpermuted per-expert launches:** the per-expert kernel's single M
loop is software pipelined when both loads are contiguous.
- sm80-class cards (sm80 / 86 / 89 / 120): it needs `(stages - 1) * X
tile + one dY tile`.
  - sm90+: it needs `stages * (X tile + dY tile)`.
- **Measured against the estimate:**

| Card | Tile (M, N, K, stages) | gathered | not gathered | estimate on
main | limit |
|---|---|---|---|---|---|
| L4 (sm89) | heuristic 64x64x256x4 | 41216 | 106496 | 41984 | 101376 |
| A100 (sm80) | explicit 128x256x256x4 | 131584 | 262144 | 132096 |
166912 |

- **Effect:** neither the smem refit nor the unslothai#14723 fallback fired. With
no permute, `grouped_gemm` / `grouped_gemm_dW` on L4 raised
`OutOfResources(106496, 101376)` for the heuristic tile.
- **T4 (sm75):** the estimate is right there, but explicit tiles sized
for bigger cards overflow the legacy kernel as well (131072 B against
65536 B), and nothing refit them.

### Change
- **New estimate input:** `_estimate_smem` takes `pipelined_dW` and adds
the measured per-stage cost for unpermuted per-expert launches.
- **Stage drop:** those launches lower `num_stages` until the tile fits.
The tile stays the same, so the result is bit-identical.
- **Retry on a too-big tile:** if a non-autotuned dW launch still raises
`OutOfResources`, it retries once with a tile fitted to that card.
Triton raises before the kernel runs, so `dW` is untouched. A tile that
already launches is never changed.
- **Unchanged:** permuted launches, which are what the MoE training
paths use (one operand is always gathered), keep main's estimate and
launch parameters. ROCm keeps its current behaviour.
- **Test fix:** `test_moe_fallback_tile_dims.py` expected the heuristic
dX tile to keep 4 stages on L4. That tile needs 122880 B there, over the
101376 B limit, so the 3 stages the smem fit picks is correct. The test
now turns the smem fit off, since the smem tests already cover it.

### Tests
Colab, failing test IDs, main vs this PR, on torch 2.10.0 and 2.14.1
(same IDs on both versions):

| GPU | main | this PR |
|---|---|---|
| T4 | `test_explicit_tile_launches_on_this_gpu`,
`test_per_expert_fp32_activations_bf16_weight[False]` / `[True]` fail |
pass |
| L4 | 7 `test_moe_fallback_tile_dims` cases fail (stale stage count) |
pass |
| A100 | 0 failures | 0 failures, 9 new tests pass |

- **New test failing on main:**
`test_unpermuted_heuristic_tile_launches_on_this_gpu`. On L4 it raises
`OutOfResources` (106496 > 101376).
- **Failures on both sides** (same IDs, not touched here):
- L4: two `test_fp8_ragged_block_dequant` cases and
`test_fp8_dequant_save_policy[False]`;
- T4: two fullgraph compile tests, which fail because Inductor on sm75
skips bf16 graphs (handled separately).

**L4 timing.** bf16, heuristic dW config, no permute, median over 3
alternating runs:

| case | main | this PR (3 stages) | legacy kernel |
|---|---|---|---|
| gate_up T=4096, torch 2.10.0 | OutOfResources | 7.07 ms | 10.57 ms |
| gate_up T=4096, torch 2.14.1 | OutOfResources | 7.08 ms | 10.48 ms |
| gate_up T=512, torch 2.14.1 | OutOfResources | 3.59 ms | 7.11 ms |
| down T=4096, torch 2.14.1 | OutOfResources | 3.60 ms | 5.23 ms |

- **Permuted launches:** they take the identical path with identical
launch parameters.
- **A100:** stage counts are unchanged, and timings are within 0.1 to
0.4% of main.

### Not covered
- **Other GPUs:** no H100, B200 or sm120 runs. The sm90 numbers come
from offline compiles only.
- **A100 explicit unpermuted tile:** the 128x256x256 case now runs at 2
stages (131072 B by offline compile) but was not launched on a real
A100.
danielhanchen added a commit that referenced this pull request Oct 25, 2026
…ws and no smaller tile is known (#15238)

Follow-up to #14550 (per-expert MoE dW kernel) for ROCm.

### Problem
The per-expert dW kernel can overflow shared memory (LDS) on ROCm, and
nothing catches it:
- **Overflow:** the heuristic tile used with
`UNSLOTH_MOE_DISABLE_AUTOTUNE=1` (64x64x256, 8 warps, 4 stages, bf16)
needs about 80 KiB of LDS in the per-expert kernel. gfx1151 has 64 KiB.
The legacy kernel needs 32 KiB for the same tile.
- **Retry cannot help:** on an `OutOfResources` launch, the launcher
retries once with a tile fitted to the card. On HIP, `_card_smem`
returns None, so there is no shared memory model, the "fitted" tile
equals the failed one, and the launch re-raises.

The result is a backward-pass crash in MoE training with the
unsloth_triton backend on gfx1151:
```
OutOfResources: out of resource: shared memory, Required: 81920, Hardware limit: 65536
```
NVIDIA is not affected, because `_per_expert_dW_stages` and the retry
both use the card's real shared memory limit there.

### Change
Only in `_launch_grouped_gemm_dW` (`interface.py`), and only when a
per-expert launch raises `OutOfResources` and no smaller tile is known:
- that launch runs the legacy dW kernel with the same tile, the legacy
grid and the requested stage count;
- `dW` is zeroed first unless accumulating, since the legacy kernel
skips empty experts;
- the result is recorded in `_PER_EXPERT_DW_FITS`, so later calls with
that tile go straight to legacy without a failed launch.

The NVIDIA shrink-and-retry path is unchanged, and a legacy launch that
overflows still raises as before.

### Tests
New `tests/test_moe_dw_rocm_lds_fallback.py` simulates the ROCm
condition on any CUDA GPU:
- `_card_smem` returns None, and the per-expert launch raises
`OutOfResources(81920, 65536)`;
- the test checks that the result equals the legacy kernel bit for bit,
for a fresh `dW` and an accumulated one, with an empty expert in the
routing.

| | main | this PR |
|---|---|---|
| new test + `test_moe_dw_per_expert.py` + `test_moe_dw_accumulate.py`
(B200, torch 2.14.1) | 2 failed (the OutOfResources above), 181 passed |
183 passed |

### gfx1151 (Radeon 8060S, ROCm 7.13, torch 2.11), base vs this PR on
the same runner
The heuristic tile runs once with `permute_x` (gate_up style) and once
unpermuted (down_proj style):

| case | main | this PR |
|---|---|---|
| `permute_x=True` | `OutOfResources: shared memory, Required: 73728,
Hardware limit: 65536` | runs, equal to the legacy kernel bit for bit |
| `permute_x=False` | `OutOfResources: shared memory, Required: 106496,
Hardware limit: 65536` | runs, equal to the legacy kernel bit for bit |

The dW test files give 108 passed, 1 failed on main and 110 passed, 1
failed with this PR (the new file adds 2). The one failure is the same
test on both:
`test_moe_dw_accumulate.py::test_existing_gradient_survives_in_microbatch_cancellation`.
It is a separate, pre-existing gfx1151 accumulate precision issue that
this PR does not touch; I will follow up on it separately.

### Not covered
- Windows ROCm was not run.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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