Skip to content

NVFP4: decode weight tiles inside the GEMM for small-batch forward and dX - #13840

Merged
danielhanchen merged 16 commits into
mainfrom
nvfp4-fused-gemm
Oct 15, 2026
Merged

danielhanchen merged 16 commits into
mainfrom
nvfp4-fused-gemm

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Problem

nvfp4_linear (compressed-tensors nvfp4-pack-quantized W4A16 checkpoints) dequantizes the full packed weight to a 16 bit copy on every forward and every input-gradient call, then runs torch.matmul on it. For decode and small batches that temporary dominates: a 4096 x 4096 layer allocates 33.7 MB per call for 16 activation rows.

Change

unsloth/kernels/nvfp4.py:

  • Two tiled Triton GEMMs, X @ W^T (forward) and dY @ W (dX), sharing one tile decoder: the weight is decoded one K tile at a time inside the GEMM, never materialized. fp32 accumulation.
  • Same rounding as the dense path: each element is the E2M1 value times (block scale / global scale) in fp32, cast once to the activation dtype. E2M1 is decoded by placing the 3 magnitude bits as fp16 exponent / mantissa bits (exact upcast, then an exact power of two rescale); E4M3 scale bytes use the existing _e4m3_to_float.
  • When the output has few tiles the reduction is split into fp32 partials (capped at 1/8 of the 16 bit weight size) and summed in a fixed order by a small kernel, so results are deterministic.
  • Any strides, masked tails, int64 offsets past 2^31 elements. The switch sits inside the existing compile-opaque forward / backward ops, so torch.compile behaviour is unchanged.
  • Dispatch: the fused path is used only up to a measured activation row count per GPU (sm80: 64, sm89: 256, sm120: 128). Larger inputs, shapes whose N or K is not a multiple of 64 (padded tiles lose to dense), and GPUs without a measured win (T4, H100, B200, sm103), ROCm, XPU and fp32 activations keep the dense path exactly as today. UNSLOTH_NVFP4_FUSED=0 forces dense, =1 forces fused, UNSLOTH_NVFP4_FUSED_MAX_ROWS overrides the row limit; both are read on the first NVFP4 call. On GPUs without a row limit the added check costs about 1 us per call before the unchanged dense path.

Performance

Fused vs dense (dequantize + torch.matmul) speedup, Colab, shapes 4096 x 4096, 14336 x 4096, 4096 x 14336, forward and dX, interleaved with a second dense arm as the A/A (median gap: L4 0.08%, A100 0%, RTX PRO 6000 0.01%):

GPU M=1 8 32 64 128 256 512 2048
L4 (sm89) 2.9-5.6 3.0-5.5 2.6-5.6 2.0-4.4 1.9-3.3 1.24-1.84 0.88-1.09 0.69-0.79
A100 40GB (sm80) 1.8-2.8 1.8-2.7 1.6-2.5 1.12-1.45 0.71-0.94 0.41-0.72 0.33-0.61 0.34-0.45
RTX PRO 6000 (sm120) 1.9-3.8 2.0-3.7 1.5-2.5 1.24-1.83 1.14-1.47 0.87-1.07 0.76-0.87 0.61-0.68
B200 (sm100) 0.63-1.03 0.60-1.03 0.58-0.79 0.50-0.67 0.41-0.81 0.42-0.87 0.32-0.57 0.22-0.26
T4 (sm75) 0.07-0.75 0.07-0.65 0.04-0.07 0.02-0.03 0.01 0.01 < 0.01 < 0.01

Each GPU's row limit is the last row count that won on every shape and op; B200 and T4 lose everywhere, so they keep the dense path and no default case is slower than today.

Re-timed after the edge case fixes in this PR (masked padding, int64 offsets, scale bound), same Colab GPUs, 5 interleaved rounds with an A/A twin: kernel time matches the first version within noise (geomean 0.999 L4, 1.004 A100, 1.001 RTX PRO 6000). Inside the row gate the worst end to end fused / dense ratio is 0.80 on L4, 0.90 on A100 and 0.82 on RTX PRO 6000; just past it A100 at 128 rows is 1.06 to 1.53 and RTX PRO 6000 at 256 rows is 0.94 to 1.14, so the limits stand. A per-call host cost the fixes added (strided offset bound, about 2 us) is skipped for contiguous operands, back to the first version's per-call time. Unaligned shapes (4096 x 4112, 4100 x 4096) are correct through the masked path but up to 2.8x slower than dense in dX, hence the 64 multiple requirement.

Peak memory (4096 x 4096, 16 rows): 2.2 MB forward and 4.3 MB dX, against 33.7 MB on main.

Numerics

Against an fp64 oracle (B200, 4096 to 14336 wide, M 1 to 2048) the fused and dense paths have the same relative error (bf16 1.62e-3 to 1.66e-3, fp16 2.07e-4 to 2.09e-4 against the rounded weight); 97.7% to 100% of outputs are bit-identical to dense, the rest differ by about one output ulp (accumulation order).

Tests

New tests/test_nvfp4_fused_gemm.py (48): all 16 E2M1 codes exact through both kernels; every finite E4M3 block scale against global scales 1e-3 and 3.7e4 matching the dense weight bit for bit; NaN scales; tails (K = 40, 48, 272, 400, 1040, odd M and N); split reduction and its determinism; strided / transposed activations, 3D inputs, sliced packed weights, fp32 block scales; fp16 and bf16; kill switch, row limit and fallbacks; autograd engaging both kernels; a 4-step AdamW LoRA parity run fused vs dense; torch.compile with no graph breaks; peak memory; offset width from the strided span, operands on two devices, degenerate operands, extra scale columns, double backward, inf scale in a partial last group, zero global scale with a partial row tile, column-strided E4M3 scales, unaligned shapes kept dense, flags read once. On B200 (torch 2.14 / Triton 3.8, two GPUs) 48 passed with tests/test_triton_fp_fusion.py 4 passed. The original 38 fail on main. With tests/test_nvfp4_kernel.py: 65 passed on torch 2.7.1 / Triton 3.3 and 38 passed + 1 skipped (no compressed-tensors) on torch 2.14 / Triton 3.8; Colab torch 2.11 / Triton 3.6: 38 / 38 on L4, A100 and RTX PRO 6000, 23 / 23 on T4 (fp16).

Not covered: H100 and sm103 timing (dense by default there), torch 2.6 / Triton 3.2. The fast_lora training path (matmul_lora) still dequantizes through fast_dequantize; moving it over is a separate change.

W4A16 NVFP4 matmuls no longer dequantize the full weight to 16 bit before
torch.matmul. Two tiled Triton kernels (X @ W^T and dY @ W) decode E2M1
codes and E4M3 block scales per K tile with the same per-element rounding
as the dense path (code * (block_scale / global_scale) in fp32, one cast),
accumulate in fp32, and split the reduction deterministically when the
grid is small.

Enabled per GPU up to a measured row count (decode / small batch), where
it beats dequantize + cuBLAS; larger inputs, unmeasured GPUs, ROCm, XPU and
fp32 activations keep the dense path. UNSLOTH_NVFP4_FUSED=0 restores the
dense path, =1 forces the fused kernels; UNSLOTH_NVFP4_FUSED_MAX_ROWS
overrides the row gate.
@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-15T19:32:52.354952Z 95c42ee Manual request
🔒 Security Review ⚠️ Failed 2026-10-15T11:29:52.917340Z 3014779 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. More of your lovely PRs please.

Reviewed commit: 94a85df3f9

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

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@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: 9310a2914c

ℹ️ 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/nvfp4.py

def _scale_args(scale):
e4m3 = scale.dtype == torch.float8_e4m3fn
return (scale.view(torch.uint8) if e4m3 else scale), e4m3

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 Handle strided E4M3 scales before reinterpreting

When an otherwise valid E4M3 scale is a column-strided view, such as base[:, ::2], _fused_ok selects the fused path but this dtype view raises because Tensor.view(dtype) requires the last stride to be 1 (PyTorch documentation). The previous dense path made the scale contiguous before reinterpreting it, so both forward and backward now fail for inputs they previously accepted; either preserve that contiguity conversion or keep such scales on the dense path.

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.

Checked: the E4M3 scale is reinterpreted as uint8, and both are 1 byte, so Tensor.view(dtype) keeps the sizes and strides and has no last-stride requirement (that rule applies only when the element size changes). On torch 2.14, base[:, ::2].view(torch.uint8) returns stride (8, 2) with the same bytes. Added test_column_strided_e4m3_scales: a stride-2 E4M3 scale gives byte-identical fused output to the contiguous one. Leaving the path as is.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@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: 3ef127b101

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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: b0615fe334

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

Copy link
Copy Markdown

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

Reviewed commit: 75043d23ce

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

Copy link
Copy Markdown

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

Reviewed commit: 95c42eea43

ℹ️ 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 fa15e69 into main Oct 15, 2026
@danielhanchen
danielhanchen deleted the nvfp4-fused-gemm branch October 15, 2026 20:50
danielhanchen added a commit that referenced this pull request Oct 15, 2026
…off the hook (#13937)

#13840 (fa15e69) landed just before #13936 and puts two checks back
to red on main:

```
FAILED tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe
    test_nvfp4_fused_gemm.py:365: torch.cuda.device_count()
FAILED tests/test_formatter_fixed_point.py::test_every_tracked_python_file_is_already_formatted
    tests/test_nvfp4_fused_gemm.py
    unsloth/kernels/nvfp4.py
```

Both are the same shape as #13936 and nothing in #13840's kernel
changes:

- `tests/test_nvfp4_fused_gemm.py` gated its two-GPU test on
`torch.cuda.device_count() < 2`, which
`tests/_zoo_aggressive_cuda_spoof.py` can patch process-wide, so it
un-skips on a CPU-only runner sharing a session with the version-compat
suites. It now reads `not has_real_cuda() or torch.cuda.device_count() <
2`, matching the rest of the tree. The module-level `pytestmark` used
`torch.cuda.is_available()` the same way; it now uses `has_real_cuda()`
too. On a real GPU both predicates answer as before.
- Formatter output for the two files (pinned ruff 0.6.9 via
`scripts/run_ruff_format.py`), no logic change.

Verification:
- `tests/python/test_accelerator_skip_guards.py`: fails on main as
above, 24 passed here.
- `tests/test_formatter_fixed_point.py`: fails on main as above, 16
passed here.
- `unsloth/kernels/nvfp4.py` compiles; the change there is line wrapping
only.
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.
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.
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 22, 2026
…ok override (unslothai#14789)

Test-only fix for `test_split_reduction_matches_unsplit` in
`tests/test_nvfp4_fused_gemm.py` (re-verify note on unslothai#13840).

The test swaps `_CONFIG_HOOK` to force split 1, then calls
`monkeypatch.undo()` and re-sets `UNSLOTH_NVFP4_FUSED=1` before its
final bitwise check. `undo()` also reverts the `live_env` fixture, so
the last calls read whatever `_fused_env` was cached earlier in the
session. When a previous test cached a dense decision, the final
`torch.equal` compares a fused result against a dense one and all six
cases fail.

## Change

The `_CONFIG_HOOK` override now sits in a nested
`monkeypatch.context()`, so only the hook is restored and the fixture's
environment stays in place. No library code changes.

## Validation

With a pytest plugin that seeds a cached dense decision before the test
(the order-dependent case):

| torch | main | this PR |
|---|---|---|
| 2.10 | 6 failed | 6 passed |
| 2.14 | 6 failed | 6 passed |

Without the seeded cache the file passes on both sides as before
(`test_nvfp4_fused_gemm.py`: 57 passed, 1 skipped on B200, torch 2.14).
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