Skip to content

FP8 block dequant below sm89: decode e4m3fn bytes in one Triton pass - #14408

Merged
danielhanchen merged 2 commits into
mainfrom
fp8-block-dequant-pre-sm89
Oct 20, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
fp8-block-dequant-pre-sm89

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Below sm89 (T4, A100, sm86) Triton cannot compile fp8e4nv, so block-scaled FP8 weight dequant (_blockwise_weight_dequant_any_shape) falls back to the chunked torch loop _torch_blockwise_dequant. That loop is 6 to 8x slower than one pass over the weight and allocates float32 scratch on top of the output. On these GPUs it runs on every forward and backward of a block-FP8 checkpoint routed through the FP8 kernels (compressed-tensors block-FP8 with UNSLOTH_COMPRESSED_TENSORS_FP8_KERNELS=1 and UNSLOTH_COMPRESSED_TENSORS_FP8_BLOCK_KERNELS=1, plus ragged / rectangular block shapes).

Change

  • New Triton kernel _e4m3fn_bytes_dequant reads the weight as raw bytes, decodes E4M3FN in registers (subnormals, -0.0 and NaN included), multiplies by the block scale in fp32 and rounds once to the output dtype: the same arithmetic as the torch loop, so the output is bit-identical. It handles any strides (transposed views, column slices), ragged and rectangular blocks, fp32 / fp16 / bf16 / e8m0 scales and int64 offsets for large weights, and is opaque under torch.compile.
  • Used only for e4m3fn weights on NVIDIA below sm89 (_fp8_kernel_unsupported). sm89+ routing, ROCm, e5m2 weights and CPU are unchanged.

Validation

New tests/test_fp8_pre_sm89_byte_dequant.py: bit equality with _torch_blockwise_dequant over 9 shapes (1 to 3 blocks, ragged, one row, real sizes) x 3 block shapes x 3 output dtypes with every byte value; the four scale dtypes; transposed and strided weights; offsets past 2^31; peak memory equal to the output; routing per arch / dtype (sm89+ and e5m2 keep their paths, ROCm keeps the torch loop); forward / backward equality; fullgraph compile; CPU. With the existing FP8 tests: 207 passed, 5 skipped on B200 (pre-sm89 paths forced).

weight_dequant on Colab, main vs this PR interleaved, 3 runs each in fresh processes, median ms (spread = main run to run):

GPU / torch weight main (spread) this PR speedup
T4 fp16 / 2.10.0 14336 x 4096 7.038 (0.1%) 0.875 8.04x
T4 fp16 / 2.14.1 14336 x 4096 7.052 (0.3%) 0.916 7.70x
T4 fp16 / 2.14.1 4096 x 14336 7.060 (0.1%) 0.923 7.65x
T4 fp16 / 2.14.1 14400 x 4160 (ragged) 7.148 (0.1%) 1.082 6.61x
A100 bf16 / 2.14.1 14336 x 4096 1.664 (0.7%) 0.224 7.42x
A100 bf16 / 2.14.1 14400 x 4160 (ragged) 1.602 (1.1%) 0.252 6.36x

Every row is bit-exact against main; extra peak memory beyond the output: 47 to 96 MiB on main, 0 here.

End to end, inference-optimization/Llama-3.2-1B-Instruct-FP8-Block (112 layers routed), transformers 5.17.0:

main this PR
T4 greedy decode tok/s, torch 2.10 / 2.14.1 8.71 / 8.67 23.18 / 24.11
A100 greedy decode tok/s, torch 2.10 / 2.14.1 19.29 / 19.89 24.02 / 24.90
A100 LoRA step (20 steps), torch 2.10 / 2.14.1 0.278 / 0.251 s 0.236 / 0.211 s
  • All 128 greedy tokens identical between arms and runs on both GPUs; decode peak 1.565 GiB on main, 1.487 GiB here.
  • The 20 LoRA losses are identical to 6 decimals; peak memory equal (1.833 GiB).
  • Every dequant call went through the new kernel on this branch (448 per decode step, 6720 per training run) and through the torch loop on main.

The A100 torch 2.10 end-to-end rows ran an earlier tile (64 x 128, 8 warps); the committed 8 x 512 tile measured 0.224 ms vs 0.218 ms for the best tile in the A100 torch 2.10 sweep.

Not covered: ROCm (path unchanged), L4 / sm86 timing, and fp16 LoRA training on FP8 checkpoints, which fails on main and here alike (fast_dequantize calls weight_dequant without a dtype, so the bf16 result meets fp16 activations; separate fix).

T4 / A100 / sm86 cannot compile Triton fp8e4nv, so block FP8 weights went
through a chunked torch loop (repeat_interleave scale expansion plus float32
scratch). Read the weight as uint8, decode e4m3fn in registers and scale in
float32 in one kernel: bit-identical to the torch loop, any strides, ragged
and rectangular blocks, fp32 / fp16 / bf16 / e8m0 scales, and no scratch
beyond the output. sm89+ and ROCm keep their current paths.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 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-20T21:01:54.133980Z 51edb7c Manual request
🔒 Security Review ⚠️ Failed 2026-10-20T20:59:35.762083Z
We couldn’t complete this review. Comment @codex security review to try again.
51edb7c 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: 51edb7caf7

ℹ️ 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 98010f6 into main Oct 20, 2026
@danielhanchen
danielhanchen deleted the fp8-block-dequant-pre-sm89 branch October 20, 2026 21:17
meefs pushed a commit to meefs/unsloth that referenced this pull request Oct 21, 2026
`tests/test_triton_fp_fusion.py::test_every_launch_requests_fp_fusion`
fails on main since unslothai#14408: the new `_e4m3fn_bytes_dequant_kernel`
launch in `unsloth/kernels/fp8.py` does not pass `enable_fp_fusion`,
which every Triton launch in `unsloth/kernels` sets explicitly.

## Change
- Pass `enable_fp_fusion = True` at that launch, like the other FP8
dequant kernels in the file.

The output does not change: after the byte decode (exact in fp32) the
kernel does a single multiply by the block scale and one rounding to the
output dtype, so there is no multiply-add for the backend to contract.

## Validation
On B200 (pre-sm89 path forced as in the test file):
`tests/test_triton_fp_fusion.py` and
`tests/test_fp8_pre_sm89_byte_dequant.py` give 99 passed, including bit
equality with `_torch_blockwise_dequant` over every byte value, all
shapes, block shapes and output dtypes. On main the fusion test fails
with `Triton launches without enable_fp_fusion:
['fp8.py:722:_e4m3fn_bytes_dequant_kernel']`.
danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Oct 21, 2026
…ecoder on every NVIDIA GPU (4-16x) (unslothai#14450)

Block-FP8 weights whose shape does not tile into whole blocks (2880 x
2880 for gpt-oss-sized layers, 14400 x 4160, ...) or that use
rectangular blocks are dequantized by the chunked torch loop
`_torch_blockwise_dequant` on sm89+ GPUs (L4, H100, B200, RTX PRO 6000).
That is 4 to 16x slower than one pass over the weight. unslothai#14408 added a
bit-identical e4m3fn byte decoder (`_e4m3fn_bytes_dequant`), but routed
only pre-sm89 GPUs to it.

## Change
- In `_blockwise_weight_dequant_any_shape`, every case that took the
torch loop on NVIDIA now takes the byte decoder for e4m3fn weights with
a 2-D scale: ragged shapes and rectangular blocks on any arch, plus
pre-sm89 as before.
- Unchanged:
  - even square tiles on sm89+ keep the native fp8 Triton kernel;
  - e5m2 weights, per-tensor scales, CPU and ROCm keep their routes.

The byte decoder's output is bit-identical to the torch loop: same
arithmetic, one rounding, every byte value incl. subnormals, -0.0 and
NaN, as tested in unslothai#14408.

## Validation
`tests/test_fp8_pre_sm89_byte_dequant.py`:
- **Routing:** sm89 / sm90 / sm100 send ragged and rectangular-block
e4m3fn weights to the byte decoder, keep even tiles on the fp8 kernel,
and keep ragged e5m2 on the torch loop.
- **New unmocked test:** on the real device, ragged (130 x 256, 300 x
520) and rectangular-block (128 x 64) weights take the byte decoder and
are bit-equal to the torch loop.
- **Results:** with the other FP8 tests and `test_triton_fp_fusion.py`
on B200, 330 passed, 25 skipped; on Colab L4 (torch 2.11, Triton 3.6)
the two pre-sm89 FP8 files gave 140 passed.

`_blockwise_weight_dequant_any_shape` per call, bf16 output, ms. Main
and this PR in fresh processes; main's route is the torch loop (main /
torch loop = 1.00 in every row):

| GPU | weight | block | main | this PR | speedup |
|---|---|---|---|---|---|
| B200 | 14400 x 4160 | 128 x 128 | 1.348 | 0.121 | 11.1x |
| B200 | 2880 x 2880 | 128 x 128 | 0.201 | 0.012 | 16.1x |
| B200 | 4096 x 14336 | 128 x 64 | 1.106 | 0.113 | 9.8x |
| B200 | 1000 x 4096 | 128 x 128 | 0.041 | 0.008 | 5.0x |
| L4 | 14400 x 4160 | 128 x 128 | 5.32 | 0.81 | 6.6x |
| L4 | 2880 x 2880 | 128 x 128 | 0.742 | 0.059 / 0.080 | 9.3 to 12.5x |
| L4 | 4096 x 14336 | 128 x 64 | 5.12 | 0.755 | 6.8x |
| L4 | 1000 x 4096 | 128 x 128 | 0.256 | 0.060 | 4.2x |

L4 rows: two rounds each, main within 0.1% of itself; the 2880 x 2880
row gave 0.080 and 0.059 ms on this PR.

Not covered:
- H100 (no Colab capacity on either account): same route as L4 / B200
(sm89+).
- End-to-end training or decode on a ragged block-FP8 checkpoint.
- ROCm is untouched here (separate change).

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 23, 2026
…es (unslothai#14886)

Per-tensor and rowwise FP8 weight dequant (`weight_dequant` with a
scalar or `(rows, 1)` scale) ran as two passes: `x.to(dtype)` writes a
16-bit copy, then a multiply reads it back and writes the result. Every
LoRA backward on FBGEMM / compressed-tensors rowwise FP8 checkpoints
dequantizes each frozen weight this way, as does `fast_dequantize` and
the dequant forward on GPUs without a working rowwise GEMM.

This PR adds `_e4m3fn_scale_dequant_kernel`: one Triton pass that reads
the e4m3fn bytes once and writes the output once (3 bytes per element
instead of 7).

## Same bits as before

- fp16 multiplies by the fp32 scale and rounds once, as unslothai#14677 does.
- bf16 / fp32 round the scale to the output dtype first, as `x.to(dtype)
* s.to(dtype)` does. An e4m3 value times a bf16 scale is exact in fp32,
so one rounding gives torch's result.
- The bytes are decoded with the existing `_e4m3fn_byte_to_float`
(unslothai#14408), so it also runs on GPUs below sm89 (T4).
- Transposed views keep the strides the torch expression returns.

## When it is used

Eager NVIDIA calls only, when all of these hold:

- the weight is e4m3fn and has more than 4M elements;
- the output is fp16 / bf16 / fp32, with an fp32 / bf16 / fp16 scale;
- neither the weight nor the scale needs a gradient, and a transposed
view is a dense transpose.

Everything else keeps the current torch path:

- compiled regions (Inductor already fuses the expression);
- ROCm, e5m2 weights, float64;
- smaller weights. At or below 4M elements the call is launch-bound on
A100 and newer, and the torch path is no slower there.

## Speed

Colab, torch 2.11 / Triton 3.6, CUDA events, median of 5, A/A spread of
the base mostly under 5%. Times are base -> this PR in microseconds for
the rowwise layout; all layouts (rowwise, transposed rowwise,
per-tensor) are within a few percent of each other.

| shape | dtype | T4 | L4 | A100 |
|---|---|---|---|---|
| 2048 x 6144 | bf16 | 629 -> 192 (3.3x) | 298 -> 48 (6.2x) | 132 -> 43
(3.1x) |
| 2048 x 6144 | fp16 | 715 -> 190 (3.8x) | 350 -> 46 (7.6x) | 155 -> 44
(3.6x) |
| 4096 x 4096 | bf16 | 844 -> 249 (3.4x) | 480 -> 82 (5.9x) | 172 -> 45
(3.8x) |
| 4096 x 4096 | fp16 | 965 -> 253 (3.8x) | 537 -> 74 (7.3x) | 204 -> 45
(4.5x) |
| 14336 x 4096 | bf16 | 2971 -> 873 (3.4x) | 1763 -> 766 (2.3x) | 565 ->
146 (3.9x) |
| 14336 x 4096 | fp16 | 3439 -> 880 (3.9x) | 1850 -> 766 (2.4x) | 686 ->
146 (4.7x) |

At 4M elements (2048 x 2048, 1024 x 4096), T4 still gains 3.3-5.5x. On
A100 the result ranged from 0.78x to 1.44x there, because both versions
are launch-bound. Hence the size gate.

## Tests

`tests/test_fp8_scale_dequant_one_pass.py`:

- Bit patterns are compared against the torch expression for every byte
value (NaN, both zeros, subnormals) in each of these cases:
  - output fp16 / bf16 / fp32;
  - scale fp32 / bf16;
- rowwise, transposed rowwise, per-tensor, and transposed per-tensor
layouts.
- fp16 at extreme scales (1e-8, 1e5) still rounds once.
- e5m2 weights, float64 scales, a weight or scale that requires grad, a
transposed view whose transpose is not dense, and compiled regions keep
the torch path.
- A 2048 x 2048 weight stays on the torch path, and a 2049 x 2048 weight
takes the kernel.

Results on B200:

| torch | main | this PR |
|---|---|---|
| 2.10 | 32 of the 36 new tests fail (kernel never used) | 36 passed |
| 2.14 | 32 of the 36 new tests fail (kernel never used) | 36 passed |

Every `tests/test_fp8_*.py` file, plus
`test_compressed_tensors_fp8_kernel_route.py` and
`test_fp8linear_high_precision_weight.py`, was also run on B200. For
this run the size gate was off, so the kernel served every per-tensor /
rowwise call in those tests.

- main and this branch fail the same 3 test IDs on torch 2.10 and 2.14:
`test_fp8_dequant_save_policy.py::test_explicit_and_automatic_dequantize_reload[False]`
and
`test_fp8_ragged_block_dequant.py::test_ragged_rows_match_block_reference[glm5_3|ling3]`.
These fail on main too.
- Everything else passes: torch 2.14 658 passed, torch 2.10 707 passed.

## End to end

LoRA r 16 on all linear layers of `RedHatAI/Qwen3-1.7B-FP8-dynamic`
(compressed-tensors per-channel FP8), batch 4 x 512, torch 2.10, B200:

- Each training step makes 196 dequant calls; 84 of them take the new
kernel (the three 6144 x 2048 MLP weights in each of the 28 layers). The
other calls are below the size gate.
- Every kernel output was compared with the torch expression inside the
training run: 0 mismatches in 252 calls, in both bf16 and fp16.
- Losses match main within run-to-run noise (bf16 max difference 0.0044
against 0.0048 between two main runs; fp16 is noisier on both sides).

## Not covered

- No end-to-end step time: the end-to-end run was on a shared GPU, so
only correctness is claimed from it.
- H100 / B200 timing was not run on a dedicated card.
- ROCm is unchanged (`torch.version.hip` keeps the torch path).
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