Skip to content

FP8 per-tensor / rowwise dequant: one Triton pass over the e4m3fn bytes - #14886

Merged
danielhanchen merged 3 commits into
mainfrom
fp8-rowwise-dequant-one-pass
Oct 23, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
fp8-rowwise-dequant-one-pass

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

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

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).

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 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-23T03:35:52.564226Z 795ed2b Manual request
ℹ️ 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 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: 10c6f56204

ℹ️ 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
and x.dim() == 2
and s.device == x.device
and s.dtype in (torch.float32, torch.bfloat16, torch.float16)
and not (s.requires_grad and torch.is_grad_enabled())

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 Preserve gradients for trainable FP8 inputs

When x is a greater-than-4M-element e4m3fn tensor with requires_grad=True, grad mode is enabled, the scale is frozen, and the requested output is bf16 or fp32, this gate selects a raw Triton launch whose freshly allocated output has no autograd connection to x. The previous x.to(dtype) * s.to(dtype) path propagated gradients through the cast and multiply, so this silently changes the public function's backward behavior; reject the fast path when x requires gradients or provide an autograd 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 795ed2b: the fast path is skipped whenever grad mode is on and either the weight or the scale requires grad, so the torch expression (and its graph) is used. test_trainable_fp8_input_keeps_autograd fails on the previous head and passes now (torch 2.10 and 2.14).

Comment thread unsloth/kernels/fp8.py Outdated
and s.device == x.device
and s.dtype in (torch.float32, torch.bfloat16, torch.float16)
and not (s.requires_grad and torch.is_grad_enabled())
and (x.is_contiguous() or _is_transposed_view(x))

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 Require a dense transpose before using flat indexing

For a large non-dense input whose transpose satisfies _is_transposed_view—for example, x = base.expand(m, n) with column scales, which makes the internal x.t() have strides (1, 0)—this condition admits the fast path. _scale_dequant_one_pass then transposes back but indexes the bytes as a dense r * N + c array, ignoring the zero or gapped strides, so it reads beyond the view's backing storage and returns incorrect data instead of preserving the prior strided-tensor behavior. Restrict this branch to views whose transpose is actually contiguous, or pass and honor both input strides in the kernel.

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 795ed2b: a transposed view only takes the kernel when its transpose is contiguous, since the kernel indexes dense rows. test_strided_transposed_view_keeps_the_torch_path (the transpose of a column slice) fails on the previous head and matches the torch expression now (torch 2.10 and 2.14).

@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: 795ed2ba32

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

[skip ci]
@danielhanchen
danielhanchen merged commit effa4c3 into main Oct 23, 2026
@danielhanchen
danielhanchen deleted the fp8-rowwise-dequant-one-pass branch October 23, 2026 03:49
danielhanchen added a commit that referenced this pull request Oct 23, 2026
… (#14885)

Two files merged without the repo formatter, so pre-commit.ci's
`ruff-format-with-kwargs` hook (which runs on all files) rewrites them
on every PR queued after:

- `studio/backend/tests/test_diffusion_learned_peaks.py` from #14821
(03:15 UTC)
- `tests/test_fp8_scale_dequant_one_pass.py` from #14886 (03:49 UTC),
folded in while this was in review

Same class as #14817, #14852 and #14878. `python
scripts/run_ruff_format.py` (the hook's entry point, `ruff==0.6.9`)
applied to those two files. Both parse to identical ASTs before and
after, `ruff check` passes, and a full run of the hook over every
tracked Python file on this branch changes nothing else.
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 23, 2026
…opaque byte-decode op (unslothai#14913)

Below sm89, compiling a per-tensor or rowwise FP8 dequant
(`weight_dequant` on an e4m3fn weight inside `torch.compile`) crashed.
Inductor fused `x.to(dtype) * s` into a Triton kernel that loads
fp8e4nv, which Triton does not support before sm89:

```
torch._inductor.exc.InductorError: CompilationError: ... ValueError("type fp8e4nv not supported in this architecture. The supported fp8 dtypes are ('fp8e4b15', 'fp8e5')")
```

On a real T4, `test_compiled_dequant_keeps_the_fused_expression` failed
this way on torch 2.10.0, 2.11.0 and 2.12.1. This affects any compiled
region that dequantizes a per-tensor or rowwise FP8 weight on T4, V100,
A100 or A10.

## Change

`unsloth/kernels/fp8.py`:
- Under compile, when the device cannot compile fp8e4nv
(`_fp8_kernel_unsupported`, the gate the block path already uses),
`_scale_mul` now calls the byte-decode kernel from unslothai#14886. The kernel is
registered as one opaque op, `unsloth::fp8_scale_dequant`, via
`_opaque_under_compile`, so Inductor never generates fp8 code for it.
- The op returns the same bits and strides as the torch expression.
- On sm89 and newer, compiled regions keep the fused torch expression as
before.
- The eager size gate from unslothai#14886 still applies only to eager calls.

## Tests

`tests/test_fp8_scale_dequant_one_pass.py`:
- `test_compiled_dequant_below_sm89_is_one_opaque_op`: fp16 / bf16
output with rowwise, transposed rowwise and per-tensor scales. The test
forces the pre-sm89 gate, then checks that the compiled graph holds the
opaque op, that strides match, and that the bits match the torch
expression.
- `test_compiled_dequant_keeps_the_fused_expression`: on sm89 and newer,
checks that the graph has no opaque op and that Inductor gives the same
bits. It is skipped where the new test applies.

Real T4 (Colab), with a fresh venv per torch version. The FP8 files run
were the new test file, `test_fp8_pre_sm89_byte_dequant.py` and
`test_fp8_pre_sm89_dequant_fallback.py`.

| torch | main | this PR |
|---|---|---|
| 2.10.0 | 8 failed, 203 passed | 1 failed, 174 passed |
| 2.11.0 | 8 failed, 203 passed | 1 failed, 174 passed |
| 2.12.1 | 8 failed, 203 passed | 1 failed, 174 passed |
| 2.13.0 | 7 failed, 204 passed | 1 failed, 174 passed |

How to read the main column:
- 6 of main's failures are the new opaque-op test, which main cannot
pass.
- One is the compile crash above (it does not reproduce on 2.13.0).
- The remaining one is
`test_fp8_pre_sm89_byte_dequant.py::test_under_torch_compile`, which
fails the same way on both sides; see below.
- Main also runs a copy of the PR's test file under a different name, so
its pass count is not comparable.

Compiled with the default Inductor backend, `fullgraph=True`, comparing
bit patterns and strides against the torch expression:

| GPU | torch | fp16 rowwise / transposed / per-tensor | bf16 rowwise /
transposed / per-tensor |
|---|---|---|---|
| T4 | 2.10.0, 2.13.0 | identical | fails with `torch.* op returned
non-Tensor` (`device_count`) |
| A100 | 2.10.0, 2.13.0 | identical | identical |

B200 (sm100, torch 2.10 and 2.14): 43 passed, with the pre-sm89 gate
simulated for the new tests.
`test_compiled_dequant_reads_no_device_capability` checks that the
compiled gate queries no device capability while tracing (it reads a
per-device tuple built at import).

## Not changed / not covered

- **bf16 under compile on T4.** It still fails with `torch.* op returned
non-Tensor` (`device_count`), for this op and for the existing block op
(`test_under_torch_compile`). A100 compiles both. T4 has no native bf16,
and Unsloth trains in fp16 there, so this PR does not address it.
- **Main on A100.** The A100 rows above were run on this branch only,
not on main.
- **ROCm** keeps its current path (`torch.version.hip`).
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