Skip to content

FP8 rowwise scaled_mm: keep fp16 output in range before torch 2.14, and drop the row guard for always-dequant dtypes when compiled - #16598

Merged
danielhanchen merged 8 commits into
mainfrom
dh/fp8-rowwise-compile-guards
Nov 4, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
dh/fp8-rowwise-compile-guards

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

Problem

Two issues in the FP8 rowwise scaled_mm path, unsloth/kernels/fp8.py.

A. fp16 output overflows to inf on torch < 2.14. Those builds cannot write fp16 directly from the rowwise kernel, so fp16 goes through a bf16 detour and is cast back. Values near the fp16 limit (65450, 65504) round up to 65536 in bf16, which is inf in fp16.

On an RTX PRO 6000 (sm120), 128 rows, targets 65450 / 65504, 4 of 18 cells come out all inf on main for torch 2.13, 2.10 and 2.9.1. On 2.9.1 that is about 1M inf values per cell.

C. The compiled row guard runs before the float32 support check. float32 always dequantizes, but the row-count guard still ran under torch.compile, so dynamic shapes recompiled: 2 graphs (dynamic) and 3 (marked) on main, where 1 is enough.

Fix

  • torch 2.10 to 2.13: fp16 output uses a zero fp16 bias, which makes the kernel write fp16 directly. The bias is cached per (rows, device, stream) in eager, with a 64-entry bound. Fake tensors are never cached, CUDA graph capture always gets a private bias, and the bias is built outside inference mode. Under compile it is built in the graph.
  • torch < 2.10, and ROCm before 2.14: fp16 always takes the exact dequant + fp16 GEMM path, at every row count, because those builds cannot produce fp16 from the rowwise kernel.
  • Compile: dtypes that always dequantize (float32, and fp16 on the builds above) skip the row-count guard, and support is checked before the guard.
  • Version checks: computed once at import, so bf16 calls do no extra per-call work.

Results

RTX PRO 6000 (sm120) on Colab; main and this branch on the same VM.

Defect A, cells with inf out of 18:

torch main this branch
2.13.0 4 0
2.10.0 4 0
2.9.1 4 0

On 2.9.1 the fp16 random-input relative error at 128 rows drops from 0.0265 to 0.0003. Eager matches compiled everywhere.

Defect C, torch 2.13 and 2.10: float32 compiles to 1 graph both dynamic and marked (main: 2 and 3). bf16 graph counts are unchanged, and there are 0 graph breaks.

Timing, torch 2.13, medians over 3 interleaved rounds, main measured twice (A/A):

case main (A/A) this branch main spread
fp16, N=14336, 128 rows 45.40 / 45.39 us -13.6% 0.09%
fp16, N=4096, 128 rows 40.17 / 40.23 us -9.7% 1.55%
bf16, N=4096, 128 rows 34.64 / 34.86 us +1.2% 2.64% (noise)
compiled training forward cells +0.1% to +2.6% 2.6% to 4.7% (noise)
1 and 32 rows (dequant) within 0.6%

Tests

  • New tests/test_fp8_rowwise_compile_guards.py (39 cases), small updates to two existing fp8 test files. The new file covers:
    • routing at 17 to 4096 rows for each mode;
    • finite output at 65504 in eager and compiled, asserting _scaled_mm is never called on the dequant-only builds;
    • the bias cache bounds and exclusions;
    • graph counts.
  • CPU fp8 suite: 414 passed on torch 2.13 and on 2.15.
  • On the GPU: 75 passed on this branch; the new file fails 36 tests on main.

Cost on torch < 2.10: fp16 there now always dequantizes, so it is correct but slower on large layers. On the RTX PRO 6000 with torch 2.9.1, a 14336x4096 layer at 128 rows goes from 43.2 to 166.0 us per call (A/A 0.0%), and the compiled training forward from 74 to 164 us. 4096x4096 gets faster (40.1 to 32.9 us); 1 and 32 rows are unchanged. The fast path on those builds is the bf16 detour that produces the inf. Keeping it with a clamp would hide real overflows from GradScaler, so correctness is kept here. bf16 is unaffected on every torch.

Also checked on an L4 (sm89) and an RTX PRO 6000 for torch 2.13, 2.10 and 2.9.1:

  • fp16 inf counts go to 0 there too, including 32 rows on an L2-spilling weight on the L4;
  • bf16 outputs, gradients, losses and compiled graph counts are byte-identical to main on every route and row bucket.

Not covered: ROCm, and timing on other GPUs.

…d for always-dequant dtypes when compiled

On torch < 2.14 the rowwise CUTLASS kernel picks its output type from the
bias dtype, so fp16 activations asked for bf16 and cast back. A finite fp16
result in 65408..65504 rounds to 65536 in bf16 and becomes inf in fp16; #15791
sent 17-64 row calls on L2-spilling sm89 weights down this route, and every
call over 64 rows took it already.

torch 2.10-2.13 (CUDA): pass a zero fp16 bias instead. It selects the fp16
epilogue (RowwiseScaledMM.cu), so fp16 keeps its range and rounding. The bias
is cached per (rows, device) for eager calls (bounded, never for fake tensors
or tensors made during CUDA graph capture) and built in the graph when traced.

torch < 2.10 and ROCm before 2.14 have no fp16 rowwise output at all, so the
scaled_mm backend now serves fp16 with the exact dequant + fp16 GEMM at every
row count, in the eager direct route and the autograd function alike. bf16 and
float32 routing is unchanged.

Since #16393 the compiled forward compared the row count before checking that
the output dtype is supported, so calls that always dequantize gained an
M <= 64 guard: an extra graph under dynamic shapes and a ConstraintViolationError
for a strict mark_dynamic range across 64. Check dtype support first while
tracing (float32 without float32 rowwise output, fp16 without fp16 output);
eager keeps rows first so decode calls never run the float32 probe.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 3, 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-11-04T00:40:56.953165Z b353f96 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: 8c417ee6b0

ℹ️ 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
Comment on lines +2072 to +2076
key = (n, device)
bias = _SCALED_MM_FP16_ZERO_BIAS_CACHE.get(key)
if bias is None:
with torch.inference_mode(False), torch.no_grad():
bias = torch.zeros(n, dtype = torch.float16, device = device)

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 Make the zero-bias cache CUDA-stream aware

On torch 2.10–2.13, independent CUDA streams running eager fp16 forwards with the same output width share this cached tensor. Its torch.zeros initialization is asynchronous on the first caller's stream, but a cache hit on another stream neither waits for that initialization nor records the tensor's use on that stream. Consequently, _scaled_mm can read an uninitialized bias; cache eviction can also allow its storage to be recycled while another stream still uses it. Key the cache by stream, or track initialization dependencies and cross-stream storage lifetime explicitly.

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 905e7b1. The cache is now keyed by (rows, device, stream): a bias is only handed back on the stream whose zeros fill made it, so another stream gets its own, and its storage stays tied to that stream for the caching allocator. The stream is only read when CUDA is initialized, so fake CUDA tensors in tracing and tests do not initialize it. New CUDA test test_fp16_zero_bias_is_not_shared_across_cuda_streams; the CPU suite gives 73 passed on torch 2.13 and 2.15.

The zeros fill is asynchronous on the stream that made it, and the caching allocator ties the storage
to that stream, so a bias cached on one stream must not be handed to another.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 905e7b1fc9

ℹ️ 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
Comment on lines +2081 to +2082
bias = _SCALED_MM_FP16_ZERO_BIAS_CACHE.get(key)
if bias is None:

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 Bypass cached biases during CUDA graph capture

On torch 2.10–2.13 CUDA, warming up an eager fp16 forward on the capture stream populates this cache, so capture subsequently reuses an externally allocated bias without reaching the capture check below. This is the warmup/capture ordering used by GraphedForward._capture in unsloth/models/diffusion_infer.py. If later calls fill the 64-entry cache, clear() can release that bias while the captured graph still references its address; subsequent allocations can overwrite it, corrupting graph replay results. Check for capture before the cache lookup and allocate a graph-private zero bias during capture, or retain the cached tensor for the graph's entire lifetime.

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 66cec5c. Capture is checked before the cache lookup: while the current stream is capturing, a graph-private zero bias is returned and never cached, so a later clear() cannot free memory the graph reads. New CUDA test test_fp16_zero_bias_is_graph_private_during_cuda_graph_capture warms the cache on the capture stream, captures, replays, and checks the captured bias is not the cached one and the replayed output is correct.

On a real pre-sm89 card the e4m3fn trace check refused every cell, so the 18 routing cases failed on a T4
while the decision under test is the same everywhere.
A warmup on the capture stream filled the cache, so capture reused an evictable bias; a later clear() could
free memory the captured graph still reads. Capture now always gets its own bias, before any cache lookup.
@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: 66cec5c2bc

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

…lacks rowwise float32 output

torch 2.10 and older only support per-tensor scales for CPU _scaled_mm, which the CPU CI shard installs.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: b353f96d38

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

torch.cuda.is_available() is patched to True by the CUDA spoof when the CPU shards share a session with
version_compat, so the guard lint requires the real-device probe.
@danielhanchen
danielhanchen merged commit 1e4643c into main Nov 4, 2026
@danielhanchen
danielhanchen deleted the dh/fp8-rowwise-compile-guards branch November 4, 2026 08:53
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