Skip to content

Kernel follow-ups: NVFP4 shape-aware fused gate, MoE fallback tiles, test fixes across torch 2.10 - 2.14 - #14122

Merged
danielhanchen merged 12 commits into
mainfrom
kernel-reverify-followups
Oct 18, 2026
Merged

danielhanchen merged 12 commits into
mainfrom
kernel-reverify-followups

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 18, 2026 •

Copy link
Copy Markdown
Member

Follow-up fixes from a re-verification of the recent kernel PRs (#13828, #13829, #13830, #13831, #13840, #13851, #13889, #13893, #13967, #14026, #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.

The flat per-GPU row limit picked the fused GEMM at M=64, N=K=4096 where it
loses to dense (RTX PRO 6000 +12%, A100 +4.5%) while 4096x14336 still wins at
the same rows. The limit is now clamp(N * K // div, floor, max_rows) per
capability, floor 32 rows forward and 16 or 32 for dX, fitted to a bf16 sweep
of rows 1 to 256 over ten (N, K) shapes on A100, L4 and RTX PRO 6000.
UNSLOTH_NVFP4_FUSED=0 / 1 and UNSLOTH_NVFP4_FUSED_MAX_ROWS keep their meaning;
unmeasured GPUs stay dense.
Forward and dX now each get (div, c, floor, max_rows) per capability.
rows <= clamp(max(N * K // div, k_rows), floor, max_rows), where k_rows is
c // K for forward (a narrow reduction keeps fused ahead) and K // c for dX
(a wide output does). Weights whose N or K is not a multiple of 128 run
masked edge tiles and are fused only up to the floor. Refitted on both bf16
sweep passes: no auto pick is slower than the other path beyond the A/A
noise, and the RTX PRO 6000 dX M=64 4096x4096 and forward M=64 3072x768 wins
are back.
Requiring K % 64 for dX moved K = 4112 at 16 rows to the dense path, 1.8x
slower on L4 and 1.9x on RTX PRO 6000 with no accuracy gain (fused error vs
fp32 0.00275 on both, dense 0.00275 / 0.00453).
…ithout native bf16

Inductor raises SkipFrame for bf16 graphs on GPUs without native bf16 (T4, sm_75), so
torch.compile(fullgraph = True) cannot hold a bf16 LayerNorm there; on torch 2.14 the same holds
for a plain F.layer_norm. fp16, what T4 trains in, still checks compiled vs eager bytes.
The heuristic (UNSLOTH_MOE_DISABLE_AUTOTUNE=1) and default (autotune failed)
configs used fixed tiles, but the grouped GEMM kernels static_assert that
BLOCK_SIZE_K divides K and BLOCK_SIZE_N divides N. Intermediate size 1408
(DeepSeek-V2-Lite, Qwen1.5-MoE-A2.7B) crashed in the heuristic backward.

Pass the per-GEMM N and K from get_or_autotune_moe_kernels and shrink
BLOCK_SIZE_N / BLOCK_SIZE_K to the largest power of two (>= 16) that divides
them. Shapes that already divided keep identical configs; tiles only shrink,
so shared memory use never grows.

(cherry picked from commit 5307e6c124418b15d2bc1e6460f01f84ddaf47d4)
The UNSLOTH_MOE_DISABLE_AUTOTUNE=1 heuristic dX config (64x64x256, 4 stages)
needs 122,880 B of shared memory on sm_80+ (Triton keeps num_stages - 1
cp.async buffers), over the 101,376 B of sm_86 / sm_89 / sm_120, so the
heuristic path raised OutOfResources on L4 and RTX PRO 6000 for every shape.

Read the device's opt-in shared memory per block and, on CUDA sm_80+ devices
below the measured requirement, use 3 stages (81,920 B). A small table holds
the measured bytes. Devices with enough shared memory (T4, A100, H100, B200)
keep byte-identical configs.

(cherry picked from commit d68c54069cbc75a2c3c2f640822e765aec292e78)
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 18, 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-18T11:50:20.035604Z ef8b17b Manual request
🔒 Security Review ⚠️ Failed 2026-10-18T11:36:42.425315Z cb8fb2c 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@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: cb8fb2cd80

ℹ️ 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 thread unsloth/kernels/fp8.py Outdated
return False
if torch.is_grad_enabled() and (X.requires_grad or weight.requires_grad):
if torch.is_grad_enabled() and (
X.requires_grad or weight.requires_grad or weight_scale.requires_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 Propagate gradients for the trainable FP8 scale

When only weight_scale requires gradients, this new condition routes the call away from GEMV into fp8_linear, but the rowwise path uses FbgemmFp8Linear_matmul, whose backward returns None for the scale argument at line 908. The output now has an autograd history and backward completes without error, but weight_scale.grad remains None, silently preventing the supposedly trainable scale from updating; the added test checks only dispatch and therefore misses this. The fallback must compute a scale gradient or otherwise use a genuinely differentiable implementation.

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 ef8b17b by dropping the change: the fallback fp8_linear has never produced a scale gradient, and a trainable FP8 scale is not a supported setup, so the gate stays as it was.

Comment thread unsloth/kernels/moe/autotune_cache.py Outdated
Comment on lines +395 to +396
from .grouped_gemm.kernels.tuning import get_device_properties
return int(get_device_properties().SIZE_SMEM) # triton max_shared_mem (opt-in)

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 Query shared memory for the current CUDA device

In a process using heterogeneous GPUs, get_device_properties() cannot safely supply this limit because grouped_gemm/kernels/tuning.py stores its result in the single module-global _DEVICE_PROPERTIES, rather than caching per device. For example, if an A100 call primes that cache before the current device changes to an L4, this line still reports the A100's 166,912-byte limit, so the new 4-to-3-stage adjustment is skipped and the heuristic dX kernel continues to fail with OutOfResources on the L4. Query the explicitly current device here or make the underlying cache device-indexed.

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 ef8b17b: the limit now comes from torch.cuda.get_device_properties(current_device()).shared_memory_per_block_optin (Triton's driver as fallback), with a test switching devices.

@danielhanchen danielhanchen changed the title Kernel follow-ups: NVFP4 shape-aware fused gate, FP8 GEMV trainable scale, MoE fallback tiles, test fixes across torch 2.10 - 2.14 Kernel follow-ups: NVFP4 shape-aware fused gate, MoE fallback tiles, test fixes across torch 2.10 - 2.14 Oct 18, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: ef8b17b957

ℹ️ 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 added a commit that referenced this pull request Oct 18, 2026
…pability picks (#14138)

## Summary

`Repo tests (CPU, studio)` fails on every PR whose base includes #14083,
with the same single test:

```
tests/studio/test_model_picker_contracts.py::test_diffusion_capability_labeled_image_video_gen
    assert '{ value: "diffusion", label: "Image/video gen" }' in _read("features/hub/lib/model-type-filter.ts")
```

Seen on #14097, #14106, #14112, #14115, #14122 and #14125 (bases
`72d0d2db`, `b4a4855e`, `4c5fb400`), and it reproduces on main at
`1e2cedde`.

## Cause

#14083 (Studio Hub: On Device filters and sort) moved the On Device list
onto Discover's capability picks, on purpose. `model-type-filter.ts` no
longer keeps its own `MODEL_TYPE_FILTER_OPTIONS` (which held `{ value:
"diffusion", label: "Image/video gen" }`). Its
`matchesInventoryCapabilities` now takes `HubCapabilityFilter` picks and
matches them with Discover's own `matchesHubCapability`, so the On
Device panel shows Discover's "Image gen" and "Video gen" tiles. The PR
describes this as change 2.

The product is right and the test is stale. What the test protects
(#11681) is that the diffusion capability is never presented as "Image
to text". That still holds: the only names now shown for it are
Discover's "Image gen" / "Video gen" options and the capability badge's
"Image gen" / "Video gen".

## Change

Test only, `test_diffusion_capability_labeled_image_video_gen`:

- **Kept as before:**
  - "Image to text" must not appear in the three hub files.
- Discover's options must be `{ value: "image-gen", label: "Image gen"
}` and `{ value: "video-gen", label: "Video gen" }`.
- **New:** the capability badge in `model-capabilities.ts` must name the
same two kinds.
- **Replaced** the literal from the deleted On Device list. Now, if
`model-type-filter.ts` has a `diffusion` option, it must still be
labeled "Image/video gen". Otherwise the file must match through
`matchesHubCapability`, so On Device cannot quietly grow a second,
unchecked set of names.

## Testing

- **This change:** `tests/studio/test_model_picker_contracts.py` gives
201 passed.
- **Before (main `1e2cedde`):** the same file gives 1 failed, 200
passed, the failure CI shows.
- **Each of these makes the test fail:**
  - Relabeling Discover's `image-gen` option "Image to text".
- Renaming `matchesHubCapability` out of `model-type-filter.ts`, so On
Device no longer shares Discover's matcher.
- Adding back an On Device `{ value: "diffusion", label: "Image to text"
}` option.
@danielhanchen
danielhanchen merged commit 4487b0a into main Oct 18, 2026
@danielhanchen
danielhanchen deleted the kernel-reverify-followups branch October 18, 2026 15:22
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 22, 2026
…nslothai#14625)

## Problem

Two issues in the NVFP4 fused decode GEMM added in unslothai#13840 (gate refined
in unslothai#14122 and unslothai#14536).

1. **Fused forward ignores autocast.** The dense path it replaced is
`torch.matmul(X, W.t())`, which autocast runs in the autocast dtype. The
fused Triton GEMM allocates its output in `X.dtype` and never looks at
autocast. With fp16 activations under bf16 autocast, the result comes
back as fp16 and overflows where the dense path returned finite bf16.
bf16 activations under fp16 autocast flip the other way.

Repro: fp16 `X` of shape `[4, 128]` filled with 1000, packed weights
`0x22` (every decoded weight is 1), unit scales, `torch.autocast("cuda",
dtype=torch.bfloat16)`:

   | | before unslothai#13840 (dense) | main (fused) | this PR (fused) |
   |---|---|---|---|
   | output dtype | bf16 | fp16 | bf16 |
   | output value | 128000 | inf | 128000 |
   | loss | 1.6384e10 | inf | 1.6384e10 |
   | grad X finite | yes | no | yes |

The same happens through a PEFT LoRA wrapper (LoRA B grad non finite on
main, finite before unslothai#13840 and with this PR). The bf16 input / fp16
autocast case now also matches the dense result exactly (fp16 output, as
dense gives).

2. **Fused dX skips the K alignment check.** `_fused_ok` checks `inner %
64` and `N % 64`. In the forward pass `inner` is K, but in dX it is N,
so K was never checked. A weight with N=4096, K=4112 was refused fused
forward but accepted for fused dX on sm80, sm89 and sm120, the shape
class unslothai#13840 measured as up to 2.8x slower than dense in dX.

## Change

- `NVFP4Linear_matmul.forward` casts `X` to the active CUDA autocast
dtype before calling the matmul op, outside the opaque `torch.library`
op. The fused path, the dense path and the fake impl then all return the
autocast dtype, and `grad_X` is still returned in `X.dtype` as before.
Without autocast nothing changes. Autocast state is already a dynamo
guard, so no new graph breaks or recompiles.
- `_fused_ok` checks N and K alignment directly (`packed.shape[0] % 64`
and `packed.shape[1] % 32`) in both directions. `UNSLOTH_NVFP4_FUSED=1`
still forces the fused path past the check.

## Validation

B200 (fused path forced with `UNSLOTH_NVFP4_FUSED=1`, as the existing
tests do; dispatch for sm80 / sm89 / sm120 checked by monkeypatching the
capability).

- New tests, failing on main and passing here:
- `test_autocast_dtype_matches_dense` (fp16 under bf16 and bf16 under
fp16): fused output and grad equal the dense path bit for bit, dtype
included. 2 of 2 fail on main.
- `test_autocast_random_weights_match_dense_and_oracle` (fp16 / bf16 /
fp32 inputs): fused vs dense vs fp64 oracle, forward and dX. 3 of 3 fail
on main (the fp32 case because main never runs fused for fp32 inputs;
under autocast they now take the bf16 fused kernel, like the dense path
computes in bf16).
- `test_autocast_fullgraph_compile_has_no_graph_break`: 0 graph breaks,
compiled output bf16 and equal to eager. Fails on main (compiled output
fp16).
- `test_unaligned_k_stays_dense_in_both_directions` (sm80, sm89, sm120,
forward and dX): the 3 dX cases fail on main.
- NVFP4 test files (`tests/test_nvfp4*.py`, GPU tests included):
- torch 2.14.1 / Triton 3.8.0: 166 passed, 5 skipped, 1 failed. The
failure,
`test_nvfp4_loader.py::test_peft_merge_dequantizes_the_routed_base[nvfp4-True]`,
fails the same way on main (pre-existing, not touched here).
  - torch 2.10.0 / Triton 3.6.0: 111 passed, 4 skipped.
- torch.compile (forward + backward, rows 16 / 32 / 48 / 64 / 64,
dynamic): 0 graph breaks, 2 graphs, 0 recompiles on main and here, with
and without bf16 autocast, on both torch versions. Under autocast the
compiled output is fp16 on main and bf16 here.
- Existing fp64 oracle tests for the non autocast path pass unchanged.
- Speed, no autocast (bf16, 4096 x 4096 weight, forced fused, eager, 7
interleaved repeats of 500 calls, median per call): M=1 117.6 us vs
118.2 us on main, M=16 107.6 us vs 107.8 us. Same within noise.

## Not covered

- No A100 / L4 / RTX PRO 6000 run, so the dX slowdown on unaligned K
that the gate now avoids is unslothai#13840's measurement, not re measured here.
- Backward run inside an autocast region (not recommended by PyTorch)
still computes fused dX in the grad dtype; with the forward fix, the
grad dtype is already the autocast dtype in the normal flow.
- Non CUDA devices are unchanged (the fused path is CUDA only).
- With a bias, the output is still cast back to `X.dtype` after the bias
add, exactly as before unslothai#13840 (dense and fused alike). Only the
bias-free path changes dtype under autocast.
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