Repository navigation
FP8 scaled_mm backend: send 17-64 rows to torch._scaled_mm when the 16-bit weight spills L2 (sm89) - #15791
Merged
Conversation
A compiled fbgemm_fp8_linear call costs 75-95 us of host time before any kernel runs, which dominates decode and small prefill. Without autograd and outside a trace, launch the kernels Inductor generates directly (per-row activation quant + _scaled_mm above 64 rows, fused dequant + matmul below), bitwise equal to the compiled path.
…_DISABLE [skip ci]
…ed-weight case without view ops
… 16-bit weight spills L2 Dequant + 16-bit GEMM stays the route for L2-resident weights (launch bound, dequant wins), while a weight whose bf16 copy exceeds L2 is memory bound on the per-call dequant. UNSLOTH_FP8_DEQUANT_MAX_ROWS sets one threshold for every weight.
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. |
Member
Author
|
@codex review |
1 similar comment
Member
Author
|
@codex review |
…-threshold # Conflicts: # tests/test_fp8_rowwise_direct_route.py # unsloth/kernels/fp8.py
… writes bf16 bits into fp16 output without a bias)
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
danielhanchen
added a commit
that referenced
this pull request
Oct 28, 2026
…ners (#15838) On the AMD gfx1151 runner (ROCm 7.13, torch 2.11), 11 FP8 routing tests from #15584 and #15791 fail: - 6 in `tests/test_fp8_dequant_max_rows.py`: `assert None == 'dequant'`; - 5 in `tests/test_fp8_rowwise_direct_route.py`: `assert 'compiled' == 'direct'`. `_fp8_rowwise_direct_route` deliberately keeps the direct path off on ROCm (`torch.version.hip is None`). The tests check the NVIDIA routing table but read the real `torch.version.hip`, so on a ROCm build the route they expect never happens. FP8 outputs on that card are bit-identical before and after those PRs, and the routing did not change. ### Change - Both routing fixtures pin `torch.version.hip = None`, so the NVIDIA routing table is tested on every runner. - New `test_rocm_keeps_the_compiled_path` sets a HIP version and checks that inference calls at 32 and 128 rows stay on the compiled path. ### Tests - On CPU: 22 passed, 2 skipped. - With `torch.version.hip = "7.0"` set before pytest (simulating the ROCm runner): main fails exactly these 11 tests (11 failed, 10 passed), and this branch passes all 22.
This was referenced Oct 29, 2026
danielhanchen
added a commit
that referenced
this pull request
Oct 30, 2026
Follow-up to #15791. ## Problem #15791 sends fp16 activations through a bf16 `_scaled_mm` output on every torch version, because the rowwise kernel before torch 2.14 picks its output type from the bias dtype and writes bf16 bits into an fp16 buffer. torch 2.14 dispatches on `out.dtype`, so there the bf16 detour only drops 3 mantissa bits and turns finite fp16 results in 65408 to 65504 into inf. ## Change Keep the bf16 detour only when `torch.__version__ < "2.14.0"`. On 2.14 and later, request fp16 output directly. 2.14 pre-releases keep the detour. ## Tests `tests/test_fp8_dequant_max_rows.py`, CPU, torch 2.13: - main: 3 failed, 13 passed. Failing: `test_scaled_mm_asks_for_bf16_when_activations_are_fp16`, `test_scaled_mm_keeps_fp16_output_where_torch_writes_fp16`, `test_scaled_mm_fp16_workaround_follows_the_installed_torch`. - this branch: 16 passed. L4, rowwise `torch._scaled_mm`, fp16 activations, fp64 reference: - torch 2.12.1: native fp16 returns 7.5 for an expected 65408, so the detour stays (unchanged here). - torch 2.14.1: through bf16, 65408 becomes inf (all 131072 outputs) and 256.5 becomes 256. Native fp16 returns both exactly, which this branch now requests. On random input, the bit-exact share goes from 11.0% to 32.4%. ## Not covered L4 (sm89) only: no sm90, sm120 or ROCm run, and torch 2.13 was not run on GPU. On torch < 2.14 the 65408 to 65504 band still overflows through the detour. The CPU tests check the routing decision; on main two of them fail on a missing attribute, so the numerical proof is the L4 run.
danielhanchen
added a commit
to LeoBorcherding/unsloth
that referenced
this pull request
Nov 1, 2026
…ed autocast (unslothai#15927) Follow-up to unslothai#15584 (direct rowwise FP8 path) and unslothai#15791 (sm89 large-weight row threshold, fp16 `_scaled_mm` workaround). A recheck found three correctness gaps. Two independent reviewers reproduced each one on a B200. The first one, fp16 output rounded through bf16 on torch 2.14, is fixed on main by unslothai#16063. This branch now merges main and uses its `_SCALED_MM_FP16_OUT_BROKEN` check (torch < 2.14, pre-releases of 2.14 included). This PR fixes the other two. ## 1. float32 activations sent to rowwise `_scaled_mm` before torch 2.14 (unslothai#15791) Rowwise `_scaled_mm` accepts only bf16 / fp16 outputs on torch 2.10 - 2.13. On sm89 the new threshold sends 17 - 64 row calls with an over-L2 weight to `_scaled_mm`, so float32 activations there fail with "out.dtype must be BFloat16 or Half". Before torch 2.14 they now keep the dequant path, gated on the same `_SCALED_MM_FP16_OUT_BROKEN` check as the fp16 workaround. That also covers the same failure above 64 rows, which predates unslothai#15791. torch 2.14 can write float32, so it is unchanged. ## 2. Direct path under autocast in another dtype (unslothai#15584) The direct path dequantizes into a buffer of X's dtype and then calls `matmul`, which autocast may run in another dtype. The compiled path fuses the dequant into autocast's GEMM. With fp16 X under bf16 autocast, a finite weight times scale above 65504 overflows the fp16 buffer first: | fp16 X = 1e-4, W = 1, row scale 1e5, bf16 autocast | before unslothai#15584 | main | |---|---|---| | outputs | 5120 (finite) | inf / NaN | Random inputs also differ from the compiled result, by up to 0.25 abs. The direct route now returns None when CUDA autocast is enabled with a dtype different from X's, so those calls keep the compiled path. Same-dtype autocast and no autocast are unchanged. ## Tests The CPU tests in `tests/test_fp8_dequant_max_rows.py` route through FakeTensorMode. They sit beside the fp16 out dtype tests from unslothai#16063: - float32 keeps dequant while the fp16 output is broken (before 2.14) and keeps `_scaled_mm` after it; - mismatched autocast keeps the compiled path, while matching autocast still takes the direct path. Results after merging main (9a1ea09): - With main's `fp8.py`, 2 of the new cases fail (float32 gate, fp16 X under bf16 autocast). - With this PR, `test_fp8_dequant_max_rows.py` and `test_fp8_rowwise_direct_route.py` give 29 passed, 2 skipped (CUDA only). - All `tests/test_fp8_*.py`, `tests/test_fp8linear_*.py` and `tests/test_compressed_tensors_fp8_kernel_route.py` on torch 2.13 CPU: 328 passed, 470 skipped (CUDA only). ## GPU results (before merging main) These runs predate the merge with main. Base = merge base fa7ad0d, which still had the fp16 bf16 round trip on every torch version. The fp16 rows of the earlier runs are now main's behaviour (unslothai#16063), so only the rows below belong to this PR. Colab L4, sm89, scaled_mm backend. One VM, each torch version in its own uv venv, deleted between versions. | case | 2.10 base | 2.10 head | 2.14 base | 2.14 head | |---|---|---|---|---| | bf16 autocast, fp16 X = 1e-4, scale 1e5 (ref 5120.85) | inf | 5120 | inf | 5120 | | float32 X, 32 rows, 14336 x 4096 | ValueError | dequant, rel err 4.4e-7 | scaled_mm, rel err 0.026 | bitwise equal to base | Colab H100 80GB, sm90, same scripts and arms, torch 2.10.0 and 2.14.1: | case (public `fbgemm_fp8_linear`) | 2.10 base | 2.10 head | 2.14 base | 2.14 head | |---|---|---|---|---| | bf16 autocast, 16 rows, fp16 X = 1e-4, scale 1e5 (ref 5120.85) | inf | 5120 | inf | 5120 | | bf16 autocast, 128 rows (scaled_mm) | 4896 | 4896 (same) | 4896 | 4912 | | float32 X, 32 rows, 14336 x 4096 | dequant, rel err 8.1e-7 | same | same | same | - bf16 outputs are bitwise equal base vs head on both torch versions and both GPUs. - On sm90 the 32-row float32 call already took the dequant path on base, so the L4's ValueError does not occur there. - The 2.14 head runs above used a final release (2.14.1). Main's check also keeps the bf16 detour on 2.14 pre-releases. On those, float32 activations take the dequant path as well. Unchanged by this PR: calling `FbgemmFp8Linear_matmul.apply` directly in eager mode under a mismatched autocast still overflows, the same as main. The guard covers the public `fbgemm_fp8_linear` direct route. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Follows #15584 (merged).
Summary
With the
scaled_mmrowwise FP8 backend (sm89+ without FBGEMM, e.g. L4), calls with 17 to 64 rows dequantize the weight to 16 bits on every call and run a 16-bit GEMM. That is the right choice while the 16-bit copy fits in L2: the call is launch bound and dequant is about 25 us cheaper than activation quant plustorch._scaled_mm. Once the 16-bit copy is larger than L2 the per-call dequant becomes memory bound, and on L4 a Llama-3.1-8B MLP projection costs about 1180 us on the dequant route against 255 to 300 us ontorch._scaled_mm.This PR sends 17 to 64 rows to activation quant plus
torch._scaled_mmonly whenN * K * 2bytes exceeds the device L2 (get_device_properties().L2_cache_size, cached per device and treated as a constant undertorch.compile). Everything else keeps the current 64 row threshold: 16 rows and below, more than 64 rows, an unknown L2, and every L2-resident weight.UNSLOTH_FP8_DEQUANT_MAX_ROWS=Nsets a single threshold for every weight.Which GPUs this touches: the backend is picked by a runtime probe. With
fbgemm_gpuinstalled and working (for example H100 with FBGEMM), the FBGEMM backend is used. It quantizes activations at every row count, so this PR does not change it. Without FBGEMM, sm89+ GPUs wheretorch._scaled_mmrowwise works take thescaled_mmbackend. The large-weight gate only applies on sm89 (L4, RTX 40xx), the arch it was measured on: the L2 probe reports 0 elsewhere, so H100 without FBGEMM (50 MiB L2), RTX PRO 6000 / RTX 50xx and any other arch keep the 64 row default exactly as in #15584.Decode throughput (tok/s, 64 new tokens, greedy)
L4, torch 2.14.1+cu130. Base is #15584 (now on main). Each side ran as 3 interleaved processes. torch 2.10 was not measured for this change.
Routing counts per generate call:
RTX PRO 6000 (sm120, 128 MiB L2): no weight of either model exceeds L2. Routing, outputs (logits KL 0, identical greedy tokens) and throughput are unchanged (Llama 1101 / 1448 / 2069 tok/s on both sides).
Accuracy (Llama-3.1-8B FP8-dynamic, L4)
torch._scaled_mm, the same comparison gives 58%.fp16 output fix (also on main above 64 rows)
On torch 2.10, rowwise
torch._scaled_mmpicks its CUTLASS output element type from the bias dtype. With no bias it writes bf16 bits into anout_dtype=torch.float16buffer, so every fp16 call that reaches_scaled_mmreturns garbage. On main this already happens for fp16 calls above 64 rows. With an all-ones input (Llama-8B 14336x4096), every output should be 4096 but comes back as 5.5. torch 2.14 is correct._scaled_mm_out_dtyperequests bf16 for fp16 activations at both call sites (_fp8_rowwise_directandFbgemmFp8Linear_matmul). The existing tail already casts to the activation dtype.Colab L4, Llama-8B 14336x4096, against an fp32 reference of the dequantized weight:
test_scaled_mm_asks_for_bf16_when_activations_are_fp16checks the dtype mapping.test_every_rowwise_scaled_mm_call_uses_the_out_dtype_helperchecks that every data_scaled_mmcall goes through the helper.Tests
tests/test_fp8_dequant_max_rows.pyruns on CPU with fake tensors. It checks:torch._scaled_mm;FbgemmFp8Linear_matmulautograd path uses the same gate.All of them fail on #15584, which has no gate. The direct-path parity test now asks the route helper for the threshold instead of hard-coding 64.
Not measured
scaled_mmbackend, 50 MiB L2). Colab did not grant an H100 within 25 minutes, so the gate is off there and H100 behaves as in FP8: skip the compiled wrapper for rowwise FP8 inference linears #15584. Enabling it needs H100 numbers.