Skip to content

MoE grouped GEMM: tl.range for the dX expert loop, drop the dead dW FLATTEN - #13831

Merged
danielhanchen merged 5 commits into
mainfrom
moe-dx-loop-flatten
Oct 15, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
moe-dx-loop-flatten

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

_grouped_gemm_dX_kernel loops over experts with the builtin for expert_idx in range(NUM_EXPERTS, flatten = FLATTEN). Inside @triton.jit, Triton's code generator drops keyword arguments on the builtin range, so flatten never reached the IR (the forward already uses tl.range(..., flatten = FLATTEN)). The dW kernel also declared a FLATTEN constexpr it never reads, which only split its JIT cache.

Change

  • dX: tl.range(NUM_EXPERTS, flatten = FLATTEN), same as the forward.
  • dW: drop the unused FLATTEN constexpr and stop passing it from _grouped_gemm_dW_impl.

The grouped GEMM only runs on Triton 3.4+ (Zoo's _check_grouped_gemm_available requires tl.make_tensor_descriptor), and tl.range(flatten=) exists from 3.3, so no version gate is needed.

Effect

The dX TTIR now carries tt.flatten on the expert loop when FLATTEN is set (0 before). The final PTX is unchanged on Triton 3.3 (sm80) and 3.8 (sm75, 80, 89, 90, 100, 120) for forward, dX and dW: Triton's flatten pass only fuses directly nested for loops, and the inner loop here is a while inside an if. So this changes no generated code today; it makes the dX loop request what its argument says, matching the forward, and removes the dead dW constexpr. Autotune config counts are unchanged (108 per kernel).

Tests

New tests/test_grouped_gemm_flatten.py: no builtin range in the grouped GEMM kernels receives keywords, the dW kernel has no FLATTEN, and (compile-only, sm80 target) the dX TTIR has tt.flatten exactly when FLATTEN is set. torch 2.14 / Triton 3.8: 4 passed (3 fail on main). torch 2.7.1 / Triton 3.3: 2 passed, 2 skipped (no make_tensor_descriptor).

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 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-15T16:58:09.808166Z b9a705a Manual request
🔒 Security Review ⚠️ Failed 2026-10-15T10:39:02.222125Z 32e261b 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

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 32e261bc00

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

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: 9dd469abb2

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

sig[p.name] = "i32"
try:
src = ASTSource(fn, sig, constexprs = constexprs)
ttir = triton.compile(src, target = GPUTarget("cuda", 80, 32)).asm["ttir"]

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 Skip the CUDA-only IR test when its backend is unavailable

On ROCm or XPU Triton distributions that expose tl.make_tensor_descriptor but do not ship the CUDA compiler backend, this test passes the current skip guard and then fails while resolving the hard-coded GPUTarget("cuda", ...). That failure is typically reported as no compatible backend rather than a driver error, so the exception handler re-raises it and breaks otherwise supported non-CUDA test runs; detect the CUDA backend explicitly or skip backend-selection errors.

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 the next commit: the IR test now skips when torch is a ROCm build or Triton has no nvidia backend registered, before resolving the CUDA target.

Comment thread tests/test_grouped_gemm_flatten.py Outdated
Comment on lines +21 to +23
from unsloth.kernels.moe.grouped_gemm.kernels import backward as bw
except Exception as exc: # pragma: no cover
pytest.skip(reason = f"grouped_gemm is unimportable here: {exc}", allow_module_level = True)

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 Do not turn grouped-GEMM import regressions into skips

If importing backward raises for any reason—including a regression in the module under test—this broad module-level handler skips the entire file before test collection. That also suppresses test_no_builtin_range_receives_keywords, even though it only parses source and does not require a successful kernel import, so broken grouped-GEMM code can make this regression suite report skips rather than failures; defer the import to the tests that need it or restrict the skip to known unsupported-environment errors.

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: the kernel import moved into a fixture used only by the two tests that need it, so the AST check always runs. The fixture skips only when no GPU is available; with a GPU present an import failure now fails the tests.

@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: b9a705a21b

ℹ️ 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 d64b080 into main Oct 15, 2026
@danielhanchen
danielhanchen deleted the moe-dx-loop-flatten branch October 15, 2026 17:17
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 16, 2026
… frozen operands, no CE eviction hint on H100 (unslothai#13967)

Fixes from a post-merge audit of unslothai#13831, unslothai#13889 and unslothai#13893, checked on
T4, A100, H100, B200 and AMD gfx1151. Each item has a test that fails on
main and passes here.

## Changes

- **Eager RMSNorm / LayerNorm launch when the fast launcher is off
(unslothai#13889).** On ROCm and with `UNSLOTH_TRITON_FAST_LAUNCH=0`, every norm
call went through the fast-launch wrapper (heuristics expansion, an
extra call) before reaching `kernel[grid]`. It now calls Triton directly
in that case, as before unslothai#13889. The launch condition also checks
`torch.compiler.is_compiling()` first, so compiled graphs no longer
guard on the mutable launcher flag (a launcher fallback recompiled every
compiled LayerNorm).
- **Grouped GEMM backward skips gradients nobody needs (unslothai#13831
follow-up).** `GroupedGemm.backward` always ran the dW kernel and
allocated the (E, N, K) dW unless the caller passed `dX_only`, and none
of the MoE callers do. With frozen experts (LoRA, dequantized bnb 4-bit
/ FP8 experts) that is a wasted kernel and buffer per projection per
step. It now follows `ctx.needs_input_grad`, so a frozen W gets no dW
and a constant X no dX; trainable operands are unchanged.
- **No chunked cross entropy eviction hint on H100 (unslothai#13893).**
`evict_first` on the chunked forward measured slower on H100 (sm_90):
2048 x 262144 bf16 logits 437.6 -> 448.2 us (+2.4%, base spread 1.2%),
4096 x 128256 429.8 -> 436.6 us. It is now off on sm_90 as it already
was on sm_100; T4 / L4 / A100 keep it, where unslothai#13893 measured it faster.
- **CE eviction hint test (unslothai#13893).** Compiles each architecture's own
target (so sm_80+ exercises the L2 cache-policy lowering) and skips on
Triton 3.2, whose `ASTSource` has no `constexprs`.

## Tests

- New `tests/test_grouped_gemm_frozen_weight_grad.py`: which backward
kernels run for each (X, W) `requires_grad` combination, gradients vs an
fp32 reference. 2 of 4 fail on main (frozen W, frozen X).
- `tests/test_norm_fast_launch.py`: with the launcher off, no call goes
through `launch()`; flipping the launcher flag does not recompile a
compiled LayerNorm (both fail on main).
- `tests/test_cross_entropy_eviction_hints.py`: sm_90 gets no hint
(fails on main).
- B200, torch 2.14 / Triton 3.8, including the `gpu`-marked tests: the
touched test files pass (173 passed, 13 skipped). Earlier heads also
passed on torch 2.7.1 / Triton 3.3.1 and torch 2.10.
- `tests/test_norm_fast_launch.py`: the eager half of
`test_compiled_calls_never_use_fast_launch` now expects `launch()` only
when fast launch is on, so it holds on ROCm and with
`UNSLOTH_TRITON_FAST_LAUNCH=0` (33 passed with the launcher off, 45 with
it on).

## Training A/B (base = merge base, same seed and data, 30 steps unless
noted)

| Job | GPU | Step time (base -> PR) | Peak memory (base -> PR) | Loss |
|---|---|---|---|---|
| Grouped GEMM, frozen experts (E 128, H 2048, I 768, 4096 tokens, top
8) | A100 | 13.52 -> 7.72 ms (-42.9%) | 3.60 -> 2.85 GB (-20.8%) |
identical |
| Grouped GEMM, frozen experts (20 steps) | T4 | 812.5 -> 672.1 ms
(-17.3%) | 2.60 -> 2.60 GB | identical |
| MoE LoRA SFT (tiny Qwen3 MoE) | A100 | 28.26 -> 27.09 ms (-4.1%) |
74.1 -> 52.5 MB (-29.1%) | within tolerance |
| MoE LoRA SFT (tiny Qwen3 MoE) | T4 | 42.41 -> 42.51 ms (+0.2%, noise)
| 44 -> 44 MB | within tolerance |
| Dense LoRA SFT | T4 | 324.96 -> 318.60 ms (-2.0%) | 1.33 -> 1.33 GB |
within tolerance |

All five runs report no regression against the A/B tolerances.

## Other GPUs

- AMD gfx1151 (Strix Halo, ROCm 7.13, torch 2.11), at 7fc770d (later
commits only change CUDA-only gates): the touched test files at base,
head and the merge with main: 43 passed / 24 skipped at base, 56 passed
/ 0 failed / 24 skipped at head. No test that passed at base fails here.
- H100 (sm_90): with the hint off, the chunked cross entropy forward
compiles to PTX identical to the kernel before unslothai#13893 (Triton 3.8), so
H100 runs exactly the pre-unslothai#13893 code.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 18, 2026
…test fixes across torch 2.10 - 2.14 (unslothai#14122)

Follow-up fixes from a re-verification of the recent kernel PRs (unslothai#13828, unslothai#13829, unslothai#13830, unslothai#13831, unslothai#13840, unslothai#13851, unslothai#13889, unslothai#13893, unslothai#13967, unslothai#14026, unslothai#14027) across T4, L4, A100, H100, RTX PRO 6000, B200 and gfx1151, on torch 2.10 to 2.14. Main itself showed no regression for default training or inference. These are the real gaps the re-verification turned up.

## Changes

**NVFP4 fused GEMM row gate scales with the weight shape** (`unsloth/kernels/nvfp4.py`)
- The old gate was one row limit per GPU (A100 64, L4 256, RTX PRO 6000 128). It picked the fused kernel in cells where fused is slower than dense: up to 2.4x on A100, 2.5x on L4 and 5.9x on RTX PRO 6000. For example, at 64 rows with N = K = 4096 it was +12% on RTX PRO 6000 and +4.5% on A100.
- The limit is now `clamp(max(N * K // div, k_rows), floor, max_rows)`, with separate forward and dX entries per capability. Weights with N or K not a multiple of 128 run the masked edge tiles, so they only get the floor.
- The constants were fitted to a bf16 sweep: rows 1 to 256, ten (N, K) shapes, timed with CUDA graphs, interleaved arms and an A/A spread.
- `UNSLOTH_NVFP4_FUSED=0` / `1` and `UNSLOTH_NVFP4_FUSED_MAX_ROWS` keep their meaning. Unmeasured GPUs (H100, T4, others) stay dense as before.

Confirmation pass, 90 cells per GPU:

| GPU | old gate: fused picked but slower than dense | new gate | new slower than old by more than max(noise, 10%) |
|---|---|---|---|
| A100 | 11 | 0 | 1 (dX, 32 rows, 2048x2048, +16%) |
| L4 | 23 | 0 | 2 (fwd, 256 rows, 5120x5120, +43%; fwd, 128 rows, 3072x768, +10%) |
| RTX PRO 6000 | 21 | 0 | 0 |

Fixing those three cells would push a neighbouring shape that loses onto fused, so they are left as they are.

**MoE fallback grouped GEMM configs fit the GEMM** (`unsloth/kernels/moe/autotune_cache.py`)
- These are the configs used with `UNSLOTH_MOE_DISABLE_AUTOTUNE=1`, or when autotuning fails (for example OOM on a 16 GB card). They used fixed tiles, and the kernels assert `N % BLOCK_SIZE_N == 0` and `K % BLOCK_SIZE_K == 0`. So intermediate sizes such as 1408 (DeepSeek-V2-Lite, Qwen1.5-MoE), 352 and 2880 crashed.
- The tiles now shrink to the largest power of two (at least 16) that divides each GEMM's N and K. Configs that already worked (Qwen3-30B-A3B, Qwen3-235B, Mixtral, OLMoE) are byte-identical.
- The heuristic 64x64x256, 4-stage dX config needs 122,880 B of shared memory, more than L4 and RTX PRO 6000 have (101,376 B). It raised OutOfResources there for every shape. On sm_80+ with that limit it now drops to 3 stages (81,920 B), reading the limit of the current device. T4, A100, H100 and B200 configs are unchanged.

**Tests**
- `test_norm_fast_launch`: run the narrow-row self-check before measuring the compiled call. On torch 2.10 to 2.12, Dynamo reaches that one-time check with `is_compiling()` False, and the test counted its eager launches. The compiled graph never used the fast launcher.
- `test_cross_entropy_eviction_hints`: skip an arch the active ptxas cannot target. Once Inductor sets `TRITON_PTXAS_PATH`, the CUDA 13 ptxas has no sm_52 to sm_72.
- `test_layernorm_compiled_matches_eager_bytes`: also run in fp16, and skip bf16 on GPUs without native bf16. Inductor skips bf16 graphs there, so `fullgraph=True` fails in plain torch too.

## Validation

- **CPU tests:** new tests `test_nvfp4_fused_gate_shape.py` (27) and `test_moe_fallback_tile_dims.py` (60) pass on torch 2.10 and 2.14.
- **GPU, base (main) vs this branch:**
  - Colab L4 (torch 2.11, 2.14), RTX PRO 6000 (2.14), T4 (2.10, 2.14): no test fails on the branch that passes on main.
  - Norm self-check test: fails on main on torch 2.10 and 2.11, passes here.
- **MoE fallback, one MoE block driven exactly as unsloth-zoo calls it:**
  - T4: main crashes on 1408 / 352 / 2880. This branch trains them, with forward and all gradients within about 6e-4 of an fp32 reference.
  - L4 and RTX PRO 6000: the heuristic path crashes on main for every shape and trains here.
  - Unchanged shapes are bit-identical to main. 768 timing is unchanged on T4, L4 and RTX PRO 6000.
- **NVFP4 GPU tests:** 105 passed on A100, L4 and RTX PRO 6000. The fused vs dense outputs match.

Not covered: NVFP4 timing on H100 (no allocation) and in fp16; the MoE heuristic smem change on T4 is covered by CPU tests and earlier T4 runs of the same configs.
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