Repository navigation
FP8 per-tensor / rowwise dequant: one Triton pass over the e4m3fn bytes - #14886
Conversation
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| 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()) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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).
| 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)) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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).
…poses only [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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]
… (#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.
…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`).
Per-tensor and rowwise FP8 weight dequant (
weight_dequantwith 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 doesfast_dequantizeand 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
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._e4m3fn_byte_to_float(FP8 block dequant below sm89: decode e4m3fn bytes in one Triton pass #14408), so it also runs on GPUs below sm89 (T4).When it is used
Eager NVIDIA calls only, when all of these hold:
Everything else keeps the current torch path:
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.
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:Results on B200:
Every
tests/test_fp8_*.pyfile, plustest_compressed_tensors_fp8_kernel_route.pyandtest_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.test_fp8_dequant_save_policy.py::test_explicit_and_automatic_dequantize_reload[False]andtest_fp8_ragged_block_dequant.py::test_ragged_rows_match_block_reference[glm5_3|ling3]. These fail on main too.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:Not covered
torch.version.hipkeeps the torch path).