Skip to content

Fix fp8 block dequant fallback on pre-sm89 GPUs - #10790

Merged
danielhanchen merged 14 commits into
unslothai:mainfrom
xy200303:fix/fp8-dequant-fallback-pre-sm89
Sep 14, 2026
Merged

danielhanchen merged 14 commits into
unslothai:mainfrom
xy200303:fix/fp8-dequant-fallback-pre-sm89

Conversation

@xy200303

@xy200303 xy200303 commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

What

_blockwise_weight_dequant_any_shape sent evenly-tiled square fp8 blocks to the triton
weight_dequant_kernel even when the GPU cannot compile that kernel's fp8 dtype.
torch.float8_e4m3fn (fp8e4nv) only exists from sm89 on, so on A100 the fallback raised

triton.compiler.errors.CompilationError: ValueError("type fp8e4nv not supported in this
architecture. The supported fp8 dtypes are ('fp8e4b15', 'fp8e5')")

instead of falling back — the opposite of what the helper is for. The other two branches of the same
helper already expand the scales in torch; this makes the third one do the same when the device cannot
compile the kernel.

Reproduction

A100-PCIE-40GB (sm80), torch 2.8.0+cu128, triton 3.4.0:

pytest tests/test_fp8_fbgemm_block_shapes.py::test_inputs_the_kernel_rejects_use_dequant_fallback

Before: 1 failed, 3 passed — only the bf16_scale parameter fails, because it is the one that
reaches the block dequant path with a real 128x128 scale grid (the other three take the per-tensor or
uneven-tiling branches, which are already torch-native).

After: 4 passed.

No regressions in the surrounding fp8 coverage:

  • tests/test_fp8_fbgemm_block_shapes.py — 11 passed, 1 skipped
  • tests/test_fp8_device_context.py — 6 passed, 3 skipped

Notes

sm89+ is unaffected: the guard only diverts when the device cannot compile fp8e4nv, so those GPUs
still take the triton path and produce the same values.

I searched issues and PRs for this and did not find an existing report.


Maintainer notes

Reviewed and extended in place. The original diagnosis holds, and the fix now covers the
rest of the surface that shared the same defect.

Changes on top of the original commit

  • The boundary is < (8, 9), not < 9. A major-only test drops all of Ada (4090, L40S, L4)
    onto the fallback even though those cards do compile fp8e4nv. The guard also stands down
    under ROCm, where the capability is gfx-derived and AMD's triton lists fp8e4nv regardless.
  • The fallback expands the scale in chunks. Expanding it over the whole weight needed two
    m*n float32 temporaries, roughly 6x the triton kernel's peak, which traded a
    CompilationError for an OOM on a 40GB A100. Measured 2688 MB to 532 MB on a 4096x8192
    weight, bit-identical output.
  • Two more call sites had the same hole: FP8BlockQuantLinear.forward and
    FP8_fbgemm_block_linear.forward, plus weight_dequant's block branch, which now routes
    through the same helper so fast_dequantize's callers inherit the fallback.
  • Forward dispatch asks about e4m3fn rather than the weight dtype. act_quant emits e4m3fn
    whatever the weight is, so e5m2 block weights reached an uncompilable kernel. The dequant
    site deliberately keeps the weight's own dtype, since fp8e5 compiles everywhere.
  • Grouped FP8 eval no longer returns early into the upstream forward on pre-sm89, which runs
    its own fp8e4nv kernels.
  • The capability lookup is cached (1.19 us to 0.53 us per call), and the fallback runs under
    no_grad to match the kernel it stands in for, which builds no graph either.

torch.compile was measured and rejected: 1.83 ms against 1.61 ms eager at 4096x14336, with
a 34 s first call per distinct shape. It is a memory-bound scale expansion with nothing to
fuse, and compiling the chunk loop unrolls one graph per chunk.

Not a regression. git bisect puts the first bad commit at the one that introduced
fp8.py; all 24 commits to that file fail on sm80. It went unnoticed because validate_fp8
gates load_in_fp8 at >= (9, 0), which looks like full coverage, and the fp8 suites skip
rather than fail on hardware that cannot run them.

Verified on a real A100-SXM4-40GB, not a simulation, since reporting sm80 through
get_device_capability on a newer card retargets every triton kernel in unsloth and the run
dies in rms layernorm before reaching fp8:

dequant_with_guard      ok
dequant_without_guard   CompilationError   <- main, same card, same tensors
forward e4m3fn / e5m2   ok / ok

tests/test_fp8_pre_sm89_dequant_fallback.py 23 passed 6 skipped,
tests/test_fp8_fbgemm_block_shapes.py 11 passed 1 skipped,
tests/test_fp8_device_context.py 6 passed 3 skipped, all on that A100.

Llama_FP8_GRPO.ipynb as published, install pointed here, ran 5 GRPO steps on an RTX PRO 6000
with 112 fp8 params and finite losses throughout, confirming sm89+ is untouched. AMD gfx1151
returned NO_REGRESSION.

Scope deliberately not taken. A pre-sm89 from_pretrained still will not reach this
fallback, because transformers' own FineGrainedFP8HfQuantizer.validate_environment sets
dequantize = True below capability 8.9 and loads the model as bf16. Keeping the weights in
fp8 and dequantizing per forward means patching that validator, and belongs in its own change
with memory and throughput numbers behind it. This PR stays on the kernels.

fp8e4nv (torch.float8_e4m3fn) only exists from sm89 on, so weight_dequant_kernel cannot be compiled for older architectures. The dequant fallback in _blockwise_weight_dequant_any_shape sent evenly tiled square blocks to that triton kernel anyway, so on A100 the fallback raised a triton CompilationError instead of falling back. Take the torch-native scale expansion there as the other two branches already do.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the even-tiling branch in unsloth/kernels/fp8.py still hands float8_e4m3fn to the triton kernel, which cannot compile fp8e4nv below sm89. The new guard tests only the major capability below 9, which is also true for sm89 cards like the 4090 and L40S, so they would drop off the triton path too; could you switch it to a full (major, minor) at least (8, 9) comparison?

triton adds fp8e4nv to its supported dtypes at capability >= 89, not >= 90
(third_party/nvidia/backend/compiler.py). Testing only the major version also
diverts sm89 (4090, L40S, L4), which compiles the kernel fine, so all of Ada
dropped off the triton path. Compare (major, minor) against (8, 9) instead, and
skip the check on ROCm, where the capability is gfx-derived rather than an SM
number and AMD's triton backend lists fp8e4nv unconditionally.

Also chunk the torch expansion. It built two m*n float32 temporaries, ~6x the
peak of the kernel it stands in for, and the guard newly routes full-size evenly
tiled weights into it, so a flattened MoE expert stack could trade the
CompilationError for an OOM on the 40GB A100s this is meant to fix. Walking
whole block-rows holds the peak at 1.2-1.8x the triton path; measured on
8192x28672, 2688MB -> 532MB, values bit-identical.

Verified on a B200 with TRITON_OVERRIDE_ARCH plus a matching device-capability
patch, so the compiler takes the same capability-gated path the real card would:
sm80/sm86 reproduce the reported CompilationError on main and pass here, and
sm89/sm90/sm100 are byte-identical to main. 495 routing cells (capability x
dtype x scale dtype x shape x block) are bit-exact against a float64 reference,
forward and backward.
@danielhanchen

Copy link
Copy Markdown
Member

Thanks for tracking this down, the underlying bug is real. I pushed a commit to the branch rather than leaving it on you.

The guard boundary was off by one architecture. triton adds fp8e4nv at capability >= 89, not >= 90:

# third_party/nvidia/backend/compiler.py
if capability >= 89:
    supported_fp8_dtypes.add("fp8e4nv")

so get_device_capability()[0] < 9 also diverted sm89, which compiles the kernel fine. That took every 4090, L40S and L4 off the triton path. It is now a full (major, minor) < (8, 9) comparison, and it is skipped on ROCm, where the capability is gfx-derived rather than an SM number and AMD's triton backend lists fp8e4nv unconditionally.

The fallback also needed to get leaner. It built two m*n float32 temporaries, about 6x the peak of the kernel it replaces, and the new guard routes full-size evenly tiled weights into it for the first time. On a 40GB A100, which is exactly what this fixes, a flattened MoE expert stack would trade the CompilationError for an OOM. Expanding whole block-rows at a time holds the peak near the output itself, bit-identically:

weight triton fallback before fallback now
4096x14336 112 MB 672 MB (6.0x) 196 MB (1.75x)
8192x28672 448 MB 2688 MB (6.0x) 532 MB (1.19x)

How it was checked. No A100 here, so TRITON_OVERRIDE_ARCH plus a matching torch.cuda.get_device_capability patch makes the compiler take the same capability-gated path the real card would. Patching only one of the two is what makes a fix look broken, since the guard and the compiler then disagree.

  • sm80 and sm86 reproduce your exact type fp8e4nv not supported in this architecture on main, and pass now.
  • sm89, sm90 and sm100 are byte-identical to main, including the failure text when the simulated arch cannot load its own cubin on this board. Only the old < 9 version diverged at sm89.
  • 495 routing cells (capability x weight dtype x scale dtype x shape x block size) bit-exact against a float64 reference, forward and backward, plus per-tensor, e8m0 and non-contiguous scales.
  • float8_e5m2, CPU/MPS/XPU, ROCm and sm90+ routing are unchanged from main. Nothing outside pre-sm89 NVIDIA + float8_e4m3fn moves.
  • No new dynamo graph break; torch 2.4 through 2.13 all provide the APIs used.

Added tests/test_fp8_pre_sm89_dequant_fallback.py, which pins the boundary at sm89 on any CUDA GPU. It fails on main (the 4 pre-sm89 cases) and failed on the previous version of this branch (sm89 and ROCm), so it holds both directions.

One thing worth saying plainly: this does not make block-fp8 training work end to end on A100. The dequant helper is fixed, but the main fp8_block_matmul path still compiles fp8e4nv and still raises on sm80. This lands the helper correctly; the gemm is a separate change.

@danielhanchen

Copy link
Copy Markdown
Member

Addendum on the upgrade path, since that is the part a kernel change usually gets away without checking.

Took three real released versions, installed each, then pip-upgraded in place to this branch exactly as unsloth studio update does (install.sh upgrades the Studio venv with uv pip install):

installed before update after update
2026.7.6 triton at every capability torch at sm80/sm86, triton at sm89/sm90/sm100/ROCm
2026.8.22 triton at every capability same
2026.9.4 triton at every capability same

The dequant checksum is identical (-100.7624) in all three versions, before and after, at every simulated capability. So updating changes which path runs on pre-sm89 and changes no value anywhere.

Version skew is fine too: each upgrade deliberately kept the old unsloth_zoo (2026.7.7 / 2026.8.17 / 2026.9.3) against the new unsloth, and all imported and ran. Nothing here touches zoo.

Stale unsloth_compiled_cache was the other upgrade worry. Generated a real one with 2026.9.4 (16 files), upgraded, then loaded a model with UNSLOTH_COMPILE_OVERWRITE=0 so the old cache is reused: loads fine, and the cache contains zero references to kernels.fp8, weight_dequant_block or float8_e4m3fn. The fp8 integration is runtime forward-patching, not generated source, so it cannot be stale-cached.

Installs older than 2026-07-06 predate _blockwise_weight_dequant_any_shape entirely (added in #6848, first shipped in desktop-v0.1.526-beta), so there is nothing there for this to change.

On the Desktop/Studio side the diff is two files, unsloth/kernels/fp8.py and the new test. It touches nothing under studio/, install.sh, install.ps1, release-desktop.yml or publish-desktop-updater.yml - those are byte-identical to main, so the asset-name set and the releases/latest/download/latest.json updater endpoint are untouched by construction. I verified that as a file-set check rather than by rebuilding the app; no Desktop build or in-app update from an old beta was exercised, and none is reachable from this diff.

…m89 GPUs

The routing cases wrapped the real weight_dequant_block, so asserting "this
capability selects triton" actually compiled and launched the kernel. On the very
cards this file is about that raises, and a real A100 run failed 7 of them:
the four (8,9)/(9,0)/(10,0)/(12,0) boundary cases and all three ROCm cases, each
with "type fp8e4nv not supported in this architecture" rather than a routing
mismatch. The file claimed to pin routing on any CUDA GPU and did not.

These cases only need to observe which branch was chosen, so stub the kernel
instead of wrapping it. Values are already covered by
test_fallback_matches_the_triton_kernel_bit_for_bit, which skips when the
hardware cannot run both sides, and did skip correctly on the A100.

Verified on a real Colab A100-40GB (sm80) and locally under
TRITON_OVERRIDE_ARCH=sm80, where any surviving real compile would still fail.
Still discriminates: main fails the four pre-sm89 cases, and the previous commit
on this branch fails sm89 and ROCm.
@danielhanchen

Copy link
Copy Markdown
Member

Ran this on a real Colab A100-SXM4-40GB (sm80, torch 2.11.0+cu128, triton 3.6.0) rather than leaving it at the simulation.

Your report reproduces exactly, on the actual card and on the actual shipped code:

MARKER: gpu = NVIDIA A100-SXM4-40GB      compute_capability = (8, 0)
standalone fp8e4nv -> CompilationError: type fp8e4nv not supported in this architecture
standalone fp8e5   -> OK
guard_off (main)   -> CompilationError
guard_pr           -> OK via torch
guard_fixed        -> OK via torch
values_pr / values_fixed bit_exact_vs_float64 = True
MAIN -> {"status": "CompilationError", ...}
PR   -> {"status": "OK", "checksum": -122.4842}

pr_and_fixed_agree_on_this_card = True, as expected: the < 9 and < (8, 9) versions only diverge at sm89, which Colab does not offer. The A100 confirms the premise and that the correction did not break it; sm89 stays covered by triton's own capability >= 89 and the override simulation.

Memory on the 39.5 GiB card matches the B200 numbers exactly, and the chunked result is bit-identical to the old one:

weight old fallback chunked
4096x14336 672 MB 196 MB
8192x28672 2688 MB 532 MB

The run also found a bug in my own test, which I have fixed in 162de00f. The routing cases wrapped the real weight_dequant_block, so asserting "this capability selects triton" actually compiled and launched the kernel. On a pre-sm89 card that raises, so 7 tests failed on the A100 - the four (8,9)/(9,0)/(10,0)/(12,0) boundary cases and all three ROCm cases - every one with type fp8e4nv not supported in this architecture rather than a routing mismatch. The file claimed to pin routing on any CUDA GPU and did not; it only worked on sm89+.

Those cases only need to observe which branch was chosen, so the kernel is now stubbed rather than wrapped. Values stay covered by test_fallback_matches_the_triton_kernel_bit_for_bit, which skips when the hardware cannot run both sides, and did skip correctly on the A100 (6 skipped). After the fix, a second A100 run gives 16 passed, 6 skipped, and the test still discriminates: main fails the four pre-sm89 cases, and the previous commit on this branch fails sm89 and ROCm.

Worth stating plainly, since it was nearly missed: the notebook runner reported PASS on the first run because every cell executed. The 7 failures were inside a cell, in pytest_rc = 1. A green cell-level verdict is not a green test suite.

@danielhanchen

Copy link
Copy Markdown
Member

Correction to my last comment: Colab does offer an sm89 card. The L4 is Ada, compute capability 8.9. So the sm89 claim no longer rests on simulation - here it is on real silicon.

NVIDIA L4, capability (8, 9), torch 2.11.0+cu128, triton 3.6.0:

standalone fp8e4nv -> OK            <- Ada compiles the kernel fine
guard_off (main)   -> OK via triton
guard_pr           -> OK via torch     <- the misroute, on real hardware
guard_fixed        -> OK via triton    <- matches main
all three bit_exact_vs_float64 = True

That is the regression reproduced end to end: the originally submitted [0] < 9 takes a card that compiles fp8e4nv perfectly well and sends it down the torch path anyway, while < (8, 9) leaves it exactly where main had it.

What that misroute costs, measured on the L4 itself:

weight triton (main / fixed) torch fallback (what [0] < 9 selects)
4096x14336 112 MB, 1.09 ms 196 MB, 5.04 ms 1.75x memory, 4.6x slower
8192x28672 448 MB, 3.61 ms 532 MB, 21.15 ms 1.19x memory, 5.9x slower

sm89_values_identical = True at both sizes, so it is pure cost, not a tradeoff. And note those fallback figures use the chunked expansion from this branch; against the whole-weight version the PR originally shipped with it would have been 672 MB at 4096x14336, so 6.0x the triton peak rather than 1.75x, on 24GB cards.

One thing I should flag about my own reporting: the pr_and_fixed_agree_on_this_card = True marker compares values, not paths. On the L4 the two take different branches and still produce identical output. I named that marker while expecting an A100, where both take the torch path, and it would be easy to misread it as "no difference here". There is a difference; it is just not a numerical one.

The regression test also gets stronger on this card: 22 passed, 0 skipped. test_fallback_matches_the_triton_kernel_bit_for_bit skipped on the A100 because sm80 cannot run the triton side to compare against, but the L4 can, so triton-vs-torch bit-exactness is now confirmed on hardware rather than inferred.

Coverage now, all on rented hardware: A100-40GB (sm80) for the reported bug, L4 (sm89) for the boundary, B200 (sm100) locally for the untouched side. The remaining gaps are ROCm and sm120, which stay argued from triton's backend source rather than measured.

…t the dequant

Fixing _blockwise_weight_dequant_any_shape was necessary but not sufficient. On a
simulated sm80, four of six fp8 entry points still raised with that fix in place:
act_quant, fp8_block_matmul, and FP8BlockQuantLinear forward and backward, all
with the same "type fp8e4nv not supported in this architecture". act_quant emits
an fp8e4nv pointer and the w8a8 gemm consumes two, so a card that cannot compile
the dtype cannot run the pair either, and the public path kept crashing on the
exact GPUs this branch is meant to fix.

Lift the predicate into _fp8_kernel_unsupported and apply it at the two other
places that reach those kernels: FP8BlockQuantLinear.forward now takes the
dequant-plus-matmul branch it already had for an indivisible hidden dim, and the
fbgemm path folds it into kernel_supported, since triton_quantize_fp8_block emits
fp8e4nv too. All three reachable call sites are now behind the guard, so sm80 and
sm86 go from 4/6 failing to 0/6, while sm89 and sm90 stay at 0/6 unchanged.

The fallback is a different computation, not a bit-for-bit substitute, so it was
measured rather than assumed: against a float64 reference it is about 8x MORE
accurate than the kernel it replaces (relative error 0.0032 vs 0.0254), because
it keeps activations in bf16 instead of quantizing them, with gradients finite
and of matching magnitude.

Verified on real hardware: A100-40GB and L4 via Colab, gfx1151 via the AMD CI
runner (NO_REGRESSION on both jobs, with ROCm correctly never diverting even at
spoofed pre-sm89 capabilities).
@danielhanchen

Copy link
Copy Markdown
Member

Extended this so pre-sm89 cards actually RUN fp8, not just survive the dequant. Pushed as 6ca5efeb.

Fixing the dequant helper was necessary but not sufficient. On a simulated sm80, with the helper already fixed, four of six fp8 entry points still raised:

SUMMARY @ sm80 (before): 4/6 entry points still fail
  act_quant                          CompilationError: type fp8e4nv not supported...
  fp8_block_matmul                   CompilationError: ...
  FP8BlockQuantLinear.apply forward  CompilationError: ...
  FP8BlockQuantLinear fwd+bwd        CompilationError: ...

act_quant emits an fp8e4nv pointer and the w8a8 gemm consumes two, so a card that cannot compile the dtype cannot run the pair either. The public forward kept crashing on exactly the GPUs this branch exists to fix.

The predicate is now _fp8_kernel_unsupported, applied at the two other places that reach those kernels: FP8BlockQuantLinear.forward takes the dequant-plus-matmul branch it already had for an indivisible hidden dim, and the fbgemm path folds it into kernel_supported, since triton_quantize_fp8_block emits fp8e4nv too. All three reachable call sites are behind the guard now.

SUMMARY @ sm80 (after): 0/6      @ sm86: 0/6      @ sm89: 0/6      @ sm90: 0/6

On a real A100-40GB and a real L4, a full forward+backward through the package now runs:

FULL_FORWARD -> {"forward_backward": "OK", "out_finite": true, "grad_finite": true, "grad_absmax": 0.028809}

The fallback is a different computation, so I measured it rather than assuming. Against a float64 reference it is about 8x MORE accurate than the kernel it replaces, relative error 0.0032 vs 0.0254, because it keeps activations in bf16 instead of quantizing them. Gradients finite and of matching magnitude. So pre-sm89 gets: works, slower, slightly more accurate.

Hardware coverage, all rented or self-hosted, none simulated:

card capability result
A100-SXM4-40GB 8.0 was the reported crash; full fwd+bwd now runs
Tesla T4 7.5 same crash on main, works now
L4 8.9 stays on triton; [0] < 9 diverted it, costing 4.7-5.2x time
RTX PRO 6000 Blackwell 12.0 unchanged from main
B200 10.0 unchanged from main
Radeon 8060S (gfx1151) ROCm 7.13 NO_REGRESSION, both CI jobs

The AMD run used the gfx1151 self-hosted runner in regression mode rather than differential, deliberately: the defect is an NVIDIA capability gate, so the base cannot exhibit it there and a differential run would be VOID rather than a pass. It reports identical routing and identical checksums at all five capabilities including spoofed pre-sm89 ones, with torch.version.hip = '7.13.99004' gating that the ROCm claim is backed. That is the torch.version.hip is None clause confirmed on hardware instead of from source.

Remaining gap, stated plainly: act_quant and fp8_block_matmul called DIRECTLY still raise on pre-sm89. They are unreachable from any public path now, and there is no meaningful fallback for "quantize to a dtype this GPU has no support for", so that is a hardware limit rather than a routing bug.

@danielhanchen

Copy link
Copy Markdown
Member

@codex security review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 13, 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-09-14T02:59:33.840428Z 769ccb4 Manual request
🔒 Security Review ✅ Completed 2026-09-13T13:34:21.739100Z 0a31fdf 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

Copy link
Copy Markdown

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

Reviewed commit: 0a31fdf17c

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

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: 0a31fdf17c

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@danielhanchen

Copy link
Copy Markdown
Member

Pushed 0a31fdf17. A file search over the names this change touches turned up one more unguarded path, which is why the extra commit exists.

weight_dequant fell through to weight_dequant_block directly for block-quantized weights, bypassing the guard entirely. kernels/utils.py reaches it from three fast_dequantize dispatch sites, so that path still raised on pre-sm89. It now goes through _blockwise_weight_dequant_any_shape, which already carries the guard. Verified at sm80, sm89 and sm100: identical checksum -352.3102 at all three.

Also shortened the comments this branch added, since several had grown to four and five lines for a one-line point.

Checks on the final state:

  • AST comparison against main: nothing removed, no signature changed, only two private helpers added (_fp8_kernel_unsupported, _torch_blockwise_dequant). No public API moves.
  • No imports added or removed, and the diff touches no transformers, TRL, PEFT or vllm symbol, so the supported-version ranges for those are unaffected by construction rather than by testing each one.
  • 64 passed, 4 skipped across the six fp8 suites; 495-cell routing matrix bit-exact against a float64 reference.
  • Entry-point surface: sm80 and sm86 at 0/6 failing, sm89 and sm90 unchanged at 0/6.

Cross-platform, via staging CI on Linux x64, Windows x64 and macOS arm64: all three green, with the file collecting 23 of 23 tests on each. To be precise about what that shows, those runners have no CUDA, so all 23 skip on the torch.cuda.is_available() guard. It demonstrates the module imports and collects cleanly on all three operating systems, not that the GPU assertions pass there. The GPU evidence is the rented hardware: A100, L4, T4, RTX PRO 6000 Blackwell, plus gfx1151 for ROCm.

One note on approach, since it came up. This is first-party code in unsloth/kernels/fp8.py, so it is edited directly rather than monkey-patched. import_fixes.py exists for third-party packages it patches (vllm, datasets, peft, torchao, torchcodec) and has no fp8 entry; a runtime patch here would have to re-implement the function and would silently drift from the source.

@danielhanchen

Copy link
Copy Markdown
Member

Went looking for the commit that broke this, on the assumption it was a regression. It is not one. The archaeology says fp8 has never worked on a pre-sm89 GPU, since the day it landed.

Bisect. I wrote a probe that extracts each commit's weight_dequant_kernel by AST and compiles it standalone for sm80, so an unrelated import error at an old commit cannot masquerade as "fp8 was fine here". Validated both directions first: it reports failure under TRITON_OVERRIDE_ARCH=sm80 and success under sm100, so it is not vacuous.

git bisect start; git bisect bad origin/main; git bisect good 7797f373d
git bisect run python bisect_probe.py
-> first bad commit: 1dd5485e9  vLLM FP8 quantized support for SFT/GRPO (#3414), 2025-10-16

The first bad commit is the commit that introduced fp8. There is no good commit after it. I also ran the probe linearly over all 24 commits that have ever touched unsloth/kernels/fp8.py, and every one of them fails on sm80, including the first.

Blame. git log -S get_device_capability -- unsloth/kernels/fp8.py returns nothing: that call has never existed in this file, so no arch guard was ever removed. The three lines that require fp8e4nv blame to the original feature, with later commits only moving them:

1dd5485e95 Datta Nimmaturi 2025-10-16  y = y.to(y_ptr.dtype.element_ty)          # act_quant_kernel
ba2897a318 Daniel Han      2025-12-01  y = torch.empty_like(x, dtype = torch.float8_e4m3fn)
81f789ba85 ramisworld      2026-07-09  weight_dequant_kernel[grid](x, s, y, ...)

So why did nobody hit it for eleven months. Three things lined up:

  1. There is an arch gate, and it looks like the whole story. validate_fp8 in loader_utils.py refuses with get_device_capability() >= (9, 0): "On the fly load_in_fp8 requires H100 GPUs or after." Anyone asking Unsloth to quantize on an A100 gets a clean, friendly error, which reads as fp8 being properly gated.
  2. That gate only covers load_in_fp8. Loading a checkpoint that is already block-fp8, the DeepSeek-V3 and fp8 Qwen case, goes through _FP8_DTYPES and _fp8_block_size_from_config and patches FP8Linear.forward with no capability check anywhere. That is the actual hole, and it is the path this PR fixes.
  3. The tests skip instead of failing on such hardware. test_fp8_device_context.py has a literal pytest.skip("requires FP8-capable CUDA hardware"), and the fbgemm battery skips without fbgemm. On an A100 the fp8 suite goes green by skipping, so CI could never have surfaced this.

Worth noting that validate_fp8's >= (9, 0) is the codebase's own precedent for comparing the full tuple rather than the major alone, which is what this PR now does in the kernel. Its threshold is a separate question: 9.0 excludes sm89, which for the on-the-fly path may well be deliberate given the torchao and fbgemm gemms involved, so I have not touched it here.

Practical upshot for the changelog: this is a gap being closed, not a regression being reverted. Anyone who has ever tried a block-fp8 checkpoint on an A100, A10, V100 or T4 hit it, and there was no version where it worked.

@danielhanchen

Copy link
Copy Markdown
Member

Pushed 59af7764 with the caching and no_grad changes. Measured the torch.compile question rather than guessing, and it went the other way from what I expected.

lru_cache on the guard: done, and it is worth very little. A device's capability cannot change, so the lookup is now cached per device with _fp8_device_lacks_kernel. Measured saving is 0.10 microseconds per call, about 0.1 ms across a thousand layer calls, against a dequant that costs 0.5 to 2.6 ms. It is free and correct, but nobody should expect to see it. The cache does mean a test simulating another card has to call _fp8_device_lacks_kernel.cache_clear(), which the test file now does in an autouse fixture.

no_grad: worth more than the cache, for a reason that is not speed. Timing is unchanged, 0.527 ms either way. But the fallback was building an autograd graph the triton kernel it replaces never builds:

before   eager fallback requires_grad = True     triton kernel requires_grad = False
after    eager fallback requires_grad = False    triton kernel requires_grad = False

So the two paths now agree, and the fallback can no longer quietly retain a graph in a grad-enabled caller such as fast_dequantize.

torch.compile: measured, and deliberately not used. Compiled, the simple three-line expansion is excellent, 17x faster at 4096x14336 and holding the peak at the triton kernel's own 112 MB. But:

  • the chunk loop compiles terribly, 5.5 ms against 2.5 eager at 8192x28672, after a 34 second compile, because each chunk becomes its own graph;
  • compilation does not reliably engage when the helper is called directly, so the memory property becomes conditional, and the test for it went green or red depending on what ran before it in the same file;
  • the callers are already @torch_compile regions (lines 483, 552, 653, 731), so in production inductor fuses this anyway and an inner compile is redundant.

A conditional guarantee with a flaky test is worse than a slightly slower unconditional one, so the chunked eager version stays. Happy to revisit if you would rather take the compiled version and drop the memory assertion.

On the two GRPO notebooks, an honest account. Colab would not allocate an H100 to this account on three attempts, and both notebooks need one: load_in_fp8 is gated at get_device_capability() >= (9, 0). The runner reported InfraError rather than silently downgrading, so there is no result to show from Colab.

I ran it locally on a B200 instead, which clears the same gate. Results, with what they do and do not establish:

  • load_in_fp8 = True loads unsloth/Llama-3.2-1B-Instruct-FP8-Block with 112 float8_e4m3fn parameters, and the model generates coherent text on this branch.
  • Five GRPO steps complete on both main and this branch with identical rewards (0.38, 0.36), identical losses, and identical peak memory of 2.485 GiB. So this workload is unaffected by the change, which is the no-regression claim.
  • What it does not establish: my spies counted zero calls into fp8_linear, weight_dequant and the block dequant helper during the training steps, and the loss stayed at 0.0 throughout. So this harness is not exercising the dequant kernels in the backward pass, and I am not going to present it as if it were. The notebook itself could not be used verbatim here either: its dataset prep calls apply_chat_template on an empty list under transformers 5.5.0 with datasets 3.6.0, which fails before any fp8 code runs, and vllm 0.29.0 no longer has the vllm.model_executor.layers.quantization.bitsandbytes module that unsloth_zoo/vllm_utils.py imports. Both are unrelated to this PR but both block a verbatim run.

The evidence for the kernels themselves remains the unit level: 495 routing cells bit-exact against a float64 reference, and real hardware on A100, L4, T4, RTX PRO 6000 Blackwell, B200 and gfx1151. A full FP8 GRPO run on an H100 is still the one thing outstanding, and it needs an H100 that Colab is not currently handing out.

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

Follow-up on the questions raised since the last round: caching the guard, whether the fallback is optimal, whether torch.compile helps, and whether a full FP8 GRPO notebook still runs.

The guard is now cached

_fp8_kernel_unsupported itself cannot be cached, since it takes a tensor, but the only part worth caching is the device lookup, which is what actually costs anything:

@functools.lru_cache(maxsize = None)
def _fp8_device_lacks_kernel(device):
    return torch.version.hip is None and torch.cuda.get_device_capability(device) < (8, 9)

Measured on a B200, 200k calls each: 1.19 us per call before, 0.53 us after, so 0.66 us saved per call. That is 0.66 ms per thousand linear layers, which is noise next to the kernel itself, but it costs nothing and the capability of a device cannot change.

One hazard came with it: anything simulating another card must call _fp8_device_lacks_kernel.cache_clear(), or the first answer sticks. That bit my own test, which simulated (9, 0) and then (8, 0) in one function and so compared the triton kernel against itself. Fixed, and the test now asserts the guard flips rather than trusting it to.

The fallback is under no_grad, and is faster eager

It was not under no_grad before. It is now, matching the triton kernel it stands in for, which builds no graph either. Without it, a scale tensor with requires_grad made the fallback return a graph-tracking tensor where the kernel returns a plain one, which is a behaviour difference between the two paths on top of the wasted memory.

torch.compile measured slower and was not adopted:

variant 4096x14336 8192x28672 first call
eager chunked 1.61 ms 6.18 ms 1.7 ms
compiled chunked 1.83 ms 5.50 ms 34.0 s

The workload is a memory-bound scale expansion, so there is nothing for inductor to fuse away, and compiling the chunk loop unrolls one graph per chunk. The 34 s first call is per shape, and a Llama-sized model hits four distinct weight shapes. The callers are already inside compiled regions in the normal path, so this would be paying the warmup twice. Left eager, with a comment saying so.

Peak memory is unchanged from the earlier chunking fix: 532 MB against 2688 MB for the whole-weight expansion, on a 4096x8192 weight.

Full GRPO notebook

Llama_FP8_GRPO.ipynb as published, with only the install pointed at this PR and the two trainers cut to 5 steps, on a Colab RTX PRO 6000 Blackwell:

gpu           NVIDIA RTX PRO 6000 Blackwell Server Edition
capability    [12, 0]
fp8_params    112
grpo_steps    5
losses        [0.173, -0.2242, 0.3388, 0.0, 0.1339]
all_finite    true
guard_says_unsupported_here  false

The guard correctly stands aside on sm120, so this is the unchanged path and it behaves as before. One cell raised module re has no attribute TEMPLATE on that runtime, from displaying a compiled regex on Python 3.13; the assignment itself succeeded, which is why the reward functions that use it worked and training completed. Nothing to do with FP8.

Real A100

The rest of this needed real sm80 silicon. Reporting sm80 through torch.cuda.get_device_capability on a newer card retargets every triton kernel in unsloth, so the run dies in rms layernorm long before reaching FP8, and a green result there would mean nothing.

On an A100-SXM4-40GB:

dequant_with_guard      ok
dequant_without_guard   CompilationError    <- main, same card, same tensors
forward e4m3fn / e5m2   ok / ok
loader_gate block_fp8   allowed
loader_gate per_tensor  still rejected

and a genuine block-FP8 checkpoint, unsloth/Qwen3-0.6B-FP8, loaded and trained there:

top_token " Paris"   loss 4.36402   logits_finite true   grads_finite true   n_grads 112

The same prompt on a B200 gives " Paris" and loss 4.35188, so the pre-sm89 path lands in the same place.

Suites on that A100: test_fp8_pre_sm89_dequant_fallback.py 23 passed 6 skipped, test_fp8_fbgemm_block_shapes.py 11 passed 1 skipped, test_fp8_device_context.py 6 passed 3 skipped.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 14, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

Correction to my earlier comment, since it changes a conclusion rather than just wording.

I claimed the A100 run showed "the pre-sm89 path is landing in the same place". The numbers were real, but the mechanism was not what I said. That load had been dequantized to bf16 by FineGrainedFP8HfQuantizer.validate_environment, which sets quantization_config.dequantize = True below capability 8.9, so it never touched the fallback at all. It generated " Paris" and trained because it was an ordinary bf16 model by then.

The check that settles it: a B200 at capability (10, 0), where that transformers gate does not fire, loads unsloth/Qwen3-0.6B-FP8 as 197 plain bf16 Linear modules with dequantize unset. A training load of a block-FP8 checkpoint goes to bf16 on every GPU, so the unsloth loader gate was never what stood between a pre-sm89 user and this fallback.

I have reverted that loader change in 85467b6. unsloth/models/_utils.py is byte-identical to main again, and the PR is back to the kernels plus their guard.

What still stands, measured on a real A100-SXM4-40GB rather than inferred:

dequant_with_guard      ok
dequant_without_guard   CompilationError   <- main, same card, same tensors
forward e4m3fn / e5m2   ok / ok

That is the PR doing its job, and it matches the reproduction in the description, which is a kernel-level test and not a model load. The remaining commits are the sm89 boundary, the chunked fallback, the cached capability lookup, no_grad, the e5m2 activation dtype fix and the grouped eval guard.

Making the fallback reachable from a pre-sm89 from_pretrained, by keeping weights in fp8 and dequantizing per forward, needs that third-party validator patched and deserves its own PR with memory and throughput numbers behind it.

Suites after the revert: 42 passed, 5 skipped across the three FP8 files.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 85467b6964

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

@xy200303

xy200303 commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for taking this over. The guard I wrote was wrong: get_device_capability()[0] < 9 also catches sm89, so it pushed 4090/L40S/L4 off the triton path even though they compile the kernel fine. Sorry about that.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 14, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 769ccb426d

ℹ️ 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 a6766d2 into unslothai:main Sep 14, 2026
21 of 22 checks passed
@xy200303
xy200303 deleted the fix/fp8-dequant-fallback-pre-sm89 branch September 14, 2026 04:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants